1 //===- InstructionCombining.cpp - Combine multiple instructions -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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 algebraic
12 // 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. SetCC instructions are converted from <,>,<=,>= to ==,!= if possible
28 // 4. All SetCC 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/Pass.h"
40 #include "llvm/DerivedTypes.h"
41 #include "llvm/GlobalVariable.h"
42 #include "llvm/Target/TargetData.h"
43 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
44 #include "llvm/Transforms/Utils/Local.h"
45 #include "llvm/Support/CallSite.h"
46 #include "llvm/Support/GetElementPtrTypeIterator.h"
47 #include "llvm/Support/InstIterator.h"
48 #include "llvm/Support/InstVisitor.h"
49 #include "llvm/Support/PatternMatch.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/ADT/Statistic.h"
54 using namespace llvm::PatternMatch;
57 Statistic<> NumCombined ("instcombine", "Number of insts combined");
58 Statistic<> NumConstProp("instcombine", "Number of constant folds");
59 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
61 class InstCombiner : public FunctionPass,
62 public InstVisitor<InstCombiner, Instruction*> {
63 // Worklist of all of the instructions that need to be simplified.
64 std::vector<Instruction*> WorkList;
67 /// AddUsersToWorkList - When an instruction is simplified, add all users of
68 /// the instruction to the work lists because they might get more simplified
71 void AddUsersToWorkList(Instruction &I) {
72 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
74 WorkList.push_back(cast<Instruction>(*UI));
77 /// AddUsesToWorkList - When an instruction is simplified, add operands to
78 /// the work lists because they might get more simplified now.
80 void AddUsesToWorkList(Instruction &I) {
81 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
82 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
83 WorkList.push_back(Op);
86 // removeFromWorkList - remove all instances of I from the worklist.
87 void removeFromWorkList(Instruction *I);
89 virtual bool runOnFunction(Function &F);
91 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
92 AU.addRequired<TargetData>();
96 TargetData &getTargetData() const { return *TD; }
98 // Visitation implementation - Implement instruction combining for different
99 // instruction types. The semantics are as follows:
101 // null - No change was made
102 // I - Change was made, I is still valid, I may be dead though
103 // otherwise - Change was made, replace I with returned instruction
105 Instruction *visitAdd(BinaryOperator &I);
106 Instruction *visitSub(BinaryOperator &I);
107 Instruction *visitMul(BinaryOperator &I);
108 Instruction *visitDiv(BinaryOperator &I);
109 Instruction *visitRem(BinaryOperator &I);
110 Instruction *visitAnd(BinaryOperator &I);
111 Instruction *visitOr (BinaryOperator &I);
112 Instruction *visitXor(BinaryOperator &I);
113 Instruction *visitSetCondInst(BinaryOperator &I);
114 Instruction *visitShiftInst(ShiftInst &I);
115 Instruction *visitCastInst(CastInst &CI);
116 Instruction *visitSelectInst(SelectInst &CI);
117 Instruction *visitCallInst(CallInst &CI);
118 Instruction *visitInvokeInst(InvokeInst &II);
119 Instruction *visitPHINode(PHINode &PN);
120 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
121 Instruction *visitAllocationInst(AllocationInst &AI);
122 Instruction *visitFreeInst(FreeInst &FI);
123 Instruction *visitLoadInst(LoadInst &LI);
124 Instruction *visitBranchInst(BranchInst &BI);
125 Instruction *visitSwitchInst(SwitchInst &SI);
127 // visitInstruction - Specify what to return for unhandled instructions...
128 Instruction *visitInstruction(Instruction &I) { return 0; }
131 Instruction *visitCallSite(CallSite CS);
132 bool transformConstExprCastCall(CallSite CS);
135 // InsertNewInstBefore - insert an instruction New before instruction Old
136 // in the program. Add the new instruction to the worklist.
138 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
139 assert(New && New->getParent() == 0 &&
140 "New instruction already inserted into a basic block!");
141 BasicBlock *BB = Old.getParent();
142 BB->getInstList().insert(&Old, New); // Insert inst
143 WorkList.push_back(New); // Add to worklist
147 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
148 /// This also adds the cast to the worklist. Finally, this returns the
150 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
151 if (V->getType() == Ty) return V;
153 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
154 WorkList.push_back(C);
158 // ReplaceInstUsesWith - This method is to be used when an instruction is
159 // found to be dead, replacable with another preexisting expression. Here
160 // we add all uses of I to the worklist, replace all uses of I with the new
161 // value, then return I, so that the inst combiner will know that I was
164 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
165 AddUsersToWorkList(I); // Add all modified instrs to worklist
167 I.replaceAllUsesWith(V);
170 // If we are replacing the instruction with itself, this must be in a
171 // segment of unreachable code, so just clobber the instruction.
172 I.replaceAllUsesWith(UndefValue::get(I.getType()));
177 // EraseInstFromFunction - When dealing with an instruction that has side
178 // effects or produces a void value, we can't rely on DCE to delete the
179 // instruction. Instead, visit methods should return the value returned by
181 Instruction *EraseInstFromFunction(Instruction &I) {
182 assert(I.use_empty() && "Cannot erase instruction that is used!");
183 AddUsesToWorkList(I);
184 removeFromWorkList(&I);
186 return 0; // Don't do anything with FI
191 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
192 /// InsertBefore instruction. This is specialized a bit to avoid inserting
193 /// casts that are known to not do anything...
195 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
196 Instruction *InsertBefore);
198 // SimplifyCommutative - This performs a few simplifications for commutative
200 bool SimplifyCommutative(BinaryOperator &I);
203 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
204 // PHI node as operand #0, see if we can fold the instruction into the PHI
205 // (which is only possible if all operands to the PHI are constants).
206 Instruction *FoldOpIntoPhi(Instruction &I);
208 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
209 // operator and they all are only used by the PHI, PHI together their
210 // inputs, and do the operation once, to the result of the PHI.
211 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
213 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
214 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
216 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
217 bool Inside, Instruction &IB);
220 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
223 // getComplexity: Assign a complexity or rank value to LLVM Values...
224 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
225 static unsigned getComplexity(Value *V) {
226 if (isa<Instruction>(V)) {
227 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
231 if (isa<Argument>(V)) return 3;
232 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
235 // isOnlyUse - Return true if this instruction will be deleted if we stop using
237 static bool isOnlyUse(Value *V) {
238 return V->hasOneUse() || isa<Constant>(V);
241 // getPromotedType - Return the specified type promoted as it would be to pass
242 // though a va_arg area...
243 static const Type *getPromotedType(const Type *Ty) {
244 switch (Ty->getTypeID()) {
245 case Type::SByteTyID:
246 case Type::ShortTyID: return Type::IntTy;
247 case Type::UByteTyID:
248 case Type::UShortTyID: return Type::UIntTy;
249 case Type::FloatTyID: return Type::DoubleTy;
254 // SimplifyCommutative - This performs a few simplifications for commutative
257 // 1. Order operands such that they are listed from right (least complex) to
258 // left (most complex). This puts constants before unary operators before
261 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
262 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
264 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
265 bool Changed = false;
266 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
267 Changed = !I.swapOperands();
269 if (!I.isAssociative()) return Changed;
270 Instruction::BinaryOps Opcode = I.getOpcode();
271 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
272 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
273 if (isa<Constant>(I.getOperand(1))) {
274 Constant *Folded = ConstantExpr::get(I.getOpcode(),
275 cast<Constant>(I.getOperand(1)),
276 cast<Constant>(Op->getOperand(1)));
277 I.setOperand(0, Op->getOperand(0));
278 I.setOperand(1, Folded);
280 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
281 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
282 isOnlyUse(Op) && isOnlyUse(Op1)) {
283 Constant *C1 = cast<Constant>(Op->getOperand(1));
284 Constant *C2 = cast<Constant>(Op1->getOperand(1));
286 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
287 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
288 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
291 WorkList.push_back(New);
292 I.setOperand(0, New);
293 I.setOperand(1, Folded);
300 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
301 // if the LHS is a constant zero (which is the 'negate' form).
303 static inline Value *dyn_castNegVal(Value *V) {
304 if (BinaryOperator::isNeg(V))
305 return BinaryOperator::getNegArgument(cast<BinaryOperator>(V));
307 // Constants can be considered to be negated values if they can be folded...
308 if (Constant *C = dyn_cast<Constant>(V))
309 return ConstantExpr::getNeg(C);
313 static inline Value *dyn_castNotVal(Value *V) {
314 if (BinaryOperator::isNot(V))
315 return BinaryOperator::getNotArgument(cast<BinaryOperator>(V));
317 // Constants can be considered to be not'ed values...
318 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
319 return ConstantExpr::getNot(C);
323 // dyn_castFoldableMul - If this value is a multiply that can be folded into
324 // other computations (because it has a constant operand), return the
325 // non-constant operand of the multiply, and set CST to point to the multiplier.
326 // Otherwise, return null.
328 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
329 if (V->hasOneUse() && V->getType()->isInteger())
330 if (Instruction *I = dyn_cast<Instruction>(V)) {
331 if (I->getOpcode() == Instruction::Mul)
332 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
333 return I->getOperand(0);
334 if (I->getOpcode() == Instruction::Shl)
335 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
336 // The multiplier is really 1 << CST.
337 Constant *One = ConstantInt::get(V->getType(), 1);
338 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
339 return I->getOperand(0);
345 // Log2 - Calculate the log base 2 for the specified value if it is exactly a
347 static unsigned Log2(uint64_t Val) {
348 assert(Val > 1 && "Values 0 and 1 should be handled elsewhere!");
351 if (Val & 1) return 0; // Multiple bits set?
358 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
359 static ConstantInt *AddOne(ConstantInt *C) {
360 return cast<ConstantInt>(ConstantExpr::getAdd(C,
361 ConstantInt::get(C->getType(), 1)));
363 static ConstantInt *SubOne(ConstantInt *C) {
364 return cast<ConstantInt>(ConstantExpr::getSub(C,
365 ConstantInt::get(C->getType(), 1)));
368 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
369 // true when both operands are equal...
371 static bool isTrueWhenEqual(Instruction &I) {
372 return I.getOpcode() == Instruction::SetEQ ||
373 I.getOpcode() == Instruction::SetGE ||
374 I.getOpcode() == Instruction::SetLE;
377 /// AssociativeOpt - Perform an optimization on an associative operator. This
378 /// function is designed to check a chain of associative operators for a
379 /// potential to apply a certain optimization. Since the optimization may be
380 /// applicable if the expression was reassociated, this checks the chain, then
381 /// reassociates the expression as necessary to expose the optimization
382 /// opportunity. This makes use of a special Functor, which must define
383 /// 'shouldApply' and 'apply' methods.
385 template<typename Functor>
386 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
387 unsigned Opcode = Root.getOpcode();
388 Value *LHS = Root.getOperand(0);
390 // Quick check, see if the immediate LHS matches...
391 if (F.shouldApply(LHS))
392 return F.apply(Root);
394 // Otherwise, if the LHS is not of the same opcode as the root, return.
395 Instruction *LHSI = dyn_cast<Instruction>(LHS);
396 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
397 // Should we apply this transform to the RHS?
398 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
400 // If not to the RHS, check to see if we should apply to the LHS...
401 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
402 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
406 // If the functor wants to apply the optimization to the RHS of LHSI,
407 // reassociate the expression from ((? op A) op B) to (? op (A op B))
409 BasicBlock *BB = Root.getParent();
411 // Now all of the instructions are in the current basic block, go ahead
412 // and perform the reassociation.
413 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
415 // First move the selected RHS to the LHS of the root...
416 Root.setOperand(0, LHSI->getOperand(1));
418 // Make what used to be the LHS of the root be the user of the root...
419 Value *ExtraOperand = TmpLHSI->getOperand(1);
420 if (&Root == TmpLHSI) {
421 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
424 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
425 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
426 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
427 BasicBlock::iterator ARI = &Root; ++ARI;
428 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
431 // Now propagate the ExtraOperand down the chain of instructions until we
433 while (TmpLHSI != LHSI) {
434 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
435 // Move the instruction to immediately before the chain we are
436 // constructing to avoid breaking dominance properties.
437 NextLHSI->getParent()->getInstList().remove(NextLHSI);
438 BB->getInstList().insert(ARI, NextLHSI);
441 Value *NextOp = NextLHSI->getOperand(1);
442 NextLHSI->setOperand(1, ExtraOperand);
444 ExtraOperand = NextOp;
447 // Now that the instructions are reassociated, have the functor perform
448 // the transformation...
449 return F.apply(Root);
452 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
458 // AddRHS - Implements: X + X --> X << 1
461 AddRHS(Value *rhs) : RHS(rhs) {}
462 bool shouldApply(Value *LHS) const { return LHS == RHS; }
463 Instruction *apply(BinaryOperator &Add) const {
464 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
465 ConstantInt::get(Type::UByteTy, 1));
469 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
471 struct AddMaskingAnd {
473 AddMaskingAnd(Constant *c) : C2(c) {}
474 bool shouldApply(Value *LHS) const {
476 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
477 ConstantExpr::getAnd(C1, C2)->isNullValue();
479 Instruction *apply(BinaryOperator &Add) const {
480 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
484 static Value *FoldOperationIntoSelectOperand(Instruction &BI, Value *SO,
486 // Figure out if the constant is the left or the right argument.
487 bool ConstIsRHS = isa<Constant>(BI.getOperand(1));
488 Constant *ConstOperand = cast<Constant>(BI.getOperand(ConstIsRHS));
490 if (Constant *SOC = dyn_cast<Constant>(SO)) {
492 return ConstantExpr::get(BI.getOpcode(), SOC, ConstOperand);
493 return ConstantExpr::get(BI.getOpcode(), ConstOperand, SOC);
496 Value *Op0 = SO, *Op1 = ConstOperand;
500 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&BI))
501 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1);
502 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&BI))
503 New = new ShiftInst(SI->getOpcode(), Op0, Op1);
505 assert(0 && "Unknown binary instruction type!");
508 return IC->InsertNewInstBefore(New, BI);
512 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
513 /// node as operand #0, see if we can fold the instruction into the PHI (which
514 /// is only possible if all operands to the PHI are constants).
515 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
516 PHINode *PN = cast<PHINode>(I.getOperand(0));
517 unsigned NumPHIValues = PN->getNumIncomingValues();
518 if (!PN->hasOneUse() || NumPHIValues == 0 ||
519 !isa<Constant>(PN->getIncomingValue(0))) return 0;
521 // Check to see if all of the operands of the PHI are constants. If not, we
522 // cannot do the transformation.
523 for (unsigned i = 1; i != NumPHIValues; ++i)
524 if (!isa<Constant>(PN->getIncomingValue(i)))
527 // Okay, we can do the transformation: create the new PHI node.
528 PHINode *NewPN = new PHINode(I.getType(), I.getName());
530 NewPN->op_reserve(PN->getNumOperands());
531 InsertNewInstBefore(NewPN, *PN);
533 // Next, add all of the operands to the PHI.
534 if (I.getNumOperands() == 2) {
535 Constant *C = cast<Constant>(I.getOperand(1));
536 for (unsigned i = 0; i != NumPHIValues; ++i) {
537 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
538 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
539 PN->getIncomingBlock(i));
542 assert(isa<CastInst>(I) && "Unary op should be a cast!");
543 const Type *RetTy = I.getType();
544 for (unsigned i = 0; i != NumPHIValues; ++i) {
545 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
546 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
547 PN->getIncomingBlock(i));
550 return ReplaceInstUsesWith(I, NewPN);
553 // FoldBinOpIntoSelect - Given an instruction with a select as one operand and a
554 // constant as the other operand, try to fold the binary operator into the
556 static Instruction *FoldBinOpIntoSelect(Instruction &BI, SelectInst *SI,
558 // Don't modify shared select instructions
559 if (!SI->hasOneUse()) return 0;
560 Value *TV = SI->getOperand(1);
561 Value *FV = SI->getOperand(2);
563 if (isa<Constant>(TV) || isa<Constant>(FV)) {
564 Value *SelectTrueVal = FoldOperationIntoSelectOperand(BI, TV, IC);
565 Value *SelectFalseVal = FoldOperationIntoSelectOperand(BI, FV, IC);
567 return new SelectInst(SI->getCondition(), SelectTrueVal,
573 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
574 bool Changed = SimplifyCommutative(I);
575 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
577 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
578 // X + undef -> undef
579 if (isa<UndefValue>(RHS))
580 return ReplaceInstUsesWith(I, RHS);
583 if (!I.getType()->isFloatingPoint() && // -0 + +0 = +0, so it's not a noop
585 return ReplaceInstUsesWith(I, LHS);
587 // X + (signbit) --> X ^ signbit
588 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
589 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
590 uint64_t Val = CI->getRawValue() & (1ULL << NumBits)-1;
591 if (Val == (1ULL << (NumBits-1)))
592 return BinaryOperator::createXor(LHS, RHS);
595 if (isa<PHINode>(LHS))
596 if (Instruction *NV = FoldOpIntoPhi(I))
601 if (I.getType()->isInteger()) {
602 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
606 if (Value *V = dyn_castNegVal(LHS))
607 return BinaryOperator::createSub(RHS, V);
610 if (!isa<Constant>(RHS))
611 if (Value *V = dyn_castNegVal(RHS))
612 return BinaryOperator::createSub(LHS, V);
615 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
616 if (X == RHS) // X*C + X --> X * (C+1)
617 return BinaryOperator::createMul(RHS, AddOne(C2));
619 // X*C1 + X*C2 --> X * (C1+C2)
621 if (X == dyn_castFoldableMul(RHS, C1))
622 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
625 // X + X*C --> X * (C+1)
626 if (dyn_castFoldableMul(RHS, C2) == LHS)
627 return BinaryOperator::createMul(LHS, AddOne(C2));
630 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
631 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
632 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
634 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
636 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
637 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
638 return BinaryOperator::createSub(C, X);
641 // (X & FF00) + xx00 -> (X+xx00) & FF00
642 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
643 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
645 // See if all bits from the first bit set in the Add RHS up are included
646 // in the mask. First, get the rightmost bit.
647 uint64_t AddRHSV = CRHS->getRawValue();
649 // Form a mask of all bits from the lowest bit added through the top.
650 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
651 AddRHSHighBits &= (1ULL << C2->getType()->getPrimitiveSize()*8)-1;
653 // See if the and mask includes all of these bits.
654 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
656 if (AddRHSHighBits == AddRHSHighBitsAnd) {
657 // Okay, the xform is safe. Insert the new add pronto.
658 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
660 return BinaryOperator::createAnd(NewAdd, C2);
666 // Try to fold constant add into select arguments.
667 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
668 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
672 return Changed ? &I : 0;
675 // isSignBit - Return true if the value represented by the constant only has the
676 // highest order bit set.
677 static bool isSignBit(ConstantInt *CI) {
678 unsigned NumBits = CI->getType()->getPrimitiveSize()*8;
679 return (CI->getRawValue() & ~(-1LL << NumBits)) == (1ULL << (NumBits-1));
682 static unsigned getTypeSizeInBits(const Type *Ty) {
683 return Ty == Type::BoolTy ? 1 : Ty->getPrimitiveSize()*8;
686 /// RemoveNoopCast - Strip off nonconverting casts from the value.
688 static Value *RemoveNoopCast(Value *V) {
689 if (CastInst *CI = dyn_cast<CastInst>(V)) {
690 const Type *CTy = CI->getType();
691 const Type *OpTy = CI->getOperand(0)->getType();
692 if (CTy->isInteger() && OpTy->isInteger()) {
693 if (CTy->getPrimitiveSize() == OpTy->getPrimitiveSize())
694 return RemoveNoopCast(CI->getOperand(0));
695 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
696 return RemoveNoopCast(CI->getOperand(0));
701 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
702 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
704 if (Op0 == Op1) // sub X, X -> 0
705 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
707 // If this is a 'B = x-(-A)', change to B = x+A...
708 if (Value *V = dyn_castNegVal(Op1))
709 return BinaryOperator::createAdd(Op0, V);
711 if (isa<UndefValue>(Op0))
712 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
713 if (isa<UndefValue>(Op1))
714 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
716 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
717 // Replace (-1 - A) with (~A)...
718 if (C->isAllOnesValue())
719 return BinaryOperator::createNot(Op1);
721 // C - ~X == X + (1+C)
723 if (match(Op1, m_Not(m_Value(X))))
724 return BinaryOperator::createAdd(X,
725 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
726 // -((uint)X >> 31) -> ((int)X >> 31)
727 // -((int)X >> 31) -> ((uint)X >> 31)
728 if (C->isNullValue()) {
729 Value *NoopCastedRHS = RemoveNoopCast(Op1);
730 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
731 if (SI->getOpcode() == Instruction::Shr)
732 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
734 if (SI->getType()->isSigned())
735 NewTy = SI->getType()->getUnsignedVersion();
737 NewTy = SI->getType()->getSignedVersion();
738 // Check to see if we are shifting out everything but the sign bit.
739 if (CU->getValue() == SI->getType()->getPrimitiveSize()*8-1) {
740 // Ok, the transformation is safe. Insert a cast of the incoming
741 // value, then the new shift, then the new cast.
742 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
743 SI->getOperand(0)->getName());
744 Value *InV = InsertNewInstBefore(FirstCast, I);
745 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
747 if (NewShift->getType() == I.getType())
750 InV = InsertNewInstBefore(NewShift, I);
751 return new CastInst(NewShift, I.getType());
757 // Try to fold constant sub into select arguments.
758 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
759 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
762 if (isa<PHINode>(Op0))
763 if (Instruction *NV = FoldOpIntoPhi(I))
767 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
768 if (Op1I->hasOneUse()) {
769 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
770 // is not used by anyone else...
772 if (Op1I->getOpcode() == Instruction::Sub &&
773 !Op1I->getType()->isFloatingPoint()) {
774 // Swap the two operands of the subexpr...
775 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
776 Op1I->setOperand(0, IIOp1);
777 Op1I->setOperand(1, IIOp0);
779 // Create the new top level add instruction...
780 return BinaryOperator::createAdd(Op0, Op1);
783 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
785 if (Op1I->getOpcode() == Instruction::And &&
786 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
787 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
790 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
791 return BinaryOperator::createAnd(Op0, NewNot);
794 // -(X sdiv C) -> (X sdiv -C)
795 if (Op1I->getOpcode() == Instruction::Div)
796 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
797 if (CSI->getValue() == 0)
798 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
799 return BinaryOperator::createDiv(Op1I->getOperand(0),
800 ConstantExpr::getNeg(DivRHS));
802 // X - X*C --> X * (1-C)
804 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
806 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
807 return BinaryOperator::createMul(Op0, CP1);
813 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
814 if (X == Op1) { // X*C - X --> X * (C-1)
815 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
816 return BinaryOperator::createMul(Op1, CP1);
819 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
820 if (X == dyn_castFoldableMul(Op1, C2))
821 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
826 /// isSignBitCheck - Given an exploded setcc instruction, return true if it is
827 /// really just returns true if the most significant (sign) bit is set.
828 static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
829 if (RHS->getType()->isSigned()) {
830 // True if source is LHS < 0 or LHS <= -1
831 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
832 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
834 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
835 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
836 // the size of the integer type.
837 if (Opcode == Instruction::SetGE)
838 return RHSC->getValue() == 1ULL<<(RHS->getType()->getPrimitiveSize()*8-1);
839 if (Opcode == Instruction::SetGT)
840 return RHSC->getValue() ==
841 (1ULL << (RHS->getType()->getPrimitiveSize()*8-1))-1;
846 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
847 bool Changed = SimplifyCommutative(I);
848 Value *Op0 = I.getOperand(0);
850 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
851 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
853 // Simplify mul instructions with a constant RHS...
854 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
855 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
857 // ((X << C1)*C2) == (X * (C2 << C1))
858 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
859 if (SI->getOpcode() == Instruction::Shl)
860 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
861 return BinaryOperator::createMul(SI->getOperand(0),
862 ConstantExpr::getShl(CI, ShOp));
864 if (CI->isNullValue())
865 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
866 if (CI->equalsInt(1)) // X * 1 == X
867 return ReplaceInstUsesWith(I, Op0);
868 if (CI->isAllOnesValue()) // X * -1 == 0 - X
869 return BinaryOperator::createNeg(Op0, I.getName());
871 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
872 if (uint64_t C = Log2(Val)) // Replace X*(2^C) with X << C
873 return new ShiftInst(Instruction::Shl, Op0,
874 ConstantUInt::get(Type::UByteTy, C));
875 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
876 if (Op1F->isNullValue())
877 return ReplaceInstUsesWith(I, Op1);
879 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
880 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
881 if (Op1F->getValue() == 1.0)
882 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
885 // Try to fold constant mul into select arguments.
886 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
887 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
890 if (isa<PHINode>(Op0))
891 if (Instruction *NV = FoldOpIntoPhi(I))
895 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
896 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
897 return BinaryOperator::createMul(Op0v, Op1v);
899 // If one of the operands of the multiply is a cast from a boolean value, then
900 // we know the bool is either zero or one, so this is a 'masking' multiply.
901 // See if we can simplify things based on how the boolean was originally
903 CastInst *BoolCast = 0;
904 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
905 if (CI->getOperand(0)->getType() == Type::BoolTy)
908 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
909 if (CI->getOperand(0)->getType() == Type::BoolTy)
912 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
913 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
914 const Type *SCOpTy = SCIOp0->getType();
916 // If the setcc is true iff the sign bit of X is set, then convert this
917 // multiply into a shift/and combination.
918 if (isa<ConstantInt>(SCIOp1) &&
919 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
920 // Shift the X value right to turn it into "all signbits".
921 Constant *Amt = ConstantUInt::get(Type::UByteTy,
922 SCOpTy->getPrimitiveSize()*8-1);
923 if (SCIOp0->getType()->isUnsigned()) {
924 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
925 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
926 SCIOp0->getName()), I);
930 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
931 BoolCast->getOperand(0)->getName()+
934 // If the multiply type is not the same as the source type, sign extend
935 // or truncate to the multiply type.
936 if (I.getType() != V->getType())
937 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
939 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
940 return BinaryOperator::createAnd(V, OtherOp);
945 return Changed ? &I : 0;
948 Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
949 if (isa<UndefValue>(I.getOperand(0))) // undef / X -> 0
950 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
951 if (isa<UndefValue>(I.getOperand(1)))
952 return ReplaceInstUsesWith(I, I.getOperand(1)); // X / undef -> undef
954 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
956 if (RHS->equalsInt(1))
957 return ReplaceInstUsesWith(I, I.getOperand(0));
960 if (RHS->isAllOnesValue())
961 return BinaryOperator::createNeg(I.getOperand(0));
963 if (Instruction *LHS = dyn_cast<Instruction>(I.getOperand(0)))
964 if (LHS->getOpcode() == Instruction::Div)
965 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
966 // (X / C1) / C2 -> X / (C1*C2)
967 return BinaryOperator::createDiv(LHS->getOperand(0),
968 ConstantExpr::getMul(RHS, LHSRHS));
971 // Check to see if this is an unsigned division with an exact power of 2,
972 // if so, convert to a right shift.
973 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
974 if (uint64_t Val = C->getValue()) // Don't break X / 0
975 if (uint64_t C = Log2(Val))
976 return new ShiftInst(Instruction::Shr, I.getOperand(0),
977 ConstantUInt::get(Type::UByteTy, C));
980 if (RHS->getType()->isSigned())
981 if (Value *LHSNeg = dyn_castNegVal(I.getOperand(0)))
982 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
984 if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
985 if (Instruction *NV = FoldOpIntoPhi(I))
989 // 0 / X == 0, we don't need to preserve faults!
990 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
991 if (LHS->equalsInt(0))
992 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
998 Instruction *InstCombiner::visitRem(BinaryOperator &I) {
999 if (I.getType()->isSigned())
1000 if (Value *RHSNeg = dyn_castNegVal(I.getOperand(1)))
1001 if (!isa<ConstantSInt>(RHSNeg) ||
1002 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
1004 AddUsesToWorkList(I);
1005 I.setOperand(1, RHSNeg);
1009 if (isa<UndefValue>(I.getOperand(0))) // undef % X -> 0
1010 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1011 if (isa<UndefValue>(I.getOperand(1)))
1012 return ReplaceInstUsesWith(I, I.getOperand(1)); // X % undef -> undef
1014 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I.getOperand(1))) {
1015 if (RHS->equalsInt(1)) // X % 1 == 0
1016 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1018 // Check to see if this is an unsigned remainder with an exact power of 2,
1019 // if so, convert to a bitwise and.
1020 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1021 if (uint64_t Val = C->getValue()) // Don't break X % 0 (divide by zero)
1022 if (!(Val & (Val-1))) // Power of 2
1023 return BinaryOperator::createAnd(I.getOperand(0),
1024 ConstantUInt::get(I.getType(), Val-1));
1025 if (isa<PHINode>(I.getOperand(0)) && !RHS->isNullValue())
1026 if (Instruction *NV = FoldOpIntoPhi(I))
1030 // 0 % X == 0, we don't need to preserve faults!
1031 if (ConstantInt *LHS = dyn_cast<ConstantInt>(I.getOperand(0)))
1032 if (LHS->equalsInt(0))
1033 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1038 // isMaxValueMinusOne - return true if this is Max-1
1039 static bool isMaxValueMinusOne(const ConstantInt *C) {
1040 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C)) {
1041 // Calculate -1 casted to the right type...
1042 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1043 uint64_t Val = ~0ULL; // All ones
1044 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1045 return CU->getValue() == Val-1;
1048 const ConstantSInt *CS = cast<ConstantSInt>(C);
1050 // Calculate 0111111111..11111
1051 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1052 int64_t Val = INT64_MAX; // All ones
1053 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1054 return CS->getValue() == Val-1;
1057 // isMinValuePlusOne - return true if this is Min+1
1058 static bool isMinValuePlusOne(const ConstantInt *C) {
1059 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1060 return CU->getValue() == 1;
1062 const ConstantSInt *CS = cast<ConstantSInt>(C);
1064 // Calculate 1111111111000000000000
1065 unsigned TypeBits = C->getType()->getPrimitiveSize()*8;
1066 int64_t Val = -1; // All ones
1067 Val <<= TypeBits-1; // Shift over to the right spot
1068 return CS->getValue() == Val+1;
1071 // isOneBitSet - Return true if there is exactly one bit set in the specified
1073 static bool isOneBitSet(const ConstantInt *CI) {
1074 uint64_t V = CI->getRawValue();
1075 return V && (V & (V-1)) == 0;
1078 #if 0 // Currently unused
1079 // isLowOnes - Return true if the constant is of the form 0+1+.
1080 static bool isLowOnes(const ConstantInt *CI) {
1081 uint64_t V = CI->getRawValue();
1083 // There won't be bits set in parts that the type doesn't contain.
1084 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1086 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1087 return U && V && (U & V) == 0;
1091 // isHighOnes - Return true if the constant is of the form 1+0+.
1092 // This is the same as lowones(~X).
1093 static bool isHighOnes(const ConstantInt *CI) {
1094 uint64_t V = ~CI->getRawValue();
1096 // There won't be bits set in parts that the type doesn't contain.
1097 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
1099 uint64_t U = V+1; // If it is low ones, this should be a power of two.
1100 return U && V && (U & V) == 0;
1104 /// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
1105 /// are carefully arranged to allow folding of expressions such as:
1107 /// (A < B) | (A > B) --> (A != B)
1109 /// Bit value '4' represents that the comparison is true if A > B, bit value '2'
1110 /// represents that the comparison is true if A == B, and bit value '1' is true
1113 static unsigned getSetCondCode(const SetCondInst *SCI) {
1114 switch (SCI->getOpcode()) {
1116 case Instruction::SetGT: return 1;
1117 case Instruction::SetEQ: return 2;
1118 case Instruction::SetGE: return 3;
1119 case Instruction::SetLT: return 4;
1120 case Instruction::SetNE: return 5;
1121 case Instruction::SetLE: return 6;
1124 assert(0 && "Invalid SetCC opcode!");
1129 /// getSetCCValue - This is the complement of getSetCondCode, which turns an
1130 /// opcode and two operands into either a constant true or false, or a brand new
1131 /// SetCC instruction.
1132 static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
1134 case 0: return ConstantBool::False;
1135 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
1136 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
1137 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
1138 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
1139 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
1140 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
1141 case 7: return ConstantBool::True;
1142 default: assert(0 && "Illegal SetCCCode!"); return 0;
1146 // FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1147 struct FoldSetCCLogical {
1150 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
1151 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
1152 bool shouldApply(Value *V) const {
1153 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
1154 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
1155 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
1158 Instruction *apply(BinaryOperator &Log) const {
1159 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
1160 if (SCI->getOperand(0) != LHS) {
1161 assert(SCI->getOperand(1) == LHS);
1162 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
1165 unsigned LHSCode = getSetCondCode(SCI);
1166 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
1168 switch (Log.getOpcode()) {
1169 case Instruction::And: Code = LHSCode & RHSCode; break;
1170 case Instruction::Or: Code = LHSCode | RHSCode; break;
1171 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
1172 default: assert(0 && "Illegal logical opcode!"); return 0;
1175 Value *RV = getSetCCValue(Code, LHS, RHS);
1176 if (Instruction *I = dyn_cast<Instruction>(RV))
1178 // Otherwise, it's a constant boolean value...
1179 return IC.ReplaceInstUsesWith(Log, RV);
1184 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
1185 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
1186 // guaranteed to be either a shift instruction or a binary operator.
1187 Instruction *InstCombiner::OptAndOp(Instruction *Op,
1188 ConstantIntegral *OpRHS,
1189 ConstantIntegral *AndRHS,
1190 BinaryOperator &TheAnd) {
1191 Value *X = Op->getOperand(0);
1192 Constant *Together = 0;
1193 if (!isa<ShiftInst>(Op))
1194 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
1196 switch (Op->getOpcode()) {
1197 case Instruction::Xor:
1198 if (Together->isNullValue()) {
1199 // (X ^ C1) & C2 --> (X & C2) iff (C1&C2) == 0
1200 return BinaryOperator::createAnd(X, AndRHS);
1201 } else if (Op->hasOneUse()) {
1202 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
1203 std::string OpName = Op->getName(); Op->setName("");
1204 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
1205 InsertNewInstBefore(And, TheAnd);
1206 return BinaryOperator::createXor(And, Together);
1209 case Instruction::Or:
1210 // (X | C1) & C2 --> X & C2 iff C1 & C1 == 0
1211 if (Together->isNullValue())
1212 return BinaryOperator::createAnd(X, AndRHS);
1214 if (Together == AndRHS) // (X | C) & C --> C
1215 return ReplaceInstUsesWith(TheAnd, AndRHS);
1217 if (Op->hasOneUse() && Together != OpRHS) {
1218 // (X | C1) & C2 --> (X | (C1&C2)) & C2
1219 std::string Op0Name = Op->getName(); Op->setName("");
1220 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
1221 InsertNewInstBefore(Or, TheAnd);
1222 return BinaryOperator::createAnd(Or, AndRHS);
1226 case Instruction::Add:
1227 if (Op->hasOneUse()) {
1228 // Adding a one to a single bit bit-field should be turned into an XOR
1229 // of the bit. First thing to check is to see if this AND is with a
1230 // single bit constant.
1231 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
1233 // Clear bits that are not part of the constant.
1234 AndRHSV &= (1ULL << AndRHS->getType()->getPrimitiveSize()*8)-1;
1236 // If there is only one bit set...
1237 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
1238 // Ok, at this point, we know that we are masking the result of the
1239 // ADD down to exactly one bit. If the constant we are adding has
1240 // no bits set below this bit, then we can eliminate the ADD.
1241 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
1243 // Check to see if any bits below the one bit set in AndRHSV are set.
1244 if ((AddRHS & (AndRHSV-1)) == 0) {
1245 // If not, the only thing that can effect the output of the AND is
1246 // the bit specified by AndRHSV. If that bit is set, the effect of
1247 // the XOR is to toggle the bit. If it is clear, then the ADD has
1249 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
1250 TheAnd.setOperand(0, X);
1253 std::string Name = Op->getName(); Op->setName("");
1254 // Pull the XOR out of the AND.
1255 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
1256 InsertNewInstBefore(NewAnd, TheAnd);
1257 return BinaryOperator::createXor(NewAnd, AndRHS);
1264 case Instruction::Shl: {
1265 // We know that the AND will not produce any of the bits shifted in, so if
1266 // the anded constant includes them, clear them now!
1268 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1269 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
1270 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
1272 if (CI == ShlMask) { // Masking out bits that the shift already masks
1273 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
1274 } else if (CI != AndRHS) { // Reducing bits set in and.
1275 TheAnd.setOperand(1, CI);
1280 case Instruction::Shr:
1281 // We know that the AND will not produce any of the bits shifted in, so if
1282 // the anded constant includes them, clear them now! This only applies to
1283 // unsigned shifts, because a signed shr may bring in set bits!
1285 if (AndRHS->getType()->isUnsigned()) {
1286 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1287 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
1288 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1290 if (CI == ShrMask) { // Masking out bits that the shift already masks.
1291 return ReplaceInstUsesWith(TheAnd, Op);
1292 } else if (CI != AndRHS) {
1293 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
1296 } else { // Signed shr.
1297 // See if this is shifting in some sign extension, then masking it out
1299 if (Op->hasOneUse()) {
1300 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
1301 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
1302 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
1303 if (CI == AndRHS) { // Masking out bits shifted in.
1304 // Make the argument unsigned.
1305 Value *ShVal = Op->getOperand(0);
1306 ShVal = InsertCastBefore(ShVal,
1307 ShVal->getType()->getUnsignedVersion(),
1309 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
1310 OpRHS, Op->getName()),
1312 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
1313 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
1316 return new CastInst(ShVal, Op->getType());
1326 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
1327 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
1328 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
1329 /// insert new instructions.
1330 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
1331 bool Inside, Instruction &IB) {
1332 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
1333 "Lo is not <= Hi in range emission code!");
1335 if (Lo == Hi) // Trivially false.
1336 return new SetCondInst(Instruction::SetNE, V, V);
1337 if (cast<ConstantIntegral>(Lo)->isMinValue())
1338 return new SetCondInst(Instruction::SetLT, V, Hi);
1340 Constant *AddCST = ConstantExpr::getNeg(Lo);
1341 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
1342 InsertNewInstBefore(Add, IB);
1343 // Convert to unsigned for the comparison.
1344 const Type *UnsType = Add->getType()->getUnsignedVersion();
1345 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1346 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1347 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1348 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1351 if (Lo == Hi) // Trivially true.
1352 return new SetCondInst(Instruction::SetEQ, V, V);
1354 Hi = SubOne(cast<ConstantInt>(Hi));
1355 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
1356 return new SetCondInst(Instruction::SetGT, V, Hi);
1358 // Emit X-Lo > Hi-Lo-1
1359 Constant *AddCST = ConstantExpr::getNeg(Lo);
1360 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
1361 InsertNewInstBefore(Add, IB);
1362 // Convert to unsigned for the comparison.
1363 const Type *UnsType = Add->getType()->getUnsignedVersion();
1364 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
1365 AddCST = ConstantExpr::getAdd(AddCST, Hi);
1366 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1367 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1371 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
1372 bool Changed = SimplifyCommutative(I);
1373 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1375 if (isa<UndefValue>(Op1)) // X & undef -> 0
1376 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1378 // and X, X = X and X, 0 == 0
1379 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1380 return ReplaceInstUsesWith(I, Op1);
1383 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
1384 if (RHS->isAllOnesValue())
1385 return ReplaceInstUsesWith(I, Op0);
1387 // Optimize a variety of ((val OP C1) & C2) combinations...
1388 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
1389 Instruction *Op0I = cast<Instruction>(Op0);
1390 Value *X = Op0I->getOperand(0);
1391 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1392 if (Instruction *Res = OptAndOp(Op0I, Op0CI, RHS, I))
1396 // Try to fold constant and into select arguments.
1397 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1398 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1400 if (isa<PHINode>(Op0))
1401 if (Instruction *NV = FoldOpIntoPhi(I))
1405 Value *Op0NotVal = dyn_castNotVal(Op0);
1406 Value *Op1NotVal = dyn_castNotVal(Op1);
1408 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
1409 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1411 // (~A & ~B) == (~(A | B)) - De Morgan's Law
1412 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1413 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
1414 I.getName()+".demorgan");
1415 InsertNewInstBefore(Or, I);
1416 return BinaryOperator::createNot(Or);
1419 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
1420 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
1421 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1424 Value *LHSVal, *RHSVal;
1425 ConstantInt *LHSCst, *RHSCst;
1426 Instruction::BinaryOps LHSCC, RHSCC;
1427 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1428 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1429 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
1430 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1431 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1432 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1433 // Ensure that the larger constant is on the RHS.
1434 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1435 SetCondInst *LHS = cast<SetCondInst>(Op0);
1436 if (cast<ConstantBool>(Cmp)->getValue()) {
1437 std::swap(LHS, RHS);
1438 std::swap(LHSCst, RHSCst);
1439 std::swap(LHSCC, RHSCC);
1442 // At this point, we know we have have two setcc instructions
1443 // comparing a value against two constants and and'ing the result
1444 // together. Because of the above check, we know that we only have
1445 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1446 // FoldSetCCLogical check above), that the two constants are not
1448 assert(LHSCst != RHSCst && "Compares not folded above?");
1451 default: assert(0 && "Unknown integer condition code!");
1452 case Instruction::SetEQ:
1454 default: assert(0 && "Unknown integer condition code!");
1455 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
1456 case Instruction::SetGT: // (X == 13 & X > 15) -> false
1457 return ReplaceInstUsesWith(I, ConstantBool::False);
1458 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
1459 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
1460 return ReplaceInstUsesWith(I, LHS);
1462 case Instruction::SetNE:
1464 default: assert(0 && "Unknown integer condition code!");
1465 case Instruction::SetLT:
1466 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
1467 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
1468 break; // (X != 13 & X < 15) -> no change
1469 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
1470 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
1471 return ReplaceInstUsesWith(I, RHS);
1472 case Instruction::SetNE:
1473 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
1474 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1475 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1476 LHSVal->getName()+".off");
1477 InsertNewInstBefore(Add, I);
1478 const Type *UnsType = Add->getType()->getUnsignedVersion();
1479 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1480 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
1481 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1482 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
1484 break; // (X != 13 & X != 15) -> no change
1487 case Instruction::SetLT:
1489 default: assert(0 && "Unknown integer condition code!");
1490 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
1491 case Instruction::SetGT: // (X < 13 & X > 15) -> false
1492 return ReplaceInstUsesWith(I, ConstantBool::False);
1493 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
1494 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
1495 return ReplaceInstUsesWith(I, LHS);
1497 case Instruction::SetGT:
1499 default: assert(0 && "Unknown integer condition code!");
1500 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
1501 return ReplaceInstUsesWith(I, LHS);
1502 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
1503 return ReplaceInstUsesWith(I, RHS);
1504 case Instruction::SetNE:
1505 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
1506 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
1507 break; // (X > 13 & X != 15) -> no change
1508 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
1509 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
1515 return Changed ? &I : 0;
1518 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
1519 bool Changed = SimplifyCommutative(I);
1520 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1522 if (isa<UndefValue>(Op1))
1523 return ReplaceInstUsesWith(I, // X | undef -> -1
1524 ConstantIntegral::getAllOnesValue(I.getType()));
1526 // or X, X = X or X, 0 == X
1527 if (Op0 == Op1 || Op1 == Constant::getNullValue(I.getType()))
1528 return ReplaceInstUsesWith(I, Op0);
1531 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
1532 if (RHS->isAllOnesValue())
1533 return ReplaceInstUsesWith(I, Op1);
1535 ConstantInt *C1; Value *X;
1536 // (X & C1) | C2 --> (X | C2) & (C1|C2)
1537 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1538 std::string Op0Name = Op0->getName(); Op0->setName("");
1539 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1540 InsertNewInstBefore(Or, I);
1541 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
1544 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
1545 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
1546 std::string Op0Name = Op0->getName(); Op0->setName("");
1547 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
1548 InsertNewInstBefore(Or, I);
1549 return BinaryOperator::createXor(Or,
1550 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
1553 // Try to fold constant and into select arguments.
1554 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1555 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1557 if (isa<PHINode>(Op0))
1558 if (Instruction *NV = FoldOpIntoPhi(I))
1562 // (A & C1)|(A & C2) == A & (C1|C2)
1563 Value *A, *B; ConstantInt *C1, *C2;
1564 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1565 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) && A == B)
1566 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
1568 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
1569 if (A == Op1) // ~A | A == -1
1570 return ReplaceInstUsesWith(I,
1571 ConstantIntegral::getAllOnesValue(I.getType()));
1576 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
1578 return ReplaceInstUsesWith(I,
1579 ConstantIntegral::getAllOnesValue(I.getType()));
1581 // (~A | ~B) == (~(A & B)) - De Morgan's Law
1582 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
1583 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
1584 I.getName()+".demorgan"), I);
1585 return BinaryOperator::createNot(And);
1589 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
1590 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
1591 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1594 Value *LHSVal, *RHSVal;
1595 ConstantInt *LHSCst, *RHSCst;
1596 Instruction::BinaryOps LHSCC, RHSCC;
1597 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
1598 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
1599 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
1600 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
1601 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
1602 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
1603 // Ensure that the larger constant is on the RHS.
1604 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
1605 SetCondInst *LHS = cast<SetCondInst>(Op0);
1606 if (cast<ConstantBool>(Cmp)->getValue()) {
1607 std::swap(LHS, RHS);
1608 std::swap(LHSCst, RHSCst);
1609 std::swap(LHSCC, RHSCC);
1612 // At this point, we know we have have two setcc instructions
1613 // comparing a value against two constants and or'ing the result
1614 // together. Because of the above check, we know that we only have
1615 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
1616 // FoldSetCCLogical check above), that the two constants are not
1618 assert(LHSCst != RHSCst && "Compares not folded above?");
1621 default: assert(0 && "Unknown integer condition code!");
1622 case Instruction::SetEQ:
1624 default: assert(0 && "Unknown integer condition code!");
1625 case Instruction::SetEQ:
1626 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
1627 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
1628 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
1629 LHSVal->getName()+".off");
1630 InsertNewInstBefore(Add, I);
1631 const Type *UnsType = Add->getType()->getUnsignedVersion();
1632 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
1633 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
1634 AddCST = ConstantExpr::getCast(AddCST, UnsType);
1635 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
1637 break; // (X == 13 | X == 15) -> no change
1639 case Instruction::SetGT:
1640 if (LHSCst == SubOne(RHSCst)) // (X == 13 | X > 14) -> X > 13
1641 return new SetCondInst(Instruction::SetGT, LHSVal, LHSCst);
1642 break; // (X == 13 | X > 15) -> no change
1643 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
1644 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
1645 return ReplaceInstUsesWith(I, RHS);
1648 case Instruction::SetNE:
1650 default: assert(0 && "Unknown integer condition code!");
1651 case Instruction::SetLT: // (X != 13 | X < 15) -> X < 15
1652 return ReplaceInstUsesWith(I, RHS);
1653 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
1654 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
1655 return ReplaceInstUsesWith(I, LHS);
1656 case Instruction::SetNE: // (X != 13 | X != 15) -> true
1657 return ReplaceInstUsesWith(I, ConstantBool::True);
1660 case Instruction::SetLT:
1662 default: assert(0 && "Unknown integer condition code!");
1663 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
1665 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
1666 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
1667 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
1668 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
1669 return ReplaceInstUsesWith(I, RHS);
1672 case Instruction::SetGT:
1674 default: assert(0 && "Unknown integer condition code!");
1675 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
1676 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
1677 return ReplaceInstUsesWith(I, LHS);
1678 case Instruction::SetNE: // (X > 13 | X != 15) -> true
1679 case Instruction::SetLT: // (X > 13 | X < 15) -> true
1680 return ReplaceInstUsesWith(I, ConstantBool::True);
1685 return Changed ? &I : 0;
1688 // XorSelf - Implements: X ^ X --> 0
1691 XorSelf(Value *rhs) : RHS(rhs) {}
1692 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1693 Instruction *apply(BinaryOperator &Xor) const {
1699 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
1700 bool Changed = SimplifyCommutative(I);
1701 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1703 if (isa<UndefValue>(Op1))
1704 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
1706 // xor X, X = 0, even if X is nested in a sequence of Xor's.
1707 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
1708 assert(Result == &I && "AssociativeOpt didn't work?");
1709 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1712 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
1714 if (RHS->isNullValue())
1715 return ReplaceInstUsesWith(I, Op0);
1717 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
1718 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
1719 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
1720 if (RHS == ConstantBool::True && SCI->hasOneUse())
1721 return new SetCondInst(SCI->getInverseCondition(),
1722 SCI->getOperand(0), SCI->getOperand(1));
1724 // ~(c-X) == X-c-1 == X+(-c-1)
1725 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
1726 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
1727 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
1728 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
1729 ConstantInt::get(I.getType(), 1));
1730 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
1733 // ~(~X & Y) --> (X | ~Y)
1734 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
1735 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
1736 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
1738 BinaryOperator::createNot(Op0I->getOperand(1),
1739 Op0I->getOperand(1)->getName()+".not");
1740 InsertNewInstBefore(NotY, I);
1741 return BinaryOperator::createOr(Op0NotVal, NotY);
1745 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
1746 switch (Op0I->getOpcode()) {
1747 case Instruction::Add:
1748 // ~(X-c) --> (-c-1)-X
1749 if (RHS->isAllOnesValue()) {
1750 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
1751 return BinaryOperator::createSub(
1752 ConstantExpr::getSub(NegOp0CI,
1753 ConstantInt::get(I.getType(), 1)),
1754 Op0I->getOperand(0));
1757 case Instruction::And:
1758 // (X & C1) ^ C2 --> (X & C1) | C2 iff (C1&C2) == 0
1759 if (ConstantExpr::getAnd(RHS, Op0CI)->isNullValue())
1760 return BinaryOperator::createOr(Op0, RHS);
1762 case Instruction::Or:
1763 // (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1764 if (ConstantExpr::getAnd(RHS, Op0CI) == RHS)
1765 return BinaryOperator::createAnd(Op0, ConstantExpr::getNot(RHS));
1771 // Try to fold constant and into select arguments.
1772 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1773 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
1775 if (isa<PHINode>(Op0))
1776 if (Instruction *NV = FoldOpIntoPhi(I))
1780 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
1782 return ReplaceInstUsesWith(I,
1783 ConstantIntegral::getAllOnesValue(I.getType()));
1785 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
1787 return ReplaceInstUsesWith(I,
1788 ConstantIntegral::getAllOnesValue(I.getType()));
1790 if (Instruction *Op1I = dyn_cast<Instruction>(Op1))
1791 if (Op1I->getOpcode() == Instruction::Or) {
1792 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
1793 cast<BinaryOperator>(Op1I)->swapOperands();
1795 std::swap(Op0, Op1);
1796 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
1798 std::swap(Op0, Op1);
1800 } else if (Op1I->getOpcode() == Instruction::Xor) {
1801 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
1802 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
1803 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
1804 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
1807 if (Instruction *Op0I = dyn_cast<Instruction>(Op0))
1808 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
1809 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
1810 cast<BinaryOperator>(Op0I)->swapOperands();
1811 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
1812 Value *NotB = InsertNewInstBefore(BinaryOperator::createNot(Op1,
1813 Op1->getName()+".not"), I);
1814 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
1816 } else if (Op0I->getOpcode() == Instruction::Xor) {
1817 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
1818 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1819 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
1820 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
1823 // (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1824 Value *A, *B; ConstantInt *C1, *C2;
1825 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
1826 match(Op1, m_And(m_Value(B), m_ConstantInt(C2))) &&
1827 ConstantExpr::getAnd(C1, C2)->isNullValue())
1828 return BinaryOperator::createOr(Op0, Op1);
1830 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
1831 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
1832 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
1835 return Changed ? &I : 0;
1838 /// MulWithOverflow - Compute Result = In1*In2, returning true if the result
1839 /// overflowed for this type.
1840 static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1842 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
1843 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
1846 static bool isPositive(ConstantInt *C) {
1847 return cast<ConstantSInt>(C)->getValue() >= 0;
1850 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
1851 /// overflowed for this type.
1852 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
1854 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
1856 if (In1->getType()->isUnsigned())
1857 return cast<ConstantUInt>(Result)->getValue() <
1858 cast<ConstantUInt>(In1)->getValue();
1859 if (isPositive(In1) != isPositive(In2))
1861 if (isPositive(In1))
1862 return cast<ConstantSInt>(Result)->getValue() <
1863 cast<ConstantSInt>(In1)->getValue();
1864 return cast<ConstantSInt>(Result)->getValue() >
1865 cast<ConstantSInt>(In1)->getValue();
1868 Instruction *InstCombiner::visitSetCondInst(BinaryOperator &I) {
1869 bool Changed = SimplifyCommutative(I);
1870 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1871 const Type *Ty = Op0->getType();
1875 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
1877 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
1878 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
1880 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
1881 // addresses never equal each other! We already know that Op0 != Op1.
1882 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
1883 isa<ConstantPointerNull>(Op0)) &&
1884 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
1885 isa<ConstantPointerNull>(Op1)))
1886 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
1888 // setcc's with boolean values can always be turned into bitwise operations
1889 if (Ty == Type::BoolTy) {
1890 switch (I.getOpcode()) {
1891 default: assert(0 && "Invalid setcc instruction!");
1892 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
1893 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
1894 InsertNewInstBefore(Xor, I);
1895 return BinaryOperator::createNot(Xor);
1897 case Instruction::SetNE:
1898 return BinaryOperator::createXor(Op0, Op1);
1900 case Instruction::SetGT:
1901 std::swap(Op0, Op1); // Change setgt -> setlt
1903 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
1904 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1905 InsertNewInstBefore(Not, I);
1906 return BinaryOperator::createAnd(Not, Op1);
1908 case Instruction::SetGE:
1909 std::swap(Op0, Op1); // Change setge -> setle
1911 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
1912 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
1913 InsertNewInstBefore(Not, I);
1914 return BinaryOperator::createOr(Not, Op1);
1919 // See if we are doing a comparison between a constant and an instruction that
1920 // can be folded into the comparison.
1921 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1922 // Check to see if we are comparing against the minimum or maximum value...
1923 if (CI->isMinValue()) {
1924 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
1925 return ReplaceInstUsesWith(I, ConstantBool::False);
1926 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
1927 return ReplaceInstUsesWith(I, ConstantBool::True);
1928 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
1929 return BinaryOperator::createSetEQ(Op0, Op1);
1930 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
1931 return BinaryOperator::createSetNE(Op0, Op1);
1933 } else if (CI->isMaxValue()) {
1934 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
1935 return ReplaceInstUsesWith(I, ConstantBool::False);
1936 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
1937 return ReplaceInstUsesWith(I, ConstantBool::True);
1938 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
1939 return BinaryOperator::createSetEQ(Op0, Op1);
1940 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
1941 return BinaryOperator::createSetNE(Op0, Op1);
1943 // Comparing against a value really close to min or max?
1944 } else if (isMinValuePlusOne(CI)) {
1945 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
1946 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
1947 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
1948 return BinaryOperator::createSetNE(Op0, SubOne(CI));
1950 } else if (isMaxValueMinusOne(CI)) {
1951 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
1952 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
1953 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
1954 return BinaryOperator::createSetNE(Op0, AddOne(CI));
1957 // If we still have a setle or setge instruction, turn it into the
1958 // appropriate setlt or setgt instruction. Since the border cases have
1959 // already been handled above, this requires little checking.
1961 if (I.getOpcode() == Instruction::SetLE)
1962 return BinaryOperator::createSetLT(Op0, AddOne(CI));
1963 if (I.getOpcode() == Instruction::SetGE)
1964 return BinaryOperator::createSetGT(Op0, SubOne(CI));
1966 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
1967 switch (LHSI->getOpcode()) {
1968 case Instruction::PHI:
1969 if (Instruction *NV = FoldOpIntoPhi(I))
1972 case Instruction::And:
1973 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
1974 LHSI->getOperand(0)->hasOneUse()) {
1975 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
1976 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
1977 // happens a LOT in code produced by the C front-end, for bitfield
1979 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
1980 ConstantUInt *ShAmt;
1981 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
1982 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
1983 const Type *Ty = LHSI->getType();
1985 // We can fold this as long as we can't shift unknown bits
1986 // into the mask. This can only happen with signed shift
1987 // rights, as they sign-extend.
1989 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
1990 Shift->getType()->isUnsigned();
1992 // To test for the bad case of the signed shr, see if any
1993 // of the bits shifted in could be tested after the mask.
1994 Constant *OShAmt = ConstantUInt::get(Type::UByteTy,
1995 Ty->getPrimitiveSize()*8-ShAmt->getValue());
1997 ConstantExpr::getShl(ConstantInt::getAllOnesValue(Ty), OShAmt);
1998 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
2004 if (Shift->getOpcode() == Instruction::Shl)
2005 NewCst = ConstantExpr::getUShr(CI, ShAmt);
2007 NewCst = ConstantExpr::getShl(CI, ShAmt);
2009 // Check to see if we are shifting out any of the bits being
2011 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
2012 // If we shifted bits out, the fold is not going to work out.
2013 // As a special case, check to see if this means that the
2014 // result is always true or false now.
2015 if (I.getOpcode() == Instruction::SetEQ)
2016 return ReplaceInstUsesWith(I, ConstantBool::False);
2017 if (I.getOpcode() == Instruction::SetNE)
2018 return ReplaceInstUsesWith(I, ConstantBool::True);
2020 I.setOperand(1, NewCst);
2021 Constant *NewAndCST;
2022 if (Shift->getOpcode() == Instruction::Shl)
2023 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
2025 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
2026 LHSI->setOperand(1, NewAndCST);
2027 LHSI->setOperand(0, Shift->getOperand(0));
2028 WorkList.push_back(Shift); // Shift is dead.
2029 AddUsesToWorkList(I);
2037 case Instruction::Cast: { // (setcc (cast X to larger), CI)
2038 const Type *SrcTy = LHSI->getOperand(0)->getType();
2039 if (SrcTy->isIntegral() && LHSI->getType()->isIntegral()) {
2040 unsigned SrcBits = SrcTy->getPrimitiveSize()*8;
2041 if (SrcTy == Type::BoolTy) SrcBits = 1;
2042 unsigned DestBits = LHSI->getType()->getPrimitiveSize()*8;
2043 if (LHSI->getType() == Type::BoolTy) DestBits = 1;
2044 if (SrcBits < DestBits &&
2045 // FIXME: Reenable the code below for < and >. However, we have
2046 // to handle the cases when the source of the cast and the dest of
2047 // the cast have different signs. e.g:
2048 // (cast sbyte %X to uint) >u 255U -> X <s (sbyte)0
2049 (I.getOpcode() == Instruction::SetEQ ||
2050 I.getOpcode() == Instruction::SetNE)) {
2051 // Check to see if the comparison is always true or false.
2052 Constant *NewCst = ConstantExpr::getCast(CI, SrcTy);
2053 if (ConstantExpr::getCast(NewCst, LHSI->getType()) != CI) {
2054 switch (I.getOpcode()) {
2055 default: assert(0 && "unknown integer comparison");
2057 case Instruction::SetLT: {
2058 Constant *Max = ConstantIntegral::getMaxValue(SrcTy);
2059 Max = ConstantExpr::getCast(Max, LHSI->getType());
2060 return ReplaceInstUsesWith(I, ConstantExpr::getSetLT(Max, CI));
2062 case Instruction::SetGT: {
2063 Constant *Min = ConstantIntegral::getMinValue(SrcTy);
2064 Min = ConstantExpr::getCast(Min, LHSI->getType());
2065 return ReplaceInstUsesWith(I, ConstantExpr::getSetGT(Min, CI));
2068 case Instruction::SetEQ:
2069 return ReplaceInstUsesWith(I, ConstantBool::False);
2070 case Instruction::SetNE:
2071 return ReplaceInstUsesWith(I, ConstantBool::True);
2075 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0), NewCst);
2080 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
2081 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2082 switch (I.getOpcode()) {
2084 case Instruction::SetEQ:
2085 case Instruction::SetNE: {
2086 // If we are comparing against bits always shifted out, the
2087 // comparison cannot succeed.
2089 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
2090 if (Comp != CI) {// Comparing against a bit that we know is zero.
2091 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2092 Constant *Cst = ConstantBool::get(IsSetNE);
2093 return ReplaceInstUsesWith(I, Cst);
2096 if (LHSI->hasOneUse()) {
2097 // Otherwise strength reduce the shift into an and.
2098 unsigned ShAmtVal = ShAmt->getValue();
2099 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2100 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
2103 if (CI->getType()->isUnsigned()) {
2104 Mask = ConstantUInt::get(CI->getType(), Val);
2105 } else if (ShAmtVal != 0) {
2106 Mask = ConstantSInt::get(CI->getType(), Val);
2108 Mask = ConstantInt::getAllOnesValue(CI->getType());
2112 BinaryOperator::createAnd(LHSI->getOperand(0),
2113 Mask, LHSI->getName()+".mask");
2114 Value *And = InsertNewInstBefore(AndI, I);
2115 return new SetCondInst(I.getOpcode(), And,
2116 ConstantExpr::getUShr(CI, ShAmt));
2123 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
2124 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
2125 switch (I.getOpcode()) {
2127 case Instruction::SetEQ:
2128 case Instruction::SetNE: {
2129 // If we are comparing against bits always shifted out, the
2130 // comparison cannot succeed.
2132 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
2134 if (Comp != CI) {// Comparing against a bit that we know is zero.
2135 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
2136 Constant *Cst = ConstantBool::get(IsSetNE);
2137 return ReplaceInstUsesWith(I, Cst);
2140 if (LHSI->hasOneUse() || CI->isNullValue()) {
2141 unsigned ShAmtVal = ShAmt->getValue();
2143 // Otherwise strength reduce the shift into an and.
2144 uint64_t Val = ~0ULL; // All ones.
2145 Val <<= ShAmtVal; // Shift over to the right spot.
2148 if (CI->getType()->isUnsigned()) {
2149 unsigned TypeBits = CI->getType()->getPrimitiveSize()*8;
2150 Val &= (1ULL << TypeBits)-1;
2151 Mask = ConstantUInt::get(CI->getType(), Val);
2153 Mask = ConstantSInt::get(CI->getType(), Val);
2157 BinaryOperator::createAnd(LHSI->getOperand(0),
2158 Mask, LHSI->getName()+".mask");
2159 Value *And = InsertNewInstBefore(AndI, I);
2160 return new SetCondInst(I.getOpcode(), And,
2161 ConstantExpr::getShl(CI, ShAmt));
2169 case Instruction::Div:
2170 // Fold: (div X, C1) op C2 -> range check
2171 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
2172 // Fold this div into the comparison, producing a range check.
2173 // Determine, based on the divide type, what the range is being
2174 // checked. If there is an overflow on the low or high side, remember
2175 // it, otherwise compute the range [low, hi) bounding the new value.
2176 bool LoOverflow = false, HiOverflow = 0;
2177 ConstantInt *LoBound = 0, *HiBound = 0;
2180 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
2182 Instruction::BinaryOps Opcode = I.getOpcode();
2184 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
2185 } else if (LHSI->getType()->isUnsigned()) { // udiv
2187 LoOverflow = ProdOV;
2188 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
2189 } else if (isPositive(DivRHS)) { // Divisor is > 0.
2190 if (CI->isNullValue()) { // (X / pos) op 0
2192 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
2194 } else if (isPositive(CI)) { // (X / pos) op pos
2196 LoOverflow = ProdOV;
2197 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
2198 } else { // (X / pos) op neg
2199 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
2200 LoOverflow = AddWithOverflow(LoBound, Prod,
2201 cast<ConstantInt>(DivRHSH));
2203 HiOverflow = ProdOV;
2205 } else { // Divisor is < 0.
2206 if (CI->isNullValue()) { // (X / neg) op 0
2207 LoBound = AddOne(DivRHS);
2208 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
2209 } else if (isPositive(CI)) { // (X / neg) op pos
2210 HiOverflow = LoOverflow = ProdOV;
2212 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
2213 HiBound = AddOne(Prod);
2214 } else { // (X / neg) op neg
2216 LoOverflow = HiOverflow = ProdOV;
2217 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
2220 // Dividing by a negate swaps the condition.
2221 Opcode = SetCondInst::getSwappedCondition(Opcode);
2225 Value *X = LHSI->getOperand(0);
2227 default: assert(0 && "Unhandled setcc opcode!");
2228 case Instruction::SetEQ:
2229 if (LoOverflow && HiOverflow)
2230 return ReplaceInstUsesWith(I, ConstantBool::False);
2231 else if (HiOverflow)
2232 return new SetCondInst(Instruction::SetGE, X, LoBound);
2233 else if (LoOverflow)
2234 return new SetCondInst(Instruction::SetLT, X, HiBound);
2236 return InsertRangeTest(X, LoBound, HiBound, true, I);
2237 case Instruction::SetNE:
2238 if (LoOverflow && HiOverflow)
2239 return ReplaceInstUsesWith(I, ConstantBool::True);
2240 else if (HiOverflow)
2241 return new SetCondInst(Instruction::SetLT, X, LoBound);
2242 else if (LoOverflow)
2243 return new SetCondInst(Instruction::SetGE, X, HiBound);
2245 return InsertRangeTest(X, LoBound, HiBound, false, I);
2246 case Instruction::SetLT:
2248 return ReplaceInstUsesWith(I, ConstantBool::False);
2249 return new SetCondInst(Instruction::SetLT, X, LoBound);
2250 case Instruction::SetGT:
2252 return ReplaceInstUsesWith(I, ConstantBool::False);
2253 return new SetCondInst(Instruction::SetGE, X, HiBound);
2258 case Instruction::Select:
2259 // If either operand of the select is a constant, we can fold the
2260 // comparison into the select arms, which will cause one to be
2261 // constant folded and the select turned into a bitwise or.
2262 Value *Op1 = 0, *Op2 = 0;
2263 if (LHSI->hasOneUse()) {
2264 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
2265 // Fold the known value into the constant operand.
2266 Op1 = ConstantExpr::get(I.getOpcode(), C, CI);
2267 // Insert a new SetCC of the other select operand.
2268 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
2269 LHSI->getOperand(2), CI,
2271 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
2272 // Fold the known value into the constant operand.
2273 Op2 = ConstantExpr::get(I.getOpcode(), C, CI);
2274 // Insert a new SetCC of the other select operand.
2275 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
2276 LHSI->getOperand(1), CI,
2282 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
2286 // Simplify seteq and setne instructions...
2287 if (I.getOpcode() == Instruction::SetEQ ||
2288 I.getOpcode() == Instruction::SetNE) {
2289 bool isSetNE = I.getOpcode() == Instruction::SetNE;
2291 // If the first operand is (and|or|xor) with a constant, and the second
2292 // operand is a constant, simplify a bit.
2293 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
2294 switch (BO->getOpcode()) {
2295 case Instruction::Rem:
2296 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
2297 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
2299 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1)
2301 Log2(cast<ConstantSInt>(BO->getOperand(1))->getValue())) {
2302 const Type *UTy = BO->getType()->getUnsignedVersion();
2303 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
2305 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
2306 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
2307 RHSCst, BO->getName()), I);
2308 return BinaryOperator::create(I.getOpcode(), NewRem,
2309 Constant::getNullValue(UTy));
2313 case Instruction::Add:
2314 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
2315 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2316 if (BO->hasOneUse())
2317 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2318 ConstantExpr::getSub(CI, BOp1C));
2319 } else if (CI->isNullValue()) {
2320 // Replace ((add A, B) != 0) with (A != -B) if A or B is
2321 // efficiently invertible, or if the add has just this one use.
2322 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
2324 if (Value *NegVal = dyn_castNegVal(BOp1))
2325 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
2326 else if (Value *NegVal = dyn_castNegVal(BOp0))
2327 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
2328 else if (BO->hasOneUse()) {
2329 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
2331 InsertNewInstBefore(Neg, I);
2332 return new SetCondInst(I.getOpcode(), BOp0, Neg);
2336 case Instruction::Xor:
2337 // For the xor case, we can xor two constants together, eliminating
2338 // the explicit xor.
2339 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
2340 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
2341 ConstantExpr::getXor(CI, BOC));
2344 case Instruction::Sub:
2345 // Replace (([sub|xor] A, B) != 0) with (A != B)
2346 if (CI->isNullValue())
2347 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
2351 case Instruction::Or:
2352 // If bits are being or'd in that are not present in the constant we
2353 // are comparing against, then the comparison could never succeed!
2354 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
2355 Constant *NotCI = ConstantExpr::getNot(CI);
2356 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
2357 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
2361 case Instruction::And:
2362 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
2363 // If bits are being compared against that are and'd out, then the
2364 // comparison can never succeed!
2365 if (!ConstantExpr::getAnd(CI,
2366 ConstantExpr::getNot(BOC))->isNullValue())
2367 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
2369 // If we have ((X & C) == C), turn it into ((X & C) != 0).
2370 if (CI == BOC && isOneBitSet(CI))
2371 return new SetCondInst(isSetNE ? Instruction::SetEQ :
2372 Instruction::SetNE, Op0,
2373 Constant::getNullValue(CI->getType()));
2375 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
2376 // to be a signed value as appropriate.
2377 if (isSignBit(BOC)) {
2378 Value *X = BO->getOperand(0);
2379 // If 'X' is not signed, insert a cast now...
2380 if (!BOC->getType()->isSigned()) {
2381 const Type *DestTy = BOC->getType()->getSignedVersion();
2382 X = InsertCastBefore(X, DestTy, I);
2384 return new SetCondInst(isSetNE ? Instruction::SetLT :
2385 Instruction::SetGE, X,
2386 Constant::getNullValue(X->getType()));
2389 // ((X & ~7) == 0) --> X < 8
2390 if (CI->isNullValue() && isHighOnes(BOC)) {
2391 Value *X = BO->getOperand(0);
2392 Constant *NegX = ConstantExpr::getNeg(BOC);
2394 // If 'X' is signed, insert a cast now.
2395 if (NegX->getType()->isSigned()) {
2396 const Type *DestTy = NegX->getType()->getUnsignedVersion();
2397 X = InsertCastBefore(X, DestTy, I);
2398 NegX = ConstantExpr::getCast(NegX, DestTy);
2401 return new SetCondInst(isSetNE ? Instruction::SetGE :
2402 Instruction::SetLT, X, NegX);
2409 } else { // Not a SetEQ/SetNE
2410 // If the LHS is a cast from an integral value of the same size,
2411 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
2412 Value *CastOp = Cast->getOperand(0);
2413 const Type *SrcTy = CastOp->getType();
2414 unsigned SrcTySize = SrcTy->getPrimitiveSize();
2415 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
2416 SrcTySize == Cast->getType()->getPrimitiveSize()) {
2417 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
2418 "Source and destination signednesses should differ!");
2419 if (Cast->getType()->isSigned()) {
2420 // If this is a signed comparison, check for comparisons in the
2421 // vicinity of zero.
2422 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
2424 return BinaryOperator::createSetGT(CastOp,
2425 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize*8-1))-1));
2426 else if (I.getOpcode() == Instruction::SetGT &&
2427 cast<ConstantSInt>(CI)->getValue() == -1)
2428 // X > -1 => x < 128
2429 return BinaryOperator::createSetLT(CastOp,
2430 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize*8-1)));
2432 ConstantUInt *CUI = cast<ConstantUInt>(CI);
2433 if (I.getOpcode() == Instruction::SetLT &&
2434 CUI->getValue() == 1ULL << (SrcTySize*8-1))
2435 // X < 128 => X > -1
2436 return BinaryOperator::createSetGT(CastOp,
2437 ConstantSInt::get(SrcTy, -1));
2438 else if (I.getOpcode() == Instruction::SetGT &&
2439 CUI->getValue() == (1ULL << (SrcTySize*8-1))-1)
2441 return BinaryOperator::createSetLT(CastOp,
2442 Constant::getNullValue(SrcTy));
2449 // Test to see if the operands of the setcc are casted versions of other
2450 // values. If the cast can be stripped off both arguments, we do so now.
2451 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2452 Value *CastOp0 = CI->getOperand(0);
2453 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
2454 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
2455 (I.getOpcode() == Instruction::SetEQ ||
2456 I.getOpcode() == Instruction::SetNE)) {
2457 // We keep moving the cast from the left operand over to the right
2458 // operand, where it can often be eliminated completely.
2461 // If operand #1 is a cast instruction, see if we can eliminate it as
2463 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
2464 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
2466 Op1 = CI2->getOperand(0);
2468 // If Op1 is a constant, we can fold the cast into the constant.
2469 if (Op1->getType() != Op0->getType())
2470 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
2471 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
2473 // Otherwise, cast the RHS right before the setcc
2474 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
2475 InsertNewInstBefore(cast<Instruction>(Op1), I);
2477 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
2480 // Handle the special case of: setcc (cast bool to X), <cst>
2481 // This comes up when you have code like
2484 // For generality, we handle any zero-extension of any operand comparison
2486 if (ConstantInt *ConstantRHS = dyn_cast<ConstantInt>(Op1)) {
2487 const Type *SrcTy = CastOp0->getType();
2488 const Type *DestTy = Op0->getType();
2489 if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
2490 (SrcTy->isUnsigned() || SrcTy == Type::BoolTy)) {
2491 // Ok, we have an expansion of operand 0 into a new type. Get the
2492 // constant value, masink off bits which are not set in the RHS. These
2493 // could be set if the destination value is signed.
2494 uint64_t ConstVal = ConstantRHS->getRawValue();
2495 ConstVal &= (1ULL << DestTy->getPrimitiveSize()*8)-1;
2497 // If the constant we are comparing it with has high bits set, which
2498 // don't exist in the original value, the values could never be equal,
2499 // because the source would be zero extended.
2501 SrcTy == Type::BoolTy ? 1 : SrcTy->getPrimitiveSize()*8;
2502 bool HasSignBit = ConstVal & (1ULL << (DestTy->getPrimitiveSize()*8-1));
2503 if (ConstVal & ~((1ULL << SrcBits)-1)) {
2504 switch (I.getOpcode()) {
2505 default: assert(0 && "Unknown comparison type!");
2506 case Instruction::SetEQ:
2507 return ReplaceInstUsesWith(I, ConstantBool::False);
2508 case Instruction::SetNE:
2509 return ReplaceInstUsesWith(I, ConstantBool::True);
2510 case Instruction::SetLT:
2511 case Instruction::SetLE:
2512 if (DestTy->isSigned() && HasSignBit)
2513 return ReplaceInstUsesWith(I, ConstantBool::False);
2514 return ReplaceInstUsesWith(I, ConstantBool::True);
2515 case Instruction::SetGT:
2516 case Instruction::SetGE:
2517 if (DestTy->isSigned() && HasSignBit)
2518 return ReplaceInstUsesWith(I, ConstantBool::True);
2519 return ReplaceInstUsesWith(I, ConstantBool::False);
2523 // Otherwise, we can replace the setcc with a setcc of the smaller
2525 Op1 = ConstantExpr::getCast(cast<Constant>(Op1), SrcTy);
2526 return BinaryOperator::create(I.getOpcode(), CastOp0, Op1);
2530 return Changed ? &I : 0;
2535 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
2536 assert(I.getOperand(1)->getType() == Type::UByteTy);
2537 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2538 bool isLeftShift = I.getOpcode() == Instruction::Shl;
2540 // shl X, 0 == X and shr X, 0 == X
2541 // shl 0, X == 0 and shr 0, X == 0
2542 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
2543 Op0 == Constant::getNullValue(Op0->getType()))
2544 return ReplaceInstUsesWith(I, Op0);
2546 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
2547 if (!isLeftShift && I.getType()->isSigned())
2548 return ReplaceInstUsesWith(I, Op0);
2549 else // undef << X -> 0 AND undef >>u X -> 0
2550 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2552 if (isa<UndefValue>(Op1)) {
2553 if (isLeftShift || I.getType()->isUnsigned())
2554 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2556 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
2559 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
2561 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
2562 if (CSI->isAllOnesValue())
2563 return ReplaceInstUsesWith(I, CSI);
2565 // Try to fold constant and into select arguments.
2566 if (isa<Constant>(Op0))
2567 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2568 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2571 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1)) {
2572 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
2573 // of a signed value.
2575 unsigned TypeBits = Op0->getType()->getPrimitiveSize()*8;
2576 if (CUI->getValue() >= TypeBits) {
2577 if (!Op0->getType()->isSigned() || isLeftShift)
2578 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
2580 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
2585 // ((X*C1) << C2) == (X * (C1 << C2))
2586 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
2587 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
2588 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
2589 return BinaryOperator::createMul(BO->getOperand(0),
2590 ConstantExpr::getShl(BOOp, CUI));
2592 // Try to fold constant and into select arguments.
2593 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2594 if (Instruction *R = FoldBinOpIntoSelect(I, SI, this))
2596 if (isa<PHINode>(Op0))
2597 if (Instruction *NV = FoldOpIntoPhi(I))
2600 // If the operand is an bitwise operator with a constant RHS, and the
2601 // shift is the only use, we can pull it out of the shift.
2602 if (Op0->hasOneUse())
2603 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0))
2604 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
2605 bool isValid = true; // Valid only for And, Or, Xor
2606 bool highBitSet = false; // Transform if high bit of constant set?
2608 switch (Op0BO->getOpcode()) {
2609 default: isValid = false; break; // Do not perform transform!
2610 case Instruction::Add:
2611 isValid = isLeftShift;
2613 case Instruction::Or:
2614 case Instruction::Xor:
2617 case Instruction::And:
2622 // If this is a signed shift right, and the high bit is modified
2623 // by the logical operation, do not perform the transformation.
2624 // The highBitSet boolean indicates the value of the high bit of
2625 // the constant which would cause it to be modified for this
2628 if (isValid && !isLeftShift && !I.getType()->isUnsigned()) {
2629 uint64_t Val = Op0C->getRawValue();
2630 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
2634 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, CUI);
2636 Instruction *NewShift =
2637 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), CUI,
2640 InsertNewInstBefore(NewShift, I);
2642 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
2647 // If this is a shift of a shift, see if we can fold the two together...
2648 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
2649 if (ConstantUInt *ShiftAmt1C =
2650 dyn_cast<ConstantUInt>(Op0SI->getOperand(1))) {
2651 unsigned ShiftAmt1 = ShiftAmt1C->getValue();
2652 unsigned ShiftAmt2 = CUI->getValue();
2654 // Check for (A << c1) << c2 and (A >> c1) >> c2
2655 if (I.getOpcode() == Op0SI->getOpcode()) {
2656 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift...
2657 if (Op0->getType()->getPrimitiveSize()*8 < Amt)
2658 Amt = Op0->getType()->getPrimitiveSize()*8;
2659 return new ShiftInst(I.getOpcode(), Op0SI->getOperand(0),
2660 ConstantUInt::get(Type::UByteTy, Amt));
2663 // Check for (A << c1) >> c2 or visaversa. If we are dealing with
2664 // signed types, we can only support the (A >> c1) << c2 configuration,
2665 // because it can not turn an arbitrary bit of A into a sign bit.
2666 if (I.getType()->isUnsigned() || isLeftShift) {
2667 // Calculate bitmask for what gets shifted off the edge...
2668 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
2670 C = ConstantExpr::getShl(C, ShiftAmt1C);
2672 C = ConstantExpr::getShr(C, ShiftAmt1C);
2675 BinaryOperator::createAnd(Op0SI->getOperand(0), C,
2676 Op0SI->getOperand(0)->getName()+".mask");
2677 InsertNewInstBefore(Mask, I);
2679 // Figure out what flavor of shift we should use...
2680 if (ShiftAmt1 == ShiftAmt2)
2681 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
2682 else if (ShiftAmt1 < ShiftAmt2) {
2683 return new ShiftInst(I.getOpcode(), Mask,
2684 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
2686 return new ShiftInst(Op0SI->getOpcode(), Mask,
2687 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
2703 /// getCastType - In the future, we will split the cast instruction into these
2704 /// various types. Until then, we have to do the analysis here.
2705 static CastType getCastType(const Type *Src, const Type *Dest) {
2706 assert(Src->isIntegral() && Dest->isIntegral() &&
2707 "Only works on integral types!");
2708 unsigned SrcSize = Src->getPrimitiveSize()*8;
2709 if (Src == Type::BoolTy) SrcSize = 1;
2710 unsigned DestSize = Dest->getPrimitiveSize()*8;
2711 if (Dest == Type::BoolTy) DestSize = 1;
2713 if (SrcSize == DestSize) return Noop;
2714 if (SrcSize > DestSize) return Truncate;
2715 if (Src->isSigned()) return Signext;
2720 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
2723 static inline bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
2724 const Type *DstTy, TargetData *TD) {
2726 // It is legal to eliminate the instruction if casting A->B->A if the sizes
2727 // are identical and the bits don't get reinterpreted (for example
2728 // int->float->int would not be allowed).
2729 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
2732 // If we are casting between pointer and integer types, treat pointers as
2733 // integers of the appropriate size for the code below.
2734 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
2735 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
2736 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
2738 // Allow free casting and conversion of sizes as long as the sign doesn't
2740 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
2741 CastType FirstCast = getCastType(SrcTy, MidTy);
2742 CastType SecondCast = getCastType(MidTy, DstTy);
2744 // Capture the effect of these two casts. If the result is a legal cast,
2745 // the CastType is stored here, otherwise a special code is used.
2746 static const unsigned CastResult[] = {
2747 // First cast is noop
2749 // First cast is a truncate
2750 1, 1, 4, 4, // trunc->extend is not safe to eliminate
2751 // First cast is a sign ext
2752 2, 5, 2, 4, // signext->zeroext never ok
2753 // First cast is a zero ext
2757 unsigned Result = CastResult[FirstCast*4+SecondCast];
2759 default: assert(0 && "Illegal table value!");
2764 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
2765 // truncates, we could eliminate more casts.
2766 return (unsigned)getCastType(SrcTy, DstTy) == Result;
2768 return false; // Not possible to eliminate this here.
2770 // Sign or zero extend followed by truncate is always ok if the result
2771 // is a truncate or noop.
2772 CastType ResultCast = getCastType(SrcTy, DstTy);
2773 if (ResultCast == Noop || ResultCast == Truncate)
2775 // Otherwise we are still growing the value, we are only safe if the
2776 // result will match the sign/zeroextendness of the result.
2777 return ResultCast == FirstCast;
2783 static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
2784 if (V->getType() == Ty || isa<Constant>(V)) return false;
2785 if (const CastInst *CI = dyn_cast<CastInst>(V))
2786 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
2792 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
2793 /// InsertBefore instruction. This is specialized a bit to avoid inserting
2794 /// casts that are known to not do anything...
2796 Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
2797 Instruction *InsertBefore) {
2798 if (V->getType() == DestTy) return V;
2799 if (Constant *C = dyn_cast<Constant>(V))
2800 return ConstantExpr::getCast(C, DestTy);
2802 CastInst *CI = new CastInst(V, DestTy, V->getName());
2803 InsertNewInstBefore(CI, *InsertBefore);
2807 // CastInst simplification
2809 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
2810 Value *Src = CI.getOperand(0);
2812 // If the user is casting a value to the same type, eliminate this cast
2814 if (CI.getType() == Src->getType())
2815 return ReplaceInstUsesWith(CI, Src);
2817 if (isa<UndefValue>(Src)) // cast undef -> undef
2818 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
2820 // If casting the result of another cast instruction, try to eliminate this
2823 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) {
2824 if (isEliminableCastOfCast(CSrc->getOperand(0)->getType(),
2825 CSrc->getType(), CI.getType(), TD)) {
2826 // This instruction now refers directly to the cast's src operand. This
2827 // has a good chance of making CSrc dead.
2828 CI.setOperand(0, CSrc->getOperand(0));
2832 // If this is an A->B->A cast, and we are dealing with integral types, try
2833 // to convert this into a logical 'and' instruction.
2835 if (CSrc->getOperand(0)->getType() == CI.getType() &&
2836 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
2837 CI.getType()->isUnsigned() && CSrc->getType()->isUnsigned() &&
2838 CSrc->getType()->getPrimitiveSize() < CI.getType()->getPrimitiveSize()){
2839 assert(CSrc->getType() != Type::ULongTy &&
2840 "Cannot have type bigger than ulong!");
2841 uint64_t AndValue = (1ULL << CSrc->getType()->getPrimitiveSize()*8)-1;
2842 Constant *AndOp = ConstantUInt::get(CI.getType(), AndValue);
2843 return BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
2847 // If this is a cast to bool, turn it into the appropriate setne instruction.
2848 if (CI.getType() == Type::BoolTy)
2849 return BinaryOperator::createSetNE(CI.getOperand(0),
2850 Constant::getNullValue(CI.getOperand(0)->getType()));
2852 // If casting the result of a getelementptr instruction with no offset, turn
2853 // this into a cast of the original pointer!
2855 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
2856 bool AllZeroOperands = true;
2857 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
2858 if (!isa<Constant>(GEP->getOperand(i)) ||
2859 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
2860 AllZeroOperands = false;
2863 if (AllZeroOperands) {
2864 CI.setOperand(0, GEP->getOperand(0));
2869 // If we are casting a malloc or alloca to a pointer to a type of the same
2870 // size, rewrite the allocation instruction to allocate the "right" type.
2872 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
2873 if (AI->hasOneUse() && !AI->isArrayAllocation())
2874 if (const PointerType *PTy = dyn_cast<PointerType>(CI.getType())) {
2875 // Get the type really allocated and the type casted to...
2876 const Type *AllocElTy = AI->getAllocatedType();
2877 const Type *CastElTy = PTy->getElementType();
2878 if (AllocElTy->isSized() && CastElTy->isSized()) {
2879 unsigned AllocElTySize = TD->getTypeSize(AllocElTy);
2880 unsigned CastElTySize = TD->getTypeSize(CastElTy);
2882 // If the allocation is for an even multiple of the cast type size
2883 if (CastElTySize && (AllocElTySize % CastElTySize == 0)) {
2884 Value *Amt = ConstantUInt::get(Type::UIntTy,
2885 AllocElTySize/CastElTySize);
2886 std::string Name = AI->getName(); AI->setName("");
2887 AllocationInst *New;
2888 if (isa<MallocInst>(AI))
2889 New = new MallocInst(CastElTy, Amt, Name);
2891 New = new AllocaInst(CastElTy, Amt, Name);
2892 InsertNewInstBefore(New, *AI);
2893 return ReplaceInstUsesWith(CI, New);
2898 if (isa<PHINode>(Src))
2899 if (Instruction *NV = FoldOpIntoPhi(CI))
2902 // If the source value is an instruction with only this use, we can attempt to
2903 // propagate the cast into the instruction. Also, only handle integral types
2905 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
2906 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
2907 CI.getType()->isInteger()) { // Don't mess with casts to bool here
2908 const Type *DestTy = CI.getType();
2909 unsigned SrcBitSize = getTypeSizeInBits(Src->getType());
2910 unsigned DestBitSize = getTypeSizeInBits(DestTy);
2912 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
2913 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
2915 switch (SrcI->getOpcode()) {
2916 case Instruction::Add:
2917 case Instruction::Mul:
2918 case Instruction::And:
2919 case Instruction::Or:
2920 case Instruction::Xor:
2921 // If we are discarding information, or just changing the sign, rewrite.
2922 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
2923 // Don't insert two casts if they cannot be eliminated. We allow two
2924 // casts to be inserted if the sizes are the same. This could only be
2925 // converting signedness, which is a noop.
2926 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
2927 !ValueRequiresCast(Op0, DestTy, TD)) {
2928 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2929 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
2930 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
2931 ->getOpcode(), Op0c, Op1c);
2935 case Instruction::Shl:
2936 // Allow changing the sign of the source operand. Do not allow changing
2937 // the size of the shift, UNLESS the shift amount is a constant. We
2938 // mush not change variable sized shifts to a smaller size, because it
2939 // is undefined to shift more bits out than exist in the value.
2940 if (DestBitSize == SrcBitSize ||
2941 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
2942 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
2943 return new ShiftInst(Instruction::Shl, Op0c, Op1);
2952 /// GetSelectFoldableOperands - We want to turn code that looks like this:
2954 /// %D = select %cond, %C, %A
2956 /// %C = select %cond, %B, 0
2959 /// Assuming that the specified instruction is an operand to the select, return
2960 /// a bitmask indicating which operands of this instruction are foldable if they
2961 /// equal the other incoming value of the select.
2963 static unsigned GetSelectFoldableOperands(Instruction *I) {
2964 switch (I->getOpcode()) {
2965 case Instruction::Add:
2966 case Instruction::Mul:
2967 case Instruction::And:
2968 case Instruction::Or:
2969 case Instruction::Xor:
2970 return 3; // Can fold through either operand.
2971 case Instruction::Sub: // Can only fold on the amount subtracted.
2972 case Instruction::Shl: // Can only fold on the shift amount.
2973 case Instruction::Shr:
2976 return 0; // Cannot fold
2980 /// GetSelectFoldableConstant - For the same transformation as the previous
2981 /// function, return the identity constant that goes into the select.
2982 static Constant *GetSelectFoldableConstant(Instruction *I) {
2983 switch (I->getOpcode()) {
2984 default: assert(0 && "This cannot happen!"); abort();
2985 case Instruction::Add:
2986 case Instruction::Sub:
2987 case Instruction::Or:
2988 case Instruction::Xor:
2989 return Constant::getNullValue(I->getType());
2990 case Instruction::Shl:
2991 case Instruction::Shr:
2992 return Constant::getNullValue(Type::UByteTy);
2993 case Instruction::And:
2994 return ConstantInt::getAllOnesValue(I->getType());
2995 case Instruction::Mul:
2996 return ConstantInt::get(I->getType(), 1);
3000 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
3001 Value *CondVal = SI.getCondition();
3002 Value *TrueVal = SI.getTrueValue();
3003 Value *FalseVal = SI.getFalseValue();
3005 // select true, X, Y -> X
3006 // select false, X, Y -> Y
3007 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
3008 if (C == ConstantBool::True)
3009 return ReplaceInstUsesWith(SI, TrueVal);
3011 assert(C == ConstantBool::False);
3012 return ReplaceInstUsesWith(SI, FalseVal);
3015 // select C, X, X -> X
3016 if (TrueVal == FalseVal)
3017 return ReplaceInstUsesWith(SI, TrueVal);
3019 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
3020 return ReplaceInstUsesWith(SI, FalseVal);
3021 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
3022 return ReplaceInstUsesWith(SI, TrueVal);
3023 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
3024 if (isa<Constant>(TrueVal))
3025 return ReplaceInstUsesWith(SI, TrueVal);
3027 return ReplaceInstUsesWith(SI, FalseVal);
3030 if (SI.getType() == Type::BoolTy)
3031 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
3032 if (C == ConstantBool::True) {
3033 // Change: A = select B, true, C --> A = or B, C
3034 return BinaryOperator::createOr(CondVal, FalseVal);
3036 // Change: A = select B, false, C --> A = and !B, C
3038 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3039 "not."+CondVal->getName()), SI);
3040 return BinaryOperator::createAnd(NotCond, FalseVal);
3042 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
3043 if (C == ConstantBool::False) {
3044 // Change: A = select B, C, false --> A = and B, C
3045 return BinaryOperator::createAnd(CondVal, TrueVal);
3047 // Change: A = select B, C, true --> A = or !B, C
3049 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3050 "not."+CondVal->getName()), SI);
3051 return BinaryOperator::createOr(NotCond, TrueVal);
3055 // Selecting between two integer constants?
3056 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
3057 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
3058 // select C, 1, 0 -> cast C to int
3059 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
3060 return new CastInst(CondVal, SI.getType());
3061 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
3062 // select C, 0, 1 -> cast !C to int
3064 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
3065 "not."+CondVal->getName()), SI);
3066 return new CastInst(NotCond, SI.getType());
3069 // If one of the constants is zero (we know they can't both be) and we
3070 // have a setcc instruction with zero, and we have an 'and' with the
3071 // non-constant value, eliminate this whole mess. This corresponds to
3072 // cases like this: ((X & 27) ? 27 : 0)
3073 if (TrueValC->isNullValue() || FalseValC->isNullValue())
3074 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
3075 if ((IC->getOpcode() == Instruction::SetEQ ||
3076 IC->getOpcode() == Instruction::SetNE) &&
3077 isa<ConstantInt>(IC->getOperand(1)) &&
3078 cast<Constant>(IC->getOperand(1))->isNullValue())
3079 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
3080 if (ICA->getOpcode() == Instruction::And &&
3081 isa<ConstantInt>(ICA->getOperand(1)) &&
3082 (ICA->getOperand(1) == TrueValC ||
3083 ICA->getOperand(1) == FalseValC) &&
3084 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
3085 // Okay, now we know that everything is set up, we just don't
3086 // know whether we have a setne or seteq and whether the true or
3087 // false val is the zero.
3088 bool ShouldNotVal = !TrueValC->isNullValue();
3089 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
3092 V = InsertNewInstBefore(BinaryOperator::create(
3093 Instruction::Xor, V, ICA->getOperand(1)), SI);
3094 return ReplaceInstUsesWith(SI, V);
3098 // See if we are selecting two values based on a comparison of the two values.
3099 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
3100 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
3101 // Transform (X == Y) ? X : Y -> Y
3102 if (SCI->getOpcode() == Instruction::SetEQ)
3103 return ReplaceInstUsesWith(SI, FalseVal);
3104 // Transform (X != Y) ? X : Y -> X
3105 if (SCI->getOpcode() == Instruction::SetNE)
3106 return ReplaceInstUsesWith(SI, TrueVal);
3107 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3109 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
3110 // Transform (X == Y) ? Y : X -> X
3111 if (SCI->getOpcode() == Instruction::SetEQ)
3112 return ReplaceInstUsesWith(SI, FalseVal);
3113 // Transform (X != Y) ? Y : X -> Y
3114 if (SCI->getOpcode() == Instruction::SetNE)
3115 return ReplaceInstUsesWith(SI, TrueVal);
3116 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
3120 // See if we can fold the select into one of our operands.
3121 if (SI.getType()->isInteger()) {
3122 // See the comment above GetSelectFoldableOperands for a description of the
3123 // transformation we are doing here.
3124 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
3125 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
3126 !isa<Constant>(FalseVal))
3127 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
3128 unsigned OpToFold = 0;
3129 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
3131 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
3136 Constant *C = GetSelectFoldableConstant(TVI);
3137 std::string Name = TVI->getName(); TVI->setName("");
3138 Instruction *NewSel =
3139 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
3141 InsertNewInstBefore(NewSel, SI);
3142 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
3143 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
3144 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
3145 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
3147 assert(0 && "Unknown instruction!!");
3152 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
3153 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
3154 !isa<Constant>(TrueVal))
3155 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
3156 unsigned OpToFold = 0;
3157 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
3159 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
3164 Constant *C = GetSelectFoldableConstant(FVI);
3165 std::string Name = FVI->getName(); FVI->setName("");
3166 Instruction *NewSel =
3167 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
3169 InsertNewInstBefore(NewSel, SI);
3170 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
3171 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
3172 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
3173 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
3175 assert(0 && "Unknown instruction!!");
3184 // CallInst simplification
3186 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
3187 // Intrinsics cannot occur in an invoke, so handle them here instead of in
3189 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(&CI)) {
3190 bool Changed = false;
3192 // memmove/cpy/set of zero bytes is a noop.
3193 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
3194 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
3196 // FIXME: Increase alignment here.
3198 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
3199 if (CI->getRawValue() == 1) {
3200 // Replace the instruction with just byte operations. We would
3201 // transform other cases to loads/stores, but we don't know if
3202 // alignment is sufficient.
3206 // If we have a memmove and the source operation is a constant global,
3207 // then the source and dest pointers can't alias, so we can change this
3208 // into a call to memcpy.
3209 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI))
3210 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
3211 if (GVSrc->isConstant()) {
3212 Module *M = CI.getParent()->getParent()->getParent();
3213 Function *MemCpy = M->getOrInsertFunction("llvm.memcpy",
3214 CI.getCalledFunction()->getFunctionType());
3215 CI.setOperand(0, MemCpy);
3219 if (Changed) return &CI;
3220 } else if (DbgStopPointInst *SPI = dyn_cast<DbgStopPointInst>(&CI)) {
3221 // If this stoppoint is at the same source location as the previous
3222 // stoppoint in the chain, it is not needed.
3223 if (DbgStopPointInst *PrevSPI =
3224 dyn_cast<DbgStopPointInst>(SPI->getChain()))
3225 if (SPI->getLineNo() == PrevSPI->getLineNo() &&
3226 SPI->getColNo() == PrevSPI->getColNo()) {
3227 SPI->replaceAllUsesWith(PrevSPI);
3228 return EraseInstFromFunction(CI);
3232 return visitCallSite(&CI);
3235 // InvokeInst simplification
3237 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
3238 return visitCallSite(&II);
3241 // visitCallSite - Improvements for call and invoke instructions.
3243 Instruction *InstCombiner::visitCallSite(CallSite CS) {
3244 bool Changed = false;
3246 // If the callee is a constexpr cast of a function, attempt to move the cast
3247 // to the arguments of the call/invoke.
3248 if (transformConstExprCastCall(CS)) return 0;
3250 Value *Callee = CS.getCalledValue();
3252 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
3253 // This instruction is not reachable, just remove it. We insert a store to
3254 // undef so that we know that this code is not reachable, despite the fact
3255 // that we can't modify the CFG here.
3256 new StoreInst(ConstantBool::True,
3257 UndefValue::get(PointerType::get(Type::BoolTy)),
3258 CS.getInstruction());
3260 if (!CS.getInstruction()->use_empty())
3261 CS.getInstruction()->
3262 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
3264 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
3265 // Don't break the CFG, insert a dummy cond branch.
3266 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
3267 ConstantBool::True, II);
3269 return EraseInstFromFunction(*CS.getInstruction());
3272 const PointerType *PTy = cast<PointerType>(Callee->getType());
3273 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
3274 if (FTy->isVarArg()) {
3275 // See if we can optimize any arguments passed through the varargs area of
3277 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
3278 E = CS.arg_end(); I != E; ++I)
3279 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
3280 // If this cast does not effect the value passed through the varargs
3281 // area, we can eliminate the use of the cast.
3282 Value *Op = CI->getOperand(0);
3283 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
3290 return Changed ? CS.getInstruction() : 0;
3293 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
3294 // attempt to move the cast to the arguments of the call/invoke.
3296 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
3297 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
3298 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
3299 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
3301 Function *Callee = cast<Function>(CE->getOperand(0));
3302 Instruction *Caller = CS.getInstruction();
3304 // Okay, this is a cast from a function to a different type. Unless doing so
3305 // would cause a type conversion of one of our arguments, change this call to
3306 // be a direct call with arguments casted to the appropriate types.
3308 const FunctionType *FT = Callee->getFunctionType();
3309 const Type *OldRetTy = Caller->getType();
3311 // Check to see if we are changing the return type...
3312 if (OldRetTy != FT->getReturnType()) {
3313 if (Callee->isExternal() &&
3314 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
3315 !Caller->use_empty())
3316 return false; // Cannot transform this return value...
3318 // If the callsite is an invoke instruction, and the return value is used by
3319 // a PHI node in a successor, we cannot change the return type of the call
3320 // because there is no place to put the cast instruction (without breaking
3321 // the critical edge). Bail out in this case.
3322 if (!Caller->use_empty())
3323 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
3324 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
3326 if (PHINode *PN = dyn_cast<PHINode>(*UI))
3327 if (PN->getParent() == II->getNormalDest() ||
3328 PN->getParent() == II->getUnwindDest())
3332 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
3333 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
3335 CallSite::arg_iterator AI = CS.arg_begin();
3336 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
3337 const Type *ParamTy = FT->getParamType(i);
3338 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
3339 if (Callee->isExternal() && !isConvertible) return false;
3342 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
3343 Callee->isExternal())
3344 return false; // Do not delete arguments unless we have a function body...
3346 // Okay, we decided that this is a safe thing to do: go ahead and start
3347 // inserting cast instructions as necessary...
3348 std::vector<Value*> Args;
3349 Args.reserve(NumActualArgs);
3351 AI = CS.arg_begin();
3352 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
3353 const Type *ParamTy = FT->getParamType(i);
3354 if ((*AI)->getType() == ParamTy) {
3355 Args.push_back(*AI);
3357 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
3362 // If the function takes more arguments than the call was taking, add them
3364 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
3365 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
3367 // If we are removing arguments to the function, emit an obnoxious warning...
3368 if (FT->getNumParams() < NumActualArgs)
3369 if (!FT->isVarArg()) {
3370 std::cerr << "WARNING: While resolving call to function '"
3371 << Callee->getName() << "' arguments were dropped!\n";
3373 // Add all of the arguments in their promoted form to the arg list...
3374 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
3375 const Type *PTy = getPromotedType((*AI)->getType());
3376 if (PTy != (*AI)->getType()) {
3377 // Must promote to pass through va_arg area!
3378 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
3379 InsertNewInstBefore(Cast, *Caller);
3380 Args.push_back(Cast);
3382 Args.push_back(*AI);
3387 if (FT->getReturnType() == Type::VoidTy)
3388 Caller->setName(""); // Void type should not have a name...
3391 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3392 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
3393 Args, Caller->getName(), Caller);
3395 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
3398 // Insert a cast of the return type as necessary...
3400 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
3401 if (NV->getType() != Type::VoidTy) {
3402 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
3404 // If this is an invoke instruction, we should insert it after the first
3405 // non-phi, instruction in the normal successor block.
3406 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
3407 BasicBlock::iterator I = II->getNormalDest()->begin();
3408 while (isa<PHINode>(I)) ++I;
3409 InsertNewInstBefore(NC, *I);
3411 // Otherwise, it's a call, just insert cast right after the call instr
3412 InsertNewInstBefore(NC, *Caller);
3414 AddUsersToWorkList(*Caller);
3416 NV = UndefValue::get(Caller->getType());
3420 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
3421 Caller->replaceAllUsesWith(NV);
3422 Caller->getParent()->getInstList().erase(Caller);
3423 removeFromWorkList(Caller);
3428 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
3429 // operator and they all are only used by the PHI, PHI together their
3430 // inputs, and do the operation once, to the result of the PHI.
3431 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
3432 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
3434 // Scan the instruction, looking for input operations that can be folded away.
3435 // If all input operands to the phi are the same instruction (e.g. a cast from
3436 // the same type or "+42") we can pull the operation through the PHI, reducing
3437 // code size and simplifying code.
3438 Constant *ConstantOp = 0;
3439 const Type *CastSrcTy = 0;
3440 if (isa<CastInst>(FirstInst)) {
3441 CastSrcTy = FirstInst->getOperand(0)->getType();
3442 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
3443 // Can fold binop or shift if the RHS is a constant.
3444 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
3445 if (ConstantOp == 0) return 0;
3447 return 0; // Cannot fold this operation.
3450 // Check to see if all arguments are the same operation.
3451 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
3452 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
3453 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
3454 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
3457 if (I->getOperand(0)->getType() != CastSrcTy)
3458 return 0; // Cast operation must match.
3459 } else if (I->getOperand(1) != ConstantOp) {
3464 // Okay, they are all the same operation. Create a new PHI node of the
3465 // correct type, and PHI together all of the LHS's of the instructions.
3466 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
3467 PN.getName()+".in");
3468 NewPN->op_reserve(PN.getNumOperands());
3470 Value *InVal = FirstInst->getOperand(0);
3471 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
3473 // Add all operands to the new PHI.
3474 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
3475 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
3476 if (NewInVal != InVal)
3478 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
3483 // The new PHI unions all of the same values together. This is really
3484 // common, so we handle it intelligently here for compile-time speed.
3488 InsertNewInstBefore(NewPN, PN);
3492 // Insert and return the new operation.
3493 if (isa<CastInst>(FirstInst))
3494 return new CastInst(PhiVal, PN.getType());
3495 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
3496 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
3498 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
3499 PhiVal, ConstantOp);
3502 // PHINode simplification
3504 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
3505 if (Value *V = hasConstantValue(&PN)) {
3506 // If V is an instruction, we have to be certain that it dominates PN.
3507 // However, because we don't have dom info, we can't do a perfect job.
3508 if (Instruction *I = dyn_cast<Instruction>(V)) {
3509 // We know that the instruction dominates the PHI if there are no undef
3510 // values coming in.
3511 if (I->getParent() != &I->getParent()->getParent()->front() ||
3513 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3514 if (isa<UndefValue>(PN.getIncomingValue(i))) {
3521 return ReplaceInstUsesWith(PN, V);
3524 // If the only user of this instruction is a cast instruction, and all of the
3525 // incoming values are constants, change this PHI to merge together the casted
3528 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
3529 if (CI->getType() != PN.getType()) { // noop casts will be folded
3530 bool AllConstant = true;
3531 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
3532 if (!isa<Constant>(PN.getIncomingValue(i))) {
3533 AllConstant = false;
3537 // Make a new PHI with all casted values.
3538 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
3539 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
3540 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
3541 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
3542 PN.getIncomingBlock(i));
3545 // Update the cast instruction.
3546 CI->setOperand(0, New);
3547 WorkList.push_back(CI); // revisit the cast instruction to fold.
3548 WorkList.push_back(New); // Make sure to revisit the new Phi
3549 return &PN; // PN is now dead!
3553 // If all PHI operands are the same operation, pull them through the PHI,
3554 // reducing code size.
3555 if (isa<Instruction>(PN.getIncomingValue(0)) &&
3556 PN.getIncomingValue(0)->hasOneUse())
3557 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
3564 static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
3565 Instruction *InsertPoint,
3567 unsigned PS = IC->getTargetData().getPointerSize();
3568 const Type *VTy = V->getType();
3569 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
3570 // We must insert a cast to ensure we sign-extend.
3571 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
3572 V->getName()), *InsertPoint);
3573 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
3578 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
3579 Value *PtrOp = GEP.getOperand(0);
3580 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
3581 // If so, eliminate the noop.
3582 if (GEP.getNumOperands() == 1)
3583 return ReplaceInstUsesWith(GEP, PtrOp);
3585 if (isa<UndefValue>(GEP.getOperand(0)))
3586 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
3588 bool HasZeroPointerIndex = false;
3589 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
3590 HasZeroPointerIndex = C->isNullValue();
3592 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
3593 return ReplaceInstUsesWith(GEP, PtrOp);
3595 // Eliminate unneeded casts for indices.
3596 bool MadeChange = false;
3597 gep_type_iterator GTI = gep_type_begin(GEP);
3598 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
3599 if (isa<SequentialType>(*GTI)) {
3600 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
3601 Value *Src = CI->getOperand(0);
3602 const Type *SrcTy = Src->getType();
3603 const Type *DestTy = CI->getType();
3604 if (Src->getType()->isInteger()) {
3605 if (SrcTy->getPrimitiveSize() == DestTy->getPrimitiveSize()) {
3606 // We can always eliminate a cast from ulong or long to the other.
3607 // We can always eliminate a cast from uint to int or the other on
3608 // 32-bit pointer platforms.
3609 if (DestTy->getPrimitiveSize() >= TD->getPointerSize()) {
3611 GEP.setOperand(i, Src);
3613 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
3614 SrcTy->getPrimitiveSize() == 4) {
3615 // We can always eliminate a cast from int to [u]long. We can
3616 // eliminate a cast from uint to [u]long iff the target is a 32-bit
3618 if (SrcTy->isSigned() ||
3619 SrcTy->getPrimitiveSize() >= TD->getPointerSize()) {
3621 GEP.setOperand(i, Src);
3626 // If we are using a wider index than needed for this platform, shrink it
3627 // to what we need. If the incoming value needs a cast instruction,
3628 // insert it. This explicit cast can make subsequent optimizations more
3630 Value *Op = GEP.getOperand(i);
3631 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
3632 if (Constant *C = dyn_cast<Constant>(Op)) {
3633 GEP.setOperand(i, ConstantExpr::getCast(C,
3634 TD->getIntPtrType()->getSignedVersion()));
3637 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
3638 Op->getName()), GEP);
3639 GEP.setOperand(i, Op);
3643 // If this is a constant idx, make sure to canonicalize it to be a signed
3644 // operand, otherwise CSE and other optimizations are pessimized.
3645 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
3646 GEP.setOperand(i, ConstantExpr::getCast(CUI,
3647 CUI->getType()->getSignedVersion()));
3651 if (MadeChange) return &GEP;
3653 // Combine Indices - If the source pointer to this getelementptr instruction
3654 // is a getelementptr instruction, combine the indices of the two
3655 // getelementptr instructions into a single instruction.
3657 std::vector<Value*> SrcGEPOperands;
3658 if (GetElementPtrInst *Src = dyn_cast<GetElementPtrInst>(PtrOp)) {
3659 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
3660 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
3661 if (CE->getOpcode() == Instruction::GetElementPtr)
3662 SrcGEPOperands.assign(CE->op_begin(), CE->op_end());
3665 if (!SrcGEPOperands.empty()) {
3666 // Note that if our source is a gep chain itself that we wait for that
3667 // chain to be resolved before we perform this transformation. This
3668 // avoids us creating a TON of code in some cases.
3670 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
3671 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
3672 return 0; // Wait until our source is folded to completion.
3674 std::vector<Value *> Indices;
3676 // Find out whether the last index in the source GEP is a sequential idx.
3677 bool EndsWithSequential = false;
3678 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
3679 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
3680 EndsWithSequential = !isa<StructType>(*I);
3682 // Can we combine the two pointer arithmetics offsets?
3683 if (EndsWithSequential) {
3684 // Replace: gep (gep %P, long B), long A, ...
3685 // With: T = long A+B; gep %P, T, ...
3687 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
3688 if (SO1 == Constant::getNullValue(SO1->getType())) {
3690 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
3693 // If they aren't the same type, convert both to an integer of the
3694 // target's pointer size.
3695 if (SO1->getType() != GO1->getType()) {
3696 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
3697 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
3698 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
3699 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
3701 unsigned PS = TD->getPointerSize();
3702 if (SO1->getType()->getPrimitiveSize() == PS) {
3703 // Convert GO1 to SO1's type.
3704 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
3706 } else if (GO1->getType()->getPrimitiveSize() == PS) {
3707 // Convert SO1 to GO1's type.
3708 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
3710 const Type *PT = TD->getIntPtrType();
3711 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
3712 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
3716 if (isa<Constant>(SO1) && isa<Constant>(GO1))
3717 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
3719 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
3720 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
3724 // Recycle the GEP we already have if possible.
3725 if (SrcGEPOperands.size() == 2) {
3726 GEP.setOperand(0, SrcGEPOperands[0]);
3727 GEP.setOperand(1, Sum);
3730 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3731 SrcGEPOperands.end()-1);
3732 Indices.push_back(Sum);
3733 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
3735 } else if (isa<Constant>(*GEP.idx_begin()) &&
3736 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
3737 SrcGEPOperands.size() != 1) {
3738 // Otherwise we can do the fold if the first index of the GEP is a zero
3739 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
3740 SrcGEPOperands.end());
3741 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
3744 if (!Indices.empty())
3745 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
3747 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
3748 // GEP of global variable. If all of the indices for this GEP are
3749 // constants, we can promote this to a constexpr instead of an instruction.
3751 // Scan for nonconstants...
3752 std::vector<Constant*> Indices;
3753 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
3754 for (; I != E && isa<Constant>(*I); ++I)
3755 Indices.push_back(cast<Constant>(*I));
3757 if (I == E) { // If they are all constants...
3758 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
3760 // Replace all uses of the GEP with the new constexpr...
3761 return ReplaceInstUsesWith(GEP, CE);
3763 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PtrOp)) {
3764 if (CE->getOpcode() == Instruction::Cast) {
3765 if (HasZeroPointerIndex) {
3766 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
3767 // into : GEP [10 x ubyte]* X, long 0, ...
3769 // This occurs when the program declares an array extern like "int X[];"
3771 Constant *X = CE->getOperand(0);
3772 const PointerType *CPTy = cast<PointerType>(CE->getType());
3773 if (const PointerType *XTy = dyn_cast<PointerType>(X->getType()))
3774 if (const ArrayType *XATy =
3775 dyn_cast<ArrayType>(XTy->getElementType()))
3776 if (const ArrayType *CATy =
3777 dyn_cast<ArrayType>(CPTy->getElementType()))
3778 if (CATy->getElementType() == XATy->getElementType()) {
3779 // At this point, we know that the cast source type is a pointer
3780 // to an array of the same type as the destination pointer
3781 // array. Because the array type is never stepped over (there
3782 // is a leading zero) we can fold the cast into this GEP.
3783 GEP.setOperand(0, X);
3793 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
3794 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
3795 if (AI.isArrayAllocation()) // Check C != 1
3796 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
3797 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
3798 AllocationInst *New = 0;
3800 // Create and insert the replacement instruction...
3801 if (isa<MallocInst>(AI))
3802 New = new MallocInst(NewTy, 0, AI.getName());
3804 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
3805 New = new AllocaInst(NewTy, 0, AI.getName());
3808 InsertNewInstBefore(New, AI);
3810 // Scan to the end of the allocation instructions, to skip over a block of
3811 // allocas if possible...
3813 BasicBlock::iterator It = New;
3814 while (isa<AllocationInst>(*It)) ++It;
3816 // Now that I is pointing to the first non-allocation-inst in the block,
3817 // insert our getelementptr instruction...
3819 std::vector<Value*> Idx(2, Constant::getNullValue(Type::IntTy));
3820 Value *V = new GetElementPtrInst(New, Idx, New->getName()+".sub", It);
3822 // Now make everything use the getelementptr instead of the original
3824 return ReplaceInstUsesWith(AI, V);
3825 } else if (isa<UndefValue>(AI.getArraySize())) {
3826 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
3829 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
3830 // Note that we only do this for alloca's, because malloc should allocate and
3831 // return a unique pointer, even for a zero byte allocation.
3832 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
3833 TD->getTypeSize(AI.getAllocatedType()) == 0)
3834 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
3839 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
3840 Value *Op = FI.getOperand(0);
3842 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
3843 if (CastInst *CI = dyn_cast<CastInst>(Op))
3844 if (isa<PointerType>(CI->getOperand(0)->getType())) {
3845 FI.setOperand(0, CI->getOperand(0));
3849 // free undef -> unreachable.
3850 if (isa<UndefValue>(Op)) {
3851 // Insert a new store to null because we cannot modify the CFG here.
3852 new StoreInst(ConstantBool::True,
3853 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
3854 return EraseInstFromFunction(FI);
3857 // If we have 'free null' delete the instruction. This can happen in stl code
3858 // when lots of inlining happens.
3859 if (isa<ConstantPointerNull>(Op))
3860 return EraseInstFromFunction(FI);
3866 /// GetGEPGlobalInitializer - Given a constant, and a getelementptr
3867 /// constantexpr, return the constant value being addressed by the constant
3868 /// expression, or null if something is funny.
3870 static Constant *GetGEPGlobalInitializer(Constant *C, ConstantExpr *CE) {
3871 if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))
3872 return 0; // Do not allow stepping over the value!
3874 // Loop over all of the operands, tracking down which value we are
3876 gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);
3877 for (++I; I != E; ++I)
3878 if (const StructType *STy = dyn_cast<StructType>(*I)) {
3879 ConstantUInt *CU = cast<ConstantUInt>(I.getOperand());
3880 assert(CU->getValue() < STy->getNumElements() &&
3881 "Struct index out of range!");
3882 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(C)) {
3883 C = CS->getOperand(CU->getValue());
3884 } else if (isa<ConstantAggregateZero>(C)) {
3885 C = Constant::getNullValue(STy->getElementType(CU->getValue()));
3886 } else if (isa<UndefValue>(C)) {
3887 C = UndefValue::get(STy->getElementType(CU->getValue()));
3891 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(I.getOperand())) {
3892 const ArrayType *ATy = cast<ArrayType>(*I);
3893 if ((uint64_t)CI->getRawValue() >= ATy->getNumElements()) return 0;
3894 if (ConstantArray *CA = dyn_cast<ConstantArray>(C))
3895 C = CA->getOperand(CI->getRawValue());
3896 else if (isa<ConstantAggregateZero>(C))
3897 C = Constant::getNullValue(ATy->getElementType());
3898 else if (isa<UndefValue>(C))
3899 C = UndefValue::get(ATy->getElementType());
3908 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
3909 User *CI = cast<User>(LI.getOperand(0));
3911 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
3912 if (const PointerType *SrcTy =
3913 dyn_cast<PointerType>(CI->getOperand(0)->getType())) {
3914 const Type *SrcPTy = SrcTy->getElementType();
3915 if (SrcPTy->isSized() && DestPTy->isSized() &&
3916 IC.getTargetData().getTypeSize(SrcPTy) ==
3917 IC.getTargetData().getTypeSize(DestPTy) &&
3918 (SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
3919 (DestPTy->isInteger() || isa<PointerType>(DestPTy))) {
3920 // Okay, we are casting from one integer or pointer type to another of
3921 // the same size. Instead of casting the pointer before the load, cast
3922 // the result of the loaded value.
3923 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CI->getOperand(0),
3925 LI.isVolatile()),LI);
3926 // Now cast the result of the load.
3927 return new CastInst(NewLoad, LI.getType());
3933 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
3934 /// from this value cannot trap. If it is not obviously safe to load from the
3935 /// specified pointer, we do a quick local scan of the basic block containing
3936 /// ScanFrom, to determine if the address is already accessed.
3937 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
3938 // If it is an alloca or global variable, it is always safe to load from.
3939 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
3941 // Otherwise, be a little bit agressive by scanning the local block where we
3942 // want to check to see if the pointer is already being loaded or stored
3943 // from/to. If so, the previous load or store would have already trapped,
3944 // so there is no harm doing an extra load (also, CSE will later eliminate
3945 // the load entirely).
3946 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
3951 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
3952 if (LI->getOperand(0) == V) return true;
3953 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
3954 if (SI->getOperand(1) == V) return true;
3960 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
3961 Value *Op = LI.getOperand(0);
3963 if (Constant *C = dyn_cast<Constant>(Op)) {
3964 if ((C->isNullValue() || isa<UndefValue>(C)) &&
3965 !LI.isVolatile()) { // load null/undef -> undef
3966 // Insert a new store to null instruction before the load to indicate that
3967 // this code is not reachable. We do this instead of inserting an
3968 // unreachable instruction directly because we cannot modify the CFG.
3969 new StoreInst(UndefValue::get(LI.getType()), C, &LI);
3970 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
3973 // Instcombine load (constant global) into the value loaded.
3974 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
3975 if (GV->isConstant() && !GV->isExternal())
3976 return ReplaceInstUsesWith(LI, GV->getInitializer());
3978 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
3979 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
3980 if (CE->getOpcode() == Instruction::GetElementPtr) {
3981 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
3982 if (GV->isConstant() && !GV->isExternal())
3983 if (Constant *V = GetGEPGlobalInitializer(GV->getInitializer(), CE))
3984 return ReplaceInstUsesWith(LI, V);
3985 } else if (CE->getOpcode() == Instruction::Cast) {
3986 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3991 // load (cast X) --> cast (load X) iff safe
3992 if (CastInst *CI = dyn_cast<CastInst>(Op))
3993 if (Instruction *Res = InstCombineLoadCast(*this, LI))
3996 if (!LI.isVolatile() && Op->hasOneUse()) {
3997 // Change select and PHI nodes to select values instead of addresses: this
3998 // helps alias analysis out a lot, allows many others simplifications, and
3999 // exposes redundancy in the code.
4001 // Note that we cannot do the transformation unless we know that the
4002 // introduced loads cannot trap! Something like this is valid as long as
4003 // the condition is always false: load (select bool %C, int* null, int* %G),
4004 // but it would not be valid if we transformed it to load from null
4007 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
4008 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
4009 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
4010 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
4011 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
4012 SI->getOperand(1)->getName()+".val"), LI);
4013 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
4014 SI->getOperand(2)->getName()+".val"), LI);
4015 return new SelectInst(SI->getCondition(), V1, V2);
4018 // load (select (cond, null, P)) -> load P
4019 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
4020 if (C->isNullValue()) {
4021 LI.setOperand(0, SI->getOperand(2));
4025 // load (select (cond, P, null)) -> load P
4026 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
4027 if (C->isNullValue()) {
4028 LI.setOperand(0, SI->getOperand(1));
4032 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
4033 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
4034 bool Safe = PN->getParent() == LI.getParent();
4036 // Scan all of the instructions between the PHI and the load to make
4037 // sure there are no instructions that might possibly alter the value
4038 // loaded from the PHI.
4040 BasicBlock::iterator I = &LI;
4041 for (--I; !isa<PHINode>(I); --I)
4042 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
4048 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
4049 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
4050 PN->getIncomingBlock(i)->getTerminator()))
4055 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
4056 InsertNewInstBefore(NewPN, *PN);
4057 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
4059 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
4060 BasicBlock *BB = PN->getIncomingBlock(i);
4061 Value *&TheLoad = LoadMap[BB];
4063 Value *InVal = PN->getIncomingValue(i);
4064 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
4065 InVal->getName()+".val"),
4066 *BB->getTerminator());
4068 NewPN->addIncoming(TheLoad, BB);
4070 return ReplaceInstUsesWith(LI, NewPN);
4077 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
4078 // Change br (not X), label True, label False to: br X, label False, True
4080 BasicBlock *TrueDest;
4081 BasicBlock *FalseDest;
4082 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
4083 !isa<Constant>(X)) {
4084 // Swap Destinations and condition...
4086 BI.setSuccessor(0, FalseDest);
4087 BI.setSuccessor(1, TrueDest);
4091 // Cannonicalize setne -> seteq
4092 Instruction::BinaryOps Op; Value *Y;
4093 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
4094 TrueDest, FalseDest)))
4095 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
4096 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
4097 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
4098 std::string Name = I->getName(); I->setName("");
4099 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
4100 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
4101 // Swap Destinations and condition...
4102 BI.setCondition(NewSCC);
4103 BI.setSuccessor(0, FalseDest);
4104 BI.setSuccessor(1, TrueDest);
4105 removeFromWorkList(I);
4106 I->getParent()->getInstList().erase(I);
4107 WorkList.push_back(cast<Instruction>(NewSCC));
4114 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
4115 Value *Cond = SI.getCondition();
4116 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
4117 if (I->getOpcode() == Instruction::Add)
4118 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
4119 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
4120 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
4121 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
4123 SI.setOperand(0, I->getOperand(0));
4124 WorkList.push_back(I);
4132 void InstCombiner::removeFromWorkList(Instruction *I) {
4133 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
4137 bool InstCombiner::runOnFunction(Function &F) {
4138 bool Changed = false;
4139 TD = &getAnalysis<TargetData>();
4141 for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
4142 WorkList.push_back(&*i);
4145 while (!WorkList.empty()) {
4146 Instruction *I = WorkList.back(); // Get an instruction from the worklist
4147 WorkList.pop_back();
4149 // Check to see if we can DCE or ConstantPropagate the instruction...
4150 // Check to see if we can DIE the instruction...
4151 if (isInstructionTriviallyDead(I)) {
4152 // Add operands to the worklist...
4153 if (I->getNumOperands() < 4)
4154 AddUsesToWorkList(*I);
4157 I->getParent()->getInstList().erase(I);
4158 removeFromWorkList(I);
4162 // Instruction isn't dead, see if we can constant propagate it...
4163 if (Constant *C = ConstantFoldInstruction(I)) {
4164 if (isa<GetElementPtrInst>(I) &&
4165 cast<Constant>(I->getOperand(0))->isNullValue() &&
4166 !isa<ConstantPointerNull>(C)) {
4167 // If this is a constant expr gep that is effectively computing an
4168 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
4169 bool isFoldableGEP = true;
4170 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
4171 if (!isa<ConstantInt>(I->getOperand(i)))
4172 isFoldableGEP = false;
4173 if (isFoldableGEP) {
4174 uint64_t Offset = TD->getIndexedOffset(I->getOperand(0)->getType(),
4175 std::vector<Value*>(I->op_begin()+1, I->op_end()));
4176 C = ConstantUInt::get(Type::ULongTy, Offset);
4177 C = ConstantExpr::getCast(C, TD->getIntPtrType());
4178 C = ConstantExpr::getCast(C, I->getType());
4182 // Add operands to the worklist...
4183 AddUsesToWorkList(*I);
4184 ReplaceInstUsesWith(*I, C);
4187 I->getParent()->getInstList().erase(I);
4188 removeFromWorkList(I);
4192 // Now that we have an instruction, try combining it to simplify it...
4193 if (Instruction *Result = visit(*I)) {
4195 // Should we replace the old instruction with a new one?
4197 DEBUG(std::cerr << "IC: Old = " << *I
4198 << " New = " << *Result);
4200 // Everything uses the new instruction now.
4201 I->replaceAllUsesWith(Result);
4203 // Push the new instruction and any users onto the worklist.
4204 WorkList.push_back(Result);
4205 AddUsersToWorkList(*Result);
4207 // Move the name to the new instruction first...
4208 std::string OldName = I->getName(); I->setName("");
4209 Result->setName(OldName);
4211 // Insert the new instruction into the basic block...
4212 BasicBlock *InstParent = I->getParent();
4213 BasicBlock::iterator InsertPos = I;
4215 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
4216 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
4219 InstParent->getInstList().insert(InsertPos, Result);
4221 // Make sure that we reprocess all operands now that we reduced their
4223 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
4224 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
4225 WorkList.push_back(OpI);
4227 // Instructions can end up on the worklist more than once. Make sure
4228 // we do not process an instruction that has been deleted.
4229 removeFromWorkList(I);
4231 // Erase the old instruction.
4232 InstParent->getInstList().erase(I);
4234 DEBUG(std::cerr << "IC: MOD = " << *I);
4236 // If the instruction was modified, it's possible that it is now dead.
4237 // if so, remove it.
4238 if (isInstructionTriviallyDead(I)) {
4239 // Make sure we process all operands now that we are reducing their
4241 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
4242 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
4243 WorkList.push_back(OpI);
4245 // Instructions may end up in the worklist more than once. Erase all
4246 // occurrances of this instruction.
4247 removeFromWorkList(I);
4248 I->getParent()->getInstList().erase(I);
4250 WorkList.push_back(Result);
4251 AddUsersToWorkList(*Result);
4261 FunctionPass *llvm::createInstructionCombiningPass() {
4262 return new InstCombiner();