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/Debug.h"
47 #include "llvm/Support/GetElementPtrTypeIterator.h"
48 #include "llvm/Support/InstVisitor.h"
49 #include "llvm/Support/MathExtras.h"
50 #include "llvm/Support/PatternMatch.h"
51 #include "llvm/ADT/DepthFirstIterator.h"
52 #include "llvm/ADT/Statistic.h"
53 #include "llvm/ADT/STLExtras.h"
57 using namespace llvm::PatternMatch;
60 Statistic<> NumCombined ("instcombine", "Number of insts combined");
61 Statistic<> NumConstProp("instcombine", "Number of constant folds");
62 Statistic<> NumDeadInst ("instcombine", "Number of dead inst eliminated");
63 Statistic<> NumDeadStore("instcombine", "Number of dead stores eliminated");
64 Statistic<> NumSunkInst ("instcombine", "Number of instructions sunk");
66 class InstCombiner : public FunctionPass,
67 public InstVisitor<InstCombiner, Instruction*> {
68 // Worklist of all of the instructions that need to be simplified.
69 std::vector<Instruction*> WorkList;
72 /// AddUsersToWorkList - When an instruction is simplified, add all users of
73 /// the instruction to the work lists because they might get more simplified
76 void AddUsersToWorkList(Value &I) {
77 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
79 WorkList.push_back(cast<Instruction>(*UI));
82 /// AddUsesToWorkList - When an instruction is simplified, add operands to
83 /// the work lists because they might get more simplified now.
85 void AddUsesToWorkList(Instruction &I) {
86 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
87 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
88 WorkList.push_back(Op);
91 // removeFromWorkList - remove all instances of I from the worklist.
92 void removeFromWorkList(Instruction *I);
94 virtual bool runOnFunction(Function &F);
96 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
97 AU.addRequired<TargetData>();
101 TargetData &getTargetData() const { return *TD; }
103 // Visitation implementation - Implement instruction combining for different
104 // instruction types. The semantics are as follows:
106 // null - No change was made
107 // I - Change was made, I is still valid, I may be dead though
108 // otherwise - Change was made, replace I with returned instruction
110 Instruction *visitAdd(BinaryOperator &I);
111 Instruction *visitSub(BinaryOperator &I);
112 Instruction *visitMul(BinaryOperator &I);
113 Instruction *visitDiv(BinaryOperator &I);
114 Instruction *visitRem(BinaryOperator &I);
115 Instruction *visitAnd(BinaryOperator &I);
116 Instruction *visitOr (BinaryOperator &I);
117 Instruction *visitXor(BinaryOperator &I);
118 Instruction *visitSetCondInst(SetCondInst &I);
119 Instruction *visitSetCondInstWithCastAndCast(SetCondInst &SCI);
121 Instruction *FoldGEPSetCC(User *GEPLHS, Value *RHS,
122 Instruction::BinaryOps Cond, Instruction &I);
123 Instruction *visitShiftInst(ShiftInst &I);
124 Instruction *FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
126 Instruction *visitCastInst(CastInst &CI);
127 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
129 Instruction *visitSelectInst(SelectInst &CI);
130 Instruction *visitCallInst(CallInst &CI);
131 Instruction *visitInvokeInst(InvokeInst &II);
132 Instruction *visitPHINode(PHINode &PN);
133 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
134 Instruction *visitAllocationInst(AllocationInst &AI);
135 Instruction *visitFreeInst(FreeInst &FI);
136 Instruction *visitLoadInst(LoadInst &LI);
137 Instruction *visitStoreInst(StoreInst &SI);
138 Instruction *visitBranchInst(BranchInst &BI);
139 Instruction *visitSwitchInst(SwitchInst &SI);
140 Instruction *visitExtractElementInst(ExtractElementInst &EI);
141 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
143 // visitInstruction - Specify what to return for unhandled instructions...
144 Instruction *visitInstruction(Instruction &I) { return 0; }
147 Instruction *visitCallSite(CallSite CS);
148 bool transformConstExprCastCall(CallSite CS);
151 // InsertNewInstBefore - insert an instruction New before instruction Old
152 // in the program. Add the new instruction to the worklist.
154 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
155 assert(New && New->getParent() == 0 &&
156 "New instruction already inserted into a basic block!");
157 BasicBlock *BB = Old.getParent();
158 BB->getInstList().insert(&Old, New); // Insert inst
159 WorkList.push_back(New); // Add to worklist
163 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
164 /// This also adds the cast to the worklist. Finally, this returns the
166 Value *InsertCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
167 if (V->getType() == Ty) return V;
169 if (Constant *CV = dyn_cast<Constant>(V))
170 return ConstantExpr::getCast(CV, Ty);
172 Instruction *C = new CastInst(V, Ty, V->getName(), &Pos);
173 WorkList.push_back(C);
177 // ReplaceInstUsesWith - This method is to be used when an instruction is
178 // found to be dead, replacable with another preexisting expression. Here
179 // we add all uses of I to the worklist, replace all uses of I with the new
180 // value, then return I, so that the inst combiner will know that I was
183 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
184 AddUsersToWorkList(I); // Add all modified instrs to worklist
186 I.replaceAllUsesWith(V);
189 // If we are replacing the instruction with itself, this must be in a
190 // segment of unreachable code, so just clobber the instruction.
191 I.replaceAllUsesWith(UndefValue::get(I.getType()));
196 // UpdateValueUsesWith - This method is to be used when an value is
197 // found to be replacable with another preexisting expression or was
198 // updated. Here we add all uses of I to the worklist, replace all uses of
199 // I with the new value (unless the instruction was just updated), then
200 // return true, so that the inst combiner will know that I was modified.
202 bool UpdateValueUsesWith(Value *Old, Value *New) {
203 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
205 Old->replaceAllUsesWith(New);
206 if (Instruction *I = dyn_cast<Instruction>(Old))
207 WorkList.push_back(I);
208 if (Instruction *I = dyn_cast<Instruction>(New))
209 WorkList.push_back(I);
213 // EraseInstFromFunction - When dealing with an instruction that has side
214 // effects or produces a void value, we can't rely on DCE to delete the
215 // instruction. Instead, visit methods should return the value returned by
217 Instruction *EraseInstFromFunction(Instruction &I) {
218 assert(I.use_empty() && "Cannot erase instruction that is used!");
219 AddUsesToWorkList(I);
220 removeFromWorkList(&I);
222 return 0; // Don't do anything with FI
226 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
227 /// InsertBefore instruction. This is specialized a bit to avoid inserting
228 /// casts that are known to not do anything...
230 Value *InsertOperandCastBefore(Value *V, const Type *DestTy,
231 Instruction *InsertBefore);
233 // SimplifyCommutative - This performs a few simplifications for commutative
235 bool SimplifyCommutative(BinaryOperator &I);
237 bool SimplifyDemandedBits(Value *V, uint64_t Mask,
238 uint64_t &KnownZero, uint64_t &KnownOne,
241 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
242 // PHI node as operand #0, see if we can fold the instruction into the PHI
243 // (which is only possible if all operands to the PHI are constants).
244 Instruction *FoldOpIntoPhi(Instruction &I);
246 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
247 // operator and they all are only used by the PHI, PHI together their
248 // inputs, and do the operation once, to the result of the PHI.
249 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
251 Instruction *OptAndOp(Instruction *Op, ConstantIntegral *OpRHS,
252 ConstantIntegral *AndRHS, BinaryOperator &TheAnd);
254 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantIntegral *Mask,
255 bool isSub, Instruction &I);
256 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
257 bool Inside, Instruction &IB);
258 Instruction *PromoteCastOfAllocation(CastInst &CI, AllocationInst &AI);
261 RegisterOpt<InstCombiner> X("instcombine", "Combine redundant instructions");
264 // getComplexity: Assign a complexity or rank value to LLVM Values...
265 // 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
266 static unsigned getComplexity(Value *V) {
267 if (isa<Instruction>(V)) {
268 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
272 if (isa<Argument>(V)) return 3;
273 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
276 // isOnlyUse - Return true if this instruction will be deleted if we stop using
278 static bool isOnlyUse(Value *V) {
279 return V->hasOneUse() || isa<Constant>(V);
282 // getPromotedType - Return the specified type promoted as it would be to pass
283 // though a va_arg area...
284 static const Type *getPromotedType(const Type *Ty) {
285 switch (Ty->getTypeID()) {
286 case Type::SByteTyID:
287 case Type::ShortTyID: return Type::IntTy;
288 case Type::UByteTyID:
289 case Type::UShortTyID: return Type::UIntTy;
290 case Type::FloatTyID: return Type::DoubleTy;
295 /// isCast - If the specified operand is a CastInst or a constant expr cast,
296 /// return the operand value, otherwise return null.
297 static Value *isCast(Value *V) {
298 if (CastInst *I = dyn_cast<CastInst>(V))
299 return I->getOperand(0);
300 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
301 if (CE->getOpcode() == Instruction::Cast)
302 return CE->getOperand(0);
306 // SimplifyCommutative - This performs a few simplifications for commutative
309 // 1. Order operands such that they are listed from right (least complex) to
310 // left (most complex). This puts constants before unary operators before
313 // 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
314 // 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
316 bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
317 bool Changed = false;
318 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
319 Changed = !I.swapOperands();
321 if (!I.isAssociative()) return Changed;
322 Instruction::BinaryOps Opcode = I.getOpcode();
323 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
324 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
325 if (isa<Constant>(I.getOperand(1))) {
326 Constant *Folded = ConstantExpr::get(I.getOpcode(),
327 cast<Constant>(I.getOperand(1)),
328 cast<Constant>(Op->getOperand(1)));
329 I.setOperand(0, Op->getOperand(0));
330 I.setOperand(1, Folded);
332 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
333 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
334 isOnlyUse(Op) && isOnlyUse(Op1)) {
335 Constant *C1 = cast<Constant>(Op->getOperand(1));
336 Constant *C2 = cast<Constant>(Op1->getOperand(1));
338 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
339 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
340 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
343 WorkList.push_back(New);
344 I.setOperand(0, New);
345 I.setOperand(1, Folded);
352 // dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
353 // if the LHS is a constant zero (which is the 'negate' form).
355 static inline Value *dyn_castNegVal(Value *V) {
356 if (BinaryOperator::isNeg(V))
357 return BinaryOperator::getNegArgument(V);
359 // Constants can be considered to be negated values if they can be folded.
360 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
361 return ConstantExpr::getNeg(C);
365 static inline Value *dyn_castNotVal(Value *V) {
366 if (BinaryOperator::isNot(V))
367 return BinaryOperator::getNotArgument(V);
369 // Constants can be considered to be not'ed values...
370 if (ConstantIntegral *C = dyn_cast<ConstantIntegral>(V))
371 return ConstantExpr::getNot(C);
375 // dyn_castFoldableMul - If this value is a multiply that can be folded into
376 // other computations (because it has a constant operand), return the
377 // non-constant operand of the multiply, and set CST to point to the multiplier.
378 // Otherwise, return null.
380 static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
381 if (V->hasOneUse() && V->getType()->isInteger())
382 if (Instruction *I = dyn_cast<Instruction>(V)) {
383 if (I->getOpcode() == Instruction::Mul)
384 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
385 return I->getOperand(0);
386 if (I->getOpcode() == Instruction::Shl)
387 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
388 // The multiplier is really 1 << CST.
389 Constant *One = ConstantInt::get(V->getType(), 1);
390 CST = cast<ConstantInt>(ConstantExpr::getShl(One, CST));
391 return I->getOperand(0);
397 /// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
398 /// expression, return it.
399 static User *dyn_castGetElementPtr(Value *V) {
400 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
401 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
402 if (CE->getOpcode() == Instruction::GetElementPtr)
403 return cast<User>(V);
407 // AddOne, SubOne - Add or subtract a constant one from an integer constant...
408 static ConstantInt *AddOne(ConstantInt *C) {
409 return cast<ConstantInt>(ConstantExpr::getAdd(C,
410 ConstantInt::get(C->getType(), 1)));
412 static ConstantInt *SubOne(ConstantInt *C) {
413 return cast<ConstantInt>(ConstantExpr::getSub(C,
414 ConstantInt::get(C->getType(), 1)));
417 /// GetConstantInType - Return a ConstantInt with the specified type and value.
419 static ConstantIntegral *GetConstantInType(const Type *Ty, uint64_t Val) {
420 if (Ty->isUnsigned())
421 return ConstantUInt::get(Ty, Val);
422 else if (Ty->getTypeID() == Type::BoolTyID)
423 return ConstantBool::get(Val);
425 SVal <<= 64-Ty->getPrimitiveSizeInBits();
426 SVal >>= 64-Ty->getPrimitiveSizeInBits();
427 return ConstantSInt::get(Ty, SVal);
431 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
432 /// known to be either zero or one and return them in the KnownZero/KnownOne
433 /// bitsets. This code only analyzes bits in Mask, in order to short-circuit
435 static void ComputeMaskedBits(Value *V, uint64_t Mask, uint64_t &KnownZero,
436 uint64_t &KnownOne, unsigned Depth = 0) {
437 // Note, we cannot consider 'undef' to be "IsZero" here. The problem is that
438 // we cannot optimize based on the assumption that it is zero without changing
439 // it to be an explicit zero. If we don't change it to zero, other code could
440 // optimized based on the contradictory assumption that it is non-zero.
441 // Because instcombine aggressively folds operations with undef args anyway,
442 // this won't lose us code quality.
443 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
444 // We know all of the bits for a constant!
445 KnownOne = CI->getZExtValue() & Mask;
446 KnownZero = ~KnownOne & Mask;
450 KnownZero = KnownOne = 0; // Don't know anything.
451 if (Depth == 6 || Mask == 0)
452 return; // Limit search depth.
454 uint64_t KnownZero2, KnownOne2;
455 Instruction *I = dyn_cast<Instruction>(V);
458 switch (I->getOpcode()) {
459 case Instruction::And:
460 // If either the LHS or the RHS are Zero, the result is zero.
461 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
463 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
464 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
465 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
467 // Output known-1 bits are only known if set in both the LHS & RHS.
468 KnownOne &= KnownOne2;
469 // Output known-0 are known to be clear if zero in either the LHS | RHS.
470 KnownZero |= KnownZero2;
472 case Instruction::Or:
473 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
475 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
476 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
477 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
479 // Output known-0 bits are only known if clear in both the LHS & RHS.
480 KnownZero &= KnownZero2;
481 // Output known-1 are known to be set if set in either the LHS | RHS.
482 KnownOne |= KnownOne2;
484 case Instruction::Xor: {
485 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
486 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
487 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
488 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
490 // Output known-0 bits are known if clear or set in both the LHS & RHS.
491 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
492 // Output known-1 are known to be set if set in only one of the LHS, RHS.
493 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
494 KnownZero = KnownZeroOut;
497 case Instruction::Select:
498 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
499 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
500 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
501 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
503 // Only known if known in both the LHS and RHS.
504 KnownOne &= KnownOne2;
505 KnownZero &= KnownZero2;
507 case Instruction::Cast: {
508 const Type *SrcTy = I->getOperand(0)->getType();
509 if (!SrcTy->isIntegral()) return;
511 // If this is an integer truncate or noop, just look in the input.
512 if (SrcTy->getPrimitiveSizeInBits() >=
513 I->getType()->getPrimitiveSizeInBits()) {
514 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
518 // Sign or Zero extension. Compute the bits in the result that are not
519 // present in the input.
520 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
521 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
523 // Handle zero extension.
524 if (!SrcTy->isSigned()) {
525 Mask &= SrcTy->getIntegralTypeMask();
526 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
527 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
528 // The top bits are known to be zero.
529 KnownZero |= NewBits;
532 Mask &= SrcTy->getIntegralTypeMask();
533 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
534 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
536 // If the sign bit of the input is known set or clear, then we know the
537 // top bits of the result.
538 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
539 if (KnownZero & InSignBit) { // Input sign bit known zero
540 KnownZero |= NewBits;
541 KnownOne &= ~NewBits;
542 } else if (KnownOne & InSignBit) { // Input sign bit known set
544 KnownZero &= ~NewBits;
545 } else { // Input sign bit unknown
546 KnownZero &= ~NewBits;
547 KnownOne &= ~NewBits;
552 case Instruction::Shl:
553 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
554 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
555 Mask >>= SA->getValue();
556 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
557 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
558 KnownZero <<= SA->getValue();
559 KnownOne <<= SA->getValue();
560 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
564 case Instruction::Shr:
565 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
566 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
567 // Compute the new bits that are at the top now.
568 uint64_t HighBits = (1ULL << SA->getValue())-1;
569 HighBits <<= I->getType()->getPrimitiveSizeInBits()-SA->getValue();
571 if (I->getType()->isUnsigned()) { // Unsigned shift right.
572 Mask <<= SA->getValue();
573 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
574 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
575 KnownZero >>= SA->getValue();
576 KnownOne >>= SA->getValue();
577 KnownZero |= HighBits; // high bits known zero.
579 Mask <<= SA->getValue();
580 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero,KnownOne,Depth+1);
581 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
582 KnownZero >>= SA->getValue();
583 KnownOne >>= SA->getValue();
585 // Handle the sign bits.
586 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
587 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
589 if (KnownZero & SignBit) { // New bits are known zero.
590 KnownZero |= HighBits;
591 } else if (KnownOne & SignBit) { // New bits are known one.
592 KnownOne |= HighBits;
601 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
602 /// this predicate to simplify operations downstream. Mask is known to be zero
603 /// for bits that V cannot have.
604 static bool MaskedValueIsZero(Value *V, uint64_t Mask, unsigned Depth = 0) {
605 uint64_t KnownZero, KnownOne;
606 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
607 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
608 return (KnownZero & Mask) == Mask;
611 /// ShrinkDemandedConstant - Check to see if the specified operand of the
612 /// specified instruction is a constant integer. If so, check to see if there
613 /// are any bits set in the constant that are not demanded. If so, shrink the
614 /// constant and return true.
615 static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
617 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
618 if (!OpC) return false;
620 // If there are no bits set that aren't demanded, nothing to do.
621 if ((~Demanded & OpC->getZExtValue()) == 0)
624 // This is producing any bits that are not needed, shrink the RHS.
625 uint64_t Val = Demanded & OpC->getZExtValue();
626 I->setOperand(OpNo, GetConstantInType(OpC->getType(), Val));
630 // ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
631 // set of known zero and one bits, compute the maximum and minimum values that
632 // could have the specified known zero and known one bits, returning them in
634 static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
637 int64_t &Min, int64_t &Max) {
638 uint64_t TypeBits = Ty->getIntegralTypeMask();
639 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
641 uint64_t SignBit = 1ULL << (Ty->getPrimitiveSizeInBits()-1);
643 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
644 // bit if it is unknown.
646 Max = KnownOne|UnknownBits;
648 if (SignBit & UnknownBits) { // Sign bit is unknown
653 // Sign extend the min/max values.
654 int ShAmt = 64-Ty->getPrimitiveSizeInBits();
655 Min = (Min << ShAmt) >> ShAmt;
656 Max = (Max << ShAmt) >> ShAmt;
659 // ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
660 // a set of known zero and one bits, compute the maximum and minimum values that
661 // could have the specified known zero and known one bits, returning them in
663 static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
668 uint64_t TypeBits = Ty->getIntegralTypeMask();
669 uint64_t UnknownBits = ~(KnownZero|KnownOne) & TypeBits;
671 // The minimum value is when the unknown bits are all zeros.
673 // The maximum value is when the unknown bits are all ones.
674 Max = KnownOne|UnknownBits;
678 /// SimplifyDemandedBits - Look at V. At this point, we know that only the
679 /// DemandedMask bits of the result of V are ever used downstream. If we can
680 /// use this information to simplify V, do so and return true. Otherwise,
681 /// analyze the expression and return a mask of KnownOne and KnownZero bits for
682 /// the expression (used to simplify the caller). The KnownZero/One bits may
683 /// only be accurate for those bits in the DemandedMask.
684 bool InstCombiner::SimplifyDemandedBits(Value *V, uint64_t DemandedMask,
685 uint64_t &KnownZero, uint64_t &KnownOne,
687 if (ConstantIntegral *CI = dyn_cast<ConstantIntegral>(V)) {
688 // We know all of the bits for a constant!
689 KnownOne = CI->getZExtValue() & DemandedMask;
690 KnownZero = ~KnownOne & DemandedMask;
694 KnownZero = KnownOne = 0;
695 if (!V->hasOneUse()) { // Other users may use these bits.
696 if (Depth != 0) { // Not at the root.
697 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
698 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
701 // If this is the root being simplified, allow it to have multiple uses,
702 // just set the DemandedMask to all bits.
703 DemandedMask = V->getType()->getIntegralTypeMask();
704 } else if (DemandedMask == 0) { // Not demanding any bits from V.
705 if (V != UndefValue::get(V->getType()))
706 return UpdateValueUsesWith(V, UndefValue::get(V->getType()));
708 } else if (Depth == 6) { // Limit search depth.
712 Instruction *I = dyn_cast<Instruction>(V);
713 if (!I) return false; // Only analyze instructions.
715 uint64_t KnownZero2, KnownOne2;
716 switch (I->getOpcode()) {
718 case Instruction::And:
719 // If either the LHS or the RHS are Zero, the result is zero.
720 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
721 KnownZero, KnownOne, Depth+1))
723 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
725 // If something is known zero on the RHS, the bits aren't demanded on the
727 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownZero,
728 KnownZero2, KnownOne2, Depth+1))
730 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
732 // If all of the demanded bits are known one on one side, return the other.
733 // These bits cannot contribute to the result of the 'and'.
734 if ((DemandedMask & ~KnownZero2 & KnownOne) == (DemandedMask & ~KnownZero2))
735 return UpdateValueUsesWith(I, I->getOperand(0));
736 if ((DemandedMask & ~KnownZero & KnownOne2) == (DemandedMask & ~KnownZero))
737 return UpdateValueUsesWith(I, I->getOperand(1));
739 // If all of the demanded bits in the inputs are known zeros, return zero.
740 if ((DemandedMask & (KnownZero|KnownZero2)) == DemandedMask)
741 return UpdateValueUsesWith(I, Constant::getNullValue(I->getType()));
743 // If the RHS is a constant, see if we can simplify it.
744 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~KnownZero2))
745 return UpdateValueUsesWith(I, I);
747 // Output known-1 bits are only known if set in both the LHS & RHS.
748 KnownOne &= KnownOne2;
749 // Output known-0 are known to be clear if zero in either the LHS | RHS.
750 KnownZero |= KnownZero2;
752 case Instruction::Or:
753 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
754 KnownZero, KnownOne, Depth+1))
756 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
757 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~KnownOne,
758 KnownZero2, KnownOne2, Depth+1))
760 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
762 // If all of the demanded bits are known zero on one side, return the other.
763 // These bits cannot contribute to the result of the 'or'.
764 if ((DemandedMask & ~KnownOne2 & KnownZero) == (DemandedMask & ~KnownOne2))
765 return UpdateValueUsesWith(I, I->getOperand(0));
766 if ((DemandedMask & ~KnownOne & KnownZero2) == (DemandedMask & ~KnownOne))
767 return UpdateValueUsesWith(I, I->getOperand(1));
769 // If all of the potentially set bits on one side are known to be set on
770 // the other side, just use the 'other' side.
771 if ((DemandedMask & (~KnownZero) & KnownOne2) ==
772 (DemandedMask & (~KnownZero)))
773 return UpdateValueUsesWith(I, I->getOperand(0));
774 if ((DemandedMask & (~KnownZero2) & KnownOne) ==
775 (DemandedMask & (~KnownZero2)))
776 return UpdateValueUsesWith(I, I->getOperand(1));
778 // If the RHS is a constant, see if we can simplify it.
779 if (ShrinkDemandedConstant(I, 1, DemandedMask))
780 return UpdateValueUsesWith(I, I);
782 // Output known-0 bits are only known if clear in both the LHS & RHS.
783 KnownZero &= KnownZero2;
784 // Output known-1 are known to be set if set in either the LHS | RHS.
785 KnownOne |= KnownOne2;
787 case Instruction::Xor: {
788 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
789 KnownZero, KnownOne, Depth+1))
791 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
792 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
793 KnownZero2, KnownOne2, Depth+1))
795 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
797 // If all of the demanded bits are known zero on one side, return the other.
798 // These bits cannot contribute to the result of the 'xor'.
799 if ((DemandedMask & KnownZero) == DemandedMask)
800 return UpdateValueUsesWith(I, I->getOperand(0));
801 if ((DemandedMask & KnownZero2) == DemandedMask)
802 return UpdateValueUsesWith(I, I->getOperand(1));
804 // Output known-0 bits are known if clear or set in both the LHS & RHS.
805 uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
806 // Output known-1 are known to be set if set in only one of the LHS, RHS.
807 uint64_t KnownOneOut = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
809 // If all of the unknown bits are known to be zero on one side or the other
810 // (but not both) turn this into an *inclusive* or.
811 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
812 if (uint64_t UnknownBits = DemandedMask & ~(KnownZeroOut|KnownOneOut)) {
813 if ((UnknownBits & (KnownZero|KnownZero2)) == UnknownBits) {
815 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
817 InsertNewInstBefore(Or, *I);
818 return UpdateValueUsesWith(I, Or);
822 // If all of the demanded bits on one side are known, and all of the set
823 // bits on that side are also known to be set on the other side, turn this
824 // into an AND, as we know the bits will be cleared.
825 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
826 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask) { // all known
827 if ((KnownOne & KnownOne2) == KnownOne) {
828 Constant *AndC = GetConstantInType(I->getType(),
829 ~KnownOne & DemandedMask);
831 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
832 InsertNewInstBefore(And, *I);
833 return UpdateValueUsesWith(I, And);
837 // If the RHS is a constant, see if we can simplify it.
838 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
839 if (ShrinkDemandedConstant(I, 1, DemandedMask))
840 return UpdateValueUsesWith(I, I);
842 KnownZero = KnownZeroOut;
843 KnownOne = KnownOneOut;
846 case Instruction::Select:
847 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
848 KnownZero, KnownOne, Depth+1))
850 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
851 KnownZero2, KnownOne2, Depth+1))
853 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
854 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
856 // If the operands are constants, see if we can simplify them.
857 if (ShrinkDemandedConstant(I, 1, DemandedMask))
858 return UpdateValueUsesWith(I, I);
859 if (ShrinkDemandedConstant(I, 2, DemandedMask))
860 return UpdateValueUsesWith(I, I);
862 // Only known if known in both the LHS and RHS.
863 KnownOne &= KnownOne2;
864 KnownZero &= KnownZero2;
866 case Instruction::Cast: {
867 const Type *SrcTy = I->getOperand(0)->getType();
868 if (!SrcTy->isIntegral()) return false;
870 // If this is an integer truncate or noop, just look in the input.
871 if (SrcTy->getPrimitiveSizeInBits() >=
872 I->getType()->getPrimitiveSizeInBits()) {
873 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
874 KnownZero, KnownOne, Depth+1))
876 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
880 // Sign or Zero extension. Compute the bits in the result that are not
881 // present in the input.
882 uint64_t NotIn = ~SrcTy->getIntegralTypeMask();
883 uint64_t NewBits = I->getType()->getIntegralTypeMask() & NotIn;
885 // Handle zero extension.
886 if (!SrcTy->isSigned()) {
887 DemandedMask &= SrcTy->getIntegralTypeMask();
888 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
889 KnownZero, KnownOne, Depth+1))
891 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
892 // The top bits are known to be zero.
893 KnownZero |= NewBits;
896 uint64_t InSignBit = 1ULL << (SrcTy->getPrimitiveSizeInBits()-1);
897 int64_t InputDemandedBits = DemandedMask & SrcTy->getIntegralTypeMask();
899 // If any of the sign extended bits are demanded, we know that the sign
901 if (NewBits & DemandedMask)
902 InputDemandedBits |= InSignBit;
904 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
905 KnownZero, KnownOne, Depth+1))
907 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
909 // If the sign bit of the input is known set or clear, then we know the
910 // top bits of the result.
912 // If the input sign bit is known zero, or if the NewBits are not demanded
913 // convert this into a zero extension.
914 if ((KnownZero & InSignBit) || (NewBits & ~DemandedMask) == NewBits) {
915 // Convert to unsigned first.
917 NewVal = new CastInst(I->getOperand(0), SrcTy->getUnsignedVersion(),
918 I->getOperand(0)->getName());
919 InsertNewInstBefore(NewVal, *I);
920 // Then cast that to the destination type.
921 NewVal = new CastInst(NewVal, I->getType(), I->getName());
922 InsertNewInstBefore(NewVal, *I);
923 return UpdateValueUsesWith(I, NewVal);
924 } else if (KnownOne & InSignBit) { // Input sign bit known set
926 KnownZero &= ~NewBits;
927 } else { // Input sign bit unknown
928 KnownZero &= ~NewBits;
929 KnownOne &= ~NewBits;
934 case Instruction::Shl:
935 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
936 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask >> SA->getValue(),
937 KnownZero, KnownOne, Depth+1))
939 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
940 KnownZero <<= SA->getValue();
941 KnownOne <<= SA->getValue();
942 KnownZero |= (1ULL << SA->getValue())-1; // low bits known zero.
945 case Instruction::Shr:
946 if (ConstantUInt *SA = dyn_cast<ConstantUInt>(I->getOperand(1))) {
947 unsigned ShAmt = SA->getValue();
949 // Compute the new bits that are at the top now.
950 uint64_t HighBits = (1ULL << ShAmt)-1;
951 HighBits <<= I->getType()->getPrimitiveSizeInBits() - ShAmt;
952 uint64_t TypeMask = I->getType()->getIntegralTypeMask();
953 if (I->getType()->isUnsigned()) { // Unsigned shift right.
954 if (SimplifyDemandedBits(I->getOperand(0),
955 (DemandedMask << ShAmt) & TypeMask,
956 KnownZero, KnownOne, Depth+1))
958 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
959 KnownZero &= TypeMask;
960 KnownOne &= TypeMask;
963 KnownZero |= HighBits; // high bits known zero.
964 } else { // Signed shift right.
965 if (SimplifyDemandedBits(I->getOperand(0),
966 (DemandedMask << ShAmt) & TypeMask,
967 KnownZero, KnownOne, Depth+1))
969 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
970 KnownZero &= TypeMask;
971 KnownOne &= TypeMask;
972 KnownZero >>= SA->getValue();
973 KnownOne >>= SA->getValue();
975 // Handle the sign bits.
976 uint64_t SignBit = 1ULL << (I->getType()->getPrimitiveSizeInBits()-1);
977 SignBit >>= SA->getValue(); // Adjust to where it is now in the mask.
979 // If the input sign bit is known to be zero, or if none of the top bits
980 // are demanded, turn this into an unsigned shift right.
981 if ((KnownZero & SignBit) || (HighBits & ~DemandedMask) == HighBits) {
982 // Convert the input to unsigned.
984 NewVal = new CastInst(I->getOperand(0),
985 I->getType()->getUnsignedVersion(),
986 I->getOperand(0)->getName());
987 InsertNewInstBefore(NewVal, *I);
988 // Perform the unsigned shift right.
989 NewVal = new ShiftInst(Instruction::Shr, NewVal, SA, I->getName());
990 InsertNewInstBefore(NewVal, *I);
991 // Then cast that to the destination type.
992 NewVal = new CastInst(NewVal, I->getType(), I->getName());
993 InsertNewInstBefore(NewVal, *I);
994 return UpdateValueUsesWith(I, NewVal);
995 } else if (KnownOne & SignBit) { // New bits are known one.
996 KnownOne |= HighBits;
1003 // If the client is only demanding bits that we know, return the known
1005 if ((DemandedMask & (KnownZero|KnownOne)) == DemandedMask)
1006 return UpdateValueUsesWith(I, GetConstantInType(I->getType(), KnownOne));
1010 // isTrueWhenEqual - Return true if the specified setcondinst instruction is
1011 // true when both operands are equal...
1013 static bool isTrueWhenEqual(Instruction &I) {
1014 return I.getOpcode() == Instruction::SetEQ ||
1015 I.getOpcode() == Instruction::SetGE ||
1016 I.getOpcode() == Instruction::SetLE;
1019 /// AssociativeOpt - Perform an optimization on an associative operator. This
1020 /// function is designed to check a chain of associative operators for a
1021 /// potential to apply a certain optimization. Since the optimization may be
1022 /// applicable if the expression was reassociated, this checks the chain, then
1023 /// reassociates the expression as necessary to expose the optimization
1024 /// opportunity. This makes use of a special Functor, which must define
1025 /// 'shouldApply' and 'apply' methods.
1027 template<typename Functor>
1028 Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1029 unsigned Opcode = Root.getOpcode();
1030 Value *LHS = Root.getOperand(0);
1032 // Quick check, see if the immediate LHS matches...
1033 if (F.shouldApply(LHS))
1034 return F.apply(Root);
1036 // Otherwise, if the LHS is not of the same opcode as the root, return.
1037 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1038 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1039 // Should we apply this transform to the RHS?
1040 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1042 // If not to the RHS, check to see if we should apply to the LHS...
1043 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1044 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1048 // If the functor wants to apply the optimization to the RHS of LHSI,
1049 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1051 BasicBlock *BB = Root.getParent();
1053 // Now all of the instructions are in the current basic block, go ahead
1054 // and perform the reassociation.
1055 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1057 // First move the selected RHS to the LHS of the root...
1058 Root.setOperand(0, LHSI->getOperand(1));
1060 // Make what used to be the LHS of the root be the user of the root...
1061 Value *ExtraOperand = TmpLHSI->getOperand(1);
1062 if (&Root == TmpLHSI) {
1063 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1066 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1067 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1068 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1069 BasicBlock::iterator ARI = &Root; ++ARI;
1070 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1073 // Now propagate the ExtraOperand down the chain of instructions until we
1075 while (TmpLHSI != LHSI) {
1076 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1077 // Move the instruction to immediately before the chain we are
1078 // constructing to avoid breaking dominance properties.
1079 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1080 BB->getInstList().insert(ARI, NextLHSI);
1083 Value *NextOp = NextLHSI->getOperand(1);
1084 NextLHSI->setOperand(1, ExtraOperand);
1086 ExtraOperand = NextOp;
1089 // Now that the instructions are reassociated, have the functor perform
1090 // the transformation...
1091 return F.apply(Root);
1094 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1100 // AddRHS - Implements: X + X --> X << 1
1103 AddRHS(Value *rhs) : RHS(rhs) {}
1104 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1105 Instruction *apply(BinaryOperator &Add) const {
1106 return new ShiftInst(Instruction::Shl, Add.getOperand(0),
1107 ConstantInt::get(Type::UByteTy, 1));
1111 // AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1113 struct AddMaskingAnd {
1115 AddMaskingAnd(Constant *c) : C2(c) {}
1116 bool shouldApply(Value *LHS) const {
1118 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1119 ConstantExpr::getAnd(C1, C2)->isNullValue();
1121 Instruction *apply(BinaryOperator &Add) const {
1122 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1126 static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1128 if (isa<CastInst>(I)) {
1129 if (Constant *SOC = dyn_cast<Constant>(SO))
1130 return ConstantExpr::getCast(SOC, I.getType());
1132 return IC->InsertNewInstBefore(new CastInst(SO, I.getType(),
1133 SO->getName() + ".cast"), I);
1136 // Figure out if the constant is the left or the right argument.
1137 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1138 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1140 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1142 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1143 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1146 Value *Op0 = SO, *Op1 = ConstOperand;
1148 std::swap(Op0, Op1);
1150 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1151 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1152 else if (ShiftInst *SI = dyn_cast<ShiftInst>(&I))
1153 New = new ShiftInst(SI->getOpcode(), Op0, Op1, SO->getName()+".sh");
1155 assert(0 && "Unknown binary instruction type!");
1158 return IC->InsertNewInstBefore(New, I);
1161 // FoldOpIntoSelect - Given an instruction with a select as one operand and a
1162 // constant as the other operand, try to fold the binary operator into the
1163 // select arguments. This also works for Cast instructions, which obviously do
1164 // not have a second operand.
1165 static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1167 // Don't modify shared select instructions
1168 if (!SI->hasOneUse()) return 0;
1169 Value *TV = SI->getOperand(1);
1170 Value *FV = SI->getOperand(2);
1172 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1173 // Bool selects with constant operands can be folded to logical ops.
1174 if (SI->getType() == Type::BoolTy) return 0;
1176 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1177 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1179 return new SelectInst(SI->getCondition(), SelectTrueVal,
1186 /// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1187 /// node as operand #0, see if we can fold the instruction into the PHI (which
1188 /// is only possible if all operands to the PHI are constants).
1189 Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1190 PHINode *PN = cast<PHINode>(I.getOperand(0));
1191 unsigned NumPHIValues = PN->getNumIncomingValues();
1192 if (!PN->hasOneUse() || NumPHIValues == 0 ||
1193 !isa<Constant>(PN->getIncomingValue(0))) return 0;
1195 // Check to see if all of the operands of the PHI are constants. If not, we
1196 // cannot do the transformation.
1197 for (unsigned i = 1; i != NumPHIValues; ++i)
1198 if (!isa<Constant>(PN->getIncomingValue(i)))
1201 // Okay, we can do the transformation: create the new PHI node.
1202 PHINode *NewPN = new PHINode(I.getType(), I.getName());
1204 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1205 InsertNewInstBefore(NewPN, *PN);
1207 // Next, add all of the operands to the PHI.
1208 if (I.getNumOperands() == 2) {
1209 Constant *C = cast<Constant>(I.getOperand(1));
1210 for (unsigned i = 0; i != NumPHIValues; ++i) {
1211 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1212 NewPN->addIncoming(ConstantExpr::get(I.getOpcode(), InV, C),
1213 PN->getIncomingBlock(i));
1216 assert(isa<CastInst>(I) && "Unary op should be a cast!");
1217 const Type *RetTy = I.getType();
1218 for (unsigned i = 0; i != NumPHIValues; ++i) {
1219 Constant *InV = cast<Constant>(PN->getIncomingValue(i));
1220 NewPN->addIncoming(ConstantExpr::getCast(InV, RetTy),
1221 PN->getIncomingBlock(i));
1224 return ReplaceInstUsesWith(I, NewPN);
1227 Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1228 bool Changed = SimplifyCommutative(I);
1229 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1231 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1232 // X + undef -> undef
1233 if (isa<UndefValue>(RHS))
1234 return ReplaceInstUsesWith(I, RHS);
1237 if (!I.getType()->isFloatingPoint()) { // NOTE: -0 + +0 = +0.
1238 if (RHSC->isNullValue())
1239 return ReplaceInstUsesWith(I, LHS);
1240 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
1241 if (CFP->isExactlyValue(-0.0))
1242 return ReplaceInstUsesWith(I, LHS);
1245 // X + (signbit) --> X ^ signbit
1246 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1247 uint64_t Val = CI->getZExtValue();
1248 if (Val == (1ULL << (CI->getType()->getPrimitiveSizeInBits()-1)))
1249 return BinaryOperator::createXor(LHS, RHS);
1252 if (isa<PHINode>(LHS))
1253 if (Instruction *NV = FoldOpIntoPhi(I))
1256 ConstantInt *XorRHS = 0;
1258 if (match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1259 unsigned TySizeBits = I.getType()->getPrimitiveSizeInBits();
1260 int64_t RHSSExt = cast<ConstantInt>(RHSC)->getSExtValue();
1261 uint64_t RHSZExt = cast<ConstantInt>(RHSC)->getZExtValue();
1263 uint64_t C0080Val = 1ULL << 31;
1264 int64_t CFF80Val = -C0080Val;
1267 if (TySizeBits > Size) {
1269 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1270 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1271 if (RHSSExt == CFF80Val) {
1272 if (XorRHS->getZExtValue() == C0080Val)
1274 } else if (RHSZExt == C0080Val) {
1275 if (XorRHS->getSExtValue() == CFF80Val)
1279 // This is a sign extend if the top bits are known zero.
1280 uint64_t Mask = ~0ULL;
1281 Mask <<= 64-(TySizeBits-Size);
1282 Mask &= XorLHS->getType()->getIntegralTypeMask();
1283 if (!MaskedValueIsZero(XorLHS, Mask))
1284 Size = 0; // Not a sign ext, but can't be any others either.
1291 } while (Size >= 8);
1294 const Type *MiddleType = 0;
1297 case 32: MiddleType = Type::IntTy; break;
1298 case 16: MiddleType = Type::ShortTy; break;
1299 case 8: MiddleType = Type::SByteTy; break;
1302 Instruction *NewTrunc = new CastInst(XorLHS, MiddleType, "sext");
1303 InsertNewInstBefore(NewTrunc, I);
1304 return new CastInst(NewTrunc, I.getType());
1310 if (I.getType()->isInteger()) {
1311 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
1313 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
1314 if (RHSI->getOpcode() == Instruction::Sub)
1315 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
1316 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
1318 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
1319 if (LHSI->getOpcode() == Instruction::Sub)
1320 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
1321 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
1326 if (Value *V = dyn_castNegVal(LHS))
1327 return BinaryOperator::createSub(RHS, V);
1330 if (!isa<Constant>(RHS))
1331 if (Value *V = dyn_castNegVal(RHS))
1332 return BinaryOperator::createSub(LHS, V);
1336 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
1337 if (X == RHS) // X*C + X --> X * (C+1)
1338 return BinaryOperator::createMul(RHS, AddOne(C2));
1340 // X*C1 + X*C2 --> X * (C1+C2)
1342 if (X == dyn_castFoldableMul(RHS, C1))
1343 return BinaryOperator::createMul(X, ConstantExpr::getAdd(C1, C2));
1346 // X + X*C --> X * (C+1)
1347 if (dyn_castFoldableMul(RHS, C2) == LHS)
1348 return BinaryOperator::createMul(LHS, AddOne(C2));
1351 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
1352 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
1353 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2))) return R;
1355 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
1357 if (match(LHS, m_Not(m_Value(X)))) { // ~X + C --> (C-1) - X
1358 Constant *C= ConstantExpr::getSub(CRHS, ConstantInt::get(I.getType(), 1));
1359 return BinaryOperator::createSub(C, X);
1362 // (X & FF00) + xx00 -> (X+xx00) & FF00
1363 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
1364 Constant *Anded = ConstantExpr::getAnd(CRHS, C2);
1365 if (Anded == CRHS) {
1366 // See if all bits from the first bit set in the Add RHS up are included
1367 // in the mask. First, get the rightmost bit.
1368 uint64_t AddRHSV = CRHS->getRawValue();
1370 // Form a mask of all bits from the lowest bit added through the top.
1371 uint64_t AddRHSHighBits = ~((AddRHSV & -AddRHSV)-1);
1372 AddRHSHighBits &= C2->getType()->getIntegralTypeMask();
1374 // See if the and mask includes all of these bits.
1375 uint64_t AddRHSHighBitsAnd = AddRHSHighBits & C2->getRawValue();
1377 if (AddRHSHighBits == AddRHSHighBitsAnd) {
1378 // Okay, the xform is safe. Insert the new add pronto.
1379 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
1380 LHS->getName()), I);
1381 return BinaryOperator::createAnd(NewAdd, C2);
1386 // Try to fold constant add into select arguments.
1387 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
1388 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1392 return Changed ? &I : 0;
1395 // isSignBit - Return true if the value represented by the constant only has the
1396 // highest order bit set.
1397 static bool isSignBit(ConstantInt *CI) {
1398 unsigned NumBits = CI->getType()->getPrimitiveSizeInBits();
1399 return (CI->getRawValue() & (~0ULL >> (64-NumBits))) == (1ULL << (NumBits-1));
1402 /// RemoveNoopCast - Strip off nonconverting casts from the value.
1404 static Value *RemoveNoopCast(Value *V) {
1405 if (CastInst *CI = dyn_cast<CastInst>(V)) {
1406 const Type *CTy = CI->getType();
1407 const Type *OpTy = CI->getOperand(0)->getType();
1408 if (CTy->isInteger() && OpTy->isInteger()) {
1409 if (CTy->getPrimitiveSizeInBits() == OpTy->getPrimitiveSizeInBits())
1410 return RemoveNoopCast(CI->getOperand(0));
1411 } else if (isa<PointerType>(CTy) && isa<PointerType>(OpTy))
1412 return RemoveNoopCast(CI->getOperand(0));
1417 Instruction *InstCombiner::visitSub(BinaryOperator &I) {
1418 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1420 if (Op0 == Op1) // sub X, X -> 0
1421 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1423 // If this is a 'B = x-(-A)', change to B = x+A...
1424 if (Value *V = dyn_castNegVal(Op1))
1425 return BinaryOperator::createAdd(Op0, V);
1427 if (isa<UndefValue>(Op0))
1428 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
1429 if (isa<UndefValue>(Op1))
1430 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
1432 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
1433 // Replace (-1 - A) with (~A)...
1434 if (C->isAllOnesValue())
1435 return BinaryOperator::createNot(Op1);
1437 // C - ~X == X + (1+C)
1439 if (match(Op1, m_Not(m_Value(X))))
1440 return BinaryOperator::createAdd(X,
1441 ConstantExpr::getAdd(C, ConstantInt::get(I.getType(), 1)));
1442 // -((uint)X >> 31) -> ((int)X >> 31)
1443 // -((int)X >> 31) -> ((uint)X >> 31)
1444 if (C->isNullValue()) {
1445 Value *NoopCastedRHS = RemoveNoopCast(Op1);
1446 if (ShiftInst *SI = dyn_cast<ShiftInst>(NoopCastedRHS))
1447 if (SI->getOpcode() == Instruction::Shr)
1448 if (ConstantUInt *CU = dyn_cast<ConstantUInt>(SI->getOperand(1))) {
1450 if (SI->getType()->isSigned())
1451 NewTy = SI->getType()->getUnsignedVersion();
1453 NewTy = SI->getType()->getSignedVersion();
1454 // Check to see if we are shifting out everything but the sign bit.
1455 if (CU->getValue() == SI->getType()->getPrimitiveSizeInBits()-1) {
1456 // Ok, the transformation is safe. Insert a cast of the incoming
1457 // value, then the new shift, then the new cast.
1458 Instruction *FirstCast = new CastInst(SI->getOperand(0), NewTy,
1459 SI->getOperand(0)->getName());
1460 Value *InV = InsertNewInstBefore(FirstCast, I);
1461 Instruction *NewShift = new ShiftInst(Instruction::Shr, FirstCast,
1463 if (NewShift->getType() == I.getType())
1466 InV = InsertNewInstBefore(NewShift, I);
1467 return new CastInst(NewShift, I.getType());
1473 // Try to fold constant sub into select arguments.
1474 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1475 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1478 if (isa<PHINode>(Op0))
1479 if (Instruction *NV = FoldOpIntoPhi(I))
1483 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
1484 if (Op1I->getOpcode() == Instruction::Add &&
1485 !Op0->getType()->isFloatingPoint()) {
1486 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
1487 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
1488 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
1489 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
1490 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
1491 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
1492 // C1-(X+C2) --> (C1-C2)-X
1493 return BinaryOperator::createSub(ConstantExpr::getSub(CI1, CI2),
1494 Op1I->getOperand(0));
1498 if (Op1I->hasOneUse()) {
1499 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
1500 // is not used by anyone else...
1502 if (Op1I->getOpcode() == Instruction::Sub &&
1503 !Op1I->getType()->isFloatingPoint()) {
1504 // Swap the two operands of the subexpr...
1505 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
1506 Op1I->setOperand(0, IIOp1);
1507 Op1I->setOperand(1, IIOp0);
1509 // Create the new top level add instruction...
1510 return BinaryOperator::createAdd(Op0, Op1);
1513 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
1515 if (Op1I->getOpcode() == Instruction::And &&
1516 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
1517 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
1520 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
1521 return BinaryOperator::createAnd(Op0, NewNot);
1524 // -(X sdiv C) -> (X sdiv -C)
1525 if (Op1I->getOpcode() == Instruction::Div)
1526 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
1527 if (CSI->isNullValue())
1528 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
1529 return BinaryOperator::createDiv(Op1I->getOperand(0),
1530 ConstantExpr::getNeg(DivRHS));
1532 // X - X*C --> X * (1-C)
1533 ConstantInt *C2 = 0;
1534 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
1536 ConstantExpr::getSub(ConstantInt::get(I.getType(), 1), C2);
1537 return BinaryOperator::createMul(Op0, CP1);
1542 if (!Op0->getType()->isFloatingPoint())
1543 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1544 if (Op0I->getOpcode() == Instruction::Add) {
1545 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
1546 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
1547 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
1548 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
1549 } else if (Op0I->getOpcode() == Instruction::Sub) {
1550 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
1551 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
1555 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
1556 if (X == Op1) { // X*C - X --> X * (C-1)
1557 Constant *CP1 = ConstantExpr::getSub(C1, ConstantInt::get(I.getType(),1));
1558 return BinaryOperator::createMul(Op1, CP1);
1561 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
1562 if (X == dyn_castFoldableMul(Op1, C2))
1563 return BinaryOperator::createMul(Op1, ConstantExpr::getSub(C1, C2));
1568 /// isSignBitCheck - Given an exploded setcc instruction, return true if it is
1569 /// really just returns true if the most significant (sign) bit is set.
1570 static bool isSignBitCheck(unsigned Opcode, Value *LHS, ConstantInt *RHS) {
1571 if (RHS->getType()->isSigned()) {
1572 // True if source is LHS < 0 or LHS <= -1
1573 return Opcode == Instruction::SetLT && RHS->isNullValue() ||
1574 Opcode == Instruction::SetLE && RHS->isAllOnesValue();
1576 ConstantUInt *RHSC = cast<ConstantUInt>(RHS);
1577 // True if source is LHS > 127 or LHS >= 128, where the constants depend on
1578 // the size of the integer type.
1579 if (Opcode == Instruction::SetGE)
1580 return RHSC->getValue() ==
1581 1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1);
1582 if (Opcode == Instruction::SetGT)
1583 return RHSC->getValue() ==
1584 (1ULL << (RHS->getType()->getPrimitiveSizeInBits()-1))-1;
1589 Instruction *InstCombiner::visitMul(BinaryOperator &I) {
1590 bool Changed = SimplifyCommutative(I);
1591 Value *Op0 = I.getOperand(0);
1593 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
1594 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1596 // Simplify mul instructions with a constant RHS...
1597 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
1598 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
1600 // ((X << C1)*C2) == (X * (C2 << C1))
1601 if (ShiftInst *SI = dyn_cast<ShiftInst>(Op0))
1602 if (SI->getOpcode() == Instruction::Shl)
1603 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
1604 return BinaryOperator::createMul(SI->getOperand(0),
1605 ConstantExpr::getShl(CI, ShOp));
1607 if (CI->isNullValue())
1608 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
1609 if (CI->equalsInt(1)) // X * 1 == X
1610 return ReplaceInstUsesWith(I, Op0);
1611 if (CI->isAllOnesValue()) // X * -1 == 0 - X
1612 return BinaryOperator::createNeg(Op0, I.getName());
1614 int64_t Val = (int64_t)cast<ConstantInt>(CI)->getRawValue();
1615 if (isPowerOf2_64(Val)) { // Replace X*(2^C) with X << C
1616 uint64_t C = Log2_64(Val);
1617 return new ShiftInst(Instruction::Shl, Op0,
1618 ConstantUInt::get(Type::UByteTy, C));
1620 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
1621 if (Op1F->isNullValue())
1622 return ReplaceInstUsesWith(I, Op1);
1624 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
1625 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
1626 if (Op1F->getValue() == 1.0)
1627 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
1630 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
1631 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
1632 isa<ConstantInt>(Op0I->getOperand(1))) {
1633 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
1634 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
1636 InsertNewInstBefore(Add, I);
1637 Value *C1C2 = ConstantExpr::getMul(Op1,
1638 cast<Constant>(Op0I->getOperand(1)));
1639 return BinaryOperator::createAdd(Add, C1C2);
1643 // Try to fold constant mul into select arguments.
1644 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1645 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1648 if (isa<PHINode>(Op0))
1649 if (Instruction *NV = FoldOpIntoPhi(I))
1653 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
1654 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
1655 return BinaryOperator::createMul(Op0v, Op1v);
1657 // If one of the operands of the multiply is a cast from a boolean value, then
1658 // we know the bool is either zero or one, so this is a 'masking' multiply.
1659 // See if we can simplify things based on how the boolean was originally
1661 CastInst *BoolCast = 0;
1662 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(0)))
1663 if (CI->getOperand(0)->getType() == Type::BoolTy)
1666 if (CastInst *CI = dyn_cast<CastInst>(I.getOperand(1)))
1667 if (CI->getOperand(0)->getType() == Type::BoolTy)
1670 if (SetCondInst *SCI = dyn_cast<SetCondInst>(BoolCast->getOperand(0))) {
1671 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
1672 const Type *SCOpTy = SCIOp0->getType();
1674 // If the setcc is true iff the sign bit of X is set, then convert this
1675 // multiply into a shift/and combination.
1676 if (isa<ConstantInt>(SCIOp1) &&
1677 isSignBitCheck(SCI->getOpcode(), SCIOp0, cast<ConstantInt>(SCIOp1))) {
1678 // Shift the X value right to turn it into "all signbits".
1679 Constant *Amt = ConstantUInt::get(Type::UByteTy,
1680 SCOpTy->getPrimitiveSizeInBits()-1);
1681 if (SCIOp0->getType()->isUnsigned()) {
1682 const Type *NewTy = SCIOp0->getType()->getSignedVersion();
1683 SCIOp0 = InsertNewInstBefore(new CastInst(SCIOp0, NewTy,
1684 SCIOp0->getName()), I);
1688 InsertNewInstBefore(new ShiftInst(Instruction::Shr, SCIOp0, Amt,
1689 BoolCast->getOperand(0)->getName()+
1692 // If the multiply type is not the same as the source type, sign extend
1693 // or truncate to the multiply type.
1694 if (I.getType() != V->getType())
1695 V = InsertNewInstBefore(new CastInst(V, I.getType(), V->getName()),I);
1697 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
1698 return BinaryOperator::createAnd(V, OtherOp);
1703 return Changed ? &I : 0;
1706 Instruction *InstCombiner::visitDiv(BinaryOperator &I) {
1707 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1709 if (isa<UndefValue>(Op0)) // undef / X -> 0
1710 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1711 if (isa<UndefValue>(Op1))
1712 return ReplaceInstUsesWith(I, Op1); // X / undef -> undef
1714 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1716 if (RHS->equalsInt(1))
1717 return ReplaceInstUsesWith(I, Op0);
1720 if (RHS->isAllOnesValue())
1721 return BinaryOperator::createNeg(Op0);
1723 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
1724 if (LHS->getOpcode() == Instruction::Div)
1725 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
1726 // (X / C1) / C2 -> X / (C1*C2)
1727 return BinaryOperator::createDiv(LHS->getOperand(0),
1728 ConstantExpr::getMul(RHS, LHSRHS));
1731 // Check to see if this is an unsigned division with an exact power of 2,
1732 // if so, convert to a right shift.
1733 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1734 if (uint64_t Val = C->getValue()) // Don't break X / 0
1735 if (isPowerOf2_64(Val)) {
1736 uint64_t C = Log2_64(Val);
1737 return new ShiftInst(Instruction::Shr, Op0,
1738 ConstantUInt::get(Type::UByteTy, C));
1742 if (RHS->getType()->isSigned())
1743 if (Value *LHSNeg = dyn_castNegVal(Op0))
1744 return BinaryOperator::createDiv(LHSNeg, ConstantExpr::getNeg(RHS));
1746 if (!RHS->isNullValue()) {
1747 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
1748 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1750 if (isa<PHINode>(Op0))
1751 if (Instruction *NV = FoldOpIntoPhi(I))
1756 // If this is 'udiv X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1757 // transform this into: '(Cond ? (udiv X, C1) : (udiv X, C2))'.
1758 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1759 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1760 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1761 if (STO->getValue() == 0) { // Couldn't be this argument.
1762 I.setOperand(1, SFO);
1764 } else if (SFO->getValue() == 0) {
1765 I.setOperand(1, STO);
1769 uint64_t TVA = STO->getValue(), FVA = SFO->getValue();
1770 if (isPowerOf2_64(TVA) && isPowerOf2_64(FVA)) {
1771 unsigned TSA = Log2_64(TVA), FSA = Log2_64(FVA);
1772 Constant *TC = ConstantUInt::get(Type::UByteTy, TSA);
1773 Instruction *TSI = new ShiftInst(Instruction::Shr, Op0,
1774 TC, SI->getName()+".t");
1775 TSI = InsertNewInstBefore(TSI, I);
1777 Constant *FC = ConstantUInt::get(Type::UByteTy, FSA);
1778 Instruction *FSI = new ShiftInst(Instruction::Shr, Op0,
1779 FC, SI->getName()+".f");
1780 FSI = InsertNewInstBefore(FSI, I);
1781 return new SelectInst(SI->getOperand(0), TSI, FSI);
1785 // 0 / X == 0, we don't need to preserve faults!
1786 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
1787 if (LHS->equalsInt(0))
1788 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1790 if (I.getType()->isSigned()) {
1791 // If the sign bits of both operands are zero (i.e. we can prove they are
1792 // unsigned inputs), turn this into a udiv.
1793 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1794 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
1795 const Type *NTy = Op0->getType()->getUnsignedVersion();
1796 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1797 InsertNewInstBefore(LHS, I);
1799 if (Constant *R = dyn_cast<Constant>(Op1))
1800 RHS = ConstantExpr::getCast(R, NTy);
1802 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1803 Instruction *Div = BinaryOperator::createDiv(LHS, RHS, I.getName());
1804 InsertNewInstBefore(Div, I);
1805 return new CastInst(Div, I.getType());
1808 // Known to be an unsigned division.
1809 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1810 // Turn A / (C1 << N), where C1 is "1<<C2" into A >> (N+C2) [udiv only].
1811 if (RHSI->getOpcode() == Instruction::Shl &&
1812 isa<ConstantUInt>(RHSI->getOperand(0))) {
1813 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1814 if (isPowerOf2_64(C1)) {
1815 unsigned C2 = Log2_64(C1);
1816 Value *Add = RHSI->getOperand(1);
1818 Constant *C2V = ConstantUInt::get(Add->getType(), C2);
1819 Add = InsertNewInstBefore(BinaryOperator::createAdd(Add, C2V,
1822 return new ShiftInst(Instruction::Shr, Op0, Add);
1832 /// GetFactor - If we can prove that the specified value is at least a multiple
1833 /// of some factor, return that factor.
1834 static Constant *GetFactor(Value *V) {
1835 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1838 // Unless we can be tricky, we know this is a multiple of 1.
1839 Constant *Result = ConstantInt::get(V->getType(), 1);
1841 Instruction *I = dyn_cast<Instruction>(V);
1842 if (!I) return Result;
1844 if (I->getOpcode() == Instruction::Mul) {
1845 // Handle multiplies by a constant, etc.
1846 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
1847 GetFactor(I->getOperand(1)));
1848 } else if (I->getOpcode() == Instruction::Shl) {
1849 // (X<<C) -> X * (1 << C)
1850 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
1851 ShRHS = ConstantExpr::getShl(Result, ShRHS);
1852 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
1854 } else if (I->getOpcode() == Instruction::And) {
1855 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1856 // X & 0xFFF0 is known to be a multiple of 16.
1857 unsigned Zeros = CountTrailingZeros_64(RHS->getZExtValue());
1858 if (Zeros != V->getType()->getPrimitiveSizeInBits())
1859 return ConstantExpr::getShl(Result,
1860 ConstantUInt::get(Type::UByteTy, Zeros));
1862 } else if (I->getOpcode() == Instruction::Cast) {
1863 Value *Op = I->getOperand(0);
1864 // Only handle int->int casts.
1865 if (!Op->getType()->isInteger()) return Result;
1866 return ConstantExpr::getCast(GetFactor(Op), V->getType());
1871 Instruction *InstCombiner::visitRem(BinaryOperator &I) {
1872 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
1874 // 0 % X == 0, we don't need to preserve faults!
1875 if (Constant *LHS = dyn_cast<Constant>(Op0))
1876 if (LHS->isNullValue())
1877 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1879 if (isa<UndefValue>(Op0)) // undef % X -> 0
1880 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1881 if (isa<UndefValue>(Op1))
1882 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
1884 if (I.getType()->isSigned()) {
1885 if (Value *RHSNeg = dyn_castNegVal(Op1))
1886 if (!isa<ConstantSInt>(RHSNeg) ||
1887 cast<ConstantSInt>(RHSNeg)->getValue() > 0) {
1889 AddUsesToWorkList(I);
1890 I.setOperand(1, RHSNeg);
1894 // If the top bits of both operands are zero (i.e. we can prove they are
1895 // unsigned inputs), turn this into a urem.
1896 uint64_t Mask = 1ULL << (I.getType()->getPrimitiveSizeInBits()-1);
1897 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
1898 const Type *NTy = Op0->getType()->getUnsignedVersion();
1899 Instruction *LHS = new CastInst(Op0, NTy, Op0->getName());
1900 InsertNewInstBefore(LHS, I);
1902 if (Constant *R = dyn_cast<Constant>(Op1))
1903 RHS = ConstantExpr::getCast(R, NTy);
1905 RHS = InsertNewInstBefore(new CastInst(Op1, NTy, Op1->getName()), I);
1906 Instruction *Rem = BinaryOperator::createRem(LHS, RHS, I.getName());
1907 InsertNewInstBefore(Rem, I);
1908 return new CastInst(Rem, I.getType());
1912 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
1913 // X % 0 == undef, we don't need to preserve faults!
1914 if (RHS->equalsInt(0))
1915 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
1917 if (RHS->equalsInt(1)) // X % 1 == 0
1918 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1920 // Check to see if this is an unsigned remainder with an exact power of 2,
1921 // if so, convert to a bitwise and.
1922 if (ConstantUInt *C = dyn_cast<ConstantUInt>(RHS))
1923 if (isPowerOf2_64(C->getValue()))
1924 return BinaryOperator::createAnd(Op0, SubOne(C));
1926 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
1927 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
1928 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
1930 } else if (isa<PHINode>(Op0I)) {
1931 if (Instruction *NV = FoldOpIntoPhi(I))
1935 // X*C1%C2 --> 0 iff C1%C2 == 0
1936 if (ConstantExpr::getRem(GetFactor(Op0I), RHS)->isNullValue())
1937 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
1941 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
1942 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1) [urem only].
1943 if (I.getType()->isUnsigned() &&
1944 RHSI->getOpcode() == Instruction::Shl &&
1945 isa<ConstantUInt>(RHSI->getOperand(0))) {
1946 unsigned C1 = cast<ConstantUInt>(RHSI->getOperand(0))->getRawValue();
1947 if (isPowerOf2_64(C1)) {
1948 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
1949 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
1951 return BinaryOperator::createAnd(Op0, Add);
1955 // If this is 'urem X, (Cond ? C1, C2)' where C1&C2 are powers of two,
1956 // transform this into: '(Cond ? (urem X, C1) : (urem X, C2))'.
1957 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
1958 if (ConstantUInt *STO = dyn_cast<ConstantUInt>(SI->getOperand(1)))
1959 if (ConstantUInt *SFO = dyn_cast<ConstantUInt>(SI->getOperand(2))) {
1960 if (STO->getValue() == 0) { // Couldn't be this argument.
1961 I.setOperand(1, SFO);
1963 } else if (SFO->getValue() == 0) {
1964 I.setOperand(1, STO);
1968 if (isPowerOf2_64(STO->getValue()) && isPowerOf2_64(SFO->getValue())){
1969 Value *TrueAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1970 SubOne(STO), SI->getName()+".t"), I);
1971 Value *FalseAnd = InsertNewInstBefore(BinaryOperator::createAnd(Op0,
1972 SubOne(SFO), SI->getName()+".f"), I);
1973 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
1981 // isMaxValueMinusOne - return true if this is Max-1
1982 static bool isMaxValueMinusOne(const ConstantInt *C) {
1983 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1984 return CU->getValue() == C->getType()->getIntegralTypeMask()-1;
1986 const ConstantSInt *CS = cast<ConstantSInt>(C);
1988 // Calculate 0111111111..11111
1989 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
1990 int64_t Val = INT64_MAX; // All ones
1991 Val >>= 64-TypeBits; // Shift out unwanted 1 bits...
1992 return CS->getValue() == Val-1;
1995 // isMinValuePlusOne - return true if this is Min+1
1996 static bool isMinValuePlusOne(const ConstantInt *C) {
1997 if (const ConstantUInt *CU = dyn_cast<ConstantUInt>(C))
1998 return CU->getValue() == 1;
2000 const ConstantSInt *CS = cast<ConstantSInt>(C);
2002 // Calculate 1111111111000000000000
2003 unsigned TypeBits = C->getType()->getPrimitiveSizeInBits();
2004 int64_t Val = -1; // All ones
2005 Val <<= TypeBits-1; // Shift over to the right spot
2006 return CS->getValue() == Val+1;
2009 // isOneBitSet - Return true if there is exactly one bit set in the specified
2011 static bool isOneBitSet(const ConstantInt *CI) {
2012 uint64_t V = CI->getRawValue();
2013 return V && (V & (V-1)) == 0;
2016 #if 0 // Currently unused
2017 // isLowOnes - Return true if the constant is of the form 0+1+.
2018 static bool isLowOnes(const ConstantInt *CI) {
2019 uint64_t V = CI->getRawValue();
2021 // There won't be bits set in parts that the type doesn't contain.
2022 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2024 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2025 return U && V && (U & V) == 0;
2029 // isHighOnes - Return true if the constant is of the form 1+0+.
2030 // This is the same as lowones(~X).
2031 static bool isHighOnes(const ConstantInt *CI) {
2032 uint64_t V = ~CI->getRawValue();
2033 if (~V == 0) return false; // 0's does not match "1+"
2035 // There won't be bits set in parts that the type doesn't contain.
2036 V &= ConstantInt::getAllOnesValue(CI->getType())->getRawValue();
2038 uint64_t U = V+1; // If it is low ones, this should be a power of two.
2039 return U && V && (U & V) == 0;
2043 /// getSetCondCode - Encode a setcc opcode into a three bit mask. These bits
2044 /// are carefully arranged to allow folding of expressions such as:
2046 /// (A < B) | (A > B) --> (A != B)
2048 /// Bit value '4' represents that the comparison is true if A > B, bit value '2'
2049 /// represents that the comparison is true if A == B, and bit value '1' is true
2052 static unsigned getSetCondCode(const SetCondInst *SCI) {
2053 switch (SCI->getOpcode()) {
2055 case Instruction::SetGT: return 1;
2056 case Instruction::SetEQ: return 2;
2057 case Instruction::SetGE: return 3;
2058 case Instruction::SetLT: return 4;
2059 case Instruction::SetNE: return 5;
2060 case Instruction::SetLE: return 6;
2063 assert(0 && "Invalid SetCC opcode!");
2068 /// getSetCCValue - This is the complement of getSetCondCode, which turns an
2069 /// opcode and two operands into either a constant true or false, or a brand new
2070 /// SetCC instruction.
2071 static Value *getSetCCValue(unsigned Opcode, Value *LHS, Value *RHS) {
2073 case 0: return ConstantBool::False;
2074 case 1: return new SetCondInst(Instruction::SetGT, LHS, RHS);
2075 case 2: return new SetCondInst(Instruction::SetEQ, LHS, RHS);
2076 case 3: return new SetCondInst(Instruction::SetGE, LHS, RHS);
2077 case 4: return new SetCondInst(Instruction::SetLT, LHS, RHS);
2078 case 5: return new SetCondInst(Instruction::SetNE, LHS, RHS);
2079 case 6: return new SetCondInst(Instruction::SetLE, LHS, RHS);
2080 case 7: return ConstantBool::True;
2081 default: assert(0 && "Illegal SetCCCode!"); return 0;
2085 // FoldSetCCLogical - Implements (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2086 struct FoldSetCCLogical {
2089 FoldSetCCLogical(InstCombiner &ic, SetCondInst *SCI)
2090 : IC(ic), LHS(SCI->getOperand(0)), RHS(SCI->getOperand(1)) {}
2091 bool shouldApply(Value *V) const {
2092 if (SetCondInst *SCI = dyn_cast<SetCondInst>(V))
2093 return (SCI->getOperand(0) == LHS && SCI->getOperand(1) == RHS ||
2094 SCI->getOperand(0) == RHS && SCI->getOperand(1) == LHS);
2097 Instruction *apply(BinaryOperator &Log) const {
2098 SetCondInst *SCI = cast<SetCondInst>(Log.getOperand(0));
2099 if (SCI->getOperand(0) != LHS) {
2100 assert(SCI->getOperand(1) == LHS);
2101 SCI->swapOperands(); // Swap the LHS and RHS of the SetCC
2104 unsigned LHSCode = getSetCondCode(SCI);
2105 unsigned RHSCode = getSetCondCode(cast<SetCondInst>(Log.getOperand(1)));
2107 switch (Log.getOpcode()) {
2108 case Instruction::And: Code = LHSCode & RHSCode; break;
2109 case Instruction::Or: Code = LHSCode | RHSCode; break;
2110 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
2111 default: assert(0 && "Illegal logical opcode!"); return 0;
2114 Value *RV = getSetCCValue(Code, LHS, RHS);
2115 if (Instruction *I = dyn_cast<Instruction>(RV))
2117 // Otherwise, it's a constant boolean value...
2118 return IC.ReplaceInstUsesWith(Log, RV);
2122 // OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2123 // the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2124 // guaranteed to be either a shift instruction or a binary operator.
2125 Instruction *InstCombiner::OptAndOp(Instruction *Op,
2126 ConstantIntegral *OpRHS,
2127 ConstantIntegral *AndRHS,
2128 BinaryOperator &TheAnd) {
2129 Value *X = Op->getOperand(0);
2130 Constant *Together = 0;
2131 if (!isa<ShiftInst>(Op))
2132 Together = ConstantExpr::getAnd(AndRHS, OpRHS);
2134 switch (Op->getOpcode()) {
2135 case Instruction::Xor:
2136 if (Op->hasOneUse()) {
2137 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
2138 std::string OpName = Op->getName(); Op->setName("");
2139 Instruction *And = BinaryOperator::createAnd(X, AndRHS, OpName);
2140 InsertNewInstBefore(And, TheAnd);
2141 return BinaryOperator::createXor(And, Together);
2144 case Instruction::Or:
2145 if (Together == AndRHS) // (X | C) & C --> C
2146 return ReplaceInstUsesWith(TheAnd, AndRHS);
2148 if (Op->hasOneUse() && Together != OpRHS) {
2149 // (X | C1) & C2 --> (X | (C1&C2)) & C2
2150 std::string Op0Name = Op->getName(); Op->setName("");
2151 Instruction *Or = BinaryOperator::createOr(X, Together, Op0Name);
2152 InsertNewInstBefore(Or, TheAnd);
2153 return BinaryOperator::createAnd(Or, AndRHS);
2156 case Instruction::Add:
2157 if (Op->hasOneUse()) {
2158 // Adding a one to a single bit bit-field should be turned into an XOR
2159 // of the bit. First thing to check is to see if this AND is with a
2160 // single bit constant.
2161 uint64_t AndRHSV = cast<ConstantInt>(AndRHS)->getRawValue();
2163 // Clear bits that are not part of the constant.
2164 AndRHSV &= AndRHS->getType()->getIntegralTypeMask();
2166 // If there is only one bit set...
2167 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
2168 // Ok, at this point, we know that we are masking the result of the
2169 // ADD down to exactly one bit. If the constant we are adding has
2170 // no bits set below this bit, then we can eliminate the ADD.
2171 uint64_t AddRHS = cast<ConstantInt>(OpRHS)->getRawValue();
2173 // Check to see if any bits below the one bit set in AndRHSV are set.
2174 if ((AddRHS & (AndRHSV-1)) == 0) {
2175 // If not, the only thing that can effect the output of the AND is
2176 // the bit specified by AndRHSV. If that bit is set, the effect of
2177 // the XOR is to toggle the bit. If it is clear, then the ADD has
2179 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
2180 TheAnd.setOperand(0, X);
2183 std::string Name = Op->getName(); Op->setName("");
2184 // Pull the XOR out of the AND.
2185 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS, Name);
2186 InsertNewInstBefore(NewAnd, TheAnd);
2187 return BinaryOperator::createXor(NewAnd, AndRHS);
2194 case Instruction::Shl: {
2195 // We know that the AND will not produce any of the bits shifted in, so if
2196 // the anded constant includes them, clear them now!
2198 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2199 Constant *ShlMask = ConstantExpr::getShl(AllOne, OpRHS);
2200 Constant *CI = ConstantExpr::getAnd(AndRHS, ShlMask);
2202 if (CI == ShlMask) { // Masking out bits that the shift already masks
2203 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
2204 } else if (CI != AndRHS) { // Reducing bits set in and.
2205 TheAnd.setOperand(1, CI);
2210 case Instruction::Shr:
2211 // We know that the AND will not produce any of the bits shifted in, so if
2212 // the anded constant includes them, clear them now! This only applies to
2213 // unsigned shifts, because a signed shr may bring in set bits!
2215 if (AndRHS->getType()->isUnsigned()) {
2216 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2217 Constant *ShrMask = ConstantExpr::getShr(AllOne, OpRHS);
2218 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2220 if (CI == ShrMask) { // Masking out bits that the shift already masks.
2221 return ReplaceInstUsesWith(TheAnd, Op);
2222 } else if (CI != AndRHS) {
2223 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
2226 } else { // Signed shr.
2227 // See if this is shifting in some sign extension, then masking it out
2229 if (Op->hasOneUse()) {
2230 Constant *AllOne = ConstantIntegral::getAllOnesValue(AndRHS->getType());
2231 Constant *ShrMask = ConstantExpr::getUShr(AllOne, OpRHS);
2232 Constant *CI = ConstantExpr::getAnd(AndRHS, ShrMask);
2233 if (CI == AndRHS) { // Masking out bits shifted in.
2234 // Make the argument unsigned.
2235 Value *ShVal = Op->getOperand(0);
2236 ShVal = InsertCastBefore(ShVal,
2237 ShVal->getType()->getUnsignedVersion(),
2239 ShVal = InsertNewInstBefore(new ShiftInst(Instruction::Shr, ShVal,
2240 OpRHS, Op->getName()),
2242 Value *AndRHS2 = ConstantExpr::getCast(AndRHS, ShVal->getType());
2243 ShVal = InsertNewInstBefore(BinaryOperator::createAnd(ShVal, AndRHS2,
2246 return new CastInst(ShVal, Op->getType());
2256 /// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
2257 /// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
2258 /// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. IB is the location to
2259 /// insert new instructions.
2260 Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
2261 bool Inside, Instruction &IB) {
2262 assert(cast<ConstantBool>(ConstantExpr::getSetLE(Lo, Hi))->getValue() &&
2263 "Lo is not <= Hi in range emission code!");
2265 if (Lo == Hi) // Trivially false.
2266 return new SetCondInst(Instruction::SetNE, V, V);
2267 if (cast<ConstantIntegral>(Lo)->isMinValue())
2268 return new SetCondInst(Instruction::SetLT, V, Hi);
2270 Constant *AddCST = ConstantExpr::getNeg(Lo);
2271 Instruction *Add = BinaryOperator::createAdd(V, AddCST,V->getName()+".off");
2272 InsertNewInstBefore(Add, IB);
2273 // Convert to unsigned for the comparison.
2274 const Type *UnsType = Add->getType()->getUnsignedVersion();
2275 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2276 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2277 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2278 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2281 if (Lo == Hi) // Trivially true.
2282 return new SetCondInst(Instruction::SetEQ, V, V);
2284 Hi = SubOne(cast<ConstantInt>(Hi));
2285 if (cast<ConstantIntegral>(Lo)->isMinValue()) // V < 0 || V >= Hi ->'V > Hi-1'
2286 return new SetCondInst(Instruction::SetGT, V, Hi);
2288 // Emit X-Lo > Hi-Lo-1
2289 Constant *AddCST = ConstantExpr::getNeg(Lo);
2290 Instruction *Add = BinaryOperator::createAdd(V, AddCST, V->getName()+".off");
2291 InsertNewInstBefore(Add, IB);
2292 // Convert to unsigned for the comparison.
2293 const Type *UnsType = Add->getType()->getUnsignedVersion();
2294 Value *OffsetVal = InsertCastBefore(Add, UnsType, IB);
2295 AddCST = ConstantExpr::getAdd(AddCST, Hi);
2296 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2297 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2300 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
2301 // any number of 0s on either side. The 1s are allowed to wrap from LSB to
2302 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
2303 // not, since all 1s are not contiguous.
2304 static bool isRunOfOnes(ConstantIntegral *Val, unsigned &MB, unsigned &ME) {
2305 uint64_t V = Val->getRawValue();
2306 if (!isShiftedMask_64(V)) return false;
2308 // look for the first zero bit after the run of ones
2309 MB = 64-CountLeadingZeros_64((V - 1) ^ V);
2310 // look for the first non-zero bit
2311 ME = 64-CountLeadingZeros_64(V);
2317 /// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
2318 /// where isSub determines whether the operator is a sub. If we can fold one of
2319 /// the following xforms:
2321 /// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
2322 /// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2323 /// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
2325 /// return (A +/- B).
2327 Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
2328 ConstantIntegral *Mask, bool isSub,
2330 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2331 if (!LHSI || LHSI->getNumOperands() != 2 ||
2332 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
2334 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
2336 switch (LHSI->getOpcode()) {
2338 case Instruction::And:
2339 if (ConstantExpr::getAnd(N, Mask) == Mask) {
2340 // If the AndRHS is a power of two minus one (0+1+), this is simple.
2341 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0)
2344 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
2345 // part, we don't need any explicit masks to take them out of A. If that
2346 // is all N is, ignore it.
2348 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
2349 uint64_t Mask = RHS->getType()->getIntegralTypeMask();
2351 if (MaskedValueIsZero(RHS, Mask))
2356 case Instruction::Or:
2357 case Instruction::Xor:
2358 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
2359 if ((Mask->getRawValue() & Mask->getRawValue()+1) == 0 &&
2360 ConstantExpr::getAnd(N, Mask)->isNullValue())
2367 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
2369 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
2370 return InsertNewInstBefore(New, I);
2373 Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
2374 bool Changed = SimplifyCommutative(I);
2375 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2377 if (isa<UndefValue>(Op1)) // X & undef -> 0
2378 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2382 return ReplaceInstUsesWith(I, Op1);
2384 // See if we can simplify any instructions used by the instruction whose sole
2385 // purpose is to compute bits we don't care about.
2386 uint64_t KnownZero, KnownOne;
2387 if (!isa<PackedType>(I.getType()) &&
2388 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
2389 KnownZero, KnownOne))
2392 if (ConstantIntegral *AndRHS = dyn_cast<ConstantIntegral>(Op1)) {
2393 uint64_t AndRHSMask = AndRHS->getZExtValue();
2394 uint64_t TypeMask = Op0->getType()->getIntegralTypeMask();
2395 uint64_t NotAndRHS = AndRHSMask^TypeMask;
2397 // Optimize a variety of ((val OP C1) & C2) combinations...
2398 if (isa<BinaryOperator>(Op0) || isa<ShiftInst>(Op0)) {
2399 Instruction *Op0I = cast<Instruction>(Op0);
2400 Value *Op0LHS = Op0I->getOperand(0);
2401 Value *Op0RHS = Op0I->getOperand(1);
2402 switch (Op0I->getOpcode()) {
2403 case Instruction::Xor:
2404 case Instruction::Or:
2405 // If the mask is only needed on one incoming arm, push it up.
2406 if (Op0I->hasOneUse()) {
2407 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
2408 // Not masking anything out for the LHS, move to RHS.
2409 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
2410 Op0RHS->getName()+".masked");
2411 InsertNewInstBefore(NewRHS, I);
2412 return BinaryOperator::create(
2413 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
2415 if (!isa<Constant>(Op0RHS) &&
2416 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
2417 // Not masking anything out for the RHS, move to LHS.
2418 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
2419 Op0LHS->getName()+".masked");
2420 InsertNewInstBefore(NewLHS, I);
2421 return BinaryOperator::create(
2422 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
2427 case Instruction::Add:
2428 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
2429 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2430 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
2431 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
2432 return BinaryOperator::createAnd(V, AndRHS);
2433 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
2434 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
2437 case Instruction::Sub:
2438 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
2439 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2440 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
2441 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
2442 return BinaryOperator::createAnd(V, AndRHS);
2446 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
2447 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
2449 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
2450 const Type *SrcTy = CI->getOperand(0)->getType();
2452 // If this is an integer truncation or change from signed-to-unsigned, and
2453 // if the source is an and/or with immediate, transform it. This
2454 // frequently occurs for bitfield accesses.
2455 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
2456 if (SrcTy->getPrimitiveSizeInBits() >=
2457 I.getType()->getPrimitiveSizeInBits() &&
2458 CastOp->getNumOperands() == 2)
2459 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
2460 if (CastOp->getOpcode() == Instruction::And) {
2461 // Change: and (cast (and X, C1) to T), C2
2462 // into : and (cast X to T), trunc(C1)&C2
2463 // This will folds the two ands together, which may allow other
2465 Instruction *NewCast =
2466 new CastInst(CastOp->getOperand(0), I.getType(),
2467 CastOp->getName()+".shrunk");
2468 NewCast = InsertNewInstBefore(NewCast, I);
2470 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2471 C3 = ConstantExpr::getAnd(C3, AndRHS); // trunc(C1)&C2
2472 return BinaryOperator::createAnd(NewCast, C3);
2473 } else if (CastOp->getOpcode() == Instruction::Or) {
2474 // Change: and (cast (or X, C1) to T), C2
2475 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
2476 Constant *C3=ConstantExpr::getCast(AndCI, I.getType());//trunc(C1)
2477 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
2478 return ReplaceInstUsesWith(I, AndRHS);
2483 // Try to fold constant and into select arguments.
2484 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2485 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2487 if (isa<PHINode>(Op0))
2488 if (Instruction *NV = FoldOpIntoPhi(I))
2492 Value *Op0NotVal = dyn_castNotVal(Op0);
2493 Value *Op1NotVal = dyn_castNotVal(Op1);
2495 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
2496 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2498 // (~A & ~B) == (~(A | B)) - De Morgan's Law
2499 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2500 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
2501 I.getName()+".demorgan");
2502 InsertNewInstBefore(Or, I);
2503 return BinaryOperator::createNot(Or);
2507 Value *A = 0, *B = 0;
2508 ConstantInt *C1 = 0, *C2 = 0;
2509 if (match(Op0, m_Or(m_Value(A), m_Value(B))))
2510 if (A == Op1 || B == Op1) // (A | ?) & A --> A
2511 return ReplaceInstUsesWith(I, Op1);
2512 if (match(Op1, m_Or(m_Value(A), m_Value(B))))
2513 if (A == Op0 || B == Op0) // A & (A | ?) --> A
2514 return ReplaceInstUsesWith(I, Op0);
2516 if (Op0->hasOneUse() &&
2517 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
2518 if (A == Op1) { // (A^B)&A -> A&(A^B)
2519 I.swapOperands(); // Simplify below
2520 std::swap(Op0, Op1);
2521 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
2522 cast<BinaryOperator>(Op0)->swapOperands();
2523 I.swapOperands(); // Simplify below
2524 std::swap(Op0, Op1);
2527 if (Op1->hasOneUse() &&
2528 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
2529 if (B == Op0) { // B&(A^B) -> B&(B^A)
2530 cast<BinaryOperator>(Op1)->swapOperands();
2533 if (A == Op0) { // A&(A^B) -> A & ~B
2534 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
2535 InsertNewInstBefore(NotB, I);
2536 return BinaryOperator::createAnd(A, NotB);
2542 if (SetCondInst *RHS = dyn_cast<SetCondInst>(Op1)) {
2543 // (setcc1 A, B) & (setcc2 A, B) --> (setcc3 A, B)
2544 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2547 Value *LHSVal, *RHSVal;
2548 ConstantInt *LHSCst, *RHSCst;
2549 Instruction::BinaryOps LHSCC, RHSCC;
2550 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2551 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2552 if (LHSVal == RHSVal && // Found (X setcc C1) & (X setcc C2)
2553 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
2554 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
2555 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2556 // Ensure that the larger constant is on the RHS.
2557 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2558 SetCondInst *LHS = cast<SetCondInst>(Op0);
2559 if (cast<ConstantBool>(Cmp)->getValue()) {
2560 std::swap(LHS, RHS);
2561 std::swap(LHSCst, RHSCst);
2562 std::swap(LHSCC, RHSCC);
2565 // At this point, we know we have have two setcc instructions
2566 // comparing a value against two constants and and'ing the result
2567 // together. Because of the above check, we know that we only have
2568 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2569 // FoldSetCCLogical check above), that the two constants are not
2571 assert(LHSCst != RHSCst && "Compares not folded above?");
2574 default: assert(0 && "Unknown integer condition code!");
2575 case Instruction::SetEQ:
2577 default: assert(0 && "Unknown integer condition code!");
2578 case Instruction::SetEQ: // (X == 13 & X == 15) -> false
2579 case Instruction::SetGT: // (X == 13 & X > 15) -> false
2580 return ReplaceInstUsesWith(I, ConstantBool::False);
2581 case Instruction::SetNE: // (X == 13 & X != 15) -> X == 13
2582 case Instruction::SetLT: // (X == 13 & X < 15) -> X == 13
2583 return ReplaceInstUsesWith(I, LHS);
2585 case Instruction::SetNE:
2587 default: assert(0 && "Unknown integer condition code!");
2588 case Instruction::SetLT:
2589 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X < 14) -> X < 13
2590 return new SetCondInst(Instruction::SetLT, LHSVal, LHSCst);
2591 break; // (X != 13 & X < 15) -> no change
2592 case Instruction::SetEQ: // (X != 13 & X == 15) -> X == 15
2593 case Instruction::SetGT: // (X != 13 & X > 15) -> X > 15
2594 return ReplaceInstUsesWith(I, RHS);
2595 case Instruction::SetNE:
2596 if (LHSCst == SubOne(RHSCst)) {// (X != 13 & X != 14) -> X-13 >u 1
2597 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2598 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2599 LHSVal->getName()+".off");
2600 InsertNewInstBefore(Add, I);
2601 const Type *UnsType = Add->getType()->getUnsignedVersion();
2602 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2603 AddCST = ConstantExpr::getSub(RHSCst, LHSCst);
2604 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2605 return new SetCondInst(Instruction::SetGT, OffsetVal, AddCST);
2607 break; // (X != 13 & X != 15) -> no change
2610 case Instruction::SetLT:
2612 default: assert(0 && "Unknown integer condition code!");
2613 case Instruction::SetEQ: // (X < 13 & X == 15) -> false
2614 case Instruction::SetGT: // (X < 13 & X > 15) -> false
2615 return ReplaceInstUsesWith(I, ConstantBool::False);
2616 case Instruction::SetNE: // (X < 13 & X != 15) -> X < 13
2617 case Instruction::SetLT: // (X < 13 & X < 15) -> X < 13
2618 return ReplaceInstUsesWith(I, LHS);
2620 case Instruction::SetGT:
2622 default: assert(0 && "Unknown integer condition code!");
2623 case Instruction::SetEQ: // (X > 13 & X == 15) -> X > 13
2624 return ReplaceInstUsesWith(I, LHS);
2625 case Instruction::SetGT: // (X > 13 & X > 15) -> X > 15
2626 return ReplaceInstUsesWith(I, RHS);
2627 case Instruction::SetNE:
2628 if (RHSCst == AddOne(LHSCst)) // (X > 13 & X != 14) -> X > 14
2629 return new SetCondInst(Instruction::SetGT, LHSVal, RHSCst);
2630 break; // (X > 13 & X != 15) -> no change
2631 case Instruction::SetLT: // (X > 13 & X < 15) -> (X-14) <u 1
2632 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true, I);
2638 return Changed ? &I : 0;
2641 Instruction *InstCombiner::visitOr(BinaryOperator &I) {
2642 bool Changed = SimplifyCommutative(I);
2643 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2645 if (isa<UndefValue>(Op1))
2646 return ReplaceInstUsesWith(I, // X | undef -> -1
2647 ConstantIntegral::getAllOnesValue(I.getType()));
2651 return ReplaceInstUsesWith(I, Op0);
2653 // See if we can simplify any instructions used by the instruction whose sole
2654 // purpose is to compute bits we don't care about.
2655 uint64_t KnownZero, KnownOne;
2656 if (!isa<PackedType>(I.getType()) &&
2657 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
2658 KnownZero, KnownOne))
2662 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
2663 ConstantInt *C1 = 0; Value *X = 0;
2664 // (X & C1) | C2 --> (X | C2) & (C1|C2)
2665 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2666 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0->getName());
2668 InsertNewInstBefore(Or, I);
2669 return BinaryOperator::createAnd(Or, ConstantExpr::getOr(RHS, C1));
2672 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
2673 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
2674 std::string Op0Name = Op0->getName(); Op0->setName("");
2675 Instruction *Or = BinaryOperator::createOr(X, RHS, Op0Name);
2676 InsertNewInstBefore(Or, I);
2677 return BinaryOperator::createXor(Or,
2678 ConstantExpr::getAnd(C1, ConstantExpr::getNot(RHS)));
2681 // Try to fold constant and into select arguments.
2682 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2683 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2685 if (isa<PHINode>(Op0))
2686 if (Instruction *NV = FoldOpIntoPhi(I))
2690 Value *A = 0, *B = 0;
2691 ConstantInt *C1 = 0, *C2 = 0;
2693 if (match(Op0, m_And(m_Value(A), m_Value(B))))
2694 if (A == Op1 || B == Op1) // (A & ?) | A --> A
2695 return ReplaceInstUsesWith(I, Op1);
2696 if (match(Op1, m_And(m_Value(A), m_Value(B))))
2697 if (A == Op0 || B == Op0) // A | (A & ?) --> A
2698 return ReplaceInstUsesWith(I, Op0);
2700 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
2701 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2702 MaskedValueIsZero(Op1, C1->getZExtValue())) {
2703 Instruction *NOr = BinaryOperator::createOr(A, Op1, Op0->getName());
2705 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2708 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
2709 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
2710 MaskedValueIsZero(Op0, C1->getZExtValue())) {
2711 Instruction *NOr = BinaryOperator::createOr(A, Op0, Op1->getName());
2713 return BinaryOperator::createXor(InsertNewInstBefore(NOr, I), C1);
2716 // (A & C1)|(B & C2)
2717 if (match(Op0, m_And(m_Value(A), m_ConstantInt(C1))) &&
2718 match(Op1, m_And(m_Value(B), m_ConstantInt(C2)))) {
2720 if (A == B) // (A & C1)|(A & C2) == A & (C1|C2)
2721 return BinaryOperator::createAnd(A, ConstantExpr::getOr(C1, C2));
2724 // If we have: ((V + N) & C1) | (V & C2)
2725 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
2726 // replace with V+N.
2727 if (C1 == ConstantExpr::getNot(C2)) {
2728 Value *V1 = 0, *V2 = 0;
2729 if ((C2->getRawValue() & (C2->getRawValue()+1)) == 0 && // C2 == 0+1+
2730 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
2731 // Add commutes, try both ways.
2732 if (V1 == B && MaskedValueIsZero(V2, C2->getZExtValue()))
2733 return ReplaceInstUsesWith(I, A);
2734 if (V2 == B && MaskedValueIsZero(V1, C2->getZExtValue()))
2735 return ReplaceInstUsesWith(I, A);
2737 // Or commutes, try both ways.
2738 if ((C1->getRawValue() & (C1->getRawValue()+1)) == 0 &&
2739 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
2740 // Add commutes, try both ways.
2741 if (V1 == A && MaskedValueIsZero(V2, C1->getZExtValue()))
2742 return ReplaceInstUsesWith(I, B);
2743 if (V2 == A && MaskedValueIsZero(V1, C1->getZExtValue()))
2744 return ReplaceInstUsesWith(I, B);
2749 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
2750 if (A == Op1) // ~A | A == -1
2751 return ReplaceInstUsesWith(I,
2752 ConstantIntegral::getAllOnesValue(I.getType()));
2756 // Note, A is still live here!
2757 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
2759 return ReplaceInstUsesWith(I,
2760 ConstantIntegral::getAllOnesValue(I.getType()));
2762 // (~A | ~B) == (~(A & B)) - De Morgan's Law
2763 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
2764 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
2765 I.getName()+".demorgan"), I);
2766 return BinaryOperator::createNot(And);
2770 // (setcc1 A, B) | (setcc2 A, B) --> (setcc3 A, B)
2771 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1))) {
2772 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
2775 Value *LHSVal, *RHSVal;
2776 ConstantInt *LHSCst, *RHSCst;
2777 Instruction::BinaryOps LHSCC, RHSCC;
2778 if (match(Op0, m_SetCond(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
2779 if (match(RHS, m_SetCond(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
2780 if (LHSVal == RHSVal && // Found (X setcc C1) | (X setcc C2)
2781 // Set[GL]E X, CST is folded to Set[GL]T elsewhere.
2782 LHSCC != Instruction::SetGE && LHSCC != Instruction::SetLE &&
2783 RHSCC != Instruction::SetGE && RHSCC != Instruction::SetLE) {
2784 // Ensure that the larger constant is on the RHS.
2785 Constant *Cmp = ConstantExpr::getSetGT(LHSCst, RHSCst);
2786 SetCondInst *LHS = cast<SetCondInst>(Op0);
2787 if (cast<ConstantBool>(Cmp)->getValue()) {
2788 std::swap(LHS, RHS);
2789 std::swap(LHSCst, RHSCst);
2790 std::swap(LHSCC, RHSCC);
2793 // At this point, we know we have have two setcc instructions
2794 // comparing a value against two constants and or'ing the result
2795 // together. Because of the above check, we know that we only have
2796 // SetEQ, SetNE, SetLT, and SetGT here. We also know (from the
2797 // FoldSetCCLogical check above), that the two constants are not
2799 assert(LHSCst != RHSCst && "Compares not folded above?");
2802 default: assert(0 && "Unknown integer condition code!");
2803 case Instruction::SetEQ:
2805 default: assert(0 && "Unknown integer condition code!");
2806 case Instruction::SetEQ:
2807 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
2808 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
2809 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
2810 LHSVal->getName()+".off");
2811 InsertNewInstBefore(Add, I);
2812 const Type *UnsType = Add->getType()->getUnsignedVersion();
2813 Value *OffsetVal = InsertCastBefore(Add, UnsType, I);
2814 AddCST = ConstantExpr::getSub(AddOne(RHSCst), LHSCst);
2815 AddCST = ConstantExpr::getCast(AddCST, UnsType);
2816 return new SetCondInst(Instruction::SetLT, OffsetVal, AddCST);
2818 break; // (X == 13 | X == 15) -> no change
2820 case Instruction::SetGT: // (X == 13 | X > 14) -> no change
2822 case Instruction::SetNE: // (X == 13 | X != 15) -> X != 15
2823 case Instruction::SetLT: // (X == 13 | X < 15) -> X < 15
2824 return ReplaceInstUsesWith(I, RHS);
2827 case Instruction::SetNE:
2829 default: assert(0 && "Unknown integer condition code!");
2830 case Instruction::SetEQ: // (X != 13 | X == 15) -> X != 13
2831 case Instruction::SetGT: // (X != 13 | X > 15) -> X != 13
2832 return ReplaceInstUsesWith(I, LHS);
2833 case Instruction::SetNE: // (X != 13 | X != 15) -> true
2834 case Instruction::SetLT: // (X != 13 | X < 15) -> true
2835 return ReplaceInstUsesWith(I, ConstantBool::True);
2838 case Instruction::SetLT:
2840 default: assert(0 && "Unknown integer condition code!");
2841 case Instruction::SetEQ: // (X < 13 | X == 14) -> no change
2843 case Instruction::SetGT: // (X < 13 | X > 15) -> (X-13) > 2
2844 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false, I);
2845 case Instruction::SetNE: // (X < 13 | X != 15) -> X != 15
2846 case Instruction::SetLT: // (X < 13 | X < 15) -> X < 15
2847 return ReplaceInstUsesWith(I, RHS);
2850 case Instruction::SetGT:
2852 default: assert(0 && "Unknown integer condition code!");
2853 case Instruction::SetEQ: // (X > 13 | X == 15) -> X > 13
2854 case Instruction::SetGT: // (X > 13 | X > 15) -> X > 13
2855 return ReplaceInstUsesWith(I, LHS);
2856 case Instruction::SetNE: // (X > 13 | X != 15) -> true
2857 case Instruction::SetLT: // (X > 13 | X < 15) -> true
2858 return ReplaceInstUsesWith(I, ConstantBool::True);
2864 return Changed ? &I : 0;
2867 // XorSelf - Implements: X ^ X --> 0
2870 XorSelf(Value *rhs) : RHS(rhs) {}
2871 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2872 Instruction *apply(BinaryOperator &Xor) const {
2878 Instruction *InstCombiner::visitXor(BinaryOperator &I) {
2879 bool Changed = SimplifyCommutative(I);
2880 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2882 if (isa<UndefValue>(Op1))
2883 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
2885 // xor X, X = 0, even if X is nested in a sequence of Xor's.
2886 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
2887 assert(Result == &I && "AssociativeOpt didn't work?");
2888 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2891 // See if we can simplify any instructions used by the instruction whose sole
2892 // purpose is to compute bits we don't care about.
2893 uint64_t KnownZero, KnownOne;
2894 if (!isa<PackedType>(I.getType()) &&
2895 SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
2896 KnownZero, KnownOne))
2899 if (ConstantIntegral *RHS = dyn_cast<ConstantIntegral>(Op1)) {
2900 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2901 // xor (setcc A, B), true = not (setcc A, B) = setncc A, B
2902 if (SetCondInst *SCI = dyn_cast<SetCondInst>(Op0I))
2903 if (RHS == ConstantBool::True && SCI->hasOneUse())
2904 return new SetCondInst(SCI->getInverseCondition(),
2905 SCI->getOperand(0), SCI->getOperand(1));
2907 // ~(c-X) == X-c-1 == X+(-c-1)
2908 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
2909 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
2910 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
2911 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
2912 ConstantInt::get(I.getType(), 1));
2913 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
2916 // ~(~X & Y) --> (X | ~Y)
2917 if (Op0I->getOpcode() == Instruction::And && RHS->isAllOnesValue()) {
2918 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
2919 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
2921 BinaryOperator::createNot(Op0I->getOperand(1),
2922 Op0I->getOperand(1)->getName()+".not");
2923 InsertNewInstBefore(NotY, I);
2924 return BinaryOperator::createOr(Op0NotVal, NotY);
2928 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
2929 if (Op0I->getOpcode() == Instruction::Add) {
2930 // ~(X-c) --> (-c-1)-X
2931 if (RHS->isAllOnesValue()) {
2932 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
2933 return BinaryOperator::createSub(
2934 ConstantExpr::getSub(NegOp0CI,
2935 ConstantInt::get(I.getType(), 1)),
2936 Op0I->getOperand(0));
2938 } else if (Op0I->getOpcode() == Instruction::Or) {
2939 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
2940 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getZExtValue())) {
2941 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
2942 // Anything in both C1 and C2 is known to be zero, remove it from
2944 Constant *CommonBits = ConstantExpr::getAnd(Op0CI, RHS);
2945 NewRHS = ConstantExpr::getAnd(NewRHS,
2946 ConstantExpr::getNot(CommonBits));
2947 WorkList.push_back(Op0I);
2948 I.setOperand(0, Op0I->getOperand(0));
2949 I.setOperand(1, NewRHS);
2955 // Try to fold constant and into select arguments.
2956 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2957 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2959 if (isa<PHINode>(Op0))
2960 if (Instruction *NV = FoldOpIntoPhi(I))
2964 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
2966 return ReplaceInstUsesWith(I,
2967 ConstantIntegral::getAllOnesValue(I.getType()));
2969 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
2971 return ReplaceInstUsesWith(I,
2972 ConstantIntegral::getAllOnesValue(I.getType()));
2974 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1))
2975 if (Op1I->getOpcode() == Instruction::Or) {
2976 if (Op1I->getOperand(0) == Op0) { // B^(B|A) == (A|B)^B
2977 Op1I->swapOperands();
2979 std::swap(Op0, Op1);
2980 } else if (Op1I->getOperand(1) == Op0) { // B^(A|B) == (A|B)^B
2981 I.swapOperands(); // Simplified below.
2982 std::swap(Op0, Op1);
2984 } else if (Op1I->getOpcode() == Instruction::Xor) {
2985 if (Op0 == Op1I->getOperand(0)) // A^(A^B) == B
2986 return ReplaceInstUsesWith(I, Op1I->getOperand(1));
2987 else if (Op0 == Op1I->getOperand(1)) // A^(B^A) == B
2988 return ReplaceInstUsesWith(I, Op1I->getOperand(0));
2989 } else if (Op1I->getOpcode() == Instruction::And && Op1I->hasOneUse()) {
2990 if (Op1I->getOperand(0) == Op0) // A^(A&B) -> A^(B&A)
2991 Op1I->swapOperands();
2992 if (Op0 == Op1I->getOperand(1)) { // A^(B&A) -> (B&A)^A
2993 I.swapOperands(); // Simplified below.
2994 std::swap(Op0, Op1);
2998 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2999 if (Op0I->getOpcode() == Instruction::Or && Op0I->hasOneUse()) {
3000 if (Op0I->getOperand(0) == Op1) // (B|A)^B == (A|B)^B
3001 Op0I->swapOperands();
3002 if (Op0I->getOperand(1) == Op1) { // (A|B)^B == A & ~B
3003 Instruction *NotB = BinaryOperator::createNot(Op1, "tmp");
3004 InsertNewInstBefore(NotB, I);
3005 return BinaryOperator::createAnd(Op0I->getOperand(0), NotB);
3007 } else if (Op0I->getOpcode() == Instruction::Xor) {
3008 if (Op1 == Op0I->getOperand(0)) // (A^B)^A == B
3009 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
3010 else if (Op1 == Op0I->getOperand(1)) // (B^A)^A == B
3011 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
3012 } else if (Op0I->getOpcode() == Instruction::And && Op0I->hasOneUse()) {
3013 if (Op0I->getOperand(0) == Op1) // (A&B)^A -> (B&A)^A
3014 Op0I->swapOperands();
3015 if (Op0I->getOperand(1) == Op1 && // (B&A)^A == ~B & A
3016 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
3017 Instruction *N = BinaryOperator::createNot(Op0I->getOperand(0), "tmp");
3018 InsertNewInstBefore(N, I);
3019 return BinaryOperator::createAnd(N, Op1);
3023 // (setcc1 A, B) ^ (setcc2 A, B) --> (setcc3 A, B)
3024 if (SetCondInst *RHS = dyn_cast<SetCondInst>(I.getOperand(1)))
3025 if (Instruction *R = AssociativeOpt(I, FoldSetCCLogical(*this, RHS)))
3028 return Changed ? &I : 0;
3031 /// MulWithOverflow - Compute Result = In1*In2, returning true if the result
3032 /// overflowed for this type.
3033 static bool MulWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3035 Result = cast<ConstantInt>(ConstantExpr::getMul(In1, In2));
3036 return !In2->isNullValue() && ConstantExpr::getDiv(Result, In2) != In1;
3039 static bool isPositive(ConstantInt *C) {
3040 return cast<ConstantSInt>(C)->getValue() >= 0;
3043 /// AddWithOverflow - Compute Result = In1+In2, returning true if the result
3044 /// overflowed for this type.
3045 static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
3047 Result = cast<ConstantInt>(ConstantExpr::getAdd(In1, In2));
3049 if (In1->getType()->isUnsigned())
3050 return cast<ConstantUInt>(Result)->getValue() <
3051 cast<ConstantUInt>(In1)->getValue();
3052 if (isPositive(In1) != isPositive(In2))
3054 if (isPositive(In1))
3055 return cast<ConstantSInt>(Result)->getValue() <
3056 cast<ConstantSInt>(In1)->getValue();
3057 return cast<ConstantSInt>(Result)->getValue() >
3058 cast<ConstantSInt>(In1)->getValue();
3061 /// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
3062 /// code necessary to compute the offset from the base pointer (without adding
3063 /// in the base pointer). Return the result as a signed integer of intptr size.
3064 static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
3065 TargetData &TD = IC.getTargetData();
3066 gep_type_iterator GTI = gep_type_begin(GEP);
3067 const Type *UIntPtrTy = TD.getIntPtrType();
3068 const Type *SIntPtrTy = UIntPtrTy->getSignedVersion();
3069 Value *Result = Constant::getNullValue(SIntPtrTy);
3071 // Build a mask for high order bits.
3072 uint64_t PtrSizeMask = ~0ULL >> (64-TD.getPointerSize()*8);
3074 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
3075 Value *Op = GEP->getOperand(i);
3076 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
3077 Constant *Scale = ConstantExpr::getCast(ConstantUInt::get(UIntPtrTy, Size),
3079 if (Constant *OpC = dyn_cast<Constant>(Op)) {
3080 if (!OpC->isNullValue()) {
3081 OpC = ConstantExpr::getCast(OpC, SIntPtrTy);
3082 Scale = ConstantExpr::getMul(OpC, Scale);
3083 if (Constant *RC = dyn_cast<Constant>(Result))
3084 Result = ConstantExpr::getAdd(RC, Scale);
3086 // Emit an add instruction.
3087 Result = IC.InsertNewInstBefore(
3088 BinaryOperator::createAdd(Result, Scale,
3089 GEP->getName()+".offs"), I);
3093 // Convert to correct type.
3094 Op = IC.InsertNewInstBefore(new CastInst(Op, SIntPtrTy,
3095 Op->getName()+".c"), I);
3097 // We'll let instcombine(mul) convert this to a shl if possible.
3098 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
3099 GEP->getName()+".idx"), I);
3101 // Emit an add instruction.
3102 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
3103 GEP->getName()+".offs"), I);
3109 /// FoldGEPSetCC - Fold comparisons between a GEP instruction and something
3110 /// else. At this point we know that the GEP is on the LHS of the comparison.
3111 Instruction *InstCombiner::FoldGEPSetCC(User *GEPLHS, Value *RHS,
3112 Instruction::BinaryOps Cond,
3114 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
3116 if (CastInst *CI = dyn_cast<CastInst>(RHS))
3117 if (isa<PointerType>(CI->getOperand(0)->getType()))
3118 RHS = CI->getOperand(0);
3120 Value *PtrBase = GEPLHS->getOperand(0);
3121 if (PtrBase == RHS) {
3122 // As an optimization, we don't actually have to compute the actual value of
3123 // OFFSET if this is a seteq or setne comparison, just return whether each
3124 // index is zero or not.
3125 if (Cond == Instruction::SetEQ || Cond == Instruction::SetNE) {
3126 Instruction *InVal = 0;
3127 gep_type_iterator GTI = gep_type_begin(GEPLHS);
3128 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
3130 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
3131 if (isa<UndefValue>(C)) // undef index -> undef.
3132 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3133 if (C->isNullValue())
3135 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
3136 EmitIt = false; // This is indexing into a zero sized array?
3137 } else if (isa<ConstantInt>(C))
3138 return ReplaceInstUsesWith(I, // No comparison is needed here.
3139 ConstantBool::get(Cond == Instruction::SetNE));
3144 new SetCondInst(Cond, GEPLHS->getOperand(i),
3145 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
3149 InVal = InsertNewInstBefore(InVal, I);
3150 InsertNewInstBefore(Comp, I);
3151 if (Cond == Instruction::SetNE) // True if any are unequal
3152 InVal = BinaryOperator::createOr(InVal, Comp);
3153 else // True if all are equal
3154 InVal = BinaryOperator::createAnd(InVal, Comp);
3162 ReplaceInstUsesWith(I, // No comparison is needed here, all indexes = 0
3163 ConstantBool::get(Cond == Instruction::SetEQ));
3166 // Only lower this if the setcc is the only user of the GEP or if we expect
3167 // the result to fold to a constant!
3168 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
3169 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
3170 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
3171 return new SetCondInst(Cond, Offset,
3172 Constant::getNullValue(Offset->getType()));
3174 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
3175 // If the base pointers are different, but the indices are the same, just
3176 // compare the base pointer.
3177 if (PtrBase != GEPRHS->getOperand(0)) {
3178 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
3179 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
3180 GEPRHS->getOperand(0)->getType();
3182 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3183 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3184 IndicesTheSame = false;
3188 // If all indices are the same, just compare the base pointers.
3190 return new SetCondInst(Cond, GEPLHS->getOperand(0),
3191 GEPRHS->getOperand(0));
3193 // Otherwise, the base pointers are different and the indices are
3194 // different, bail out.
3198 // If one of the GEPs has all zero indices, recurse.
3199 bool AllZeros = true;
3200 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
3201 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
3202 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
3207 return FoldGEPSetCC(GEPRHS, GEPLHS->getOperand(0),
3208 SetCondInst::getSwappedCondition(Cond), I);
3210 // If the other GEP has all zero indices, recurse.
3212 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3213 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
3214 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
3219 return FoldGEPSetCC(GEPLHS, GEPRHS->getOperand(0), Cond, I);
3221 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
3222 // If the GEPs only differ by one index, compare it.
3223 unsigned NumDifferences = 0; // Keep track of # differences.
3224 unsigned DiffOperand = 0; // The operand that differs.
3225 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
3226 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
3227 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
3228 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
3229 // Irreconcilable differences.
3233 if (NumDifferences++) break;
3238 if (NumDifferences == 0) // SAME GEP?
3239 return ReplaceInstUsesWith(I, // No comparison is needed here.
3240 ConstantBool::get(Cond == Instruction::SetEQ));
3241 else if (NumDifferences == 1) {
3242 Value *LHSV = GEPLHS->getOperand(DiffOperand);
3243 Value *RHSV = GEPRHS->getOperand(DiffOperand);
3245 // Convert the operands to signed values to make sure to perform a
3246 // signed comparison.
3247 const Type *NewTy = LHSV->getType()->getSignedVersion();
3248 if (LHSV->getType() != NewTy)
3249 LHSV = InsertNewInstBefore(new CastInst(LHSV, NewTy,
3250 LHSV->getName()), I);
3251 if (RHSV->getType() != NewTy)
3252 RHSV = InsertNewInstBefore(new CastInst(RHSV, NewTy,
3253 RHSV->getName()), I);
3254 return new SetCondInst(Cond, LHSV, RHSV);
3258 // Only lower this if the setcc is the only user of the GEP or if we expect
3259 // the result to fold to a constant!
3260 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
3261 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
3262 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
3263 Value *L = EmitGEPOffset(GEPLHS, I, *this);
3264 Value *R = EmitGEPOffset(GEPRHS, I, *this);
3265 return new SetCondInst(Cond, L, R);
3272 Instruction *InstCombiner::visitSetCondInst(SetCondInst &I) {
3273 bool Changed = SimplifyCommutative(I);
3274 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3275 const Type *Ty = Op0->getType();
3279 return ReplaceInstUsesWith(I, ConstantBool::get(isTrueWhenEqual(I)));
3281 if (isa<UndefValue>(Op1)) // X setcc undef -> undef
3282 return ReplaceInstUsesWith(I, UndefValue::get(Type::BoolTy));
3284 // setcc <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
3285 // addresses never equal each other! We already know that Op0 != Op1.
3286 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
3287 isa<ConstantPointerNull>(Op0)) &&
3288 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
3289 isa<ConstantPointerNull>(Op1)))
3290 return ReplaceInstUsesWith(I, ConstantBool::get(!isTrueWhenEqual(I)));
3292 // setcc's with boolean values can always be turned into bitwise operations
3293 if (Ty == Type::BoolTy) {
3294 switch (I.getOpcode()) {
3295 default: assert(0 && "Invalid setcc instruction!");
3296 case Instruction::SetEQ: { // seteq bool %A, %B -> ~(A^B)
3297 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
3298 InsertNewInstBefore(Xor, I);
3299 return BinaryOperator::createNot(Xor);
3301 case Instruction::SetNE:
3302 return BinaryOperator::createXor(Op0, Op1);
3304 case Instruction::SetGT:
3305 std::swap(Op0, Op1); // Change setgt -> setlt
3307 case Instruction::SetLT: { // setlt bool A, B -> ~X & Y
3308 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3309 InsertNewInstBefore(Not, I);
3310 return BinaryOperator::createAnd(Not, Op1);
3312 case Instruction::SetGE:
3313 std::swap(Op0, Op1); // Change setge -> setle
3315 case Instruction::SetLE: { // setle bool %A, %B -> ~A | B
3316 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
3317 InsertNewInstBefore(Not, I);
3318 return BinaryOperator::createOr(Not, Op1);
3323 // See if we are doing a comparison between a constant and an instruction that
3324 // can be folded into the comparison.
3325 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
3326 // Check to see if we are comparing against the minimum or maximum value...
3327 if (CI->isMinValue()) {
3328 if (I.getOpcode() == Instruction::SetLT) // A < MIN -> FALSE
3329 return ReplaceInstUsesWith(I, ConstantBool::False);
3330 if (I.getOpcode() == Instruction::SetGE) // A >= MIN -> TRUE
3331 return ReplaceInstUsesWith(I, ConstantBool::True);
3332 if (I.getOpcode() == Instruction::SetLE) // A <= MIN -> A == MIN
3333 return BinaryOperator::createSetEQ(Op0, Op1);
3334 if (I.getOpcode() == Instruction::SetGT) // A > MIN -> A != MIN
3335 return BinaryOperator::createSetNE(Op0, Op1);
3337 } else if (CI->isMaxValue()) {
3338 if (I.getOpcode() == Instruction::SetGT) // A > MAX -> FALSE
3339 return ReplaceInstUsesWith(I, ConstantBool::False);
3340 if (I.getOpcode() == Instruction::SetLE) // A <= MAX -> TRUE
3341 return ReplaceInstUsesWith(I, ConstantBool::True);
3342 if (I.getOpcode() == Instruction::SetGE) // A >= MAX -> A == MAX
3343 return BinaryOperator::createSetEQ(Op0, Op1);
3344 if (I.getOpcode() == Instruction::SetLT) // A < MAX -> A != MAX
3345 return BinaryOperator::createSetNE(Op0, Op1);
3347 // Comparing against a value really close to min or max?
3348 } else if (isMinValuePlusOne(CI)) {
3349 if (I.getOpcode() == Instruction::SetLT) // A < MIN+1 -> A == MIN
3350 return BinaryOperator::createSetEQ(Op0, SubOne(CI));
3351 if (I.getOpcode() == Instruction::SetGE) // A >= MIN-1 -> A != MIN
3352 return BinaryOperator::createSetNE(Op0, SubOne(CI));
3354 } else if (isMaxValueMinusOne(CI)) {
3355 if (I.getOpcode() == Instruction::SetGT) // A > MAX-1 -> A == MAX
3356 return BinaryOperator::createSetEQ(Op0, AddOne(CI));
3357 if (I.getOpcode() == Instruction::SetLE) // A <= MAX-1 -> A != MAX
3358 return BinaryOperator::createSetNE(Op0, AddOne(CI));
3361 // If we still have a setle or setge instruction, turn it into the
3362 // appropriate setlt or setgt instruction. Since the border cases have
3363 // already been handled above, this requires little checking.
3365 if (I.getOpcode() == Instruction::SetLE)
3366 return BinaryOperator::createSetLT(Op0, AddOne(CI));
3367 if (I.getOpcode() == Instruction::SetGE)
3368 return BinaryOperator::createSetGT(Op0, SubOne(CI));
3371 // See if we can fold the comparison based on bits known to be zero or one
3373 uint64_t KnownZero, KnownOne;
3374 if (SimplifyDemandedBits(Op0, Ty->getIntegralTypeMask(),
3375 KnownZero, KnownOne, 0))
3378 // Given the known and unknown bits, compute a range that the LHS could be
3380 if (KnownOne | KnownZero) {
3381 if (Ty->isUnsigned()) { // Unsigned comparison.
3383 uint64_t RHSVal = CI->getZExtValue();
3384 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3386 switch (I.getOpcode()) { // LE/GE have been folded already.
3387 default: assert(0 && "Unknown setcc opcode!");
3388 case Instruction::SetEQ:
3389 if (Max < RHSVal || Min > RHSVal)
3390 return ReplaceInstUsesWith(I, ConstantBool::False);
3392 case Instruction::SetNE:
3393 if (Max < RHSVal || Min > RHSVal)
3394 return ReplaceInstUsesWith(I, ConstantBool::True);
3396 case Instruction::SetLT:
3397 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3398 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3400 case Instruction::SetGT:
3401 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3402 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3405 } else { // Signed comparison.
3407 int64_t RHSVal = CI->getSExtValue();
3408 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,
3410 switch (I.getOpcode()) { // LE/GE have been folded already.
3411 default: assert(0 && "Unknown setcc opcode!");
3412 case Instruction::SetEQ:
3413 if (Max < RHSVal || Min > RHSVal)
3414 return ReplaceInstUsesWith(I, ConstantBool::False);
3416 case Instruction::SetNE:
3417 if (Max < RHSVal || Min > RHSVal)
3418 return ReplaceInstUsesWith(I, ConstantBool::True);
3420 case Instruction::SetLT:
3421 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3422 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3424 case Instruction::SetGT:
3425 if (Min > RHSVal) return ReplaceInstUsesWith(I, ConstantBool::True);
3426 if (Max < RHSVal) return ReplaceInstUsesWith(I, ConstantBool::False);
3433 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3434 switch (LHSI->getOpcode()) {
3435 case Instruction::And:
3436 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
3437 LHSI->getOperand(0)->hasOneUse()) {
3438 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
3439 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
3440 // happens a LOT in code produced by the C front-end, for bitfield
3442 ShiftInst *Shift = dyn_cast<ShiftInst>(LHSI->getOperand(0));
3443 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
3445 // Check to see if there is a noop-cast between the shift and the and.
3447 if (CastInst *CI = dyn_cast<CastInst>(LHSI->getOperand(0)))
3448 if (CI->getOperand(0)->getType()->isIntegral() &&
3449 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
3450 CI->getType()->getPrimitiveSizeInBits())
3451 Shift = dyn_cast<ShiftInst>(CI->getOperand(0));
3454 ConstantUInt *ShAmt;
3455 ShAmt = Shift ? dyn_cast<ConstantUInt>(Shift->getOperand(1)) : 0;
3456 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
3457 const Type *AndTy = AndCST->getType(); // Type of the and.
3459 // We can fold this as long as we can't shift unknown bits
3460 // into the mask. This can only happen with signed shift
3461 // rights, as they sign-extend.
3463 bool CanFold = Shift->getOpcode() != Instruction::Shr ||
3466 // To test for the bad case of the signed shr, see if any
3467 // of the bits shifted in could be tested after the mask.
3468 int ShAmtVal = Ty->getPrimitiveSizeInBits()-ShAmt->getValue();
3469 if (ShAmtVal < 0) ShAmtVal = 0; // Out of range shift.
3471 Constant *OShAmt = ConstantUInt::get(Type::UByteTy, ShAmtVal);
3473 ConstantExpr::getShl(ConstantInt::getAllOnesValue(AndTy),
3475 if (ConstantExpr::getAnd(ShVal, AndCST)->isNullValue())
3481 if (Shift->getOpcode() == Instruction::Shl)
3482 NewCst = ConstantExpr::getUShr(CI, ShAmt);
3484 NewCst = ConstantExpr::getShl(CI, ShAmt);
3486 // Check to see if we are shifting out any of the bits being
3488 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != CI){
3489 // If we shifted bits out, the fold is not going to work out.
3490 // As a special case, check to see if this means that the
3491 // result is always true or false now.
3492 if (I.getOpcode() == Instruction::SetEQ)
3493 return ReplaceInstUsesWith(I, ConstantBool::False);
3494 if (I.getOpcode() == Instruction::SetNE)
3495 return ReplaceInstUsesWith(I, ConstantBool::True);
3497 I.setOperand(1, NewCst);
3498 Constant *NewAndCST;
3499 if (Shift->getOpcode() == Instruction::Shl)
3500 NewAndCST = ConstantExpr::getUShr(AndCST, ShAmt);
3502 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
3503 LHSI->setOperand(1, NewAndCST);
3505 LHSI->setOperand(0, Shift->getOperand(0));
3507 Value *NewCast = InsertCastBefore(Shift->getOperand(0), AndTy,
3509 LHSI->setOperand(0, NewCast);
3511 WorkList.push_back(Shift); // Shift is dead.
3512 AddUsesToWorkList(I);
3520 case Instruction::Shl: // (setcc (shl X, ShAmt), CI)
3521 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
3522 switch (I.getOpcode()) {
3524 case Instruction::SetEQ:
3525 case Instruction::SetNE: {
3526 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
3528 // Check that the shift amount is in range. If not, don't perform
3529 // undefined shifts. When the shift is visited it will be
3531 if (ShAmt->getValue() >= TypeBits)
3534 // If we are comparing against bits always shifted out, the
3535 // comparison cannot succeed.
3537 ConstantExpr::getShl(ConstantExpr::getShr(CI, ShAmt), ShAmt);
3538 if (Comp != CI) {// Comparing against a bit that we know is zero.
3539 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3540 Constant *Cst = ConstantBool::get(IsSetNE);
3541 return ReplaceInstUsesWith(I, Cst);
3544 if (LHSI->hasOneUse()) {
3545 // Otherwise strength reduce the shift into an and.
3546 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
3547 uint64_t Val = (1ULL << (TypeBits-ShAmtVal))-1;
3550 if (CI->getType()->isUnsigned()) {
3551 Mask = ConstantUInt::get(CI->getType(), Val);
3552 } else if (ShAmtVal != 0) {
3553 Mask = ConstantSInt::get(CI->getType(), Val);
3555 Mask = ConstantInt::getAllOnesValue(CI->getType());
3559 BinaryOperator::createAnd(LHSI->getOperand(0),
3560 Mask, LHSI->getName()+".mask");
3561 Value *And = InsertNewInstBefore(AndI, I);
3562 return new SetCondInst(I.getOpcode(), And,
3563 ConstantExpr::getUShr(CI, ShAmt));
3570 case Instruction::Shr: // (setcc (shr X, ShAmt), CI)
3571 if (ConstantUInt *ShAmt = dyn_cast<ConstantUInt>(LHSI->getOperand(1))) {
3572 switch (I.getOpcode()) {
3574 case Instruction::SetEQ:
3575 case Instruction::SetNE: {
3577 // Check that the shift amount is in range. If not, don't perform
3578 // undefined shifts. When the shift is visited it will be
3580 unsigned TypeBits = CI->getType()->getPrimitiveSizeInBits();
3581 if (ShAmt->getValue() >= TypeBits)
3584 // If we are comparing against bits always shifted out, the
3585 // comparison cannot succeed.
3587 ConstantExpr::getShr(ConstantExpr::getShl(CI, ShAmt), ShAmt);
3589 if (Comp != CI) {// Comparing against a bit that we know is zero.
3590 bool IsSetNE = I.getOpcode() == Instruction::SetNE;
3591 Constant *Cst = ConstantBool::get(IsSetNE);
3592 return ReplaceInstUsesWith(I, Cst);
3595 if (LHSI->hasOneUse() || CI->isNullValue()) {
3596 unsigned ShAmtVal = (unsigned)ShAmt->getValue();
3598 // Otherwise strength reduce the shift into an and.
3599 uint64_t Val = ~0ULL; // All ones.
3600 Val <<= ShAmtVal; // Shift over to the right spot.
3603 if (CI->getType()->isUnsigned()) {
3604 Val &= ~0ULL >> (64-TypeBits);
3605 Mask = ConstantUInt::get(CI->getType(), Val);
3607 Mask = ConstantSInt::get(CI->getType(), Val);
3611 BinaryOperator::createAnd(LHSI->getOperand(0),
3612 Mask, LHSI->getName()+".mask");
3613 Value *And = InsertNewInstBefore(AndI, I);
3614 return new SetCondInst(I.getOpcode(), And,
3615 ConstantExpr::getShl(CI, ShAmt));
3623 case Instruction::Div:
3624 // Fold: (div X, C1) op C2 -> range check
3625 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
3626 // Fold this div into the comparison, producing a range check.
3627 // Determine, based on the divide type, what the range is being
3628 // checked. If there is an overflow on the low or high side, remember
3629 // it, otherwise compute the range [low, hi) bounding the new value.
3630 bool LoOverflow = false, HiOverflow = 0;
3631 ConstantInt *LoBound = 0, *HiBound = 0;
3634 bool ProdOV = MulWithOverflow(Prod, CI, DivRHS);
3636 Instruction::BinaryOps Opcode = I.getOpcode();
3638 if (DivRHS->isNullValue()) { // Don't hack on divide by zeros.
3639 } else if (LHSI->getType()->isUnsigned()) { // udiv
3641 LoOverflow = ProdOV;
3642 HiOverflow = ProdOV || AddWithOverflow(HiBound, LoBound, DivRHS);
3643 } else if (isPositive(DivRHS)) { // Divisor is > 0.
3644 if (CI->isNullValue()) { // (X / pos) op 0
3646 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
3648 } else if (isPositive(CI)) { // (X / pos) op pos
3650 LoOverflow = ProdOV;
3651 HiOverflow = ProdOV || AddWithOverflow(HiBound, Prod, DivRHS);
3652 } else { // (X / pos) op neg
3653 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
3654 LoOverflow = AddWithOverflow(LoBound, Prod,
3655 cast<ConstantInt>(DivRHSH));
3657 HiOverflow = ProdOV;
3659 } else { // Divisor is < 0.
3660 if (CI->isNullValue()) { // (X / neg) op 0
3661 LoBound = AddOne(DivRHS);
3662 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
3663 if (HiBound == DivRHS)
3664 LoBound = 0; // - INTMIN = INTMIN
3665 } else if (isPositive(CI)) { // (X / neg) op pos
3666 HiOverflow = LoOverflow = ProdOV;
3668 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS));
3669 HiBound = AddOne(Prod);
3670 } else { // (X / neg) op neg
3672 LoOverflow = HiOverflow = ProdOV;
3673 HiBound = cast<ConstantInt>(ConstantExpr::getSub(Prod, DivRHS));
3676 // Dividing by a negate swaps the condition.
3677 Opcode = SetCondInst::getSwappedCondition(Opcode);
3681 Value *X = LHSI->getOperand(0);
3683 default: assert(0 && "Unhandled setcc opcode!");
3684 case Instruction::SetEQ:
3685 if (LoOverflow && HiOverflow)
3686 return ReplaceInstUsesWith(I, ConstantBool::False);
3687 else if (HiOverflow)
3688 return new SetCondInst(Instruction::SetGE, X, LoBound);
3689 else if (LoOverflow)
3690 return new SetCondInst(Instruction::SetLT, X, HiBound);
3692 return InsertRangeTest(X, LoBound, HiBound, true, I);
3693 case Instruction::SetNE:
3694 if (LoOverflow && HiOverflow)
3695 return ReplaceInstUsesWith(I, ConstantBool::True);
3696 else if (HiOverflow)
3697 return new SetCondInst(Instruction::SetLT, X, LoBound);
3698 else if (LoOverflow)
3699 return new SetCondInst(Instruction::SetGE, X, HiBound);
3701 return InsertRangeTest(X, LoBound, HiBound, false, I);
3702 case Instruction::SetLT:
3704 return ReplaceInstUsesWith(I, ConstantBool::False);
3705 return new SetCondInst(Instruction::SetLT, X, LoBound);
3706 case Instruction::SetGT:
3708 return ReplaceInstUsesWith(I, ConstantBool::False);
3709 return new SetCondInst(Instruction::SetGE, X, HiBound);
3716 // Simplify seteq and setne instructions...
3717 if (I.getOpcode() == Instruction::SetEQ ||
3718 I.getOpcode() == Instruction::SetNE) {
3719 bool isSetNE = I.getOpcode() == Instruction::SetNE;
3721 // If the first operand is (and|or|xor) with a constant, and the second
3722 // operand is a constant, simplify a bit.
3723 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0)) {
3724 switch (BO->getOpcode()) {
3725 case Instruction::Rem:
3726 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
3727 if (CI->isNullValue() && isa<ConstantSInt>(BO->getOperand(1)) &&
3729 cast<ConstantSInt>(BO->getOperand(1))->getValue() > 1) {
3730 int64_t V = cast<ConstantSInt>(BO->getOperand(1))->getValue();
3731 if (isPowerOf2_64(V)) {
3732 unsigned L2 = Log2_64(V);
3733 const Type *UTy = BO->getType()->getUnsignedVersion();
3734 Value *NewX = InsertNewInstBefore(new CastInst(BO->getOperand(0),
3736 Constant *RHSCst = ConstantUInt::get(UTy, 1ULL << L2);
3737 Value *NewRem =InsertNewInstBefore(BinaryOperator::createRem(NewX,
3738 RHSCst, BO->getName()), I);
3739 return BinaryOperator::create(I.getOpcode(), NewRem,
3740 Constant::getNullValue(UTy));
3745 case Instruction::Add:
3746 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
3747 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
3748 if (BO->hasOneUse())
3749 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3750 ConstantExpr::getSub(CI, BOp1C));
3751 } else if (CI->isNullValue()) {
3752 // Replace ((add A, B) != 0) with (A != -B) if A or B is
3753 // efficiently invertible, or if the add has just this one use.
3754 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
3756 if (Value *NegVal = dyn_castNegVal(BOp1))
3757 return new SetCondInst(I.getOpcode(), BOp0, NegVal);
3758 else if (Value *NegVal = dyn_castNegVal(BOp0))
3759 return new SetCondInst(I.getOpcode(), NegVal, BOp1);
3760 else if (BO->hasOneUse()) {
3761 Instruction *Neg = BinaryOperator::createNeg(BOp1, BO->getName());
3763 InsertNewInstBefore(Neg, I);
3764 return new SetCondInst(I.getOpcode(), BOp0, Neg);
3768 case Instruction::Xor:
3769 // For the xor case, we can xor two constants together, eliminating
3770 // the explicit xor.
3771 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
3772 return BinaryOperator::create(I.getOpcode(), BO->getOperand(0),
3773 ConstantExpr::getXor(CI, BOC));
3776 case Instruction::Sub:
3777 // Replace (([sub|xor] A, B) != 0) with (A != B)
3778 if (CI->isNullValue())
3779 return new SetCondInst(I.getOpcode(), BO->getOperand(0),
3783 case Instruction::Or:
3784 // If bits are being or'd in that are not present in the constant we
3785 // are comparing against, then the comparison could never succeed!
3786 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
3787 Constant *NotCI = ConstantExpr::getNot(CI);
3788 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
3789 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
3793 case Instruction::And:
3794 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
3795 // If bits are being compared against that are and'd out, then the
3796 // comparison can never succeed!
3797 if (!ConstantExpr::getAnd(CI,
3798 ConstantExpr::getNot(BOC))->isNullValue())
3799 return ReplaceInstUsesWith(I, ConstantBool::get(isSetNE));
3801 // If we have ((X & C) == C), turn it into ((X & C) != 0).
3802 if (CI == BOC && isOneBitSet(CI))
3803 return new SetCondInst(isSetNE ? Instruction::SetEQ :
3804 Instruction::SetNE, Op0,
3805 Constant::getNullValue(CI->getType()));
3807 // Replace (and X, (1 << size(X)-1) != 0) with x < 0, converting X
3808 // to be a signed value as appropriate.
3809 if (isSignBit(BOC)) {
3810 Value *X = BO->getOperand(0);
3811 // If 'X' is not signed, insert a cast now...
3812 if (!BOC->getType()->isSigned()) {
3813 const Type *DestTy = BOC->getType()->getSignedVersion();
3814 X = InsertCastBefore(X, DestTy, I);
3816 return new SetCondInst(isSetNE ? Instruction::SetLT :
3817 Instruction::SetGE, X,
3818 Constant::getNullValue(X->getType()));
3821 // ((X & ~7) == 0) --> X < 8
3822 if (CI->isNullValue() && isHighOnes(BOC)) {
3823 Value *X = BO->getOperand(0);
3824 Constant *NegX = ConstantExpr::getNeg(BOC);
3826 // If 'X' is signed, insert a cast now.
3827 if (NegX->getType()->isSigned()) {
3828 const Type *DestTy = NegX->getType()->getUnsignedVersion();
3829 X = InsertCastBefore(X, DestTy, I);
3830 NegX = ConstantExpr::getCast(NegX, DestTy);
3833 return new SetCondInst(isSetNE ? Instruction::SetGE :
3834 Instruction::SetLT, X, NegX);
3841 } else { // Not a SetEQ/SetNE
3842 // If the LHS is a cast from an integral value of the same size,
3843 if (CastInst *Cast = dyn_cast<CastInst>(Op0)) {
3844 Value *CastOp = Cast->getOperand(0);
3845 const Type *SrcTy = CastOp->getType();
3846 unsigned SrcTySize = SrcTy->getPrimitiveSizeInBits();
3847 if (SrcTy != Cast->getType() && SrcTy->isInteger() &&
3848 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
3849 assert((SrcTy->isSigned() ^ Cast->getType()->isSigned()) &&
3850 "Source and destination signednesses should differ!");
3851 if (Cast->getType()->isSigned()) {
3852 // If this is a signed comparison, check for comparisons in the
3853 // vicinity of zero.
3854 if (I.getOpcode() == Instruction::SetLT && CI->isNullValue())
3856 return BinaryOperator::createSetGT(CastOp,
3857 ConstantUInt::get(SrcTy, (1ULL << (SrcTySize-1))-1));
3858 else if (I.getOpcode() == Instruction::SetGT &&
3859 cast<ConstantSInt>(CI)->getValue() == -1)
3860 // X > -1 => x < 128
3861 return BinaryOperator::createSetLT(CastOp,
3862 ConstantUInt::get(SrcTy, 1ULL << (SrcTySize-1)));
3864 ConstantUInt *CUI = cast<ConstantUInt>(CI);
3865 if (I.getOpcode() == Instruction::SetLT &&
3866 CUI->getValue() == 1ULL << (SrcTySize-1))
3867 // X < 128 => X > -1
3868 return BinaryOperator::createSetGT(CastOp,
3869 ConstantSInt::get(SrcTy, -1));
3870 else if (I.getOpcode() == Instruction::SetGT &&
3871 CUI->getValue() == (1ULL << (SrcTySize-1))-1)
3873 return BinaryOperator::createSetLT(CastOp,
3874 Constant::getNullValue(SrcTy));
3881 // Handle setcc with constant RHS's that can be integer, FP or pointer.
3882 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
3883 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
3884 switch (LHSI->getOpcode()) {
3885 case Instruction::GetElementPtr:
3886 if (RHSC->isNullValue()) {
3887 // Transform setcc GEP P, int 0, int 0, int 0, null -> setcc P, null
3888 bool isAllZeros = true;
3889 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
3890 if (!isa<Constant>(LHSI->getOperand(i)) ||
3891 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
3896 return new SetCondInst(I.getOpcode(), LHSI->getOperand(0),
3897 Constant::getNullValue(LHSI->getOperand(0)->getType()));
3901 case Instruction::PHI:
3902 if (Instruction *NV = FoldOpIntoPhi(I))
3905 case Instruction::Select:
3906 // If either operand of the select is a constant, we can fold the
3907 // comparison into the select arms, which will cause one to be
3908 // constant folded and the select turned into a bitwise or.
3909 Value *Op1 = 0, *Op2 = 0;
3910 if (LHSI->hasOneUse()) {
3911 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
3912 // Fold the known value into the constant operand.
3913 Op1 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3914 // Insert a new SetCC of the other select operand.
3915 Op2 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3916 LHSI->getOperand(2), RHSC,
3918 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
3919 // Fold the known value into the constant operand.
3920 Op2 = ConstantExpr::get(I.getOpcode(), C, RHSC);
3921 // Insert a new SetCC of the other select operand.
3922 Op1 = InsertNewInstBefore(new SetCondInst(I.getOpcode(),
3923 LHSI->getOperand(1), RHSC,
3929 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
3934 // If we can optimize a 'setcc GEP, P' or 'setcc P, GEP', do so now.
3935 if (User *GEP = dyn_castGetElementPtr(Op0))
3936 if (Instruction *NI = FoldGEPSetCC(GEP, Op1, I.getOpcode(), I))
3938 if (User *GEP = dyn_castGetElementPtr(Op1))
3939 if (Instruction *NI = FoldGEPSetCC(GEP, Op0,
3940 SetCondInst::getSwappedCondition(I.getOpcode()), I))
3943 // Test to see if the operands of the setcc are casted versions of other
3944 // values. If the cast can be stripped off both arguments, we do so now.
3945 if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3946 Value *CastOp0 = CI->getOperand(0);
3947 if (CastOp0->getType()->isLosslesslyConvertibleTo(CI->getType()) &&
3948 (isa<Constant>(Op1) || isa<CastInst>(Op1)) &&
3949 (I.getOpcode() == Instruction::SetEQ ||
3950 I.getOpcode() == Instruction::SetNE)) {
3951 // We keep moving the cast from the left operand over to the right
3952 // operand, where it can often be eliminated completely.
3955 // If operand #1 is a cast instruction, see if we can eliminate it as
3957 if (CastInst *CI2 = dyn_cast<CastInst>(Op1))
3958 if (CI2->getOperand(0)->getType()->isLosslesslyConvertibleTo(
3960 Op1 = CI2->getOperand(0);
3962 // If Op1 is a constant, we can fold the cast into the constant.
3963 if (Op1->getType() != Op0->getType())
3964 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
3965 Op1 = ConstantExpr::getCast(Op1C, Op0->getType());
3967 // Otherwise, cast the RHS right before the setcc
3968 Op1 = new CastInst(Op1, Op0->getType(), Op1->getName());
3969 InsertNewInstBefore(cast<Instruction>(Op1), I);
3971 return BinaryOperator::create(I.getOpcode(), Op0, Op1);
3974 // Handle the special case of: setcc (cast bool to X), <cst>
3975 // This comes up when you have code like
3978 // For generality, we handle any zero-extension of any operand comparison
3979 // with a constant or another cast from the same type.
3980 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
3981 if (Instruction *R = visitSetCondInstWithCastAndCast(I))
3985 if (I.getOpcode() == Instruction::SetNE ||
3986 I.getOpcode() == Instruction::SetEQ) {
3988 if (match(Op0, m_Xor(m_Value(A), m_Value(B))) &&
3989 (A == Op1 || B == Op1)) {
3990 // (A^B) == A -> B == 0
3991 Value *OtherVal = A == Op1 ? B : A;
3992 return BinaryOperator::create(I.getOpcode(), OtherVal,
3993 Constant::getNullValue(A->getType()));
3994 } else if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
3995 (A == Op0 || B == Op0)) {
3996 // A == (A^B) -> B == 0
3997 Value *OtherVal = A == Op0 ? B : A;
3998 return BinaryOperator::create(I.getOpcode(), OtherVal,
3999 Constant::getNullValue(A->getType()));
4000 } else if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
4001 // (A-B) == A -> B == 0
4002 return BinaryOperator::create(I.getOpcode(), B,
4003 Constant::getNullValue(B->getType()));
4004 } else if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
4005 // A == (A-B) -> B == 0
4006 return BinaryOperator::create(I.getOpcode(), B,
4007 Constant::getNullValue(B->getType()));
4010 return Changed ? &I : 0;
4013 // visitSetCondInstWithCastAndCast - Handle setcond (cast x to y), (cast/cst).
4014 // We only handle extending casts so far.
4016 Instruction *InstCombiner::visitSetCondInstWithCastAndCast(SetCondInst &SCI) {
4017 Value *LHSCIOp = cast<CastInst>(SCI.getOperand(0))->getOperand(0);
4018 const Type *SrcTy = LHSCIOp->getType();
4019 const Type *DestTy = SCI.getOperand(0)->getType();
4022 if (!DestTy->isIntegral() || !SrcTy->isIntegral())
4025 unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
4026 unsigned DestBits = DestTy->getPrimitiveSizeInBits();
4027 if (SrcBits >= DestBits) return 0; // Only handle extending cast.
4029 // Is this a sign or zero extension?
4030 bool isSignSrc = SrcTy->isSigned();
4031 bool isSignDest = DestTy->isSigned();
4033 if (CastInst *CI = dyn_cast<CastInst>(SCI.getOperand(1))) {
4034 // Not an extension from the same type?
4035 RHSCIOp = CI->getOperand(0);
4036 if (RHSCIOp->getType() != LHSCIOp->getType()) return 0;
4037 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(SCI.getOperand(1))) {
4038 // Compute the constant that would happen if we truncated to SrcTy then
4039 // reextended to DestTy.
4040 Constant *Res = ConstantExpr::getCast(CI, SrcTy);
4042 if (ConstantExpr::getCast(Res, DestTy) == CI) {
4045 // If the value cannot be represented in the shorter type, we cannot emit
4046 // a simple comparison.
4047 if (SCI.getOpcode() == Instruction::SetEQ)
4048 return ReplaceInstUsesWith(SCI, ConstantBool::False);
4049 if (SCI.getOpcode() == Instruction::SetNE)
4050 return ReplaceInstUsesWith(SCI, ConstantBool::True);
4052 // Evaluate the comparison for LT.
4054 if (DestTy->isSigned()) {
4055 // We're performing a signed comparison.
4057 // Signed extend and signed comparison.
4058 if (cast<ConstantSInt>(CI)->getValue() < 0) // X < (small) --> false
4059 Result = ConstantBool::False;
4061 Result = ConstantBool::True; // X < (large) --> true
4063 // Unsigned extend and signed comparison.
4064 if (cast<ConstantSInt>(CI)->getValue() < 0)
4065 Result = ConstantBool::False;
4067 Result = ConstantBool::True;
4070 // We're performing an unsigned comparison.
4072 // Unsigned extend & compare -> always true.
4073 Result = ConstantBool::True;
4075 // We're performing an unsigned comp with a sign extended value.
4076 // This is true if the input is >= 0. [aka >s -1]
4077 Constant *NegOne = ConstantIntegral::getAllOnesValue(SrcTy);
4078 Result = InsertNewInstBefore(BinaryOperator::createSetGT(LHSCIOp,
4079 NegOne, SCI.getName()), SCI);
4083 // Finally, return the value computed.
4084 if (SCI.getOpcode() == Instruction::SetLT) {
4085 return ReplaceInstUsesWith(SCI, Result);
4087 assert(SCI.getOpcode()==Instruction::SetGT &&"SetCC should be folded!");
4088 if (Constant *CI = dyn_cast<Constant>(Result))
4089 return ReplaceInstUsesWith(SCI, ConstantExpr::getNot(CI));
4091 return BinaryOperator::createNot(Result);
4098 // Okay, just insert a compare of the reduced operands now!
4099 return BinaryOperator::create(SCI.getOpcode(), LHSCIOp, RHSCIOp);
4102 Instruction *InstCombiner::visitShiftInst(ShiftInst &I) {
4103 assert(I.getOperand(1)->getType() == Type::UByteTy);
4104 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4105 bool isLeftShift = I.getOpcode() == Instruction::Shl;
4107 // shl X, 0 == X and shr X, 0 == X
4108 // shl 0, X == 0 and shr 0, X == 0
4109 if (Op1 == Constant::getNullValue(Type::UByteTy) ||
4110 Op0 == Constant::getNullValue(Op0->getType()))
4111 return ReplaceInstUsesWith(I, Op0);
4113 if (isa<UndefValue>(Op0)) { // undef >>s X -> undef
4114 if (!isLeftShift && I.getType()->isSigned())
4115 return ReplaceInstUsesWith(I, Op0);
4116 else // undef << X -> 0 AND undef >>u X -> 0
4117 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4119 if (isa<UndefValue>(Op1)) {
4120 if (isLeftShift || I.getType()->isUnsigned())// X << undef, X >>u undef -> 0
4121 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4123 return ReplaceInstUsesWith(I, Op0); // X >>s undef -> X
4126 // shr int -1, X = -1 (for any arithmetic shift rights of ~0)
4128 if (ConstantSInt *CSI = dyn_cast<ConstantSInt>(Op0))
4129 if (CSI->isAllOnesValue())
4130 return ReplaceInstUsesWith(I, CSI);
4132 // Try to fold constant and into select arguments.
4133 if (isa<Constant>(Op0))
4134 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
4135 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4138 // See if we can turn a signed shr into an unsigned shr.
4139 if (!isLeftShift && I.getType()->isSigned()) {
4140 if (MaskedValueIsZero(Op0,
4141 1ULL << (I.getType()->getPrimitiveSizeInBits()-1))) {
4142 Value *V = InsertCastBefore(Op0, I.getType()->getUnsignedVersion(), I);
4143 V = InsertNewInstBefore(new ShiftInst(Instruction::Shr, V, Op1,
4145 return new CastInst(V, I.getType());
4149 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op1))
4150 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
4155 Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantUInt *Op1,
4157 bool isLeftShift = I.getOpcode() == Instruction::Shl;
4158 bool isSignedShift = Op0->getType()->isSigned();
4159 bool isUnsignedShift = !isSignedShift;
4161 // See if we can simplify any instructions used by the instruction whose sole
4162 // purpose is to compute bits we don't care about.
4163 uint64_t KnownZero, KnownOne;
4164 if (SimplifyDemandedBits(&I, I.getType()->getIntegralTypeMask(),
4165 KnownZero, KnownOne))
4168 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
4169 // of a signed value.
4171 unsigned TypeBits = Op0->getType()->getPrimitiveSizeInBits();
4172 if (Op1->getValue() >= TypeBits) {
4173 if (isUnsignedShift || isLeftShift)
4174 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
4176 I.setOperand(1, ConstantUInt::get(Type::UByteTy, TypeBits-1));
4181 // ((X*C1) << C2) == (X * (C1 << C2))
4182 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
4183 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
4184 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
4185 return BinaryOperator::createMul(BO->getOperand(0),
4186 ConstantExpr::getShl(BOOp, Op1));
4188 // Try to fold constant and into select arguments.
4189 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4190 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4192 if (isa<PHINode>(Op0))
4193 if (Instruction *NV = FoldOpIntoPhi(I))
4196 if (Op0->hasOneUse()) {
4197 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
4198 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4201 switch (Op0BO->getOpcode()) {
4203 case Instruction::Add:
4204 case Instruction::And:
4205 case Instruction::Or:
4206 case Instruction::Xor:
4207 // These operators commute.
4208 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
4209 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4210 match(Op0BO->getOperand(1),
4211 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
4212 Instruction *YS = new ShiftInst(Instruction::Shl,
4213 Op0BO->getOperand(0), Op1,
4215 InsertNewInstBefore(YS, I); // (Y << C)
4217 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4218 Op0BO->getOperand(1)->getName());
4219 InsertNewInstBefore(X, I); // (X + (Y << C))
4220 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
4221 C2 = ConstantExpr::getShl(C2, Op1);
4222 return BinaryOperator::createAnd(X, C2);
4225 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
4226 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
4227 match(Op0BO->getOperand(1),
4228 m_And(m_Shr(m_Value(V1), m_Value(V2)),
4229 m_ConstantInt(CC))) && V2 == Op1 &&
4230 cast<BinaryOperator>(Op0BO->getOperand(1))->getOperand(0)->hasOneUse()) {
4231 Instruction *YS = new ShiftInst(Instruction::Shl,
4232 Op0BO->getOperand(0), Op1,
4234 InsertNewInstBefore(YS, I); // (Y << C)
4236 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
4237 V1->getName()+".mask");
4238 InsertNewInstBefore(XM, I); // X & (CC << C)
4240 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4244 case Instruction::Sub:
4245 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
4246 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4247 match(Op0BO->getOperand(0),
4248 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
4249 Instruction *YS = new ShiftInst(Instruction::Shl,
4250 Op0BO->getOperand(1), Op1,
4252 InsertNewInstBefore(YS, I); // (Y << C)
4254 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
4255 Op0BO->getOperand(0)->getName());
4256 InsertNewInstBefore(X, I); // (X + (Y << C))
4257 Constant *C2 = ConstantInt::getAllOnesValue(X->getType());
4258 C2 = ConstantExpr::getShl(C2, Op1);
4259 return BinaryOperator::createAnd(X, C2);
4262 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
4263 match(Op0BO->getOperand(0),
4264 m_And(m_Shr(m_Value(V1), m_Value(V2)),
4265 m_ConstantInt(CC))) && V2 == Op1 &&
4266 cast<BinaryOperator>(Op0BO->getOperand(0))
4267 ->getOperand(0)->hasOneUse()) {
4268 Instruction *YS = new ShiftInst(Instruction::Shl,
4269 Op0BO->getOperand(1), Op1,
4271 InsertNewInstBefore(YS, I); // (Y << C)
4273 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
4274 V1->getName()+".mask");
4275 InsertNewInstBefore(XM, I); // X & (CC << C)
4277 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
4284 // If the operand is an bitwise operator with a constant RHS, and the
4285 // shift is the only use, we can pull it out of the shift.
4286 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
4287 bool isValid = true; // Valid only for And, Or, Xor
4288 bool highBitSet = false; // Transform if high bit of constant set?
4290 switch (Op0BO->getOpcode()) {
4291 default: isValid = false; break; // Do not perform transform!
4292 case Instruction::Add:
4293 isValid = isLeftShift;
4295 case Instruction::Or:
4296 case Instruction::Xor:
4299 case Instruction::And:
4304 // If this is a signed shift right, and the high bit is modified
4305 // by the logical operation, do not perform the transformation.
4306 // The highBitSet boolean indicates the value of the high bit of
4307 // the constant which would cause it to be modified for this
4310 if (isValid && !isLeftShift && isSignedShift) {
4311 uint64_t Val = Op0C->getRawValue();
4312 isValid = ((Val & (1 << (TypeBits-1))) != 0) == highBitSet;
4316 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
4318 Instruction *NewShift =
4319 new ShiftInst(I.getOpcode(), Op0BO->getOperand(0), Op1,
4322 InsertNewInstBefore(NewShift, I);
4324 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
4331 // Find out if this is a shift of a shift by a constant.
4332 ShiftInst *ShiftOp = 0;
4333 if (ShiftInst *Op0SI = dyn_cast<ShiftInst>(Op0))
4335 else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4336 // If this is a noop-integer case of a shift instruction, use the shift.
4337 if (CI->getOperand(0)->getType()->isInteger() &&
4338 CI->getOperand(0)->getType()->getPrimitiveSizeInBits() ==
4339 CI->getType()->getPrimitiveSizeInBits() &&
4340 isa<ShiftInst>(CI->getOperand(0))) {
4341 ShiftOp = cast<ShiftInst>(CI->getOperand(0));
4345 if (ShiftOp && isa<ConstantUInt>(ShiftOp->getOperand(1))) {
4346 // Find the operands and properties of the input shift. Note that the
4347 // signedness of the input shift may differ from the current shift if there
4348 // is a noop cast between the two.
4349 bool isShiftOfLeftShift = ShiftOp->getOpcode() == Instruction::Shl;
4350 bool isShiftOfSignedShift = ShiftOp->getType()->isSigned();
4351 bool isShiftOfUnsignedShift = !isShiftOfSignedShift;
4353 ConstantUInt *ShiftAmt1C = cast<ConstantUInt>(ShiftOp->getOperand(1));
4355 unsigned ShiftAmt1 = (unsigned)ShiftAmt1C->getValue();
4356 unsigned ShiftAmt2 = (unsigned)Op1->getValue();
4358 // Check for (A << c1) << c2 and (A >> c1) >> c2.
4359 if (isLeftShift == isShiftOfLeftShift) {
4360 // Do not fold these shifts if the first one is signed and the second one
4361 // is unsigned and this is a right shift. Further, don't do any folding
4363 if (isShiftOfSignedShift && isUnsignedShift && !isLeftShift)
4366 unsigned Amt = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
4367 if (Amt > Op0->getType()->getPrimitiveSizeInBits())
4368 Amt = Op0->getType()->getPrimitiveSizeInBits();
4370 Value *Op = ShiftOp->getOperand(0);
4371 if (isShiftOfSignedShift != isSignedShift)
4372 Op = InsertNewInstBefore(new CastInst(Op, I.getType(), "tmp"), I);
4373 return new ShiftInst(I.getOpcode(), Op,
4374 ConstantUInt::get(Type::UByteTy, Amt));
4377 // Check for (A << c1) >> c2 or (A >> c1) << c2. If we are dealing with
4378 // signed types, we can only support the (A >> c1) << c2 configuration,
4379 // because it can not turn an arbitrary bit of A into a sign bit.
4380 if (isUnsignedShift || isLeftShift) {
4381 // Calculate bitmask for what gets shifted off the edge.
4382 Constant *C = ConstantIntegral::getAllOnesValue(I.getType());
4384 C = ConstantExpr::getShl(C, ShiftAmt1C);
4386 C = ConstantExpr::getUShr(C, ShiftAmt1C);
4388 Value *Op = ShiftOp->getOperand(0);
4389 if (isShiftOfSignedShift != isSignedShift)
4390 Op = InsertNewInstBefore(new CastInst(Op, I.getType(),Op->getName()),I);
4393 BinaryOperator::createAnd(Op, C, Op->getName()+".mask");
4394 InsertNewInstBefore(Mask, I);
4396 // Figure out what flavor of shift we should use...
4397 if (ShiftAmt1 == ShiftAmt2) {
4398 return ReplaceInstUsesWith(I, Mask); // (A << c) >> c === A & c2
4399 } else if (ShiftAmt1 < ShiftAmt2) {
4400 return new ShiftInst(I.getOpcode(), Mask,
4401 ConstantUInt::get(Type::UByteTy, ShiftAmt2-ShiftAmt1));
4402 } else if (isShiftOfUnsignedShift || isShiftOfLeftShift) {
4403 if (isShiftOfUnsignedShift && !isShiftOfLeftShift && isSignedShift) {
4404 // Make sure to emit an unsigned shift right, not a signed one.
4405 Mask = InsertNewInstBefore(new CastInst(Mask,
4406 Mask->getType()->getUnsignedVersion(),
4408 Mask = new ShiftInst(Instruction::Shr, Mask,
4409 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4410 InsertNewInstBefore(Mask, I);
4411 return new CastInst(Mask, I.getType());
4413 return new ShiftInst(ShiftOp->getOpcode(), Mask,
4414 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4417 // (X >>s C1) << C2 where C1 > C2 === (X >>s (C1-C2)) & mask
4418 Op = InsertNewInstBefore(new CastInst(Mask,
4419 I.getType()->getSignedVersion(),
4420 Mask->getName()), I);
4421 Instruction *Shift =
4422 new ShiftInst(ShiftOp->getOpcode(), Op,
4423 ConstantUInt::get(Type::UByteTy, ShiftAmt1-ShiftAmt2));
4424 InsertNewInstBefore(Shift, I);
4426 C = ConstantIntegral::getAllOnesValue(Shift->getType());
4427 C = ConstantExpr::getShl(C, Op1);
4428 Mask = BinaryOperator::createAnd(Shift, C, Op->getName()+".mask");
4429 InsertNewInstBefore(Mask, I);
4430 return new CastInst(Mask, I.getType());
4433 // We can handle signed (X << C1) >>s C2 if it's a sign extend. In
4434 // this case, C1 == C2 and C1 is 8, 16, or 32.
4435 if (ShiftAmt1 == ShiftAmt2) {
4436 const Type *SExtType = 0;
4437 switch (ShiftAmt1) {
4438 case 8 : SExtType = Type::SByteTy; break;
4439 case 16: SExtType = Type::ShortTy; break;
4440 case 32: SExtType = Type::IntTy; break;
4444 Instruction *NewTrunc = new CastInst(ShiftOp->getOperand(0),
4446 InsertNewInstBefore(NewTrunc, I);
4447 return new CastInst(NewTrunc, I.getType());
4462 /// getCastType - In the future, we will split the cast instruction into these
4463 /// various types. Until then, we have to do the analysis here.
4464 static CastType getCastType(const Type *Src, const Type *Dest) {
4465 assert(Src->isIntegral() && Dest->isIntegral() &&
4466 "Only works on integral types!");
4467 unsigned SrcSize = Src->getPrimitiveSizeInBits();
4468 unsigned DestSize = Dest->getPrimitiveSizeInBits();
4470 if (SrcSize == DestSize) return Noop;
4471 if (SrcSize > DestSize) return Truncate;
4472 if (Src->isSigned()) return Signext;
4477 // isEliminableCastOfCast - Return true if it is valid to eliminate the CI
4480 static bool isEliminableCastOfCast(const Type *SrcTy, const Type *MidTy,
4481 const Type *DstTy, TargetData *TD) {
4483 // It is legal to eliminate the instruction if casting A->B->A if the sizes
4484 // are identical and the bits don't get reinterpreted (for example
4485 // int->float->int would not be allowed).
4486 if (SrcTy == DstTy && SrcTy->isLosslesslyConvertibleTo(MidTy))
4489 // If we are casting between pointer and integer types, treat pointers as
4490 // integers of the appropriate size for the code below.
4491 if (isa<PointerType>(SrcTy)) SrcTy = TD->getIntPtrType();
4492 if (isa<PointerType>(MidTy)) MidTy = TD->getIntPtrType();
4493 if (isa<PointerType>(DstTy)) DstTy = TD->getIntPtrType();
4495 // Allow free casting and conversion of sizes as long as the sign doesn't
4497 if (SrcTy->isIntegral() && MidTy->isIntegral() && DstTy->isIntegral()) {
4498 CastType FirstCast = getCastType(SrcTy, MidTy);
4499 CastType SecondCast = getCastType(MidTy, DstTy);
4501 // Capture the effect of these two casts. If the result is a legal cast,
4502 // the CastType is stored here, otherwise a special code is used.
4503 static const unsigned CastResult[] = {
4504 // First cast is noop
4506 // First cast is a truncate
4507 1, 1, 4, 4, // trunc->extend is not safe to eliminate
4508 // First cast is a sign ext
4509 2, 5, 2, 4, // signext->zeroext never ok
4510 // First cast is a zero ext
4514 unsigned Result = CastResult[FirstCast*4+SecondCast];
4516 default: assert(0 && "Illegal table value!");
4521 // FIXME: in the future, when LLVM has explicit sign/zeroextends and
4522 // truncates, we could eliminate more casts.
4523 return (unsigned)getCastType(SrcTy, DstTy) == Result;
4525 return false; // Not possible to eliminate this here.
4527 // Sign or zero extend followed by truncate is always ok if the result
4528 // is a truncate or noop.
4529 CastType ResultCast = getCastType(SrcTy, DstTy);
4530 if (ResultCast == Noop || ResultCast == Truncate)
4532 // Otherwise we are still growing the value, we are only safe if the
4533 // result will match the sign/zeroextendness of the result.
4534 return ResultCast == FirstCast;
4538 // If this is a cast from 'float -> double -> integer', cast from
4539 // 'float -> integer' directly, as the value isn't changed by the
4540 // float->double conversion.
4541 if (SrcTy->isFloatingPoint() && MidTy->isFloatingPoint() &&
4542 DstTy->isIntegral() &&
4543 SrcTy->getPrimitiveSize() < MidTy->getPrimitiveSize())
4546 // Packed type conversions don't modify bits.
4547 if (isa<PackedType>(SrcTy) && isa<PackedType>(MidTy) &&isa<PackedType>(DstTy))
4553 static bool ValueRequiresCast(const Value *V, const Type *Ty, TargetData *TD) {
4554 if (V->getType() == Ty || isa<Constant>(V)) return false;
4555 if (const CastInst *CI = dyn_cast<CastInst>(V))
4556 if (isEliminableCastOfCast(CI->getOperand(0)->getType(), CI->getType(), Ty,
4562 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
4563 /// InsertBefore instruction. This is specialized a bit to avoid inserting
4564 /// casts that are known to not do anything...
4566 Value *InstCombiner::InsertOperandCastBefore(Value *V, const Type *DestTy,
4567 Instruction *InsertBefore) {
4568 if (V->getType() == DestTy) return V;
4569 if (Constant *C = dyn_cast<Constant>(V))
4570 return ConstantExpr::getCast(C, DestTy);
4572 CastInst *CI = new CastInst(V, DestTy, V->getName());
4573 InsertNewInstBefore(CI, *InsertBefore);
4577 /// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
4578 /// expression. If so, decompose it, returning some value X, such that Val is
4581 static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
4583 assert(Val->getType() == Type::UIntTy && "Unexpected allocation size type!");
4584 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(Val)) {
4585 Offset = CI->getValue();
4587 return ConstantUInt::get(Type::UIntTy, 0);
4588 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
4589 if (I->getNumOperands() == 2) {
4590 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(I->getOperand(1))) {
4591 if (I->getOpcode() == Instruction::Shl) {
4592 // This is a value scaled by '1 << the shift amt'.
4593 Scale = 1U << CUI->getValue();
4595 return I->getOperand(0);
4596 } else if (I->getOpcode() == Instruction::Mul) {
4597 // This value is scaled by 'CUI'.
4598 Scale = CUI->getValue();
4600 return I->getOperand(0);
4601 } else if (I->getOpcode() == Instruction::Add) {
4602 // We have X+C. Check to see if we really have (X*C2)+C1, where C1 is
4605 Value *SubVal = DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
4607 Offset += CUI->getValue();
4608 if (SubScale > 1 && (Offset % SubScale == 0)) {
4617 // Otherwise, we can't look past this.
4624 /// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
4625 /// try to eliminate the cast by moving the type information into the alloc.
4626 Instruction *InstCombiner::PromoteCastOfAllocation(CastInst &CI,
4627 AllocationInst &AI) {
4628 const PointerType *PTy = dyn_cast<PointerType>(CI.getType());
4629 if (!PTy) return 0; // Not casting the allocation to a pointer type.
4631 // Remove any uses of AI that are dead.
4632 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
4633 std::vector<Instruction*> DeadUsers;
4634 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
4635 Instruction *User = cast<Instruction>(*UI++);
4636 if (isInstructionTriviallyDead(User)) {
4637 while (UI != E && *UI == User)
4638 ++UI; // If this instruction uses AI more than once, don't break UI.
4640 // Add operands to the worklist.
4641 AddUsesToWorkList(*User);
4643 DEBUG(std::cerr << "IC: DCE: " << *User);
4645 User->eraseFromParent();
4646 removeFromWorkList(User);
4650 // Get the type really allocated and the type casted to.
4651 const Type *AllocElTy = AI.getAllocatedType();
4652 const Type *CastElTy = PTy->getElementType();
4653 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
4655 unsigned AllocElTyAlign = TD->getTypeSize(AllocElTy);
4656 unsigned CastElTyAlign = TD->getTypeSize(CastElTy);
4657 if (CastElTyAlign < AllocElTyAlign) return 0;
4659 // If the allocation has multiple uses, only promote it if we are strictly
4660 // increasing the alignment of the resultant allocation. If we keep it the
4661 // same, we open the door to infinite loops of various kinds.
4662 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
4664 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
4665 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
4666 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
4668 // See if we can satisfy the modulus by pulling a scale out of the array
4670 unsigned ArraySizeScale, ArrayOffset;
4671 Value *NumElements = // See if the array size is a decomposable linear expr.
4672 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
4674 // If we can now satisfy the modulus, by using a non-1 scale, we really can
4676 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
4677 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
4679 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
4684 Amt = ConstantUInt::get(Type::UIntTy, Scale);
4685 if (ConstantUInt *CI = dyn_cast<ConstantUInt>(NumElements))
4686 Amt = ConstantExpr::getMul(CI, cast<ConstantUInt>(Amt));
4687 else if (Scale != 1) {
4688 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
4689 Amt = InsertNewInstBefore(Tmp, AI);
4693 if (unsigned Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
4694 Value *Off = ConstantUInt::get(Type::UIntTy, Offset);
4695 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
4696 Amt = InsertNewInstBefore(Tmp, AI);
4699 std::string Name = AI.getName(); AI.setName("");
4700 AllocationInst *New;
4701 if (isa<MallocInst>(AI))
4702 New = new MallocInst(CastElTy, Amt, AI.getAlignment(), Name);
4704 New = new AllocaInst(CastElTy, Amt, AI.getAlignment(), Name);
4705 InsertNewInstBefore(New, AI);
4707 // If the allocation has multiple uses, insert a cast and change all things
4708 // that used it to use the new cast. This will also hack on CI, but it will
4710 if (!AI.hasOneUse()) {
4711 AddUsesToWorkList(AI);
4712 CastInst *NewCast = new CastInst(New, AI.getType(), "tmpcast");
4713 InsertNewInstBefore(NewCast, AI);
4714 AI.replaceAllUsesWith(NewCast);
4716 return ReplaceInstUsesWith(CI, New);
4720 // CastInst simplification
4722 Instruction *InstCombiner::visitCastInst(CastInst &CI) {
4723 Value *Src = CI.getOperand(0);
4725 // If the user is casting a value to the same type, eliminate this cast
4727 if (CI.getType() == Src->getType())
4728 return ReplaceInstUsesWith(CI, Src);
4730 if (isa<UndefValue>(Src)) // cast undef -> undef
4731 return ReplaceInstUsesWith(CI, UndefValue::get(CI.getType()));
4733 // If casting the result of another cast instruction, try to eliminate this
4736 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
4737 Value *A = CSrc->getOperand(0);
4738 if (isEliminableCastOfCast(A->getType(), CSrc->getType(),
4739 CI.getType(), TD)) {
4740 // This instruction now refers directly to the cast's src operand. This
4741 // has a good chance of making CSrc dead.
4742 CI.setOperand(0, CSrc->getOperand(0));
4746 // If this is an A->B->A cast, and we are dealing with integral types, try
4747 // to convert this into a logical 'and' instruction.
4749 if (A->getType()->isInteger() &&
4750 CI.getType()->isInteger() && CSrc->getType()->isInteger() &&
4751 CSrc->getType()->isUnsigned() && // B->A cast must zero extend
4752 CSrc->getType()->getPrimitiveSizeInBits() <
4753 CI.getType()->getPrimitiveSizeInBits()&&
4754 A->getType()->getPrimitiveSizeInBits() ==
4755 CI.getType()->getPrimitiveSizeInBits()) {
4756 assert(CSrc->getType() != Type::ULongTy &&
4757 "Cannot have type bigger than ulong!");
4758 uint64_t AndValue = CSrc->getType()->getIntegralTypeMask();
4759 Constant *AndOp = ConstantUInt::get(A->getType()->getUnsignedVersion(),
4761 AndOp = ConstantExpr::getCast(AndOp, A->getType());
4762 Instruction *And = BinaryOperator::createAnd(CSrc->getOperand(0), AndOp);
4763 if (And->getType() != CI.getType()) {
4764 And->setName(CSrc->getName()+".mask");
4765 InsertNewInstBefore(And, CI);
4766 And = new CastInst(And, CI.getType());
4772 // If this is a cast to bool, turn it into the appropriate setne instruction.
4773 if (CI.getType() == Type::BoolTy)
4774 return BinaryOperator::createSetNE(CI.getOperand(0),
4775 Constant::getNullValue(CI.getOperand(0)->getType()));
4777 // See if we can simplify any instructions used by the LHS whose sole
4778 // purpose is to compute bits we don't care about.
4779 if (CI.getType()->isInteger() && CI.getOperand(0)->getType()->isIntegral()) {
4780 uint64_t KnownZero, KnownOne;
4781 if (SimplifyDemandedBits(&CI, CI.getType()->getIntegralTypeMask(),
4782 KnownZero, KnownOne))
4786 // If casting the result of a getelementptr instruction with no offset, turn
4787 // this into a cast of the original pointer!
4789 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
4790 bool AllZeroOperands = true;
4791 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
4792 if (!isa<Constant>(GEP->getOperand(i)) ||
4793 !cast<Constant>(GEP->getOperand(i))->isNullValue()) {
4794 AllZeroOperands = false;
4797 if (AllZeroOperands) {
4798 CI.setOperand(0, GEP->getOperand(0));
4803 // If we are casting a malloc or alloca to a pointer to a type of the same
4804 // size, rewrite the allocation instruction to allocate the "right" type.
4806 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
4807 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
4810 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
4811 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
4813 if (isa<PHINode>(Src))
4814 if (Instruction *NV = FoldOpIntoPhi(CI))
4817 // If the source value is an instruction with only this use, we can attempt to
4818 // propagate the cast into the instruction. Also, only handle integral types
4820 if (Instruction *SrcI = dyn_cast<Instruction>(Src))
4821 if (SrcI->hasOneUse() && Src->getType()->isIntegral() &&
4822 CI.getType()->isInteger()) { // Don't mess with casts to bool here
4823 const Type *DestTy = CI.getType();
4824 unsigned SrcBitSize = Src->getType()->getPrimitiveSizeInBits();
4825 unsigned DestBitSize = DestTy->getPrimitiveSizeInBits();
4827 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
4828 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
4830 switch (SrcI->getOpcode()) {
4831 case Instruction::Add:
4832 case Instruction::Mul:
4833 case Instruction::And:
4834 case Instruction::Or:
4835 case Instruction::Xor:
4836 // If we are discarding information, or just changing the sign, rewrite.
4837 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
4838 // Don't insert two casts if they cannot be eliminated. We allow two
4839 // casts to be inserted if the sizes are the same. This could only be
4840 // converting signedness, which is a noop.
4841 if (DestBitSize == SrcBitSize || !ValueRequiresCast(Op1, DestTy,TD) ||
4842 !ValueRequiresCast(Op0, DestTy, TD)) {
4843 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4844 Value *Op1c = InsertOperandCastBefore(Op1, DestTy, SrcI);
4845 return BinaryOperator::create(cast<BinaryOperator>(SrcI)
4846 ->getOpcode(), Op0c, Op1c);
4850 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
4851 if (SrcBitSize == 1 && SrcI->getOpcode() == Instruction::Xor &&
4852 Op1 == ConstantBool::True &&
4853 (!Op0->hasOneUse() || !isa<SetCondInst>(Op0))) {
4854 Value *New = InsertOperandCastBefore(Op0, DestTy, &CI);
4855 return BinaryOperator::createXor(New,
4856 ConstantInt::get(CI.getType(), 1));
4859 case Instruction::Shl:
4860 // Allow changing the sign of the source operand. Do not allow changing
4861 // the size of the shift, UNLESS the shift amount is a constant. We
4862 // mush not change variable sized shifts to a smaller size, because it
4863 // is undefined to shift more bits out than exist in the value.
4864 if (DestBitSize == SrcBitSize ||
4865 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
4866 Value *Op0c = InsertOperandCastBefore(Op0, DestTy, SrcI);
4867 return new ShiftInst(Instruction::Shl, Op0c, Op1);
4870 case Instruction::Shr:
4871 // If this is a signed shr, and if all bits shifted in are about to be
4872 // truncated off, turn it into an unsigned shr to allow greater
4874 if (DestBitSize < SrcBitSize && Src->getType()->isSigned() &&
4875 isa<ConstantInt>(Op1)) {
4876 unsigned ShiftAmt = cast<ConstantUInt>(Op1)->getValue();
4877 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
4878 // Convert to unsigned.
4879 Value *N1 = InsertOperandCastBefore(Op0,
4880 Op0->getType()->getUnsignedVersion(), &CI);
4881 // Insert the new shift, which is now unsigned.
4882 N1 = InsertNewInstBefore(new ShiftInst(Instruction::Shr, N1,
4883 Op1, Src->getName()), CI);
4884 return new CastInst(N1, CI.getType());
4889 case Instruction::SetEQ:
4890 case Instruction::SetNE:
4891 // We if we are just checking for a seteq of a single bit and casting it
4892 // to an integer. If so, shift the bit to the appropriate place then
4893 // cast to integer to avoid the comparison.
4894 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(Op1)) {
4895 uint64_t Op1CV = Op1C->getZExtValue();
4896 // cast (X == 0) to int --> X^1 iff X has only the low bit set.
4897 // cast (X == 0) to int --> (X>>1)^1 iff X has only the 2nd bit set.
4898 // cast (X == 1) to int --> X iff X has only the low bit set.
4899 // cast (X == 2) to int --> X>>1 iff X has only the 2nd bit set.
4900 // cast (X != 0) to int --> X iff X has only the low bit set.
4901 // cast (X != 0) to int --> X>>1 iff X has only the 2nd bit set.
4902 // cast (X != 1) to int --> X^1 iff X has only the low bit set.
4903 // cast (X != 2) to int --> (X>>1)^1 iff X has only the 2nd bit set.
4904 if (Op1CV == 0 || isPowerOf2_64(Op1CV)) {
4905 // If Op1C some other power of two, convert:
4906 uint64_t KnownZero, KnownOne;
4907 uint64_t TypeMask = Op1->getType()->getIntegralTypeMask();
4908 ComputeMaskedBits(Op0, TypeMask, KnownZero, KnownOne);
4910 if (isPowerOf2_64(KnownZero^TypeMask)) { // Exactly one possible 1?
4911 bool isSetNE = SrcI->getOpcode() == Instruction::SetNE;
4912 if (Op1CV && (Op1CV != (KnownZero^TypeMask))) {
4913 // (X&4) == 2 --> false
4914 // (X&4) != 2 --> true
4915 Constant *Res = ConstantBool::get(isSetNE);
4916 Res = ConstantExpr::getCast(Res, CI.getType());
4917 return ReplaceInstUsesWith(CI, Res);
4920 unsigned ShiftAmt = Log2_64(KnownZero^TypeMask);
4923 // Perform an unsigned shr by shiftamt. Convert input to
4924 // unsigned if it is signed.
4925 if (In->getType()->isSigned())
4926 In = InsertNewInstBefore(new CastInst(In,
4927 In->getType()->getUnsignedVersion(), In->getName()),CI);
4928 // Insert the shift to put the result in the low bit.
4929 In = InsertNewInstBefore(new ShiftInst(Instruction::Shr, In,
4930 ConstantInt::get(Type::UByteTy, ShiftAmt),
4931 In->getName()+".lobit"), CI);
4934 if ((Op1CV != 0) == isSetNE) { // Toggle the low bit.
4935 Constant *One = ConstantInt::get(In->getType(), 1);
4936 In = BinaryOperator::createXor(In, One, "tmp");
4937 InsertNewInstBefore(cast<Instruction>(In), CI);
4940 if (CI.getType() == In->getType())
4941 return ReplaceInstUsesWith(CI, In);
4943 return new CastInst(In, CI.getType());
4954 /// GetSelectFoldableOperands - We want to turn code that looks like this:
4956 /// %D = select %cond, %C, %A
4958 /// %C = select %cond, %B, 0
4961 /// Assuming that the specified instruction is an operand to the select, return
4962 /// a bitmask indicating which operands of this instruction are foldable if they
4963 /// equal the other incoming value of the select.
4965 static unsigned GetSelectFoldableOperands(Instruction *I) {
4966 switch (I->getOpcode()) {
4967 case Instruction::Add:
4968 case Instruction::Mul:
4969 case Instruction::And:
4970 case Instruction::Or:
4971 case Instruction::Xor:
4972 return 3; // Can fold through either operand.
4973 case Instruction::Sub: // Can only fold on the amount subtracted.
4974 case Instruction::Shl: // Can only fold on the shift amount.
4975 case Instruction::Shr:
4978 return 0; // Cannot fold
4982 /// GetSelectFoldableConstant - For the same transformation as the previous
4983 /// function, return the identity constant that goes into the select.
4984 static Constant *GetSelectFoldableConstant(Instruction *I) {
4985 switch (I->getOpcode()) {
4986 default: assert(0 && "This cannot happen!"); abort();
4987 case Instruction::Add:
4988 case Instruction::Sub:
4989 case Instruction::Or:
4990 case Instruction::Xor:
4991 return Constant::getNullValue(I->getType());
4992 case Instruction::Shl:
4993 case Instruction::Shr:
4994 return Constant::getNullValue(Type::UByteTy);
4995 case Instruction::And:
4996 return ConstantInt::getAllOnesValue(I->getType());
4997 case Instruction::Mul:
4998 return ConstantInt::get(I->getType(), 1);
5002 /// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
5003 /// have the same opcode and only one use each. Try to simplify this.
5004 Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
5006 if (TI->getNumOperands() == 1) {
5007 // If this is a non-volatile load or a cast from the same type,
5009 if (TI->getOpcode() == Instruction::Cast) {
5010 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
5013 return 0; // unknown unary op.
5016 // Fold this by inserting a select from the input values.
5017 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
5018 FI->getOperand(0), SI.getName()+".v");
5019 InsertNewInstBefore(NewSI, SI);
5020 return new CastInst(NewSI, TI->getType());
5023 // Only handle binary operators here.
5024 if (!isa<ShiftInst>(TI) && !isa<BinaryOperator>(TI))
5027 // Figure out if the operations have any operands in common.
5028 Value *MatchOp, *OtherOpT, *OtherOpF;
5030 if (TI->getOperand(0) == FI->getOperand(0)) {
5031 MatchOp = TI->getOperand(0);
5032 OtherOpT = TI->getOperand(1);
5033 OtherOpF = FI->getOperand(1);
5034 MatchIsOpZero = true;
5035 } else if (TI->getOperand(1) == FI->getOperand(1)) {
5036 MatchOp = TI->getOperand(1);
5037 OtherOpT = TI->getOperand(0);
5038 OtherOpF = FI->getOperand(0);
5039 MatchIsOpZero = false;
5040 } else if (!TI->isCommutative()) {
5042 } else if (TI->getOperand(0) == FI->getOperand(1)) {
5043 MatchOp = TI->getOperand(0);
5044 OtherOpT = TI->getOperand(1);
5045 OtherOpF = FI->getOperand(0);
5046 MatchIsOpZero = true;
5047 } else if (TI->getOperand(1) == FI->getOperand(0)) {
5048 MatchOp = TI->getOperand(1);
5049 OtherOpT = TI->getOperand(0);
5050 OtherOpF = FI->getOperand(1);
5051 MatchIsOpZero = true;
5056 // If we reach here, they do have operations in common.
5057 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
5058 OtherOpF, SI.getName()+".v");
5059 InsertNewInstBefore(NewSI, SI);
5061 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
5063 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
5065 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
5068 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), MatchOp, NewSI);
5070 return new ShiftInst(cast<ShiftInst>(TI)->getOpcode(), NewSI, MatchOp);
5074 Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
5075 Value *CondVal = SI.getCondition();
5076 Value *TrueVal = SI.getTrueValue();
5077 Value *FalseVal = SI.getFalseValue();
5079 // select true, X, Y -> X
5080 // select false, X, Y -> Y
5081 if (ConstantBool *C = dyn_cast<ConstantBool>(CondVal))
5082 if (C == ConstantBool::True)
5083 return ReplaceInstUsesWith(SI, TrueVal);
5085 assert(C == ConstantBool::False);
5086 return ReplaceInstUsesWith(SI, FalseVal);
5089 // select C, X, X -> X
5090 if (TrueVal == FalseVal)
5091 return ReplaceInstUsesWith(SI, TrueVal);
5093 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
5094 return ReplaceInstUsesWith(SI, FalseVal);
5095 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
5096 return ReplaceInstUsesWith(SI, TrueVal);
5097 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
5098 if (isa<Constant>(TrueVal))
5099 return ReplaceInstUsesWith(SI, TrueVal);
5101 return ReplaceInstUsesWith(SI, FalseVal);
5104 if (SI.getType() == Type::BoolTy)
5105 if (ConstantBool *C = dyn_cast<ConstantBool>(TrueVal)) {
5106 if (C == ConstantBool::True) {
5107 // Change: A = select B, true, C --> A = or B, C
5108 return BinaryOperator::createOr(CondVal, FalseVal);
5110 // Change: A = select B, false, C --> A = and !B, C
5112 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5113 "not."+CondVal->getName()), SI);
5114 return BinaryOperator::createAnd(NotCond, FalseVal);
5116 } else if (ConstantBool *C = dyn_cast<ConstantBool>(FalseVal)) {
5117 if (C == ConstantBool::False) {
5118 // Change: A = select B, C, false --> A = and B, C
5119 return BinaryOperator::createAnd(CondVal, TrueVal);
5121 // Change: A = select B, C, true --> A = or !B, C
5123 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5124 "not."+CondVal->getName()), SI);
5125 return BinaryOperator::createOr(NotCond, TrueVal);
5129 // Selecting between two integer constants?
5130 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
5131 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
5132 // select C, 1, 0 -> cast C to int
5133 if (FalseValC->isNullValue() && TrueValC->getRawValue() == 1) {
5134 return new CastInst(CondVal, SI.getType());
5135 } else if (TrueValC->isNullValue() && FalseValC->getRawValue() == 1) {
5136 // select C, 0, 1 -> cast !C to int
5138 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
5139 "not."+CondVal->getName()), SI);
5140 return new CastInst(NotCond, SI.getType());
5143 // If one of the constants is zero (we know they can't both be) and we
5144 // have a setcc instruction with zero, and we have an 'and' with the
5145 // non-constant value, eliminate this whole mess. This corresponds to
5146 // cases like this: ((X & 27) ? 27 : 0)
5147 if (TrueValC->isNullValue() || FalseValC->isNullValue())
5148 if (Instruction *IC = dyn_cast<Instruction>(SI.getCondition()))
5149 if ((IC->getOpcode() == Instruction::SetEQ ||
5150 IC->getOpcode() == Instruction::SetNE) &&
5151 isa<ConstantInt>(IC->getOperand(1)) &&
5152 cast<Constant>(IC->getOperand(1))->isNullValue())
5153 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
5154 if (ICA->getOpcode() == Instruction::And &&
5155 isa<ConstantInt>(ICA->getOperand(1)) &&
5156 (ICA->getOperand(1) == TrueValC ||
5157 ICA->getOperand(1) == FalseValC) &&
5158 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
5159 // Okay, now we know that everything is set up, we just don't
5160 // know whether we have a setne or seteq and whether the true or
5161 // false val is the zero.
5162 bool ShouldNotVal = !TrueValC->isNullValue();
5163 ShouldNotVal ^= IC->getOpcode() == Instruction::SetNE;
5166 V = InsertNewInstBefore(BinaryOperator::create(
5167 Instruction::Xor, V, ICA->getOperand(1)), SI);
5168 return ReplaceInstUsesWith(SI, V);
5172 // See if we are selecting two values based on a comparison of the two values.
5173 if (SetCondInst *SCI = dyn_cast<SetCondInst>(CondVal)) {
5174 if (SCI->getOperand(0) == TrueVal && SCI->getOperand(1) == FalseVal) {
5175 // Transform (X == Y) ? X : Y -> Y
5176 if (SCI->getOpcode() == Instruction::SetEQ)
5177 return ReplaceInstUsesWith(SI, FalseVal);
5178 // Transform (X != Y) ? X : Y -> X
5179 if (SCI->getOpcode() == Instruction::SetNE)
5180 return ReplaceInstUsesWith(SI, TrueVal);
5181 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5183 } else if (SCI->getOperand(0) == FalseVal && SCI->getOperand(1) == TrueVal){
5184 // Transform (X == Y) ? Y : X -> X
5185 if (SCI->getOpcode() == Instruction::SetEQ)
5186 return ReplaceInstUsesWith(SI, FalseVal);
5187 // Transform (X != Y) ? Y : X -> Y
5188 if (SCI->getOpcode() == Instruction::SetNE)
5189 return ReplaceInstUsesWith(SI, TrueVal);
5190 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
5194 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
5195 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
5196 if (TI->hasOneUse() && FI->hasOneUse()) {
5197 bool isInverse = false;
5198 Instruction *AddOp = 0, *SubOp = 0;
5200 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
5201 if (TI->getOpcode() == FI->getOpcode())
5202 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
5205 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
5206 // even legal for FP.
5207 if (TI->getOpcode() == Instruction::Sub &&
5208 FI->getOpcode() == Instruction::Add) {
5209 AddOp = FI; SubOp = TI;
5210 } else if (FI->getOpcode() == Instruction::Sub &&
5211 TI->getOpcode() == Instruction::Add) {
5212 AddOp = TI; SubOp = FI;
5216 Value *OtherAddOp = 0;
5217 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
5218 OtherAddOp = AddOp->getOperand(1);
5219 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
5220 OtherAddOp = AddOp->getOperand(0);
5224 // So at this point we know we have (Y -> OtherAddOp):
5225 // select C, (add X, Y), (sub X, Z)
5226 Value *NegVal; // Compute -Z
5227 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
5228 NegVal = ConstantExpr::getNeg(C);
5230 NegVal = InsertNewInstBefore(
5231 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
5234 Value *NewTrueOp = OtherAddOp;
5235 Value *NewFalseOp = NegVal;
5237 std::swap(NewTrueOp, NewFalseOp);
5238 Instruction *NewSel =
5239 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
5241 NewSel = InsertNewInstBefore(NewSel, SI);
5242 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
5247 // See if we can fold the select into one of our operands.
5248 if (SI.getType()->isInteger()) {
5249 // See the comment above GetSelectFoldableOperands for a description of the
5250 // transformation we are doing here.
5251 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
5252 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
5253 !isa<Constant>(FalseVal))
5254 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
5255 unsigned OpToFold = 0;
5256 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
5258 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
5263 Constant *C = GetSelectFoldableConstant(TVI);
5264 std::string Name = TVI->getName(); TVI->setName("");
5265 Instruction *NewSel =
5266 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C,
5268 InsertNewInstBefore(NewSel, SI);
5269 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
5270 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
5271 else if (ShiftInst *SI = dyn_cast<ShiftInst>(TVI))
5272 return new ShiftInst(SI->getOpcode(), FalseVal, NewSel);
5274 assert(0 && "Unknown instruction!!");
5279 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
5280 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
5281 !isa<Constant>(TrueVal))
5282 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
5283 unsigned OpToFold = 0;
5284 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
5286 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
5291 Constant *C = GetSelectFoldableConstant(FVI);
5292 std::string Name = FVI->getName(); FVI->setName("");
5293 Instruction *NewSel =
5294 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold),
5296 InsertNewInstBefore(NewSel, SI);
5297 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
5298 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
5299 else if (ShiftInst *SI = dyn_cast<ShiftInst>(FVI))
5300 return new ShiftInst(SI->getOpcode(), TrueVal, NewSel);
5302 assert(0 && "Unknown instruction!!");
5308 if (BinaryOperator::isNot(CondVal)) {
5309 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
5310 SI.setOperand(1, FalseVal);
5311 SI.setOperand(2, TrueVal);
5318 /// GetKnownAlignment - If the specified pointer has an alignment that we can
5319 /// determine, return it, otherwise return 0.
5320 static unsigned GetKnownAlignment(Value *V, TargetData *TD) {
5321 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
5322 unsigned Align = GV->getAlignment();
5323 if (Align == 0 && TD)
5324 Align = TD->getTypeAlignment(GV->getType()->getElementType());
5326 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
5327 unsigned Align = AI->getAlignment();
5328 if (Align == 0 && TD) {
5329 if (isa<AllocaInst>(AI))
5330 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5331 else if (isa<MallocInst>(AI)) {
5332 // Malloc returns maximally aligned memory.
5333 Align = TD->getTypeAlignment(AI->getType()->getElementType());
5334 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::DoubleTy));
5335 Align = std::max(Align, (unsigned)TD->getTypeAlignment(Type::LongTy));
5339 } else if (isa<CastInst>(V) ||
5340 (isa<ConstantExpr>(V) &&
5341 cast<ConstantExpr>(V)->getOpcode() == Instruction::Cast)) {
5342 User *CI = cast<User>(V);
5343 if (isa<PointerType>(CI->getOperand(0)->getType()))
5344 return GetKnownAlignment(CI->getOperand(0), TD);
5346 } else if (isa<GetElementPtrInst>(V) ||
5347 (isa<ConstantExpr>(V) &&
5348 cast<ConstantExpr>(V)->getOpcode()==Instruction::GetElementPtr)) {
5349 User *GEPI = cast<User>(V);
5350 unsigned BaseAlignment = GetKnownAlignment(GEPI->getOperand(0), TD);
5351 if (BaseAlignment == 0) return 0;
5353 // If all indexes are zero, it is just the alignment of the base pointer.
5354 bool AllZeroOperands = true;
5355 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
5356 if (!isa<Constant>(GEPI->getOperand(i)) ||
5357 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
5358 AllZeroOperands = false;
5361 if (AllZeroOperands)
5362 return BaseAlignment;
5364 // Otherwise, if the base alignment is >= the alignment we expect for the
5365 // base pointer type, then we know that the resultant pointer is aligned at
5366 // least as much as its type requires.
5369 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
5370 if (TD->getTypeAlignment(cast<PointerType>(BasePtrTy)->getElementType())
5372 const Type *GEPTy = GEPI->getType();
5373 return TD->getTypeAlignment(cast<PointerType>(GEPTy)->getElementType());
5381 /// visitCallInst - CallInst simplification. This mostly only handles folding
5382 /// of intrinsic instructions. For normal calls, it allows visitCallSite to do
5383 /// the heavy lifting.
5385 Instruction *InstCombiner::visitCallInst(CallInst &CI) {
5386 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
5387 if (!II) return visitCallSite(&CI);
5389 // Intrinsics cannot occur in an invoke, so handle them here instead of in
5391 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
5392 bool Changed = false;
5394 // memmove/cpy/set of zero bytes is a noop.
5395 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
5396 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
5398 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
5399 if (CI->getRawValue() == 1) {
5400 // Replace the instruction with just byte operations. We would
5401 // transform other cases to loads/stores, but we don't know if
5402 // alignment is sufficient.
5406 // If we have a memmove and the source operation is a constant global,
5407 // then the source and dest pointers can't alias, so we can change this
5408 // into a call to memcpy.
5409 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
5410 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
5411 if (GVSrc->isConstant()) {
5412 Module *M = CI.getParent()->getParent()->getParent();
5414 if (CI.getCalledFunction()->getFunctionType()->getParamType(3) ==
5416 Name = "llvm.memcpy.i32";
5418 Name = "llvm.memcpy.i64";
5419 Function *MemCpy = M->getOrInsertFunction(Name,
5420 CI.getCalledFunction()->getFunctionType());
5421 CI.setOperand(0, MemCpy);
5426 // If we can determine a pointer alignment that is bigger than currently
5427 // set, update the alignment.
5428 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
5429 unsigned Alignment1 = GetKnownAlignment(MI->getOperand(1), TD);
5430 unsigned Alignment2 = GetKnownAlignment(MI->getOperand(2), TD);
5431 unsigned Align = std::min(Alignment1, Alignment2);
5432 if (MI->getAlignment()->getRawValue() < Align) {
5433 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Align));
5436 } else if (isa<MemSetInst>(MI)) {
5437 unsigned Alignment = GetKnownAlignment(MI->getDest(), TD);
5438 if (MI->getAlignment()->getRawValue() < Alignment) {
5439 MI->setAlignment(ConstantUInt::get(Type::UIntTy, Alignment));
5444 if (Changed) return II;
5446 switch (II->getIntrinsicID()) {
5448 case Intrinsic::ppc_altivec_lvx:
5449 case Intrinsic::ppc_altivec_lvxl:
5450 // Turn lvx -> load if the pointer is known aligned.
5451 if (GetKnownAlignment(II->getOperand(1), TD) >= 16) {
5452 Value *Ptr = InsertCastBefore(II->getOperand(1),
5453 PointerType::get(II->getType()), CI);
5454 return new LoadInst(Ptr);
5457 case Intrinsic::ppc_altivec_stvx:
5458 case Intrinsic::ppc_altivec_stvxl:
5459 // Turn stvx -> store if the pointer is known aligned.
5460 if (GetKnownAlignment(II->getOperand(2), TD) >= 16) {
5461 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
5462 Value *Ptr = InsertCastBefore(II->getOperand(2), OpPtrTy, CI);
5463 return new StoreInst(II->getOperand(1), Ptr);
5466 case Intrinsic::ppc_altivec_vperm:
5467 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
5468 if (ConstantPacked *Mask = dyn_cast<ConstantPacked>(II->getOperand(3))) {
5469 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
5471 // Check that all of the elements are integer constants or undefs.
5472 bool AllEltsOk = true;
5473 for (unsigned i = 0; i != 16; ++i) {
5474 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
5475 !isa<UndefValue>(Mask->getOperand(i))) {
5482 // Cast the input vectors to byte vectors.
5483 Value *Op0 = InsertCastBefore(II->getOperand(1), Mask->getType(), CI);
5484 Value *Op1 = InsertCastBefore(II->getOperand(2), Mask->getType(), CI);
5485 Value *Result = UndefValue::get(Op0->getType());
5487 // Only extract each element once.
5488 Value *ExtractedElts[32];
5489 memset(ExtractedElts, 0, sizeof(ExtractedElts));
5491 for (unsigned i = 0; i != 16; ++i) {
5492 if (isa<UndefValue>(Mask->getOperand(i)))
5494 unsigned Idx =cast<ConstantInt>(Mask->getOperand(i))->getRawValue();
5495 Idx &= 31; // Match the hardware behavior.
5497 if (ExtractedElts[Idx] == 0) {
5499 new ExtractElementInst(Idx < 16 ? Op0 : Op1,
5500 ConstantUInt::get(Type::UIntTy, Idx&15),
5502 InsertNewInstBefore(Elt, CI);
5503 ExtractedElts[Idx] = Elt;
5506 // Insert this value into the result vector.
5507 Result = new InsertElementInst(Result, ExtractedElts[Idx],
5508 ConstantUInt::get(Type::UIntTy, i),
5510 InsertNewInstBefore(cast<Instruction>(Result), CI);
5512 return new CastInst(Result, CI.getType());
5517 case Intrinsic::stackrestore: {
5518 // If the save is right next to the restore, remove the restore. This can
5519 // happen when variable allocas are DCE'd.
5520 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
5521 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
5522 BasicBlock::iterator BI = SS;
5524 return EraseInstFromFunction(CI);
5528 // If the stack restore is in a return/unwind block and if there are no
5529 // allocas or calls between the restore and the return, nuke the restore.
5530 TerminatorInst *TI = II->getParent()->getTerminator();
5531 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
5532 BasicBlock::iterator BI = II;
5533 bool CannotRemove = false;
5534 for (++BI; &*BI != TI; ++BI) {
5535 if (isa<AllocaInst>(BI) ||
5536 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
5537 CannotRemove = true;
5542 return EraseInstFromFunction(CI);
5549 return visitCallSite(II);
5552 // InvokeInst simplification
5554 Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
5555 return visitCallSite(&II);
5558 // visitCallSite - Improvements for call and invoke instructions.
5560 Instruction *InstCombiner::visitCallSite(CallSite CS) {
5561 bool Changed = false;
5563 // If the callee is a constexpr cast of a function, attempt to move the cast
5564 // to the arguments of the call/invoke.
5565 if (transformConstExprCastCall(CS)) return 0;
5567 Value *Callee = CS.getCalledValue();
5569 if (Function *CalleeF = dyn_cast<Function>(Callee))
5570 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
5571 Instruction *OldCall = CS.getInstruction();
5572 // If the call and callee calling conventions don't match, this call must
5573 // be unreachable, as the call is undefined.
5574 new StoreInst(ConstantBool::True,
5575 UndefValue::get(PointerType::get(Type::BoolTy)), OldCall);
5576 if (!OldCall->use_empty())
5577 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
5578 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
5579 return EraseInstFromFunction(*OldCall);
5583 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
5584 // This instruction is not reachable, just remove it. We insert a store to
5585 // undef so that we know that this code is not reachable, despite the fact
5586 // that we can't modify the CFG here.
5587 new StoreInst(ConstantBool::True,
5588 UndefValue::get(PointerType::get(Type::BoolTy)),
5589 CS.getInstruction());
5591 if (!CS.getInstruction()->use_empty())
5592 CS.getInstruction()->
5593 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
5595 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
5596 // Don't break the CFG, insert a dummy cond branch.
5597 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
5598 ConstantBool::True, II);
5600 return EraseInstFromFunction(*CS.getInstruction());
5603 const PointerType *PTy = cast<PointerType>(Callee->getType());
5604 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
5605 if (FTy->isVarArg()) {
5606 // See if we can optimize any arguments passed through the varargs area of
5608 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
5609 E = CS.arg_end(); I != E; ++I)
5610 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
5611 // If this cast does not effect the value passed through the varargs
5612 // area, we can eliminate the use of the cast.
5613 Value *Op = CI->getOperand(0);
5614 if (CI->getType()->isLosslesslyConvertibleTo(Op->getType())) {
5621 return Changed ? CS.getInstruction() : 0;
5624 // transformConstExprCastCall - If the callee is a constexpr cast of a function,
5625 // attempt to move the cast to the arguments of the call/invoke.
5627 bool InstCombiner::transformConstExprCastCall(CallSite CS) {
5628 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
5629 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
5630 if (CE->getOpcode() != Instruction::Cast || !isa<Function>(CE->getOperand(0)))
5632 Function *Callee = cast<Function>(CE->getOperand(0));
5633 Instruction *Caller = CS.getInstruction();
5635 // Okay, this is a cast from a function to a different type. Unless doing so
5636 // would cause a type conversion of one of our arguments, change this call to
5637 // be a direct call with arguments casted to the appropriate types.
5639 const FunctionType *FT = Callee->getFunctionType();
5640 const Type *OldRetTy = Caller->getType();
5642 // Check to see if we are changing the return type...
5643 if (OldRetTy != FT->getReturnType()) {
5644 if (Callee->isExternal() &&
5645 !OldRetTy->isLosslesslyConvertibleTo(FT->getReturnType()) &&
5646 !Caller->use_empty())
5647 return false; // Cannot transform this return value...
5649 // If the callsite is an invoke instruction, and the return value is used by
5650 // a PHI node in a successor, we cannot change the return type of the call
5651 // because there is no place to put the cast instruction (without breaking
5652 // the critical edge). Bail out in this case.
5653 if (!Caller->use_empty())
5654 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
5655 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
5657 if (PHINode *PN = dyn_cast<PHINode>(*UI))
5658 if (PN->getParent() == II->getNormalDest() ||
5659 PN->getParent() == II->getUnwindDest())
5663 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
5664 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
5666 CallSite::arg_iterator AI = CS.arg_begin();
5667 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
5668 const Type *ParamTy = FT->getParamType(i);
5669 bool isConvertible = (*AI)->getType()->isLosslesslyConvertibleTo(ParamTy);
5670 if (Callee->isExternal() && !isConvertible) return false;
5673 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
5674 Callee->isExternal())
5675 return false; // Do not delete arguments unless we have a function body...
5677 // Okay, we decided that this is a safe thing to do: go ahead and start
5678 // inserting cast instructions as necessary...
5679 std::vector<Value*> Args;
5680 Args.reserve(NumActualArgs);
5682 AI = CS.arg_begin();
5683 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
5684 const Type *ParamTy = FT->getParamType(i);
5685 if ((*AI)->getType() == ParamTy) {
5686 Args.push_back(*AI);
5688 Args.push_back(InsertNewInstBefore(new CastInst(*AI, ParamTy, "tmp"),
5693 // If the function takes more arguments than the call was taking, add them
5695 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
5696 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
5698 // If we are removing arguments to the function, emit an obnoxious warning...
5699 if (FT->getNumParams() < NumActualArgs)
5700 if (!FT->isVarArg()) {
5701 std::cerr << "WARNING: While resolving call to function '"
5702 << Callee->getName() << "' arguments were dropped!\n";
5704 // Add all of the arguments in their promoted form to the arg list...
5705 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
5706 const Type *PTy = getPromotedType((*AI)->getType());
5707 if (PTy != (*AI)->getType()) {
5708 // Must promote to pass through va_arg area!
5709 Instruction *Cast = new CastInst(*AI, PTy, "tmp");
5710 InsertNewInstBefore(Cast, *Caller);
5711 Args.push_back(Cast);
5713 Args.push_back(*AI);
5718 if (FT->getReturnType() == Type::VoidTy)
5719 Caller->setName(""); // Void type should not have a name...
5722 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
5723 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
5724 Args, Caller->getName(), Caller);
5725 cast<InvokeInst>(II)->setCallingConv(II->getCallingConv());
5727 NC = new CallInst(Callee, Args, Caller->getName(), Caller);
5728 if (cast<CallInst>(Caller)->isTailCall())
5729 cast<CallInst>(NC)->setTailCall();
5730 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
5733 // Insert a cast of the return type as necessary...
5735 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
5736 if (NV->getType() != Type::VoidTy) {
5737 NV = NC = new CastInst(NC, Caller->getType(), "tmp");
5739 // If this is an invoke instruction, we should insert it after the first
5740 // non-phi, instruction in the normal successor block.
5741 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
5742 BasicBlock::iterator I = II->getNormalDest()->begin();
5743 while (isa<PHINode>(I)) ++I;
5744 InsertNewInstBefore(NC, *I);
5746 // Otherwise, it's a call, just insert cast right after the call instr
5747 InsertNewInstBefore(NC, *Caller);
5749 AddUsersToWorkList(*Caller);
5751 NV = UndefValue::get(Caller->getType());
5755 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
5756 Caller->replaceAllUsesWith(NV);
5757 Caller->getParent()->getInstList().erase(Caller);
5758 removeFromWorkList(Caller);
5763 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
5764 // operator and they all are only used by the PHI, PHI together their
5765 // inputs, and do the operation once, to the result of the PHI.
5766 Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
5767 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
5769 // Scan the instruction, looking for input operations that can be folded away.
5770 // If all input operands to the phi are the same instruction (e.g. a cast from
5771 // the same type or "+42") we can pull the operation through the PHI, reducing
5772 // code size and simplifying code.
5773 Constant *ConstantOp = 0;
5774 const Type *CastSrcTy = 0;
5775 if (isa<CastInst>(FirstInst)) {
5776 CastSrcTy = FirstInst->getOperand(0)->getType();
5777 } else if (isa<BinaryOperator>(FirstInst) || isa<ShiftInst>(FirstInst)) {
5778 // Can fold binop or shift if the RHS is a constant.
5779 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
5780 if (ConstantOp == 0) return 0;
5782 return 0; // Cannot fold this operation.
5785 // Check to see if all arguments are the same operation.
5786 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5787 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
5788 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
5789 if (!I->hasOneUse() || I->getOpcode() != FirstInst->getOpcode())
5792 if (I->getOperand(0)->getType() != CastSrcTy)
5793 return 0; // Cast operation must match.
5794 } else if (I->getOperand(1) != ConstantOp) {
5799 // Okay, they are all the same operation. Create a new PHI node of the
5800 // correct type, and PHI together all of the LHS's of the instructions.
5801 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
5802 PN.getName()+".in");
5803 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
5805 Value *InVal = FirstInst->getOperand(0);
5806 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
5808 // Add all operands to the new PHI.
5809 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
5810 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
5811 if (NewInVal != InVal)
5813 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
5818 // The new PHI unions all of the same values together. This is really
5819 // common, so we handle it intelligently here for compile-time speed.
5823 InsertNewInstBefore(NewPN, PN);
5827 // Insert and return the new operation.
5828 if (isa<CastInst>(FirstInst))
5829 return new CastInst(PhiVal, PN.getType());
5830 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
5831 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
5833 return new ShiftInst(cast<ShiftInst>(FirstInst)->getOpcode(),
5834 PhiVal, ConstantOp);
5837 /// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
5839 static bool DeadPHICycle(PHINode *PN, std::set<PHINode*> &PotentiallyDeadPHIs) {
5840 if (PN->use_empty()) return true;
5841 if (!PN->hasOneUse()) return false;
5843 // Remember this node, and if we find the cycle, return.
5844 if (!PotentiallyDeadPHIs.insert(PN).second)
5847 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
5848 return DeadPHICycle(PU, PotentiallyDeadPHIs);
5853 // PHINode simplification
5855 Instruction *InstCombiner::visitPHINode(PHINode &PN) {
5856 if (Value *V = PN.hasConstantValue())
5857 return ReplaceInstUsesWith(PN, V);
5859 // If the only user of this instruction is a cast instruction, and all of the
5860 // incoming values are constants, change this PHI to merge together the casted
5863 if (CastInst *CI = dyn_cast<CastInst>(PN.use_back()))
5864 if (CI->getType() != PN.getType()) { // noop casts will be folded
5865 bool AllConstant = true;
5866 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
5867 if (!isa<Constant>(PN.getIncomingValue(i))) {
5868 AllConstant = false;
5872 // Make a new PHI with all casted values.
5873 PHINode *New = new PHINode(CI->getType(), PN.getName(), &PN);
5874 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i) {
5875 Constant *OldArg = cast<Constant>(PN.getIncomingValue(i));
5876 New->addIncoming(ConstantExpr::getCast(OldArg, New->getType()),
5877 PN.getIncomingBlock(i));
5880 // Update the cast instruction.
5881 CI->setOperand(0, New);
5882 WorkList.push_back(CI); // revisit the cast instruction to fold.
5883 WorkList.push_back(New); // Make sure to revisit the new Phi
5884 return &PN; // PN is now dead!
5888 // If all PHI operands are the same operation, pull them through the PHI,
5889 // reducing code size.
5890 if (isa<Instruction>(PN.getIncomingValue(0)) &&
5891 PN.getIncomingValue(0)->hasOneUse())
5892 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
5895 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
5896 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
5897 // PHI)... break the cycle.
5899 if (PHINode *PU = dyn_cast<PHINode>(PN.use_back())) {
5900 std::set<PHINode*> PotentiallyDeadPHIs;
5901 PotentiallyDeadPHIs.insert(&PN);
5902 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
5903 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
5909 static Value *InsertSignExtendToPtrTy(Value *V, const Type *DTy,
5910 Instruction *InsertPoint,
5912 unsigned PS = IC->getTargetData().getPointerSize();
5913 const Type *VTy = V->getType();
5914 if (!VTy->isSigned() && VTy->getPrimitiveSize() < PS)
5915 // We must insert a cast to ensure we sign-extend.
5916 V = IC->InsertNewInstBefore(new CastInst(V, VTy->getSignedVersion(),
5917 V->getName()), *InsertPoint);
5918 return IC->InsertNewInstBefore(new CastInst(V, DTy, V->getName()),
5923 Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
5924 Value *PtrOp = GEP.getOperand(0);
5925 // Is it 'getelementptr %P, long 0' or 'getelementptr %P'
5926 // If so, eliminate the noop.
5927 if (GEP.getNumOperands() == 1)
5928 return ReplaceInstUsesWith(GEP, PtrOp);
5930 if (isa<UndefValue>(GEP.getOperand(0)))
5931 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
5933 bool HasZeroPointerIndex = false;
5934 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
5935 HasZeroPointerIndex = C->isNullValue();
5937 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
5938 return ReplaceInstUsesWith(GEP, PtrOp);
5940 // Eliminate unneeded casts for indices.
5941 bool MadeChange = false;
5942 gep_type_iterator GTI = gep_type_begin(GEP);
5943 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI)
5944 if (isa<SequentialType>(*GTI)) {
5945 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
5946 Value *Src = CI->getOperand(0);
5947 const Type *SrcTy = Src->getType();
5948 const Type *DestTy = CI->getType();
5949 if (Src->getType()->isInteger()) {
5950 if (SrcTy->getPrimitiveSizeInBits() ==
5951 DestTy->getPrimitiveSizeInBits()) {
5952 // We can always eliminate a cast from ulong or long to the other.
5953 // We can always eliminate a cast from uint to int or the other on
5954 // 32-bit pointer platforms.
5955 if (DestTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()){
5957 GEP.setOperand(i, Src);
5959 } else if (SrcTy->getPrimitiveSize() < DestTy->getPrimitiveSize() &&
5960 SrcTy->getPrimitiveSize() == 4) {
5961 // We can always eliminate a cast from int to [u]long. We can
5962 // eliminate a cast from uint to [u]long iff the target is a 32-bit
5964 if (SrcTy->isSigned() ||
5965 SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
5967 GEP.setOperand(i, Src);
5972 // If we are using a wider index than needed for this platform, shrink it
5973 // to what we need. If the incoming value needs a cast instruction,
5974 // insert it. This explicit cast can make subsequent optimizations more
5976 Value *Op = GEP.getOperand(i);
5977 if (Op->getType()->getPrimitiveSize() > TD->getPointerSize())
5978 if (Constant *C = dyn_cast<Constant>(Op)) {
5979 GEP.setOperand(i, ConstantExpr::getCast(C,
5980 TD->getIntPtrType()->getSignedVersion()));
5983 Op = InsertNewInstBefore(new CastInst(Op, TD->getIntPtrType(),
5984 Op->getName()), GEP);
5985 GEP.setOperand(i, Op);
5989 // If this is a constant idx, make sure to canonicalize it to be a signed
5990 // operand, otherwise CSE and other optimizations are pessimized.
5991 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(Op)) {
5992 GEP.setOperand(i, ConstantExpr::getCast(CUI,
5993 CUI->getType()->getSignedVersion()));
5997 if (MadeChange) return &GEP;
5999 // Combine Indices - If the source pointer to this getelementptr instruction
6000 // is a getelementptr instruction, combine the indices of the two
6001 // getelementptr instructions into a single instruction.
6003 std::vector<Value*> SrcGEPOperands;
6004 if (User *Src = dyn_castGetElementPtr(PtrOp))
6005 SrcGEPOperands.assign(Src->op_begin(), Src->op_end());
6007 if (!SrcGEPOperands.empty()) {
6008 // Note that if our source is a gep chain itself that we wait for that
6009 // chain to be resolved before we perform this transformation. This
6010 // avoids us creating a TON of code in some cases.
6012 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
6013 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
6014 return 0; // Wait until our source is folded to completion.
6016 std::vector<Value *> Indices;
6018 // Find out whether the last index in the source GEP is a sequential idx.
6019 bool EndsWithSequential = false;
6020 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
6021 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
6022 EndsWithSequential = !isa<StructType>(*I);
6024 // Can we combine the two pointer arithmetics offsets?
6025 if (EndsWithSequential) {
6026 // Replace: gep (gep %P, long B), long A, ...
6027 // With: T = long A+B; gep %P, T, ...
6029 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
6030 if (SO1 == Constant::getNullValue(SO1->getType())) {
6032 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
6035 // If they aren't the same type, convert both to an integer of the
6036 // target's pointer size.
6037 if (SO1->getType() != GO1->getType()) {
6038 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
6039 SO1 = ConstantExpr::getCast(SO1C, GO1->getType());
6040 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
6041 GO1 = ConstantExpr::getCast(GO1C, SO1->getType());
6043 unsigned PS = TD->getPointerSize();
6044 if (SO1->getType()->getPrimitiveSize() == PS) {
6045 // Convert GO1 to SO1's type.
6046 GO1 = InsertSignExtendToPtrTy(GO1, SO1->getType(), &GEP, this);
6048 } else if (GO1->getType()->getPrimitiveSize() == PS) {
6049 // Convert SO1 to GO1's type.
6050 SO1 = InsertSignExtendToPtrTy(SO1, GO1->getType(), &GEP, this);
6052 const Type *PT = TD->getIntPtrType();
6053 SO1 = InsertSignExtendToPtrTy(SO1, PT, &GEP, this);
6054 GO1 = InsertSignExtendToPtrTy(GO1, PT, &GEP, this);
6058 if (isa<Constant>(SO1) && isa<Constant>(GO1))
6059 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
6061 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
6062 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
6066 // Recycle the GEP we already have if possible.
6067 if (SrcGEPOperands.size() == 2) {
6068 GEP.setOperand(0, SrcGEPOperands[0]);
6069 GEP.setOperand(1, Sum);
6072 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6073 SrcGEPOperands.end()-1);
6074 Indices.push_back(Sum);
6075 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
6077 } else if (isa<Constant>(*GEP.idx_begin()) &&
6078 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
6079 SrcGEPOperands.size() != 1) {
6080 // Otherwise we can do the fold if the first index of the GEP is a zero
6081 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
6082 SrcGEPOperands.end());
6083 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
6086 if (!Indices.empty())
6087 return new GetElementPtrInst(SrcGEPOperands[0], Indices, GEP.getName());
6089 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
6090 // GEP of global variable. If all of the indices for this GEP are
6091 // constants, we can promote this to a constexpr instead of an instruction.
6093 // Scan for nonconstants...
6094 std::vector<Constant*> Indices;
6095 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
6096 for (; I != E && isa<Constant>(*I); ++I)
6097 Indices.push_back(cast<Constant>(*I));
6099 if (I == E) { // If they are all constants...
6100 Constant *CE = ConstantExpr::getGetElementPtr(GV, Indices);
6102 // Replace all uses of the GEP with the new constexpr...
6103 return ReplaceInstUsesWith(GEP, CE);
6105 } else if (Value *X = isCast(PtrOp)) { // Is the operand a cast?
6106 if (!isa<PointerType>(X->getType())) {
6107 // Not interesting. Source pointer must be a cast from pointer.
6108 } else if (HasZeroPointerIndex) {
6109 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
6110 // into : GEP [10 x ubyte]* X, long 0, ...
6112 // This occurs when the program declares an array extern like "int X[];"
6114 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
6115 const PointerType *XTy = cast<PointerType>(X->getType());
6116 if (const ArrayType *XATy =
6117 dyn_cast<ArrayType>(XTy->getElementType()))
6118 if (const ArrayType *CATy =
6119 dyn_cast<ArrayType>(CPTy->getElementType()))
6120 if (CATy->getElementType() == XATy->getElementType()) {
6121 // At this point, we know that the cast source type is a pointer
6122 // to an array of the same type as the destination pointer
6123 // array. Because the array type is never stepped over (there
6124 // is a leading zero) we can fold the cast into this GEP.
6125 GEP.setOperand(0, X);
6128 } else if (GEP.getNumOperands() == 2) {
6129 // Transform things like:
6130 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
6131 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
6132 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
6133 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
6134 if (isa<ArrayType>(SrcElTy) &&
6135 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
6136 TD->getTypeSize(ResElTy)) {
6137 Value *V = InsertNewInstBefore(
6138 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6139 GEP.getOperand(1), GEP.getName()), GEP);
6140 return new CastInst(V, GEP.getType());
6143 // Transform things like:
6144 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
6145 // (where tmp = 8*tmp2) into:
6146 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
6148 if (isa<ArrayType>(SrcElTy) &&
6149 (ResElTy == Type::SByteTy || ResElTy == Type::UByteTy)) {
6150 uint64_t ArrayEltSize =
6151 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
6153 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
6154 // allow either a mul, shift, or constant here.
6156 ConstantInt *Scale = 0;
6157 if (ArrayEltSize == 1) {
6158 NewIdx = GEP.getOperand(1);
6159 Scale = ConstantInt::get(NewIdx->getType(), 1);
6160 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
6161 NewIdx = ConstantInt::get(CI->getType(), 1);
6163 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
6164 if (Inst->getOpcode() == Instruction::Shl &&
6165 isa<ConstantInt>(Inst->getOperand(1))) {
6166 unsigned ShAmt =cast<ConstantUInt>(Inst->getOperand(1))->getValue();
6167 if (Inst->getType()->isSigned())
6168 Scale = ConstantSInt::get(Inst->getType(), 1ULL << ShAmt);
6170 Scale = ConstantUInt::get(Inst->getType(), 1ULL << ShAmt);
6171 NewIdx = Inst->getOperand(0);
6172 } else if (Inst->getOpcode() == Instruction::Mul &&
6173 isa<ConstantInt>(Inst->getOperand(1))) {
6174 Scale = cast<ConstantInt>(Inst->getOperand(1));
6175 NewIdx = Inst->getOperand(0);
6179 // If the index will be to exactly the right offset with the scale taken
6180 // out, perform the transformation.
6181 if (Scale && Scale->getRawValue() % ArrayEltSize == 0) {
6182 if (ConstantSInt *C = dyn_cast<ConstantSInt>(Scale))
6183 Scale = ConstantSInt::get(C->getType(),
6184 (int64_t)C->getRawValue() /
6185 (int64_t)ArrayEltSize);
6187 Scale = ConstantUInt::get(Scale->getType(),
6188 Scale->getRawValue() / ArrayEltSize);
6189 if (Scale->getRawValue() != 1) {
6190 Constant *C = ConstantExpr::getCast(Scale, NewIdx->getType());
6191 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
6192 NewIdx = InsertNewInstBefore(Sc, GEP);
6195 // Insert the new GEP instruction.
6197 new GetElementPtrInst(X, Constant::getNullValue(Type::IntTy),
6198 NewIdx, GEP.getName());
6199 Idx = InsertNewInstBefore(Idx, GEP);
6200 return new CastInst(Idx, GEP.getType());
6209 Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
6210 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
6211 if (AI.isArrayAllocation()) // Check C != 1
6212 if (const ConstantUInt *C = dyn_cast<ConstantUInt>(AI.getArraySize())) {
6213 const Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getValue());
6214 AllocationInst *New = 0;
6216 // Create and insert the replacement instruction...
6217 if (isa<MallocInst>(AI))
6218 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
6220 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
6221 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
6224 InsertNewInstBefore(New, AI);
6226 // Scan to the end of the allocation instructions, to skip over a block of
6227 // allocas if possible...
6229 BasicBlock::iterator It = New;
6230 while (isa<AllocationInst>(*It)) ++It;
6232 // Now that I is pointing to the first non-allocation-inst in the block,
6233 // insert our getelementptr instruction...
6235 Value *NullIdx = Constant::getNullValue(Type::IntTy);
6236 Value *V = new GetElementPtrInst(New, NullIdx, NullIdx,
6237 New->getName()+".sub", It);
6239 // Now make everything use the getelementptr instead of the original
6241 return ReplaceInstUsesWith(AI, V);
6242 } else if (isa<UndefValue>(AI.getArraySize())) {
6243 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
6246 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
6247 // Note that we only do this for alloca's, because malloc should allocate and
6248 // return a unique pointer, even for a zero byte allocation.
6249 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
6250 TD->getTypeSize(AI.getAllocatedType()) == 0)
6251 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
6256 Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
6257 Value *Op = FI.getOperand(0);
6259 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
6260 if (CastInst *CI = dyn_cast<CastInst>(Op))
6261 if (isa<PointerType>(CI->getOperand(0)->getType())) {
6262 FI.setOperand(0, CI->getOperand(0));
6266 // free undef -> unreachable.
6267 if (isa<UndefValue>(Op)) {
6268 // Insert a new store to null because we cannot modify the CFG here.
6269 new StoreInst(ConstantBool::True,
6270 UndefValue::get(PointerType::get(Type::BoolTy)), &FI);
6271 return EraseInstFromFunction(FI);
6274 // If we have 'free null' delete the instruction. This can happen in stl code
6275 // when lots of inlining happens.
6276 if (isa<ConstantPointerNull>(Op))
6277 return EraseInstFromFunction(FI);
6283 /// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
6284 static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
6285 User *CI = cast<User>(LI.getOperand(0));
6286 Value *CastOp = CI->getOperand(0);
6288 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
6289 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
6290 const Type *SrcPTy = SrcTy->getElementType();
6292 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
6293 isa<PackedType>(DestPTy)) {
6294 // If the source is an array, the code below will not succeed. Check to
6295 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6297 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6298 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6299 if (ASrcTy->getNumElements() != 0) {
6300 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6301 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6302 SrcTy = cast<PointerType>(CastOp->getType());
6303 SrcPTy = SrcTy->getElementType();
6306 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
6307 isa<PackedType>(SrcPTy)) &&
6308 // Do not allow turning this into a load of an integer, which is then
6309 // casted to a pointer, this pessimizes pointer analysis a lot.
6310 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
6311 IC.getTargetData().getTypeSize(SrcPTy) ==
6312 IC.getTargetData().getTypeSize(DestPTy)) {
6314 // Okay, we are casting from one integer or pointer type to another of
6315 // the same size. Instead of casting the pointer before the load, cast
6316 // the result of the loaded value.
6317 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
6319 LI.isVolatile()),LI);
6320 // Now cast the result of the load.
6321 return new CastInst(NewLoad, LI.getType());
6328 /// isSafeToLoadUnconditionally - Return true if we know that executing a load
6329 /// from this value cannot trap. If it is not obviously safe to load from the
6330 /// specified pointer, we do a quick local scan of the basic block containing
6331 /// ScanFrom, to determine if the address is already accessed.
6332 static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
6333 // If it is an alloca or global variable, it is always safe to load from.
6334 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
6336 // Otherwise, be a little bit agressive by scanning the local block where we
6337 // want to check to see if the pointer is already being loaded or stored
6338 // from/to. If so, the previous load or store would have already trapped,
6339 // so there is no harm doing an extra load (also, CSE will later eliminate
6340 // the load entirely).
6341 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
6346 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
6347 if (LI->getOperand(0) == V) return true;
6348 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6349 if (SI->getOperand(1) == V) return true;
6355 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
6356 Value *Op = LI.getOperand(0);
6358 // load (cast X) --> cast (load X) iff safe
6359 if (CastInst *CI = dyn_cast<CastInst>(Op))
6360 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6363 // None of the following transforms are legal for volatile loads.
6364 if (LI.isVolatile()) return 0;
6366 if (&LI.getParent()->front() != &LI) {
6367 BasicBlock::iterator BBI = &LI; --BBI;
6368 // If the instruction immediately before this is a store to the same
6369 // address, do a simple form of store->load forwarding.
6370 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
6371 if (SI->getOperand(1) == LI.getOperand(0))
6372 return ReplaceInstUsesWith(LI, SI->getOperand(0));
6373 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
6374 if (LIB->getOperand(0) == LI.getOperand(0))
6375 return ReplaceInstUsesWith(LI, LIB);
6378 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
6379 if (isa<ConstantPointerNull>(GEPI->getOperand(0)) ||
6380 isa<UndefValue>(GEPI->getOperand(0))) {
6381 // Insert a new store to null instruction before the load to indicate
6382 // that this code is not reachable. We do this instead of inserting
6383 // an unreachable instruction directly because we cannot modify the
6385 new StoreInst(UndefValue::get(LI.getType()),
6386 Constant::getNullValue(Op->getType()), &LI);
6387 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6390 if (Constant *C = dyn_cast<Constant>(Op)) {
6391 // load null/undef -> undef
6392 if ((C->isNullValue() || isa<UndefValue>(C))) {
6393 // Insert a new store to null instruction before the load to indicate that
6394 // this code is not reachable. We do this instead of inserting an
6395 // unreachable instruction directly because we cannot modify the CFG.
6396 new StoreInst(UndefValue::get(LI.getType()),
6397 Constant::getNullValue(Op->getType()), &LI);
6398 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6401 // Instcombine load (constant global) into the value loaded.
6402 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
6403 if (GV->isConstant() && !GV->isExternal())
6404 return ReplaceInstUsesWith(LI, GV->getInitializer());
6406 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
6407 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
6408 if (CE->getOpcode() == Instruction::GetElementPtr) {
6409 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
6410 if (GV->isConstant() && !GV->isExternal())
6412 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
6413 return ReplaceInstUsesWith(LI, V);
6414 if (CE->getOperand(0)->isNullValue()) {
6415 // Insert a new store to null instruction before the load to indicate
6416 // that this code is not reachable. We do this instead of inserting
6417 // an unreachable instruction directly because we cannot modify the
6419 new StoreInst(UndefValue::get(LI.getType()),
6420 Constant::getNullValue(Op->getType()), &LI);
6421 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
6424 } else if (CE->getOpcode() == Instruction::Cast) {
6425 if (Instruction *Res = InstCombineLoadCast(*this, LI))
6430 if (Op->hasOneUse()) {
6431 // Change select and PHI nodes to select values instead of addresses: this
6432 // helps alias analysis out a lot, allows many others simplifications, and
6433 // exposes redundancy in the code.
6435 // Note that we cannot do the transformation unless we know that the
6436 // introduced loads cannot trap! Something like this is valid as long as
6437 // the condition is always false: load (select bool %C, int* null, int* %G),
6438 // but it would not be valid if we transformed it to load from null
6441 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
6442 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
6443 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
6444 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
6445 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
6446 SI->getOperand(1)->getName()+".val"), LI);
6447 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
6448 SI->getOperand(2)->getName()+".val"), LI);
6449 return new SelectInst(SI->getCondition(), V1, V2);
6452 // load (select (cond, null, P)) -> load P
6453 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
6454 if (C->isNullValue()) {
6455 LI.setOperand(0, SI->getOperand(2));
6459 // load (select (cond, P, null)) -> load P
6460 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
6461 if (C->isNullValue()) {
6462 LI.setOperand(0, SI->getOperand(1));
6466 } else if (PHINode *PN = dyn_cast<PHINode>(Op)) {
6467 // load (phi (&V1, &V2, &V3)) --> phi(load &V1, load &V2, load &V3)
6468 bool Safe = PN->getParent() == LI.getParent();
6470 // Scan all of the instructions between the PHI and the load to make
6471 // sure there are no instructions that might possibly alter the value
6472 // loaded from the PHI.
6474 BasicBlock::iterator I = &LI;
6475 for (--I; !isa<PHINode>(I); --I)
6476 if (isa<StoreInst>(I) || isa<CallInst>(I)) {
6482 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e && Safe; ++i)
6483 if (!isSafeToLoadUnconditionally(PN->getIncomingValue(i),
6484 PN->getIncomingBlock(i)->getTerminator()))
6489 PHINode *NewPN = new PHINode(LI.getType(), PN->getName());
6490 InsertNewInstBefore(NewPN, *PN);
6491 std::map<BasicBlock*,Value*> LoadMap; // Don't insert duplicate loads
6493 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
6494 BasicBlock *BB = PN->getIncomingBlock(i);
6495 Value *&TheLoad = LoadMap[BB];
6497 Value *InVal = PN->getIncomingValue(i);
6498 TheLoad = InsertNewInstBefore(new LoadInst(InVal,
6499 InVal->getName()+".val"),
6500 *BB->getTerminator());
6502 NewPN->addIncoming(TheLoad, BB);
6504 return ReplaceInstUsesWith(LI, NewPN);
6511 /// InstCombineStoreToCast - Fold 'store V, (cast P)' -> store (cast V), P'
6513 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
6514 User *CI = cast<User>(SI.getOperand(1));
6515 Value *CastOp = CI->getOperand(0);
6517 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
6518 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
6519 const Type *SrcPTy = SrcTy->getElementType();
6521 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
6522 // If the source is an array, the code below will not succeed. Check to
6523 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
6525 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
6526 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
6527 if (ASrcTy->getNumElements() != 0) {
6528 std::vector<Value*> Idxs(2, Constant::getNullValue(Type::IntTy));
6529 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
6530 SrcTy = cast<PointerType>(CastOp->getType());
6531 SrcPTy = SrcTy->getElementType();
6534 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
6535 IC.getTargetData().getTypeSize(SrcPTy) ==
6536 IC.getTargetData().getTypeSize(DestPTy)) {
6538 // Okay, we are casting from one integer or pointer type to another of
6539 // the same size. Instead of casting the pointer before the store, cast
6540 // the value to be stored.
6542 if (Constant *C = dyn_cast<Constant>(SI.getOperand(0)))
6543 NewCast = ConstantExpr::getCast(C, SrcPTy);
6545 NewCast = IC.InsertNewInstBefore(new CastInst(SI.getOperand(0),
6547 SI.getOperand(0)->getName()+".c"), SI);
6549 return new StoreInst(NewCast, CastOp);
6556 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
6557 Value *Val = SI.getOperand(0);
6558 Value *Ptr = SI.getOperand(1);
6560 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
6561 EraseInstFromFunction(SI);
6566 // Do really simple DSE, to catch cases where there are several consequtive
6567 // stores to the same location, separated by a few arithmetic operations. This
6568 // situation often occurs with bitfield accesses.
6569 BasicBlock::iterator BBI = &SI;
6570 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
6574 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
6575 // Prev store isn't volatile, and stores to the same location?
6576 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
6579 EraseInstFromFunction(*PrevSI);
6585 // Don't skip over loads or things that can modify memory.
6586 if (BBI->mayWriteToMemory() || isa<LoadInst>(BBI))
6591 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
6593 // store X, null -> turns into 'unreachable' in SimplifyCFG
6594 if (isa<ConstantPointerNull>(Ptr)) {
6595 if (!isa<UndefValue>(Val)) {
6596 SI.setOperand(0, UndefValue::get(Val->getType()));
6597 if (Instruction *U = dyn_cast<Instruction>(Val))
6598 WorkList.push_back(U); // Dropped a use.
6601 return 0; // Do not modify these!
6604 // store undef, Ptr -> noop
6605 if (isa<UndefValue>(Val)) {
6606 EraseInstFromFunction(SI);
6611 // If the pointer destination is a cast, see if we can fold the cast into the
6613 if (CastInst *CI = dyn_cast<CastInst>(Ptr))
6614 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
6616 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
6617 if (CE->getOpcode() == Instruction::Cast)
6618 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
6622 // If this store is the last instruction in the basic block, and if the block
6623 // ends with an unconditional branch, try to move it to the successor block.
6625 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
6626 if (BI->isUnconditional()) {
6627 // Check to see if the successor block has exactly two incoming edges. If
6628 // so, see if the other predecessor contains a store to the same location.
6629 // if so, insert a PHI node (if needed) and move the stores down.
6630 BasicBlock *Dest = BI->getSuccessor(0);
6632 pred_iterator PI = pred_begin(Dest);
6633 BasicBlock *Other = 0;
6634 if (*PI != BI->getParent())
6637 if (PI != pred_end(Dest)) {
6638 if (*PI != BI->getParent())
6643 if (++PI != pred_end(Dest))
6646 if (Other) { // If only one other pred...
6647 BBI = Other->getTerminator();
6648 // Make sure this other block ends in an unconditional branch and that
6649 // there is an instruction before the branch.
6650 if (isa<BranchInst>(BBI) && cast<BranchInst>(BBI)->isUnconditional() &&
6651 BBI != Other->begin()) {
6653 StoreInst *OtherStore = dyn_cast<StoreInst>(BBI);
6655 // If this instruction is a store to the same location.
6656 if (OtherStore && OtherStore->getOperand(1) == SI.getOperand(1)) {
6657 // Okay, we know we can perform this transformation. Insert a PHI
6658 // node now if we need it.
6659 Value *MergedVal = OtherStore->getOperand(0);
6660 if (MergedVal != SI.getOperand(0)) {
6661 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
6662 PN->reserveOperandSpace(2);
6663 PN->addIncoming(SI.getOperand(0), SI.getParent());
6664 PN->addIncoming(OtherStore->getOperand(0), Other);
6665 MergedVal = InsertNewInstBefore(PN, Dest->front());
6668 // Advance to a place where it is safe to insert the new store and
6670 BBI = Dest->begin();
6671 while (isa<PHINode>(BBI)) ++BBI;
6672 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
6673 OtherStore->isVolatile()), *BBI);
6675 // Nuke the old stores.
6676 EraseInstFromFunction(SI);
6677 EraseInstFromFunction(*OtherStore);
6689 Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
6690 // Change br (not X), label True, label False to: br X, label False, True
6692 BasicBlock *TrueDest;
6693 BasicBlock *FalseDest;
6694 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
6695 !isa<Constant>(X)) {
6696 // Swap Destinations and condition...
6698 BI.setSuccessor(0, FalseDest);
6699 BI.setSuccessor(1, TrueDest);
6703 // Cannonicalize setne -> seteq
6704 Instruction::BinaryOps Op; Value *Y;
6705 if (match(&BI, m_Br(m_SetCond(Op, m_Value(X), m_Value(Y)),
6706 TrueDest, FalseDest)))
6707 if ((Op == Instruction::SetNE || Op == Instruction::SetLE ||
6708 Op == Instruction::SetGE) && BI.getCondition()->hasOneUse()) {
6709 SetCondInst *I = cast<SetCondInst>(BI.getCondition());
6710 std::string Name = I->getName(); I->setName("");
6711 Instruction::BinaryOps NewOpcode = SetCondInst::getInverseCondition(Op);
6712 Value *NewSCC = BinaryOperator::create(NewOpcode, X, Y, Name, I);
6713 // Swap Destinations and condition...
6714 BI.setCondition(NewSCC);
6715 BI.setSuccessor(0, FalseDest);
6716 BI.setSuccessor(1, TrueDest);
6717 removeFromWorkList(I);
6718 I->getParent()->getInstList().erase(I);
6719 WorkList.push_back(cast<Instruction>(NewSCC));
6726 Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
6727 Value *Cond = SI.getCondition();
6728 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
6729 if (I->getOpcode() == Instruction::Add)
6730 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6731 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
6732 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
6733 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
6735 SI.setOperand(0, I->getOperand(0));
6736 WorkList.push_back(I);
6743 /// CheapToScalarize - Return true if the value is cheaper to scalarize than it
6744 /// is to leave as a vector operation.
6745 static bool CheapToScalarize(Value *V, bool isConstant) {
6746 if (isa<ConstantAggregateZero>(V))
6748 if (ConstantPacked *C = dyn_cast<ConstantPacked>(V)) {
6749 if (isConstant) return true;
6750 // If all elts are the same, we can extract.
6751 Constant *Op0 = C->getOperand(0);
6752 for (unsigned i = 1; i < C->getNumOperands(); ++i)
6753 if (C->getOperand(i) != Op0)
6757 Instruction *I = dyn_cast<Instruction>(V);
6758 if (!I) return false;
6760 // Insert element gets simplified to the inserted element or is deleted if
6761 // this is constant idx extract element and its a constant idx insertelt.
6762 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
6763 isa<ConstantInt>(I->getOperand(2)))
6765 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
6767 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
6768 if (BO->hasOneUse() &&
6769 (CheapToScalarize(BO->getOperand(0), isConstant) ||
6770 CheapToScalarize(BO->getOperand(1), isConstant)))
6776 /// FindScalarElement - Given a vector and an element number, see if the scalar
6777 /// value is already around as a register, for example if it were inserted then
6778 /// extracted from the vector.
6779 static Value *FindScalarElement(Value *V, unsigned EltNo) {
6780 assert(isa<PackedType>(V->getType()) && "Not looking at a vector?");
6781 const PackedType *PTy = cast<PackedType>(V->getType());
6782 if (EltNo >= PTy->getNumElements()) // Out of range access.
6783 return UndefValue::get(PTy->getElementType());
6785 if (isa<UndefValue>(V))
6786 return UndefValue::get(PTy->getElementType());
6787 else if (isa<ConstantAggregateZero>(V))
6788 return Constant::getNullValue(PTy->getElementType());
6789 else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(V))
6790 return CP->getOperand(EltNo);
6791 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
6792 // If this is an insert to a variable element, we don't know what it is.
6793 if (!isa<ConstantUInt>(III->getOperand(2))) return 0;
6794 unsigned IIElt = cast<ConstantUInt>(III->getOperand(2))->getValue();
6796 // If this is an insert to the element we are looking for, return the
6798 if (EltNo == IIElt) return III->getOperand(1);
6800 // Otherwise, the insertelement doesn't modify the value, recurse on its
6802 return FindScalarElement(III->getOperand(0), EltNo);
6805 // Otherwise, we don't know.
6809 Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
6811 // If packed val is undef, replace extract with scalar undef.
6812 if (isa<UndefValue>(EI.getOperand(0)))
6813 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
6815 // If packed val is constant 0, replace extract with scalar 0.
6816 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
6817 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
6819 if (ConstantPacked *C = dyn_cast<ConstantPacked>(EI.getOperand(0))) {
6820 // If packed val is constant with uniform operands, replace EI
6821 // with that operand
6822 Constant *op0 = C->getOperand(0);
6823 for (unsigned i = 1; i < C->getNumOperands(); ++i)
6824 if (C->getOperand(i) != op0) {
6829 return ReplaceInstUsesWith(EI, op0);
6832 // If extracting a specified index from the vector, see if we can recursively
6833 // find a previously computed scalar that was inserted into the vector.
6834 if (ConstantUInt *IdxC = dyn_cast<ConstantUInt>(EI.getOperand(1)))
6835 if (Value *Elt = FindScalarElement(EI.getOperand(0), IdxC->getValue()))
6836 return ReplaceInstUsesWith(EI, Elt);
6838 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0)))
6839 if (I->hasOneUse()) {
6840 // Push extractelement into predecessor operation if legal and
6841 // profitable to do so
6842 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
6843 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
6844 if (CheapToScalarize(BO, isConstantElt)) {
6845 ExtractElementInst *newEI0 =
6846 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
6847 EI.getName()+".lhs");
6848 ExtractElementInst *newEI1 =
6849 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
6850 EI.getName()+".rhs");
6851 InsertNewInstBefore(newEI0, EI);
6852 InsertNewInstBefore(newEI1, EI);
6853 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
6855 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6856 Value *Ptr = InsertCastBefore(I->getOperand(0),
6857 PointerType::get(EI.getType()), EI);
6858 GetElementPtrInst *GEP =
6859 new GetElementPtrInst(Ptr, EI.getOperand(1),
6860 I->getName() + ".gep");
6861 InsertNewInstBefore(GEP, EI);
6862 return new LoadInst(GEP);
6863 } else if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
6864 // Extracting the inserted element?
6865 if (IE->getOperand(2) == EI.getOperand(1))
6866 return ReplaceInstUsesWith(EI, IE->getOperand(1));
6867 // If the inserted and extracted elements are constants, they must not
6868 // be the same value, extract from the pre-inserted value instead.
6869 if (isa<Constant>(IE->getOperand(2)) &&
6870 isa<Constant>(EI.getOperand(1))) {
6871 AddUsesToWorkList(EI);
6872 EI.setOperand(0, IE->getOperand(0));
6880 Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
6881 Value *LHS = SVI.getOperand(0);
6882 Value *RHS = SVI.getOperand(1);
6883 Constant *Mask = cast<Constant>(SVI.getOperand(2));
6885 bool MadeChange = false;
6887 if (isa<UndefValue>(Mask))
6888 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
6890 // Canonicalize shuffle(x,x) -> shuffle(x,undef)
6892 if (isa<UndefValue>(LHS)) {
6893 // shuffle(undef,undef,mask) -> undef.
6894 return ReplaceInstUsesWith(SVI, LHS);
6897 if (!isa<ConstantAggregateZero>(Mask)) {
6898 // Remap any references to RHS to use LHS.
6899 ConstantPacked *CP = cast<ConstantPacked>(Mask);
6900 std::vector<Constant*> Elts;
6901 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
6902 Elts.push_back(CP->getOperand(i));
6903 if (isa<UndefValue>(CP->getOperand(i)))
6905 unsigned MV = cast<ConstantInt>(CP->getOperand(i))->getRawValue();
6907 Elts.back() = ConstantUInt::get(Type::UIntTy, MV & (e-1));
6909 Mask = ConstantPacked::get(Elts);
6911 SVI.setOperand(1, UndefValue::get(RHS->getType()));
6912 SVI.setOperand(2, Mask);
6916 if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Mask)) {
6917 bool isLHSID = true, isRHSID = true;
6919 // Analyze the shuffle.
6920 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i) {
6921 if (isa<UndefValue>(CP->getOperand(i)))
6923 unsigned MV = cast<ConstantInt>(CP->getOperand(i))->getRawValue();
6925 // Is this an identity shuffle of the LHS value?
6926 isLHSID &= (MV == i);
6928 // Is this an identity shuffle of the RHS value?
6929 isRHSID &= (MV-e == i);
6932 // Eliminate identity shuffles.
6933 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
6934 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
6937 return MadeChange ? &SVI : 0;
6942 void InstCombiner::removeFromWorkList(Instruction *I) {
6943 WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), I),
6948 /// TryToSinkInstruction - Try to move the specified instruction from its
6949 /// current block into the beginning of DestBlock, which can only happen if it's
6950 /// safe to move the instruction past all of the instructions between it and the
6951 /// end of its block.
6952 static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
6953 assert(I->hasOneUse() && "Invariants didn't hold!");
6955 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
6956 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
6958 // Do not sink alloca instructions out of the entry block.
6959 if (isa<AllocaInst>(I) && I->getParent() == &DestBlock->getParent()->front())
6962 // We can only sink load instructions if there is nothing between the load and
6963 // the end of block that could change the value.
6964 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
6965 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
6967 if (Scan->mayWriteToMemory())
6971 BasicBlock::iterator InsertPos = DestBlock->begin();
6972 while (isa<PHINode>(InsertPos)) ++InsertPos;
6974 I->moveBefore(InsertPos);
6979 bool InstCombiner::runOnFunction(Function &F) {
6980 bool Changed = false;
6981 TD = &getAnalysis<TargetData>();
6984 // Populate the worklist with the reachable instructions.
6985 std::set<BasicBlock*> Visited;
6986 for (df_ext_iterator<BasicBlock*> BB = df_ext_begin(&F.front(), Visited),
6987 E = df_ext_end(&F.front(), Visited); BB != E; ++BB)
6988 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
6989 WorkList.push_back(I);
6991 // Do a quick scan over the function. If we find any blocks that are
6992 // unreachable, remove any instructions inside of them. This prevents
6993 // the instcombine code from having to deal with some bad special cases.
6994 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
6995 if (!Visited.count(BB)) {
6996 Instruction *Term = BB->getTerminator();
6997 while (Term != BB->begin()) { // Remove instrs bottom-up
6998 BasicBlock::iterator I = Term; --I;
7000 DEBUG(std::cerr << "IC: DCE: " << *I);
7003 if (!I->use_empty())
7004 I->replaceAllUsesWith(UndefValue::get(I->getType()));
7005 I->eraseFromParent();
7010 while (!WorkList.empty()) {
7011 Instruction *I = WorkList.back(); // Get an instruction from the worklist
7012 WorkList.pop_back();
7014 // Check to see if we can DCE or ConstantPropagate the instruction...
7015 // Check to see if we can DIE the instruction...
7016 if (isInstructionTriviallyDead(I)) {
7017 // Add operands to the worklist...
7018 if (I->getNumOperands() < 4)
7019 AddUsesToWorkList(*I);
7022 DEBUG(std::cerr << "IC: DCE: " << *I);
7024 I->eraseFromParent();
7025 removeFromWorkList(I);
7029 // Instruction isn't dead, see if we can constant propagate it...
7030 if (Constant *C = ConstantFoldInstruction(I)) {
7031 Value* Ptr = I->getOperand(0);
7032 if (isa<GetElementPtrInst>(I) &&
7033 cast<Constant>(Ptr)->isNullValue() &&
7034 !isa<ConstantPointerNull>(C) &&
7035 cast<PointerType>(Ptr->getType())->getElementType()->isSized()) {
7036 // If this is a constant expr gep that is effectively computing an
7037 // "offsetof", fold it into 'cast int X to T*' instead of 'gep 0, 0, 12'
7038 bool isFoldableGEP = true;
7039 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
7040 if (!isa<ConstantInt>(I->getOperand(i)))
7041 isFoldableGEP = false;
7042 if (isFoldableGEP) {
7043 uint64_t Offset = TD->getIndexedOffset(Ptr->getType(),
7044 std::vector<Value*>(I->op_begin()+1, I->op_end()));
7045 C = ConstantUInt::get(Type::ULongTy, Offset);
7046 C = ConstantExpr::getCast(C, TD->getIntPtrType());
7047 C = ConstantExpr::getCast(C, I->getType());
7051 DEBUG(std::cerr << "IC: ConstFold to: " << *C << " from: " << *I);
7053 // Add operands to the worklist...
7054 AddUsesToWorkList(*I);
7055 ReplaceInstUsesWith(*I, C);
7058 I->getParent()->getInstList().erase(I);
7059 removeFromWorkList(I);
7063 // See if we can trivially sink this instruction to a successor basic block.
7064 if (I->hasOneUse()) {
7065 BasicBlock *BB = I->getParent();
7066 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
7067 if (UserParent != BB) {
7068 bool UserIsSuccessor = false;
7069 // See if the user is one of our successors.
7070 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
7071 if (*SI == UserParent) {
7072 UserIsSuccessor = true;
7076 // If the user is one of our immediate successors, and if that successor
7077 // only has us as a predecessors (we'd have to split the critical edge
7078 // otherwise), we can keep going.
7079 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
7080 next(pred_begin(UserParent)) == pred_end(UserParent))
7081 // Okay, the CFG is simple enough, try to sink this instruction.
7082 Changed |= TryToSinkInstruction(I, UserParent);
7086 // Now that we have an instruction, try combining it to simplify it...
7087 if (Instruction *Result = visit(*I)) {
7089 // Should we replace the old instruction with a new one?
7091 DEBUG(std::cerr << "IC: Old = " << *I
7092 << " New = " << *Result);
7094 // Everything uses the new instruction now.
7095 I->replaceAllUsesWith(Result);
7097 // Push the new instruction and any users onto the worklist.
7098 WorkList.push_back(Result);
7099 AddUsersToWorkList(*Result);
7101 // Move the name to the new instruction first...
7102 std::string OldName = I->getName(); I->setName("");
7103 Result->setName(OldName);
7105 // Insert the new instruction into the basic block...
7106 BasicBlock *InstParent = I->getParent();
7107 BasicBlock::iterator InsertPos = I;
7109 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
7110 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
7113 InstParent->getInstList().insert(InsertPos, Result);
7115 // Make sure that we reprocess all operands now that we reduced their
7117 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
7118 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
7119 WorkList.push_back(OpI);
7121 // Instructions can end up on the worklist more than once. Make sure
7122 // we do not process an instruction that has been deleted.
7123 removeFromWorkList(I);
7125 // Erase the old instruction.
7126 InstParent->getInstList().erase(I);
7128 DEBUG(std::cerr << "IC: MOD = " << *I);
7130 // If the instruction was modified, it's possible that it is now dead.
7131 // if so, remove it.
7132 if (isInstructionTriviallyDead(I)) {
7133 // Make sure we process all operands now that we are reducing their
7135 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
7136 if (Instruction *OpI = dyn_cast<Instruction>(I->getOperand(i)))
7137 WorkList.push_back(OpI);
7139 // Instructions may end up in the worklist more than once. Erase all
7140 // occurrences of this instruction.
7141 removeFromWorkList(I);
7142 I->eraseFromParent();
7144 WorkList.push_back(Result);
7145 AddUsersToWorkList(*Result);
7155 FunctionPass *llvm::createInstructionCombiningPass() {
7156 return new InstCombiner();