blob: ab6262b47e53bf301a63169254ffd5e9cff504c2 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
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.
7//
8//===----------------------------------------------------------------------===//
9//
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.
13//
14// This pass combines things like:
15// %Y = add i32 %X, 1
16// %Z = add i32 %Y, 1
17// into:
18// %Z = add i32 %X, 2
19//
20// This is a simple worklist driven algorithm.
21//
22// This pass guarantees that the following canonicalizations are performed on
23// the program:
24// 1. If a binary operator has a constant operand, it is moved to the RHS
25// 2. Bitwise operators with constant operands are always grouped so that
26// shifts are performed first, then or's, then and's, then xor's.
27// 3. Compare instructions are converted from <,>,<=,>= to ==,!= if possible
28// 4. All cmp instructions on boolean values are replaced with logical ops
29// 5. add X, X is represented as (X*2) => (X << 1)
30// 6. Multiplies with a power-of-two constant argument are transformed into
31// shifts.
32// ... etc.
33//
34//===----------------------------------------------------------------------===//
35
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"
Duncan Sandscf7ecaa2007-09-11 14:35:41 +000042#include "llvm/ParameterAttributes.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000043#include "llvm/Analysis/ConstantFolding.h"
44#include "llvm/Target/TargetData.h"
45#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/Local.h"
47#include "llvm/Support/CallSite.h"
48#include "llvm/Support/Debug.h"
49#include "llvm/Support/GetElementPtrTypeIterator.h"
50#include "llvm/Support/InstVisitor.h"
51#include "llvm/Support/MathExtras.h"
52#include "llvm/Support/PatternMatch.h"
53#include "llvm/Support/Compiler.h"
54#include "llvm/ADT/DenseMap.h"
55#include "llvm/ADT/SmallVector.h"
56#include "llvm/ADT/SmallPtrSet.h"
57#include "llvm/ADT/Statistic.h"
58#include "llvm/ADT/STLExtras.h"
59#include <algorithm>
60#include <sstream>
61using namespace llvm;
62using namespace llvm::PatternMatch;
63
64STATISTIC(NumCombined , "Number of insts combined");
65STATISTIC(NumConstProp, "Number of constant folds");
66STATISTIC(NumDeadInst , "Number of dead inst eliminated");
67STATISTIC(NumDeadStore, "Number of dead stores eliminated");
68STATISTIC(NumSunkInst , "Number of instructions sunk");
69
70namespace {
71 class VISIBILITY_HIDDEN InstCombiner
72 : public FunctionPass,
73 public InstVisitor<InstCombiner, Instruction*> {
74 // Worklist of all of the instructions that need to be simplified.
75 std::vector<Instruction*> Worklist;
76 DenseMap<Instruction*, unsigned> WorklistMap;
77 TargetData *TD;
78 bool MustPreserveLCSSA;
79 public:
80 static char ID; // Pass identification, replacement for typeid
81 InstCombiner() : FunctionPass((intptr_t)&ID) {}
82
83 /// AddToWorkList - Add the specified instruction to the worklist if it
84 /// isn't already in it.
85 void AddToWorkList(Instruction *I) {
86 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
87 Worklist.push_back(I);
88 }
89
90 // RemoveFromWorkList - remove I from the worklist if it exists.
91 void RemoveFromWorkList(Instruction *I) {
92 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
93 if (It == WorklistMap.end()) return; // Not in worklist.
94
95 // Don't bother moving everything down, just null out the slot.
96 Worklist[It->second] = 0;
97
98 WorklistMap.erase(It);
99 }
100
101 Instruction *RemoveOneFromWorkList() {
102 Instruction *I = Worklist.back();
103 Worklist.pop_back();
104 WorklistMap.erase(I);
105 return I;
106 }
107
108
109 /// AddUsersToWorkList - When an instruction is simplified, add all users of
110 /// the instruction to the work lists because they might get more simplified
111 /// now.
112 ///
113 void AddUsersToWorkList(Value &I) {
114 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
115 UI != UE; ++UI)
116 AddToWorkList(cast<Instruction>(*UI));
117 }
118
119 /// AddUsesToWorkList - When an instruction is simplified, add operands to
120 /// the work lists because they might get more simplified now.
121 ///
122 void AddUsesToWorkList(Instruction &I) {
123 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
124 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
125 AddToWorkList(Op);
126 }
127
128 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
129 /// dead. Add all of its operands to the worklist, turning them into
130 /// undef's to reduce the number of uses of those instructions.
131 ///
132 /// Return the specified operand before it is turned into an undef.
133 ///
134 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
135 Value *R = I.getOperand(op);
136
137 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
138 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
139 AddToWorkList(Op);
140 // Set the operand to undef to drop the use.
141 I.setOperand(i, UndefValue::get(Op->getType()));
142 }
143
144 return R;
145 }
146
147 public:
148 virtual bool runOnFunction(Function &F);
149
150 bool DoOneIteration(Function &F, unsigned ItNum);
151
152 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
153 AU.addRequired<TargetData>();
154 AU.addPreservedID(LCSSAID);
155 AU.setPreservesCFG();
156 }
157
158 TargetData &getTargetData() const { return *TD; }
159
160 // Visitation implementation - Implement instruction combining for different
161 // instruction types. The semantics are as follows:
162 // Return Value:
163 // null - No change was made
164 // I - Change was made, I is still valid, I may be dead though
165 // otherwise - Change was made, replace I with returned instruction
166 //
167 Instruction *visitAdd(BinaryOperator &I);
168 Instruction *visitSub(BinaryOperator &I);
169 Instruction *visitMul(BinaryOperator &I);
170 Instruction *visitURem(BinaryOperator &I);
171 Instruction *visitSRem(BinaryOperator &I);
172 Instruction *visitFRem(BinaryOperator &I);
173 Instruction *commonRemTransforms(BinaryOperator &I);
174 Instruction *commonIRemTransforms(BinaryOperator &I);
175 Instruction *commonDivTransforms(BinaryOperator &I);
176 Instruction *commonIDivTransforms(BinaryOperator &I);
177 Instruction *visitUDiv(BinaryOperator &I);
178 Instruction *visitSDiv(BinaryOperator &I);
179 Instruction *visitFDiv(BinaryOperator &I);
180 Instruction *visitAnd(BinaryOperator &I);
181 Instruction *visitOr (BinaryOperator &I);
182 Instruction *visitXor(BinaryOperator &I);
183 Instruction *visitShl(BinaryOperator &I);
184 Instruction *visitAShr(BinaryOperator &I);
185 Instruction *visitLShr(BinaryOperator &I);
186 Instruction *commonShiftTransforms(BinaryOperator &I);
187 Instruction *visitFCmpInst(FCmpInst &I);
188 Instruction *visitICmpInst(ICmpInst &I);
189 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
190 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
191 Instruction *LHS,
192 ConstantInt *RHS);
193 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
194 ConstantInt *DivRHS);
195
196 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
197 ICmpInst::Predicate Cond, Instruction &I);
198 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
199 BinaryOperator &I);
200 Instruction *commonCastTransforms(CastInst &CI);
201 Instruction *commonIntCastTransforms(CastInst &CI);
202 Instruction *commonPointerCastTransforms(CastInst &CI);
203 Instruction *visitTrunc(TruncInst &CI);
204 Instruction *visitZExt(ZExtInst &CI);
205 Instruction *visitSExt(SExtInst &CI);
206 Instruction *visitFPTrunc(CastInst &CI);
207 Instruction *visitFPExt(CastInst &CI);
208 Instruction *visitFPToUI(CastInst &CI);
209 Instruction *visitFPToSI(CastInst &CI);
210 Instruction *visitUIToFP(CastInst &CI);
211 Instruction *visitSIToFP(CastInst &CI);
212 Instruction *visitPtrToInt(CastInst &CI);
213 Instruction *visitIntToPtr(CastInst &CI);
214 Instruction *visitBitCast(BitCastInst &CI);
215 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
216 Instruction *FI);
217 Instruction *visitSelectInst(SelectInst &CI);
218 Instruction *visitCallInst(CallInst &CI);
219 Instruction *visitInvokeInst(InvokeInst &II);
220 Instruction *visitPHINode(PHINode &PN);
221 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
222 Instruction *visitAllocationInst(AllocationInst &AI);
223 Instruction *visitFreeInst(FreeInst &FI);
224 Instruction *visitLoadInst(LoadInst &LI);
225 Instruction *visitStoreInst(StoreInst &SI);
226 Instruction *visitBranchInst(BranchInst &BI);
227 Instruction *visitSwitchInst(SwitchInst &SI);
228 Instruction *visitInsertElementInst(InsertElementInst &IE);
229 Instruction *visitExtractElementInst(ExtractElementInst &EI);
230 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
231
232 // visitInstruction - Specify what to return for unhandled instructions...
233 Instruction *visitInstruction(Instruction &I) { return 0; }
234
235 private:
236 Instruction *visitCallSite(CallSite CS);
237 bool transformConstExprCastCall(CallSite CS);
238
239 public:
240 // InsertNewInstBefore - insert an instruction New before instruction Old
241 // in the program. Add the new instruction to the worklist.
242 //
243 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
244 assert(New && New->getParent() == 0 &&
245 "New instruction already inserted into a basic block!");
246 BasicBlock *BB = Old.getParent();
247 BB->getInstList().insert(&Old, New); // Insert inst
248 AddToWorkList(New);
249 return New;
250 }
251
252 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
253 /// This also adds the cast to the worklist. Finally, this returns the
254 /// cast.
255 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
256 Instruction &Pos) {
257 if (V->getType() == Ty) return V;
258
259 if (Constant *CV = dyn_cast<Constant>(V))
260 return ConstantExpr::getCast(opc, CV, Ty);
261
262 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
263 AddToWorkList(C);
264 return C;
265 }
266
267 // ReplaceInstUsesWith - This method is to be used when an instruction is
268 // found to be dead, replacable with another preexisting expression. Here
269 // we add all uses of I to the worklist, replace all uses of I with the new
270 // value, then return I, so that the inst combiner will know that I was
271 // modified.
272 //
273 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
274 AddUsersToWorkList(I); // Add all modified instrs to worklist
275 if (&I != V) {
276 I.replaceAllUsesWith(V);
277 return &I;
278 } else {
279 // If we are replacing the instruction with itself, this must be in a
280 // segment of unreachable code, so just clobber the instruction.
281 I.replaceAllUsesWith(UndefValue::get(I.getType()));
282 return &I;
283 }
284 }
285
286 // UpdateValueUsesWith - This method is to be used when an value is
287 // found to be replacable with another preexisting expression or was
288 // updated. Here we add all uses of I to the worklist, replace all uses of
289 // I with the new value (unless the instruction was just updated), then
290 // return true, so that the inst combiner will know that I was modified.
291 //
292 bool UpdateValueUsesWith(Value *Old, Value *New) {
293 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
294 if (Old != New)
295 Old->replaceAllUsesWith(New);
296 if (Instruction *I = dyn_cast<Instruction>(Old))
297 AddToWorkList(I);
298 if (Instruction *I = dyn_cast<Instruction>(New))
299 AddToWorkList(I);
300 return true;
301 }
302
303 // EraseInstFromFunction - When dealing with an instruction that has side
304 // effects or produces a void value, we can't rely on DCE to delete the
305 // instruction. Instead, visit methods should return the value returned by
306 // this function.
307 Instruction *EraseInstFromFunction(Instruction &I) {
308 assert(I.use_empty() && "Cannot erase instruction that is used!");
309 AddUsesToWorkList(I);
310 RemoveFromWorkList(&I);
311 I.eraseFromParent();
312 return 0; // Don't do anything with FI
313 }
314
315 private:
316 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
317 /// InsertBefore instruction. This is specialized a bit to avoid inserting
318 /// casts that are known to not do anything...
319 ///
320 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
321 Value *V, const Type *DestTy,
322 Instruction *InsertBefore);
323
324 /// SimplifyCommutative - This performs a few simplifications for
325 /// commutative operators.
326 bool SimplifyCommutative(BinaryOperator &I);
327
328 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
329 /// most-complex to least-complex order.
330 bool SimplifyCompare(CmpInst &I);
331
332 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
333 /// on the demanded bits.
334 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
335 APInt& KnownZero, APInt& KnownOne,
336 unsigned Depth = 0);
337
338 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
339 uint64_t &UndefElts, unsigned Depth = 0);
340
341 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
342 // PHI node as operand #0, see if we can fold the instruction into the PHI
343 // (which is only possible if all operands to the PHI are constants).
344 Instruction *FoldOpIntoPhi(Instruction &I);
345
346 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
347 // operator and they all are only used by the PHI, PHI together their
348 // inputs, and do the operation once, to the result of the PHI.
349 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
350 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
351
352
353 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
354 ConstantInt *AndRHS, BinaryOperator &TheAnd);
355
356 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
357 bool isSub, Instruction &I);
358 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
359 bool isSigned, bool Inside, Instruction &IB);
360 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
361 Instruction *MatchBSwap(BinaryOperator &I);
362 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
363
364 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
365 };
366
367 char InstCombiner::ID = 0;
368 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
369}
370
371// getComplexity: Assign a complexity or rank value to LLVM Values...
372// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
373static unsigned getComplexity(Value *V) {
374 if (isa<Instruction>(V)) {
375 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
376 return 3;
377 return 4;
378 }
379 if (isa<Argument>(V)) return 3;
380 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
381}
382
383// isOnlyUse - Return true if this instruction will be deleted if we stop using
384// it.
385static bool isOnlyUse(Value *V) {
386 return V->hasOneUse() || isa<Constant>(V);
387}
388
389// getPromotedType - Return the specified type promoted as it would be to pass
390// though a va_arg area...
391static const Type *getPromotedType(const Type *Ty) {
392 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
393 if (ITy->getBitWidth() < 32)
394 return Type::Int32Ty;
395 }
396 return Ty;
397}
398
399/// getBitCastOperand - If the specified operand is a CastInst or a constant
400/// expression bitcast, return the operand value, otherwise return null.
401static Value *getBitCastOperand(Value *V) {
402 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
403 return I->getOperand(0);
404 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
405 if (CE->getOpcode() == Instruction::BitCast)
406 return CE->getOperand(0);
407 return 0;
408}
409
410/// This function is a wrapper around CastInst::isEliminableCastPair. It
411/// simply extracts arguments and returns what that function returns.
412static Instruction::CastOps
413isEliminableCastPair(
414 const CastInst *CI, ///< The first cast instruction
415 unsigned opcode, ///< The opcode of the second cast instruction
416 const Type *DstTy, ///< The target type for the second cast instruction
417 TargetData *TD ///< The target data for pointer size
418) {
419
420 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
421 const Type *MidTy = CI->getType(); // B from above
422
423 // Get the opcodes of the two Cast instructions
424 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
425 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
426
427 return Instruction::CastOps(
428 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
429 DstTy, TD->getIntPtrType()));
430}
431
432/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
433/// in any code being generated. It does not require codegen if V is simple
434/// enough or if the cast can be folded into other casts.
435static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
436 const Type *Ty, TargetData *TD) {
437 if (V->getType() == Ty || isa<Constant>(V)) return false;
438
439 // If this is another cast that can be eliminated, it isn't codegen either.
440 if (const CastInst *CI = dyn_cast<CastInst>(V))
441 if (isEliminableCastPair(CI, opcode, Ty, TD))
442 return false;
443 return true;
444}
445
446/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
447/// InsertBefore instruction. This is specialized a bit to avoid inserting
448/// casts that are known to not do anything...
449///
450Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
451 Value *V, const Type *DestTy,
452 Instruction *InsertBefore) {
453 if (V->getType() == DestTy) return V;
454 if (Constant *C = dyn_cast<Constant>(V))
455 return ConstantExpr::getCast(opcode, C, DestTy);
456
457 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
458}
459
460// SimplifyCommutative - This performs a few simplifications for commutative
461// operators:
462//
463// 1. Order operands such that they are listed from right (least complex) to
464// left (most complex). This puts constants before unary operators before
465// binary operators.
466//
467// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
468// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
469//
470bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
471 bool Changed = false;
472 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
473 Changed = !I.swapOperands();
474
475 if (!I.isAssociative()) return Changed;
476 Instruction::BinaryOps Opcode = I.getOpcode();
477 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
478 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
479 if (isa<Constant>(I.getOperand(1))) {
480 Constant *Folded = ConstantExpr::get(I.getOpcode(),
481 cast<Constant>(I.getOperand(1)),
482 cast<Constant>(Op->getOperand(1)));
483 I.setOperand(0, Op->getOperand(0));
484 I.setOperand(1, Folded);
485 return true;
486 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
487 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
488 isOnlyUse(Op) && isOnlyUse(Op1)) {
489 Constant *C1 = cast<Constant>(Op->getOperand(1));
490 Constant *C2 = cast<Constant>(Op1->getOperand(1));
491
492 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
493 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
494 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
495 Op1->getOperand(0),
496 Op1->getName(), &I);
497 AddToWorkList(New);
498 I.setOperand(0, New);
499 I.setOperand(1, Folded);
500 return true;
501 }
502 }
503 return Changed;
504}
505
506/// SimplifyCompare - For a CmpInst this function just orders the operands
507/// so that theyare listed from right (least complex) to left (most complex).
508/// This puts constants before unary operators before binary operators.
509bool InstCombiner::SimplifyCompare(CmpInst &I) {
510 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
511 return false;
512 I.swapOperands();
513 // Compare instructions are not associative so there's nothing else we can do.
514 return true;
515}
516
517// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
518// if the LHS is a constant zero (which is the 'negate' form).
519//
520static inline Value *dyn_castNegVal(Value *V) {
521 if (BinaryOperator::isNeg(V))
522 return BinaryOperator::getNegArgument(V);
523
524 // Constants can be considered to be negated values if they can be folded.
525 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
526 return ConstantExpr::getNeg(C);
527 return 0;
528}
529
530static inline Value *dyn_castNotVal(Value *V) {
531 if (BinaryOperator::isNot(V))
532 return BinaryOperator::getNotArgument(V);
533
534 // Constants can be considered to be not'ed values...
535 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
536 return ConstantInt::get(~C->getValue());
537 return 0;
538}
539
540// dyn_castFoldableMul - If this value is a multiply that can be folded into
541// other computations (because it has a constant operand), return the
542// non-constant operand of the multiply, and set CST to point to the multiplier.
543// Otherwise, return null.
544//
545static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
546 if (V->hasOneUse() && V->getType()->isInteger())
547 if (Instruction *I = dyn_cast<Instruction>(V)) {
548 if (I->getOpcode() == Instruction::Mul)
549 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
550 return I->getOperand(0);
551 if (I->getOpcode() == Instruction::Shl)
552 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
553 // The multiplier is really 1 << CST.
554 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
555 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
556 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
557 return I->getOperand(0);
558 }
559 }
560 return 0;
561}
562
563/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
564/// expression, return it.
565static User *dyn_castGetElementPtr(Value *V) {
566 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
567 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
568 if (CE->getOpcode() == Instruction::GetElementPtr)
569 return cast<User>(V);
570 return false;
571}
572
573/// AddOne - Add one to a ConstantInt
574static ConstantInt *AddOne(ConstantInt *C) {
575 APInt Val(C->getValue());
576 return ConstantInt::get(++Val);
577}
578/// SubOne - Subtract one from a ConstantInt
579static ConstantInt *SubOne(ConstantInt *C) {
580 APInt Val(C->getValue());
581 return ConstantInt::get(--Val);
582}
583/// Add - Add two ConstantInts together
584static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
585 return ConstantInt::get(C1->getValue() + C2->getValue());
586}
587/// And - Bitwise AND two ConstantInts together
588static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
589 return ConstantInt::get(C1->getValue() & C2->getValue());
590}
591/// Subtract - Subtract one ConstantInt from another
592static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
593 return ConstantInt::get(C1->getValue() - C2->getValue());
594}
595/// Multiply - Multiply two ConstantInts together
596static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
597 return ConstantInt::get(C1->getValue() * C2->getValue());
598}
599
600/// ComputeMaskedBits - Determine which of the bits specified in Mask are
601/// known to be either zero or one and return them in the KnownZero/KnownOne
602/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
603/// processing.
604/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
605/// we cannot optimize based on the assumption that it is zero without changing
606/// it to be an explicit zero. If we don't change it to zero, other code could
607/// optimized based on the contradictory assumption that it is non-zero.
608/// Because instcombine aggressively folds operations with undef args anyway,
609/// this won't lose us code quality.
610static void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
611 APInt& KnownOne, unsigned Depth = 0) {
612 assert(V && "No Value?");
613 assert(Depth <= 6 && "Limit Search Depth");
614 uint32_t BitWidth = Mask.getBitWidth();
615 assert(cast<IntegerType>(V->getType())->getBitWidth() == BitWidth &&
616 KnownZero.getBitWidth() == BitWidth &&
617 KnownOne.getBitWidth() == BitWidth &&
618 "V, Mask, KnownOne and KnownZero should have same BitWidth");
619 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
620 // We know all of the bits for a constant!
621 KnownOne = CI->getValue() & Mask;
622 KnownZero = ~KnownOne & Mask;
623 return;
624 }
625
626 if (Depth == 6 || Mask == 0)
627 return; // Limit search depth.
628
629 Instruction *I = dyn_cast<Instruction>(V);
630 if (!I) return;
631
632 KnownZero.clear(); KnownOne.clear(); // Don't know anything.
633 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
634
635 switch (I->getOpcode()) {
636 case Instruction::And: {
637 // If either the LHS or the RHS are Zero, the result is zero.
638 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
639 APInt Mask2(Mask & ~KnownZero);
640 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
641 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
642 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
643
644 // Output known-1 bits are only known if set in both the LHS & RHS.
645 KnownOne &= KnownOne2;
646 // Output known-0 are known to be clear if zero in either the LHS | RHS.
647 KnownZero |= KnownZero2;
648 return;
649 }
650 case Instruction::Or: {
651 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
652 APInt Mask2(Mask & ~KnownOne);
653 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
654 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
655 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
656
657 // Output known-0 bits are only known if clear in both the LHS & RHS.
658 KnownZero &= KnownZero2;
659 // Output known-1 are known to be set if set in either the LHS | RHS.
660 KnownOne |= KnownOne2;
661 return;
662 }
663 case Instruction::Xor: {
664 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
665 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
666 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
667 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
668
669 // Output known-0 bits are known if clear or set in both the LHS & RHS.
670 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
671 // Output known-1 are known to be set if set in only one of the LHS, RHS.
672 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
673 KnownZero = KnownZeroOut;
674 return;
675 }
676 case Instruction::Select:
677 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
678 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
679 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
680 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
681
682 // Only known if known in both the LHS and RHS.
683 KnownOne &= KnownOne2;
684 KnownZero &= KnownZero2;
685 return;
686 case Instruction::FPTrunc:
687 case Instruction::FPExt:
688 case Instruction::FPToUI:
689 case Instruction::FPToSI:
690 case Instruction::SIToFP:
691 case Instruction::PtrToInt:
692 case Instruction::UIToFP:
693 case Instruction::IntToPtr:
694 return; // Can't work with floating point or pointers
695 case Instruction::Trunc: {
696 // All these have integer operands
697 uint32_t SrcBitWidth =
698 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
699 APInt MaskIn(Mask);
700 MaskIn.zext(SrcBitWidth);
701 KnownZero.zext(SrcBitWidth);
702 KnownOne.zext(SrcBitWidth);
703 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
704 KnownZero.trunc(BitWidth);
705 KnownOne.trunc(BitWidth);
706 return;
707 }
708 case Instruction::BitCast: {
709 const Type *SrcTy = I->getOperand(0)->getType();
710 if (SrcTy->isInteger()) {
711 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
712 return;
713 }
714 break;
715 }
716 case Instruction::ZExt: {
717 // Compute the bits in the result that are not present in the input.
718 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
719 uint32_t SrcBitWidth = SrcTy->getBitWidth();
720
721 APInt MaskIn(Mask);
722 MaskIn.trunc(SrcBitWidth);
723 KnownZero.trunc(SrcBitWidth);
724 KnownOne.trunc(SrcBitWidth);
725 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
726 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
727 // The top bits are known to be zero.
728 KnownZero.zext(BitWidth);
729 KnownOne.zext(BitWidth);
730 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
731 return;
732 }
733 case Instruction::SExt: {
734 // Compute the bits in the result that are not present in the input.
735 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
736 uint32_t SrcBitWidth = SrcTy->getBitWidth();
737
738 APInt MaskIn(Mask);
739 MaskIn.trunc(SrcBitWidth);
740 KnownZero.trunc(SrcBitWidth);
741 KnownOne.trunc(SrcBitWidth);
742 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
743 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
744 KnownZero.zext(BitWidth);
745 KnownOne.zext(BitWidth);
746
747 // If the sign bit of the input is known set or clear, then we know the
748 // top bits of the result.
749 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
750 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
751 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
752 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
753 return;
754 }
755 case Instruction::Shl:
756 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
757 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
758 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
759 APInt Mask2(Mask.lshr(ShiftAmt));
760 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
761 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
762 KnownZero <<= ShiftAmt;
763 KnownOne <<= ShiftAmt;
764 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
765 return;
766 }
767 break;
768 case Instruction::LShr:
769 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
770 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
771 // Compute the new bits that are at the top now.
772 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
773
774 // Unsigned shift right.
775 APInt Mask2(Mask.shl(ShiftAmt));
776 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
777 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
778 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
779 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
780 // high bits known zero.
781 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
782 return;
783 }
784 break;
785 case Instruction::AShr:
786 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
787 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
788 // Compute the new bits that are at the top now.
789 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
790
791 // Signed shift right.
792 APInt Mask2(Mask.shl(ShiftAmt));
793 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
794 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
795 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
796 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
797
798 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
799 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
800 KnownZero |= HighBits;
801 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
802 KnownOne |= HighBits;
803 return;
804 }
805 break;
806 }
807}
808
809/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
810/// this predicate to simplify operations downstream. Mask is known to be zero
811/// for bits that V cannot have.
812static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
813 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
814 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
815 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
816 return (KnownZero & Mask) == Mask;
817}
818
819/// ShrinkDemandedConstant - Check to see if the specified operand of the
820/// specified instruction is a constant integer. If so, check to see if there
821/// are any bits set in the constant that are not demanded. If so, shrink the
822/// constant and return true.
823static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
824 APInt Demanded) {
825 assert(I && "No instruction?");
826 assert(OpNo < I->getNumOperands() && "Operand index too large");
827
828 // If the operand is not a constant integer, nothing to do.
829 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
830 if (!OpC) return false;
831
832 // If there are no bits set that aren't demanded, nothing to do.
833 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
834 if ((~Demanded & OpC->getValue()) == 0)
835 return false;
836
837 // This instruction is producing bits that are not demanded. Shrink the RHS.
838 Demanded &= OpC->getValue();
839 I->setOperand(OpNo, ConstantInt::get(Demanded));
840 return true;
841}
842
843// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
844// set of known zero and one bits, compute the maximum and minimum values that
845// could have the specified known zero and known one bits, returning them in
846// min/max.
847static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
848 const APInt& KnownZero,
849 const APInt& KnownOne,
850 APInt& Min, APInt& Max) {
851 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
852 assert(KnownZero.getBitWidth() == BitWidth &&
853 KnownOne.getBitWidth() == BitWidth &&
854 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
855 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
856 APInt UnknownBits = ~(KnownZero|KnownOne);
857
858 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
859 // bit if it is unknown.
860 Min = KnownOne;
861 Max = KnownOne|UnknownBits;
862
863 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
864 Min.set(BitWidth-1);
865 Max.clear(BitWidth-1);
866 }
867}
868
869// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
870// a set of known zero and one bits, compute the maximum and minimum values that
871// could have the specified known zero and known one bits, returning them in
872// min/max.
873static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnerb933ea62007-08-05 08:47:58 +0000874 const APInt &KnownZero,
875 const APInt &KnownOne,
876 APInt &Min, APInt &Max) {
877 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000878 assert(KnownZero.getBitWidth() == BitWidth &&
879 KnownOne.getBitWidth() == BitWidth &&
880 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
881 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
882 APInt UnknownBits = ~(KnownZero|KnownOne);
883
884 // The minimum value is when the unknown bits are all zeros.
885 Min = KnownOne;
886 // The maximum value is when the unknown bits are all ones.
887 Max = KnownOne|UnknownBits;
888}
889
890/// SimplifyDemandedBits - This function attempts to replace V with a simpler
891/// value based on the demanded bits. When this function is called, it is known
892/// that only the bits set in DemandedMask of the result of V are ever used
893/// downstream. Consequently, depending on the mask and V, it may be possible
894/// to replace V with a constant or one of its operands. In such cases, this
895/// function does the replacement and returns true. In all other cases, it
896/// returns false after analyzing the expression and setting KnownOne and known
897/// to be one in the expression. KnownZero contains all the bits that are known
898/// to be zero in the expression. These are provided to potentially allow the
899/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
900/// the expression. KnownOne and KnownZero always follow the invariant that
901/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
902/// the bits in KnownOne and KnownZero may only be accurate for those bits set
903/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
904/// and KnownOne must all be the same.
905bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
906 APInt& KnownZero, APInt& KnownOne,
907 unsigned Depth) {
908 assert(V != 0 && "Null pointer of Value???");
909 assert(Depth <= 6 && "Limit Search Depth");
910 uint32_t BitWidth = DemandedMask.getBitWidth();
911 const IntegerType *VTy = cast<IntegerType>(V->getType());
912 assert(VTy->getBitWidth() == BitWidth &&
913 KnownZero.getBitWidth() == BitWidth &&
914 KnownOne.getBitWidth() == BitWidth &&
915 "Value *V, DemandedMask, KnownZero and KnownOne \
916 must have same BitWidth");
917 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
918 // We know all of the bits for a constant!
919 KnownOne = CI->getValue() & DemandedMask;
920 KnownZero = ~KnownOne & DemandedMask;
921 return false;
922 }
923
924 KnownZero.clear();
925 KnownOne.clear();
926 if (!V->hasOneUse()) { // Other users may use these bits.
927 if (Depth != 0) { // Not at the root.
928 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
929 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
930 return false;
931 }
932 // If this is the root being simplified, allow it to have multiple uses,
933 // just set the DemandedMask to all bits.
934 DemandedMask = APInt::getAllOnesValue(BitWidth);
935 } else if (DemandedMask == 0) { // Not demanding any bits from V.
936 if (V != UndefValue::get(VTy))
937 return UpdateValueUsesWith(V, UndefValue::get(VTy));
938 return false;
939 } else if (Depth == 6) { // Limit search depth.
940 return false;
941 }
942
943 Instruction *I = dyn_cast<Instruction>(V);
944 if (!I) return false; // Only analyze instructions.
945
946 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
947 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
948 switch (I->getOpcode()) {
949 default: break;
950 case Instruction::And:
951 // If either the LHS or the RHS are Zero, the result is zero.
952 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
953 RHSKnownZero, RHSKnownOne, Depth+1))
954 return true;
955 assert((RHSKnownZero & RHSKnownOne) == 0 &&
956 "Bits known to be one AND zero?");
957
958 // If something is known zero on the RHS, the bits aren't demanded on the
959 // LHS.
960 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
961 LHSKnownZero, LHSKnownOne, Depth+1))
962 return true;
963 assert((LHSKnownZero & LHSKnownOne) == 0 &&
964 "Bits known to be one AND zero?");
965
966 // If all of the demanded bits are known 1 on one side, return the other.
967 // These bits cannot contribute to the result of the 'and'.
968 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
969 (DemandedMask & ~LHSKnownZero))
970 return UpdateValueUsesWith(I, I->getOperand(0));
971 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
972 (DemandedMask & ~RHSKnownZero))
973 return UpdateValueUsesWith(I, I->getOperand(1));
974
975 // If all of the demanded bits in the inputs are known zeros, return zero.
976 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
977 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
978
979 // If the RHS is a constant, see if we can simplify it.
980 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
981 return UpdateValueUsesWith(I, I);
982
983 // Output known-1 bits are only known if set in both the LHS & RHS.
984 RHSKnownOne &= LHSKnownOne;
985 // Output known-0 are known to be clear if zero in either the LHS | RHS.
986 RHSKnownZero |= LHSKnownZero;
987 break;
988 case Instruction::Or:
989 // If either the LHS or the RHS are One, the result is One.
990 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
991 RHSKnownZero, RHSKnownOne, Depth+1))
992 return true;
993 assert((RHSKnownZero & RHSKnownOne) == 0 &&
994 "Bits known to be one AND zero?");
995 // If something is known one on the RHS, the bits aren't demanded on the
996 // LHS.
997 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
998 LHSKnownZero, LHSKnownOne, Depth+1))
999 return true;
1000 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1001 "Bits known to be one AND zero?");
1002
1003 // If all of the demanded bits are known zero on one side, return the other.
1004 // These bits cannot contribute to the result of the 'or'.
1005 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1006 (DemandedMask & ~LHSKnownOne))
1007 return UpdateValueUsesWith(I, I->getOperand(0));
1008 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1009 (DemandedMask & ~RHSKnownOne))
1010 return UpdateValueUsesWith(I, I->getOperand(1));
1011
1012 // If all of the potentially set bits on one side are known to be set on
1013 // the other side, just use the 'other' side.
1014 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1015 (DemandedMask & (~RHSKnownZero)))
1016 return UpdateValueUsesWith(I, I->getOperand(0));
1017 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1018 (DemandedMask & (~LHSKnownZero)))
1019 return UpdateValueUsesWith(I, I->getOperand(1));
1020
1021 // If the RHS is a constant, see if we can simplify it.
1022 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1023 return UpdateValueUsesWith(I, I);
1024
1025 // Output known-0 bits are only known if clear in both the LHS & RHS.
1026 RHSKnownZero &= LHSKnownZero;
1027 // Output known-1 are known to be set if set in either the LHS | RHS.
1028 RHSKnownOne |= LHSKnownOne;
1029 break;
1030 case Instruction::Xor: {
1031 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1032 RHSKnownZero, RHSKnownOne, Depth+1))
1033 return true;
1034 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1035 "Bits known to be one AND zero?");
1036 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1037 LHSKnownZero, LHSKnownOne, Depth+1))
1038 return true;
1039 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1040 "Bits known to be one AND zero?");
1041
1042 // If all of the demanded bits are known zero on one side, return the other.
1043 // These bits cannot contribute to the result of the 'xor'.
1044 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1045 return UpdateValueUsesWith(I, I->getOperand(0));
1046 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1047 return UpdateValueUsesWith(I, I->getOperand(1));
1048
1049 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1050 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1051 (RHSKnownOne & LHSKnownOne);
1052 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1053 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1054 (RHSKnownOne & LHSKnownZero);
1055
1056 // If all of the demanded bits are known to be zero on one side or the
1057 // other, turn this into an *inclusive* or.
1058 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1059 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1060 Instruction *Or =
1061 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1062 I->getName());
1063 InsertNewInstBefore(Or, *I);
1064 return UpdateValueUsesWith(I, Or);
1065 }
1066
1067 // If all of the demanded bits on one side are known, and all of the set
1068 // bits on that side are also known to be set on the other side, turn this
1069 // into an AND, as we know the bits will be cleared.
1070 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1071 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1072 // all known
1073 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1074 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1075 Instruction *And =
1076 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1077 InsertNewInstBefore(And, *I);
1078 return UpdateValueUsesWith(I, And);
1079 }
1080 }
1081
1082 // If the RHS is a constant, see if we can simplify it.
1083 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1084 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1085 return UpdateValueUsesWith(I, I);
1086
1087 RHSKnownZero = KnownZeroOut;
1088 RHSKnownOne = KnownOneOut;
1089 break;
1090 }
1091 case Instruction::Select:
1092 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1093 RHSKnownZero, RHSKnownOne, Depth+1))
1094 return true;
1095 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1096 LHSKnownZero, LHSKnownOne, Depth+1))
1097 return true;
1098 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1099 "Bits known to be one AND zero?");
1100 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1101 "Bits known to be one AND zero?");
1102
1103 // If the operands are constants, see if we can simplify them.
1104 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1105 return UpdateValueUsesWith(I, I);
1106 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1107 return UpdateValueUsesWith(I, I);
1108
1109 // Only known if known in both the LHS and RHS.
1110 RHSKnownOne &= LHSKnownOne;
1111 RHSKnownZero &= LHSKnownZero;
1112 break;
1113 case Instruction::Trunc: {
1114 uint32_t truncBf =
1115 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1116 DemandedMask.zext(truncBf);
1117 RHSKnownZero.zext(truncBf);
1118 RHSKnownOne.zext(truncBf);
1119 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1120 RHSKnownZero, RHSKnownOne, Depth+1))
1121 return true;
1122 DemandedMask.trunc(BitWidth);
1123 RHSKnownZero.trunc(BitWidth);
1124 RHSKnownOne.trunc(BitWidth);
1125 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1126 "Bits known to be one AND zero?");
1127 break;
1128 }
1129 case Instruction::BitCast:
1130 if (!I->getOperand(0)->getType()->isInteger())
1131 return false;
1132
1133 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1134 RHSKnownZero, RHSKnownOne, Depth+1))
1135 return true;
1136 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1137 "Bits known to be one AND zero?");
1138 break;
1139 case Instruction::ZExt: {
1140 // Compute the bits in the result that are not present in the input.
1141 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1142 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1143
1144 DemandedMask.trunc(SrcBitWidth);
1145 RHSKnownZero.trunc(SrcBitWidth);
1146 RHSKnownOne.trunc(SrcBitWidth);
1147 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1148 RHSKnownZero, RHSKnownOne, Depth+1))
1149 return true;
1150 DemandedMask.zext(BitWidth);
1151 RHSKnownZero.zext(BitWidth);
1152 RHSKnownOne.zext(BitWidth);
1153 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1154 "Bits known to be one AND zero?");
1155 // The top bits are known to be zero.
1156 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1157 break;
1158 }
1159 case Instruction::SExt: {
1160 // Compute the bits in the result that are not present in the input.
1161 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1162 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1163
1164 APInt InputDemandedBits = DemandedMask &
1165 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1166
1167 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1168 // If any of the sign extended bits are demanded, we know that the sign
1169 // bit is demanded.
1170 if ((NewBits & DemandedMask) != 0)
1171 InputDemandedBits.set(SrcBitWidth-1);
1172
1173 InputDemandedBits.trunc(SrcBitWidth);
1174 RHSKnownZero.trunc(SrcBitWidth);
1175 RHSKnownOne.trunc(SrcBitWidth);
1176 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1177 RHSKnownZero, RHSKnownOne, Depth+1))
1178 return true;
1179 InputDemandedBits.zext(BitWidth);
1180 RHSKnownZero.zext(BitWidth);
1181 RHSKnownOne.zext(BitWidth);
1182 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1183 "Bits known to be one AND zero?");
1184
1185 // If the sign bit of the input is known set or clear, then we know the
1186 // top bits of the result.
1187
1188 // If the input sign bit is known zero, or if the NewBits are not demanded
1189 // convert this into a zero extension.
1190 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1191 {
1192 // Convert to ZExt cast
1193 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1194 return UpdateValueUsesWith(I, NewCast);
1195 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1196 RHSKnownOne |= NewBits;
1197 }
1198 break;
1199 }
1200 case Instruction::Add: {
1201 // Figure out what the input bits are. If the top bits of the and result
1202 // are not demanded, then the add doesn't demand them from its input
1203 // either.
1204 uint32_t NLZ = DemandedMask.countLeadingZeros();
1205
1206 // If there is a constant on the RHS, there are a variety of xformations
1207 // we can do.
1208 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1209 // If null, this should be simplified elsewhere. Some of the xforms here
1210 // won't work if the RHS is zero.
1211 if (RHS->isZero())
1212 break;
1213
1214 // If the top bit of the output is demanded, demand everything from the
1215 // input. Otherwise, we demand all the input bits except NLZ top bits.
1216 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1217
1218 // Find information about known zero/one bits in the input.
1219 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1220 LHSKnownZero, LHSKnownOne, Depth+1))
1221 return true;
1222
1223 // If the RHS of the add has bits set that can't affect the input, reduce
1224 // the constant.
1225 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1226 return UpdateValueUsesWith(I, I);
1227
1228 // Avoid excess work.
1229 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1230 break;
1231
1232 // Turn it into OR if input bits are zero.
1233 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1234 Instruction *Or =
1235 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1236 I->getName());
1237 InsertNewInstBefore(Or, *I);
1238 return UpdateValueUsesWith(I, Or);
1239 }
1240
1241 // We can say something about the output known-zero and known-one bits,
1242 // depending on potential carries from the input constant and the
1243 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1244 // bits set and the RHS constant is 0x01001, then we know we have a known
1245 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1246
1247 // To compute this, we first compute the potential carry bits. These are
1248 // the bits which may be modified. I'm not aware of a better way to do
1249 // this scan.
1250 const APInt& RHSVal = RHS->getValue();
1251 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1252
1253 // Now that we know which bits have carries, compute the known-1/0 sets.
1254
1255 // Bits are known one if they are known zero in one operand and one in the
1256 // other, and there is no input carry.
1257 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1258 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1259
1260 // Bits are known zero if they are known zero in both operands and there
1261 // is no input carry.
1262 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1263 } else {
1264 // If the high-bits of this ADD are not demanded, then it does not demand
1265 // the high bits of its LHS or RHS.
1266 if (DemandedMask[BitWidth-1] == 0) {
1267 // Right fill the mask of bits for this ADD to demand the most
1268 // significant bit and all those below it.
1269 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1270 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1271 LHSKnownZero, LHSKnownOne, Depth+1))
1272 return true;
1273 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1274 LHSKnownZero, LHSKnownOne, Depth+1))
1275 return true;
1276 }
1277 }
1278 break;
1279 }
1280 case Instruction::Sub:
1281 // If the high-bits of this SUB are not demanded, then it does not demand
1282 // the high bits of its LHS or RHS.
1283 if (DemandedMask[BitWidth-1] == 0) {
1284 // Right fill the mask of bits for this SUB to demand the most
1285 // significant bit and all those below it.
1286 uint32_t NLZ = DemandedMask.countLeadingZeros();
1287 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1288 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1289 LHSKnownZero, LHSKnownOne, Depth+1))
1290 return true;
1291 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1292 LHSKnownZero, LHSKnownOne, Depth+1))
1293 return true;
1294 }
1295 break;
1296 case Instruction::Shl:
1297 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1298 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1299 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1300 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1301 RHSKnownZero, RHSKnownOne, Depth+1))
1302 return true;
1303 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1304 "Bits known to be one AND zero?");
1305 RHSKnownZero <<= ShiftAmt;
1306 RHSKnownOne <<= ShiftAmt;
1307 // low bits known zero.
1308 if (ShiftAmt)
1309 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1310 }
1311 break;
1312 case Instruction::LShr:
1313 // For a logical shift right
1314 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1315 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1316
1317 // Unsigned shift right.
1318 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1319 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1320 RHSKnownZero, RHSKnownOne, Depth+1))
1321 return true;
1322 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1323 "Bits known to be one AND zero?");
1324 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1325 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1326 if (ShiftAmt) {
1327 // Compute the new bits that are at the top now.
1328 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1329 RHSKnownZero |= HighBits; // high bits known zero.
1330 }
1331 }
1332 break;
1333 case Instruction::AShr:
1334 // If this is an arithmetic shift right and only the low-bit is set, we can
1335 // always convert this into a logical shr, even if the shift amount is
1336 // variable. The low bit of the shift cannot be an input sign bit unless
1337 // the shift amount is >= the size of the datatype, which is undefined.
1338 if (DemandedMask == 1) {
1339 // Perform the logical shift right.
1340 Value *NewVal = BinaryOperator::createLShr(
1341 I->getOperand(0), I->getOperand(1), I->getName());
1342 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1343 return UpdateValueUsesWith(I, NewVal);
1344 }
1345
1346 // If the sign bit is the only bit demanded by this ashr, then there is no
1347 // need to do it, the shift doesn't change the high bit.
1348 if (DemandedMask.isSignBit())
1349 return UpdateValueUsesWith(I, I->getOperand(0));
1350
1351 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1352 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1353
1354 // Signed shift right.
1355 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1356 // If any of the "high bits" are demanded, we should set the sign bit as
1357 // demanded.
1358 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1359 DemandedMaskIn.set(BitWidth-1);
1360 if (SimplifyDemandedBits(I->getOperand(0),
1361 DemandedMaskIn,
1362 RHSKnownZero, RHSKnownOne, Depth+1))
1363 return true;
1364 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1365 "Bits known to be one AND zero?");
1366 // Compute the new bits that are at the top now.
1367 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1368 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1369 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1370
1371 // Handle the sign bits.
1372 APInt SignBit(APInt::getSignBit(BitWidth));
1373 // Adjust to where it is now in the mask.
1374 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1375
1376 // If the input sign bit is known to be zero, or if none of the top bits
1377 // are demanded, turn this into an unsigned shift right.
1378 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
1379 (HighBits & ~DemandedMask) == HighBits) {
1380 // Perform the logical shift right.
1381 Value *NewVal = BinaryOperator::createLShr(
1382 I->getOperand(0), SA, I->getName());
1383 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1384 return UpdateValueUsesWith(I, NewVal);
1385 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1386 RHSKnownOne |= HighBits;
1387 }
1388 }
1389 break;
1390 }
1391
1392 // If the client is only demanding bits that we know, return the known
1393 // constant.
1394 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1395 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1396 return false;
1397}
1398
1399
1400/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1401/// 64 or fewer elements. DemandedElts contains the set of elements that are
1402/// actually used by the caller. This method analyzes which elements of the
1403/// operand are undef and returns that information in UndefElts.
1404///
1405/// If the information about demanded elements can be used to simplify the
1406/// operation, the operation is simplified, then the resultant value is
1407/// returned. This returns null if no change was made.
1408Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1409 uint64_t &UndefElts,
1410 unsigned Depth) {
1411 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1412 assert(VWidth <= 64 && "Vector too wide to analyze!");
1413 uint64_t EltMask = ~0ULL >> (64-VWidth);
1414 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1415 "Invalid DemandedElts!");
1416
1417 if (isa<UndefValue>(V)) {
1418 // If the entire vector is undefined, just return this info.
1419 UndefElts = EltMask;
1420 return 0;
1421 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1422 UndefElts = EltMask;
1423 return UndefValue::get(V->getType());
1424 }
1425
1426 UndefElts = 0;
1427 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1428 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1429 Constant *Undef = UndefValue::get(EltTy);
1430
1431 std::vector<Constant*> Elts;
1432 for (unsigned i = 0; i != VWidth; ++i)
1433 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1434 Elts.push_back(Undef);
1435 UndefElts |= (1ULL << i);
1436 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1437 Elts.push_back(Undef);
1438 UndefElts |= (1ULL << i);
1439 } else { // Otherwise, defined.
1440 Elts.push_back(CP->getOperand(i));
1441 }
1442
1443 // If we changed the constant, return it.
1444 Constant *NewCP = ConstantVector::get(Elts);
1445 return NewCP != CP ? NewCP : 0;
1446 } else if (isa<ConstantAggregateZero>(V)) {
1447 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1448 // set to undef.
1449 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1450 Constant *Zero = Constant::getNullValue(EltTy);
1451 Constant *Undef = UndefValue::get(EltTy);
1452 std::vector<Constant*> Elts;
1453 for (unsigned i = 0; i != VWidth; ++i)
1454 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1455 UndefElts = DemandedElts ^ EltMask;
1456 return ConstantVector::get(Elts);
1457 }
1458
1459 if (!V->hasOneUse()) { // Other users may use these bits.
1460 if (Depth != 0) { // Not at the root.
1461 // TODO: Just compute the UndefElts information recursively.
1462 return false;
1463 }
1464 return false;
1465 } else if (Depth == 10) { // Limit search depth.
1466 return false;
1467 }
1468
1469 Instruction *I = dyn_cast<Instruction>(V);
1470 if (!I) return false; // Only analyze instructions.
1471
1472 bool MadeChange = false;
1473 uint64_t UndefElts2;
1474 Value *TmpV;
1475 switch (I->getOpcode()) {
1476 default: break;
1477
1478 case Instruction::InsertElement: {
1479 // If this is a variable index, we don't know which element it overwrites.
1480 // demand exactly the same input as we produce.
1481 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1482 if (Idx == 0) {
1483 // Note that we can't propagate undef elt info, because we don't know
1484 // which elt is getting updated.
1485 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1486 UndefElts2, Depth+1);
1487 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1488 break;
1489 }
1490
1491 // If this is inserting an element that isn't demanded, remove this
1492 // insertelement.
1493 unsigned IdxNo = Idx->getZExtValue();
1494 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1495 return AddSoonDeadInstToWorklist(*I, 0);
1496
1497 // Otherwise, the element inserted overwrites whatever was there, so the
1498 // input demanded set is simpler than the output set.
1499 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1500 DemandedElts & ~(1ULL << IdxNo),
1501 UndefElts, Depth+1);
1502 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1503
1504 // The inserted element is defined.
1505 UndefElts |= 1ULL << IdxNo;
1506 break;
1507 }
1508 case Instruction::BitCast: {
1509 // Vector->vector casts only.
1510 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1511 if (!VTy) break;
1512 unsigned InVWidth = VTy->getNumElements();
1513 uint64_t InputDemandedElts = 0;
1514 unsigned Ratio;
1515
1516 if (VWidth == InVWidth) {
1517 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1518 // elements as are demanded of us.
1519 Ratio = 1;
1520 InputDemandedElts = DemandedElts;
1521 } else if (VWidth > InVWidth) {
1522 // Untested so far.
1523 break;
1524
1525 // If there are more elements in the result than there are in the source,
1526 // then an input element is live if any of the corresponding output
1527 // elements are live.
1528 Ratio = VWidth/InVWidth;
1529 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1530 if (DemandedElts & (1ULL << OutIdx))
1531 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1532 }
1533 } else {
1534 // Untested so far.
1535 break;
1536
1537 // If there are more elements in the source than there are in the result,
1538 // then an input element is live if the corresponding output element is
1539 // live.
1540 Ratio = InVWidth/VWidth;
1541 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1542 if (DemandedElts & (1ULL << InIdx/Ratio))
1543 InputDemandedElts |= 1ULL << InIdx;
1544 }
1545
1546 // div/rem demand all inputs, because they don't want divide by zero.
1547 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1548 UndefElts2, Depth+1);
1549 if (TmpV) {
1550 I->setOperand(0, TmpV);
1551 MadeChange = true;
1552 }
1553
1554 UndefElts = UndefElts2;
1555 if (VWidth > InVWidth) {
1556 assert(0 && "Unimp");
1557 // If there are more elements in the result than there are in the source,
1558 // then an output element is undef if the corresponding input element is
1559 // undef.
1560 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1561 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1562 UndefElts |= 1ULL << OutIdx;
1563 } else if (VWidth < InVWidth) {
1564 assert(0 && "Unimp");
1565 // If there are more elements in the source than there are in the result,
1566 // then a result element is undef if all of the corresponding input
1567 // elements are undef.
1568 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1569 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1570 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1571 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1572 }
1573 break;
1574 }
1575 case Instruction::And:
1576 case Instruction::Or:
1577 case Instruction::Xor:
1578 case Instruction::Add:
1579 case Instruction::Sub:
1580 case Instruction::Mul:
1581 // div/rem demand all inputs, because they don't want divide by zero.
1582 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1583 UndefElts, Depth+1);
1584 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1585 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1586 UndefElts2, Depth+1);
1587 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1588
1589 // Output elements are undefined if both are undefined. Consider things
1590 // like undef&0. The result is known zero, not undef.
1591 UndefElts &= UndefElts2;
1592 break;
1593
1594 case Instruction::Call: {
1595 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1596 if (!II) break;
1597 switch (II->getIntrinsicID()) {
1598 default: break;
1599
1600 // Binary vector operations that work column-wise. A dest element is a
1601 // function of the corresponding input elements from the two inputs.
1602 case Intrinsic::x86_sse_sub_ss:
1603 case Intrinsic::x86_sse_mul_ss:
1604 case Intrinsic::x86_sse_min_ss:
1605 case Intrinsic::x86_sse_max_ss:
1606 case Intrinsic::x86_sse2_sub_sd:
1607 case Intrinsic::x86_sse2_mul_sd:
1608 case Intrinsic::x86_sse2_min_sd:
1609 case Intrinsic::x86_sse2_max_sd:
1610 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1611 UndefElts, Depth+1);
1612 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1613 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1614 UndefElts2, Depth+1);
1615 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1616
1617 // If only the low elt is demanded and this is a scalarizable intrinsic,
1618 // scalarize it now.
1619 if (DemandedElts == 1) {
1620 switch (II->getIntrinsicID()) {
1621 default: break;
1622 case Intrinsic::x86_sse_sub_ss:
1623 case Intrinsic::x86_sse_mul_ss:
1624 case Intrinsic::x86_sse2_sub_sd:
1625 case Intrinsic::x86_sse2_mul_sd:
1626 // TODO: Lower MIN/MAX/ABS/etc
1627 Value *LHS = II->getOperand(1);
1628 Value *RHS = II->getOperand(2);
1629 // Extract the element as scalars.
1630 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1631 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1632
1633 switch (II->getIntrinsicID()) {
1634 default: assert(0 && "Case stmts out of sync!");
1635 case Intrinsic::x86_sse_sub_ss:
1636 case Intrinsic::x86_sse2_sub_sd:
1637 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1638 II->getName()), *II);
1639 break;
1640 case Intrinsic::x86_sse_mul_ss:
1641 case Intrinsic::x86_sse2_mul_sd:
1642 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1643 II->getName()), *II);
1644 break;
1645 }
1646
1647 Instruction *New =
1648 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1649 II->getName());
1650 InsertNewInstBefore(New, *II);
1651 AddSoonDeadInstToWorklist(*II, 0);
1652 return New;
1653 }
1654 }
1655
1656 // Output elements are undefined if both are undefined. Consider things
1657 // like undef&0. The result is known zero, not undef.
1658 UndefElts &= UndefElts2;
1659 break;
1660 }
1661 break;
1662 }
1663 }
1664 return MadeChange ? I : 0;
1665}
1666
Nick Lewycky2de09a92007-09-06 02:40:25 +00001667/// @returns true if the specified compare predicate is
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001668/// true when both operands are equal...
Nick Lewycky2de09a92007-09-06 02:40:25 +00001669/// @brief Determine if the icmp Predicate is true when both operands are equal
1670static bool isTrueWhenEqual(ICmpInst::Predicate pred) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001671 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1672 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1673 pred == ICmpInst::ICMP_SLE;
1674}
1675
Nick Lewycky2de09a92007-09-06 02:40:25 +00001676/// @returns true if the specified compare instruction is
1677/// true when both operands are equal...
1678/// @brief Determine if the ICmpInst returns true when both operands are equal
1679static bool isTrueWhenEqual(ICmpInst &ICI) {
1680 return isTrueWhenEqual(ICI.getPredicate());
1681}
1682
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001683/// AssociativeOpt - Perform an optimization on an associative operator. This
1684/// function is designed to check a chain of associative operators for a
1685/// potential to apply a certain optimization. Since the optimization may be
1686/// applicable if the expression was reassociated, this checks the chain, then
1687/// reassociates the expression as necessary to expose the optimization
1688/// opportunity. This makes use of a special Functor, which must define
1689/// 'shouldApply' and 'apply' methods.
1690///
1691template<typename Functor>
1692Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1693 unsigned Opcode = Root.getOpcode();
1694 Value *LHS = Root.getOperand(0);
1695
1696 // Quick check, see if the immediate LHS matches...
1697 if (F.shouldApply(LHS))
1698 return F.apply(Root);
1699
1700 // Otherwise, if the LHS is not of the same opcode as the root, return.
1701 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1702 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1703 // Should we apply this transform to the RHS?
1704 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1705
1706 // If not to the RHS, check to see if we should apply to the LHS...
1707 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1708 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1709 ShouldApply = true;
1710 }
1711
1712 // If the functor wants to apply the optimization to the RHS of LHSI,
1713 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1714 if (ShouldApply) {
1715 BasicBlock *BB = Root.getParent();
1716
1717 // Now all of the instructions are in the current basic block, go ahead
1718 // and perform the reassociation.
1719 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1720
1721 // First move the selected RHS to the LHS of the root...
1722 Root.setOperand(0, LHSI->getOperand(1));
1723
1724 // Make what used to be the LHS of the root be the user of the root...
1725 Value *ExtraOperand = TmpLHSI->getOperand(1);
1726 if (&Root == TmpLHSI) {
1727 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1728 return 0;
1729 }
1730 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1731 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1732 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1733 BasicBlock::iterator ARI = &Root; ++ARI;
1734 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1735 ARI = Root;
1736
1737 // Now propagate the ExtraOperand down the chain of instructions until we
1738 // get to LHSI.
1739 while (TmpLHSI != LHSI) {
1740 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1741 // Move the instruction to immediately before the chain we are
1742 // constructing to avoid breaking dominance properties.
1743 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1744 BB->getInstList().insert(ARI, NextLHSI);
1745 ARI = NextLHSI;
1746
1747 Value *NextOp = NextLHSI->getOperand(1);
1748 NextLHSI->setOperand(1, ExtraOperand);
1749 TmpLHSI = NextLHSI;
1750 ExtraOperand = NextOp;
1751 }
1752
1753 // Now that the instructions are reassociated, have the functor perform
1754 // the transformation...
1755 return F.apply(Root);
1756 }
1757
1758 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1759 }
1760 return 0;
1761}
1762
1763
1764// AddRHS - Implements: X + X --> X << 1
1765struct AddRHS {
1766 Value *RHS;
1767 AddRHS(Value *rhs) : RHS(rhs) {}
1768 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1769 Instruction *apply(BinaryOperator &Add) const {
1770 return BinaryOperator::createShl(Add.getOperand(0),
1771 ConstantInt::get(Add.getType(), 1));
1772 }
1773};
1774
1775// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1776// iff C1&C2 == 0
1777struct AddMaskingAnd {
1778 Constant *C2;
1779 AddMaskingAnd(Constant *c) : C2(c) {}
1780 bool shouldApply(Value *LHS) const {
1781 ConstantInt *C1;
1782 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1783 ConstantExpr::getAnd(C1, C2)->isNullValue();
1784 }
1785 Instruction *apply(BinaryOperator &Add) const {
1786 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1787 }
1788};
1789
1790static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1791 InstCombiner *IC) {
1792 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1793 if (Constant *SOC = dyn_cast<Constant>(SO))
1794 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1795
1796 return IC->InsertNewInstBefore(CastInst::create(
1797 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1798 }
1799
1800 // Figure out if the constant is the left or the right argument.
1801 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1802 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1803
1804 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1805 if (ConstIsRHS)
1806 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1807 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1808 }
1809
1810 Value *Op0 = SO, *Op1 = ConstOperand;
1811 if (!ConstIsRHS)
1812 std::swap(Op0, Op1);
1813 Instruction *New;
1814 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1815 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1816 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1817 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1818 SO->getName()+".cmp");
1819 else {
1820 assert(0 && "Unknown binary instruction type!");
1821 abort();
1822 }
1823 return IC->InsertNewInstBefore(New, I);
1824}
1825
1826// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1827// constant as the other operand, try to fold the binary operator into the
1828// select arguments. This also works for Cast instructions, which obviously do
1829// not have a second operand.
1830static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1831 InstCombiner *IC) {
1832 // Don't modify shared select instructions
1833 if (!SI->hasOneUse()) return 0;
1834 Value *TV = SI->getOperand(1);
1835 Value *FV = SI->getOperand(2);
1836
1837 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1838 // Bool selects with constant operands can be folded to logical ops.
1839 if (SI->getType() == Type::Int1Ty) return 0;
1840
1841 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1842 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1843
1844 return new SelectInst(SI->getCondition(), SelectTrueVal,
1845 SelectFalseVal);
1846 }
1847 return 0;
1848}
1849
1850
1851/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1852/// node as operand #0, see if we can fold the instruction into the PHI (which
1853/// is only possible if all operands to the PHI are constants).
1854Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1855 PHINode *PN = cast<PHINode>(I.getOperand(0));
1856 unsigned NumPHIValues = PN->getNumIncomingValues();
1857 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1858
1859 // Check to see if all of the operands of the PHI are constants. If there is
1860 // one non-constant value, remember the BB it is. If there is more than one
1861 // or if *it* is a PHI, bail out.
1862 BasicBlock *NonConstBB = 0;
1863 for (unsigned i = 0; i != NumPHIValues; ++i)
1864 if (!isa<Constant>(PN->getIncomingValue(i))) {
1865 if (NonConstBB) return 0; // More than one non-const value.
1866 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1867 NonConstBB = PN->getIncomingBlock(i);
1868
1869 // If the incoming non-constant value is in I's block, we have an infinite
1870 // loop.
1871 if (NonConstBB == I.getParent())
1872 return 0;
1873 }
1874
1875 // If there is exactly one non-constant value, we can insert a copy of the
1876 // operation in that block. However, if this is a critical edge, we would be
1877 // inserting the computation one some other paths (e.g. inside a loop). Only
1878 // do this if the pred block is unconditionally branching into the phi block.
1879 if (NonConstBB) {
1880 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1881 if (!BI || !BI->isUnconditional()) return 0;
1882 }
1883
1884 // Okay, we can do the transformation: create the new PHI node.
1885 PHINode *NewPN = new PHINode(I.getType(), "");
1886 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1887 InsertNewInstBefore(NewPN, *PN);
1888 NewPN->takeName(PN);
1889
1890 // Next, add all of the operands to the PHI.
1891 if (I.getNumOperands() == 2) {
1892 Constant *C = cast<Constant>(I.getOperand(1));
1893 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00001894 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001895 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1896 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1897 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1898 else
1899 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1900 } else {
1901 assert(PN->getIncomingBlock(i) == NonConstBB);
1902 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1903 InV = BinaryOperator::create(BO->getOpcode(),
1904 PN->getIncomingValue(i), C, "phitmp",
1905 NonConstBB->getTerminator());
1906 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1907 InV = CmpInst::create(CI->getOpcode(),
1908 CI->getPredicate(),
1909 PN->getIncomingValue(i), C, "phitmp",
1910 NonConstBB->getTerminator());
1911 else
1912 assert(0 && "Unknown binop!");
1913
1914 AddToWorkList(cast<Instruction>(InV));
1915 }
1916 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1917 }
1918 } else {
1919 CastInst *CI = cast<CastInst>(&I);
1920 const Type *RetTy = CI->getType();
1921 for (unsigned i = 0; i != NumPHIValues; ++i) {
1922 Value *InV;
1923 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1924 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1925 } else {
1926 assert(PN->getIncomingBlock(i) == NonConstBB);
1927 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1928 I.getType(), "phitmp",
1929 NonConstBB->getTerminator());
1930 AddToWorkList(cast<Instruction>(InV));
1931 }
1932 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1933 }
1934 }
1935 return ReplaceInstUsesWith(I, NewPN);
1936}
1937
1938Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1939 bool Changed = SimplifyCommutative(I);
1940 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1941
1942 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1943 // X + undef -> undef
1944 if (isa<UndefValue>(RHS))
1945 return ReplaceInstUsesWith(I, RHS);
1946
1947 // X + 0 --> X
1948 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1949 if (RHSC->isNullValue())
1950 return ReplaceInstUsesWith(I, LHS);
1951 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen2fc20782007-09-14 22:26:36 +00001952 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1953 (I.getType())->getValueAPF()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001954 return ReplaceInstUsesWith(I, LHS);
1955 }
1956
1957 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1958 // X + (signbit) --> X ^ signbit
1959 const APInt& Val = CI->getValue();
1960 uint32_t BitWidth = Val.getBitWidth();
1961 if (Val == APInt::getSignBit(BitWidth))
1962 return BinaryOperator::createXor(LHS, RHS);
1963
1964 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1965 // (X & 254)+1 -> (X&254)|1
1966 if (!isa<VectorType>(I.getType())) {
1967 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1968 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1969 KnownZero, KnownOne))
1970 return &I;
1971 }
1972 }
1973
1974 if (isa<PHINode>(LHS))
1975 if (Instruction *NV = FoldOpIntoPhi(I))
1976 return NV;
1977
1978 ConstantInt *XorRHS = 0;
1979 Value *XorLHS = 0;
1980 if (isa<ConstantInt>(RHSC) &&
1981 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1982 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
1983 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
1984
1985 uint32_t Size = TySizeBits / 2;
1986 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1987 APInt CFF80Val(-C0080Val);
1988 do {
1989 if (TySizeBits > Size) {
1990 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1991 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
1992 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
1993 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
1994 // This is a sign extend if the top bits are known zero.
1995 if (!MaskedValueIsZero(XorLHS,
1996 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
1997 Size = 0; // Not a sign ext, but can't be any others either.
1998 break;
1999 }
2000 }
2001 Size >>= 1;
2002 C0080Val = APIntOps::lshr(C0080Val, Size);
2003 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2004 } while (Size >= 1);
2005
2006 // FIXME: This shouldn't be necessary. When the backends can handle types
2007 // with funny bit widths then this whole cascade of if statements should
2008 // be removed. It is just here to get the size of the "middle" type back
2009 // up to something that the back ends can handle.
2010 const Type *MiddleType = 0;
2011 switch (Size) {
2012 default: break;
2013 case 32: MiddleType = Type::Int32Ty; break;
2014 case 16: MiddleType = Type::Int16Ty; break;
2015 case 8: MiddleType = Type::Int8Ty; break;
2016 }
2017 if (MiddleType) {
2018 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2019 InsertNewInstBefore(NewTrunc, I);
2020 return new SExtInst(NewTrunc, I.getType(), I.getName());
2021 }
2022 }
2023 }
2024
2025 // X + X --> X << 1
2026 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
2027 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2028
2029 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2030 if (RHSI->getOpcode() == Instruction::Sub)
2031 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2032 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2033 }
2034 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2035 if (LHSI->getOpcode() == Instruction::Sub)
2036 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2037 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2038 }
2039 }
2040
2041 // -A + B --> B - A
2042 if (Value *V = dyn_castNegVal(LHS))
2043 return BinaryOperator::createSub(RHS, V);
2044
2045 // A + -B --> A - B
2046 if (!isa<Constant>(RHS))
2047 if (Value *V = dyn_castNegVal(RHS))
2048 return BinaryOperator::createSub(LHS, V);
2049
2050
2051 ConstantInt *C2;
2052 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2053 if (X == RHS) // X*C + X --> X * (C+1)
2054 return BinaryOperator::createMul(RHS, AddOne(C2));
2055
2056 // X*C1 + X*C2 --> X * (C1+C2)
2057 ConstantInt *C1;
2058 if (X == dyn_castFoldableMul(RHS, C1))
2059 return BinaryOperator::createMul(X, Add(C1, C2));
2060 }
2061
2062 // X + X*C --> X * (C+1)
2063 if (dyn_castFoldableMul(RHS, C2) == LHS)
2064 return BinaryOperator::createMul(LHS, AddOne(C2));
2065
2066 // X + ~X --> -1 since ~X = -X-1
2067 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2068 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2069
2070
2071 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2072 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2073 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2074 return R;
2075
2076 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2077 Value *X = 0;
2078 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2079 return BinaryOperator::createSub(SubOne(CRHS), X);
2080
2081 // (X & FF00) + xx00 -> (X+xx00) & FF00
2082 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2083 Constant *Anded = And(CRHS, C2);
2084 if (Anded == CRHS) {
2085 // See if all bits from the first bit set in the Add RHS up are included
2086 // in the mask. First, get the rightmost bit.
2087 const APInt& AddRHSV = CRHS->getValue();
2088
2089 // Form a mask of all bits from the lowest bit added through the top.
2090 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2091
2092 // See if the and mask includes all of these bits.
2093 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2094
2095 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2096 // Okay, the xform is safe. Insert the new add pronto.
2097 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2098 LHS->getName()), I);
2099 return BinaryOperator::createAnd(NewAdd, C2);
2100 }
2101 }
2102 }
2103
2104 // Try to fold constant add into select arguments.
2105 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2106 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2107 return R;
2108 }
2109
2110 // add (cast *A to intptrtype) B ->
2111 // cast (GEP (cast *A to sbyte*) B) ->
2112 // intptrtype
2113 {
2114 CastInst *CI = dyn_cast<CastInst>(LHS);
2115 Value *Other = RHS;
2116 if (!CI) {
2117 CI = dyn_cast<CastInst>(RHS);
2118 Other = LHS;
2119 }
2120 if (CI && CI->getType()->isSized() &&
2121 (CI->getType()->getPrimitiveSizeInBits() ==
2122 TD->getIntPtrType()->getPrimitiveSizeInBits())
2123 && isa<PointerType>(CI->getOperand(0)->getType())) {
2124 Value *I2 = InsertCastBefore(Instruction::BitCast, CI->getOperand(0),
2125 PointerType::get(Type::Int8Ty), I);
2126 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
2127 return new PtrToIntInst(I2, CI->getType());
2128 }
2129 }
2130
2131 return Changed ? &I : 0;
2132}
2133
2134// isSignBit - Return true if the value represented by the constant only has the
2135// highest order bit set.
2136static bool isSignBit(ConstantInt *CI) {
2137 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
2138 return CI->getValue() == APInt::getSignBit(NumBits);
2139}
2140
2141Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2142 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2143
2144 if (Op0 == Op1) // sub X, X -> 0
2145 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2146
2147 // If this is a 'B = x-(-A)', change to B = x+A...
2148 if (Value *V = dyn_castNegVal(Op1))
2149 return BinaryOperator::createAdd(Op0, V);
2150
2151 if (isa<UndefValue>(Op0))
2152 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2153 if (isa<UndefValue>(Op1))
2154 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2155
2156 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2157 // Replace (-1 - A) with (~A)...
2158 if (C->isAllOnesValue())
2159 return BinaryOperator::createNot(Op1);
2160
2161 // C - ~X == X + (1+C)
2162 Value *X = 0;
2163 if (match(Op1, m_Not(m_Value(X))))
2164 return BinaryOperator::createAdd(X, AddOne(C));
2165
2166 // -(X >>u 31) -> (X >>s 31)
2167 // -(X >>s 31) -> (X >>u 31)
2168 if (C->isZero()) {
2169 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
2170 if (SI->getOpcode() == Instruction::LShr) {
2171 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2172 // Check to see if we are shifting out everything but the sign bit.
2173 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2174 SI->getType()->getPrimitiveSizeInBits()-1) {
2175 // Ok, the transformation is safe. Insert AShr.
2176 return BinaryOperator::create(Instruction::AShr,
2177 SI->getOperand(0), CU, SI->getName());
2178 }
2179 }
2180 }
2181 else if (SI->getOpcode() == Instruction::AShr) {
2182 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2183 // Check to see if we are shifting out everything but the sign bit.
2184 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2185 SI->getType()->getPrimitiveSizeInBits()-1) {
2186 // Ok, the transformation is safe. Insert LShr.
2187 return BinaryOperator::createLShr(
2188 SI->getOperand(0), CU, SI->getName());
2189 }
2190 }
2191 }
2192 }
2193
2194 // Try to fold constant sub into select arguments.
2195 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2196 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2197 return R;
2198
2199 if (isa<PHINode>(Op0))
2200 if (Instruction *NV = FoldOpIntoPhi(I))
2201 return NV;
2202 }
2203
2204 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2205 if (Op1I->getOpcode() == Instruction::Add &&
2206 !Op0->getType()->isFPOrFPVector()) {
2207 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2208 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
2209 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2210 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2211 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2212 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2213 // C1-(X+C2) --> (C1-C2)-X
2214 return BinaryOperator::createSub(Subtract(CI1, CI2),
2215 Op1I->getOperand(0));
2216 }
2217 }
2218
2219 if (Op1I->hasOneUse()) {
2220 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2221 // is not used by anyone else...
2222 //
2223 if (Op1I->getOpcode() == Instruction::Sub &&
2224 !Op1I->getType()->isFPOrFPVector()) {
2225 // Swap the two operands of the subexpr...
2226 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2227 Op1I->setOperand(0, IIOp1);
2228 Op1I->setOperand(1, IIOp0);
2229
2230 // Create the new top level add instruction...
2231 return BinaryOperator::createAdd(Op0, Op1);
2232 }
2233
2234 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2235 //
2236 if (Op1I->getOpcode() == Instruction::And &&
2237 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2238 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2239
2240 Value *NewNot =
2241 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2242 return BinaryOperator::createAnd(Op0, NewNot);
2243 }
2244
2245 // 0 - (X sdiv C) -> (X sdiv -C)
2246 if (Op1I->getOpcode() == Instruction::SDiv)
2247 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2248 if (CSI->isZero())
2249 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2250 return BinaryOperator::createSDiv(Op1I->getOperand(0),
2251 ConstantExpr::getNeg(DivRHS));
2252
2253 // X - X*C --> X * (1-C)
2254 ConstantInt *C2 = 0;
2255 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2256 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2257 return BinaryOperator::createMul(Op0, CP1);
2258 }
2259 }
2260 }
2261
2262 if (!Op0->getType()->isFPOrFPVector())
2263 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2264 if (Op0I->getOpcode() == Instruction::Add) {
2265 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2266 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2267 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2268 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2269 } else if (Op0I->getOpcode() == Instruction::Sub) {
2270 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2271 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2272 }
2273
2274 ConstantInt *C1;
2275 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2276 if (X == Op1) // X*C - X --> X * (C-1)
2277 return BinaryOperator::createMul(Op1, SubOne(C1));
2278
2279 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2280 if (X == dyn_castFoldableMul(Op1, C2))
2281 return BinaryOperator::createMul(Op1, Subtract(C1, C2));
2282 }
2283 return 0;
2284}
2285
2286/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2287/// comparison only checks the sign bit. If it only checks the sign bit, set
2288/// TrueIfSigned if the result of the comparison is true when the input value is
2289/// signed.
2290static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2291 bool &TrueIfSigned) {
2292 switch (pred) {
2293 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2294 TrueIfSigned = true;
2295 return RHS->isZero();
2296 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2297 TrueIfSigned = true;
2298 return RHS->isAllOnesValue();
2299 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2300 TrueIfSigned = false;
2301 return RHS->isAllOnesValue();
2302 case ICmpInst::ICMP_UGT:
2303 // True if LHS u> RHS and RHS == high-bit-mask - 1
2304 TrueIfSigned = true;
2305 return RHS->getValue() ==
2306 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2307 case ICmpInst::ICMP_UGE:
2308 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2309 TrueIfSigned = true;
2310 return RHS->getValue() ==
2311 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
2312 default:
2313 return false;
2314 }
2315}
2316
2317Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2318 bool Changed = SimplifyCommutative(I);
2319 Value *Op0 = I.getOperand(0);
2320
2321 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2322 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2323
2324 // Simplify mul instructions with a constant RHS...
2325 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2326 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2327
2328 // ((X << C1)*C2) == (X * (C2 << C1))
2329 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2330 if (SI->getOpcode() == Instruction::Shl)
2331 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2332 return BinaryOperator::createMul(SI->getOperand(0),
2333 ConstantExpr::getShl(CI, ShOp));
2334
2335 if (CI->isZero())
2336 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2337 if (CI->equalsInt(1)) // X * 1 == X
2338 return ReplaceInstUsesWith(I, Op0);
2339 if (CI->isAllOnesValue()) // X * -1 == 0 - X
2340 return BinaryOperator::createNeg(Op0, I.getName());
2341
2342 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2343 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
2344 return BinaryOperator::createShl(Op0,
2345 ConstantInt::get(Op0->getType(), Val.logBase2()));
2346 }
2347 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2348 if (Op1F->isNullValue())
2349 return ReplaceInstUsesWith(I, Op1);
2350
2351 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2352 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen2fc20782007-09-14 22:26:36 +00002353 // We need a better interface for long double here.
2354 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2355 if (Op1F->isExactlyValue(1.0))
2356 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002357 }
2358
2359 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2360 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2361 isa<ConstantInt>(Op0I->getOperand(1))) {
2362 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2363 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2364 Op1, "tmp");
2365 InsertNewInstBefore(Add, I);
2366 Value *C1C2 = ConstantExpr::getMul(Op1,
2367 cast<Constant>(Op0I->getOperand(1)));
2368 return BinaryOperator::createAdd(Add, C1C2);
2369
2370 }
2371
2372 // Try to fold constant mul into select arguments.
2373 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2374 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2375 return R;
2376
2377 if (isa<PHINode>(Op0))
2378 if (Instruction *NV = FoldOpIntoPhi(I))
2379 return NV;
2380 }
2381
2382 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2383 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2384 return BinaryOperator::createMul(Op0v, Op1v);
2385
2386 // If one of the operands of the multiply is a cast from a boolean value, then
2387 // we know the bool is either zero or one, so this is a 'masking' multiply.
2388 // See if we can simplify things based on how the boolean was originally
2389 // formed.
2390 CastInst *BoolCast = 0;
2391 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2392 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2393 BoolCast = CI;
2394 if (!BoolCast)
2395 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2396 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2397 BoolCast = CI;
2398 if (BoolCast) {
2399 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2400 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2401 const Type *SCOpTy = SCIOp0->getType();
2402 bool TIS = false;
2403
2404 // If the icmp is true iff the sign bit of X is set, then convert this
2405 // multiply into a shift/and combination.
2406 if (isa<ConstantInt>(SCIOp1) &&
2407 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2408 TIS) {
2409 // Shift the X value right to turn it into "all signbits".
2410 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2411 SCOpTy->getPrimitiveSizeInBits()-1);
2412 Value *V =
2413 InsertNewInstBefore(
2414 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
2415 BoolCast->getOperand(0)->getName()+
2416 ".mask"), I);
2417
2418 // If the multiply type is not the same as the source type, sign extend
2419 // or truncate to the multiply type.
2420 if (I.getType() != V->getType()) {
2421 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2422 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2423 Instruction::CastOps opcode =
2424 (SrcBits == DstBits ? Instruction::BitCast :
2425 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2426 V = InsertCastBefore(opcode, V, I.getType(), I);
2427 }
2428
2429 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2430 return BinaryOperator::createAnd(V, OtherOp);
2431 }
2432 }
2433 }
2434
2435 return Changed ? &I : 0;
2436}
2437
2438/// This function implements the transforms on div instructions that work
2439/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2440/// used by the visitors to those instructions.
2441/// @brief Transforms common to all three div instructions
2442Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2443 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2444
2445 // undef / X -> 0
2446 if (isa<UndefValue>(Op0))
2447 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2448
2449 // X / undef -> undef
2450 if (isa<UndefValue>(Op1))
2451 return ReplaceInstUsesWith(I, Op1);
2452
2453 // Handle cases involving: div X, (select Cond, Y, Z)
2454 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2455 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
2456 // same basic block, then we replace the select with Y, and the condition
2457 // of the select with false (if the cond value is in the same BB). If the
2458 // select has uses other than the div, this allows them to be simplified
2459 // also. Note that div X, Y is just as good as div X, 0 (undef)
2460 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2461 if (ST->isNullValue()) {
2462 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2463 if (CondI && CondI->getParent() == I.getParent())
2464 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2465 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2466 I.setOperand(1, SI->getOperand(2));
2467 else
2468 UpdateValueUsesWith(SI, SI->getOperand(2));
2469 return &I;
2470 }
2471
2472 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2473 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2474 if (ST->isNullValue()) {
2475 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2476 if (CondI && CondI->getParent() == I.getParent())
2477 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2478 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2479 I.setOperand(1, SI->getOperand(1));
2480 else
2481 UpdateValueUsesWith(SI, SI->getOperand(1));
2482 return &I;
2483 }
2484 }
2485
2486 return 0;
2487}
2488
2489/// This function implements the transforms common to both integer division
2490/// instructions (udiv and sdiv). It is called by the visitors to those integer
2491/// division instructions.
2492/// @brief Common integer divide transforms
2493Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2494 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2495
2496 if (Instruction *Common = commonDivTransforms(I))
2497 return Common;
2498
2499 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2500 // div X, 1 == X
2501 if (RHS->equalsInt(1))
2502 return ReplaceInstUsesWith(I, Op0);
2503
2504 // (X / C1) / C2 -> X / (C1*C2)
2505 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2506 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2507 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2508 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2509 Multiply(RHS, LHSRHS));
2510 }
2511
2512 if (!RHS->isZero()) { // avoid X udiv 0
2513 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2514 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2515 return R;
2516 if (isa<PHINode>(Op0))
2517 if (Instruction *NV = FoldOpIntoPhi(I))
2518 return NV;
2519 }
2520 }
2521
2522 // 0 / X == 0, we don't need to preserve faults!
2523 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2524 if (LHS->equalsInt(0))
2525 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2526
2527 return 0;
2528}
2529
2530Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2531 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2532
2533 // Handle the integer div common cases
2534 if (Instruction *Common = commonIDivTransforms(I))
2535 return Common;
2536
2537 // X udiv C^2 -> X >> C
2538 // Check to see if this is an unsigned division with an exact power of 2,
2539 // if so, convert to a right shift.
2540 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2541 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
2542 return BinaryOperator::createLShr(Op0,
2543 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2544 }
2545
2546 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2547 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2548 if (RHSI->getOpcode() == Instruction::Shl &&
2549 isa<ConstantInt>(RHSI->getOperand(0))) {
2550 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2551 if (C1.isPowerOf2()) {
2552 Value *N = RHSI->getOperand(1);
2553 const Type *NTy = N->getType();
2554 if (uint32_t C2 = C1.logBase2()) {
2555 Constant *C2V = ConstantInt::get(NTy, C2);
2556 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
2557 }
2558 return BinaryOperator::createLShr(Op0, N);
2559 }
2560 }
2561 }
2562
2563 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2564 // where C1&C2 are powers of two.
2565 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2566 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2567 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2568 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2569 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2570 // Compute the shift amounts
2571 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2572 // Construct the "on true" case of the select
2573 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2574 Instruction *TSI = BinaryOperator::createLShr(
2575 Op0, TC, SI->getName()+".t");
2576 TSI = InsertNewInstBefore(TSI, I);
2577
2578 // Construct the "on false" case of the select
2579 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2580 Instruction *FSI = BinaryOperator::createLShr(
2581 Op0, FC, SI->getName()+".f");
2582 FSI = InsertNewInstBefore(FSI, I);
2583
2584 // construct the select instruction and return it.
2585 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2586 }
2587 }
2588 return 0;
2589}
2590
2591Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2592 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2593
2594 // Handle the integer div common cases
2595 if (Instruction *Common = commonIDivTransforms(I))
2596 return Common;
2597
2598 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2599 // sdiv X, -1 == -X
2600 if (RHS->isAllOnesValue())
2601 return BinaryOperator::createNeg(Op0);
2602
2603 // -X/C -> X/-C
2604 if (Value *LHSNeg = dyn_castNegVal(Op0))
2605 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2606 }
2607
2608 // If the sign bits of both operands are zero (i.e. we can prove they are
2609 // unsigned inputs), turn this into a udiv.
2610 if (I.getType()->isInteger()) {
2611 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2612 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2613 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2614 }
2615 }
2616
2617 return 0;
2618}
2619
2620Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2621 return commonDivTransforms(I);
2622}
2623
2624/// GetFactor - If we can prove that the specified value is at least a multiple
2625/// of some factor, return that factor.
2626static Constant *GetFactor(Value *V) {
2627 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2628 return CI;
2629
2630 // Unless we can be tricky, we know this is a multiple of 1.
2631 Constant *Result = ConstantInt::get(V->getType(), 1);
2632
2633 Instruction *I = dyn_cast<Instruction>(V);
2634 if (!I) return Result;
2635
2636 if (I->getOpcode() == Instruction::Mul) {
2637 // Handle multiplies by a constant, etc.
2638 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2639 GetFactor(I->getOperand(1)));
2640 } else if (I->getOpcode() == Instruction::Shl) {
2641 // (X<<C) -> X * (1 << C)
2642 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2643 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2644 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2645 }
2646 } else if (I->getOpcode() == Instruction::And) {
2647 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2648 // X & 0xFFF0 is known to be a multiple of 16.
2649 uint32_t Zeros = RHS->getValue().countTrailingZeros();
2650 if (Zeros != V->getType()->getPrimitiveSizeInBits())
2651 return ConstantExpr::getShl(Result,
2652 ConstantInt::get(Result->getType(), Zeros));
2653 }
2654 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2655 // Only handle int->int casts.
2656 if (!CI->isIntegerCast())
2657 return Result;
2658 Value *Op = CI->getOperand(0);
2659 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
2660 }
2661 return Result;
2662}
2663
2664/// This function implements the transforms on rem instructions that work
2665/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2666/// is used by the visitors to those instructions.
2667/// @brief Transforms common to all three rem instructions
2668Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2669 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2670
2671 // 0 % X == 0, we don't need to preserve faults!
2672 if (Constant *LHS = dyn_cast<Constant>(Op0))
2673 if (LHS->isNullValue())
2674 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2675
2676 if (isa<UndefValue>(Op0)) // undef % X -> 0
2677 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2678 if (isa<UndefValue>(Op1))
2679 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2680
2681 // Handle cases involving: rem X, (select Cond, Y, Z)
2682 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2683 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2684 // the same basic block, then we replace the select with Y, and the
2685 // condition of the select with false (if the cond value is in the same
2686 // BB). If the select has uses other than the div, this allows them to be
2687 // simplified also.
2688 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2689 if (ST->isNullValue()) {
2690 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2691 if (CondI && CondI->getParent() == I.getParent())
2692 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2693 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2694 I.setOperand(1, SI->getOperand(2));
2695 else
2696 UpdateValueUsesWith(SI, SI->getOperand(2));
2697 return &I;
2698 }
2699 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2700 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2701 if (ST->isNullValue()) {
2702 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2703 if (CondI && CondI->getParent() == I.getParent())
2704 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2705 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2706 I.setOperand(1, SI->getOperand(1));
2707 else
2708 UpdateValueUsesWith(SI, SI->getOperand(1));
2709 return &I;
2710 }
2711 }
2712
2713 return 0;
2714}
2715
2716/// This function implements the transforms common to both integer remainder
2717/// instructions (urem and srem). It is called by the visitors to those integer
2718/// remainder instructions.
2719/// @brief Common integer remainder transforms
2720Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2721 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2722
2723 if (Instruction *common = commonRemTransforms(I))
2724 return common;
2725
2726 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2727 // X % 0 == undef, we don't need to preserve faults!
2728 if (RHS->equalsInt(0))
2729 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2730
2731 if (RHS->equalsInt(1)) // X % 1 == 0
2732 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2733
2734 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2735 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2736 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2737 return R;
2738 } else if (isa<PHINode>(Op0I)) {
2739 if (Instruction *NV = FoldOpIntoPhi(I))
2740 return NV;
2741 }
2742 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2743 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
2744 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2745 }
2746 }
2747
2748 return 0;
2749}
2750
2751Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2752 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2753
2754 if (Instruction *common = commonIRemTransforms(I))
2755 return common;
2756
2757 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2758 // X urem C^2 -> X and C
2759 // Check to see if this is an unsigned remainder with an exact power of 2,
2760 // if so, convert to a bitwise and.
2761 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2762 if (C->getValue().isPowerOf2())
2763 return BinaryOperator::createAnd(Op0, SubOne(C));
2764 }
2765
2766 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2767 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2768 if (RHSI->getOpcode() == Instruction::Shl &&
2769 isa<ConstantInt>(RHSI->getOperand(0))) {
2770 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
2771 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2772 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2773 "tmp"), I);
2774 return BinaryOperator::createAnd(Op0, Add);
2775 }
2776 }
2777 }
2778
2779 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2780 // where C1&C2 are powers of two.
2781 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2782 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2783 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2784 // STO == 0 and SFO == 0 handled above.
2785 if ((STO->getValue().isPowerOf2()) &&
2786 (SFO->getValue().isPowerOf2())) {
2787 Value *TrueAnd = InsertNewInstBefore(
2788 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2789 Value *FalseAnd = InsertNewInstBefore(
2790 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2791 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2792 }
2793 }
2794 }
2795
2796 return 0;
2797}
2798
2799Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2800 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2801
2802 if (Instruction *common = commonIRemTransforms(I))
2803 return common;
2804
2805 if (Value *RHSNeg = dyn_castNegVal(Op1))
2806 if (!isa<ConstantInt>(RHSNeg) ||
2807 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
2808 // X % -Y -> X % Y
2809 AddUsesToWorkList(I);
2810 I.setOperand(1, RHSNeg);
2811 return &I;
2812 }
2813
2814 // If the top bits of both operands are zero (i.e. we can prove they are
2815 // unsigned inputs), turn this into a urem.
2816 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2817 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2818 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2819 return BinaryOperator::createURem(Op0, Op1, I.getName());
2820 }
2821
2822 return 0;
2823}
2824
2825Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2826 return commonRemTransforms(I);
2827}
2828
2829// isMaxValueMinusOne - return true if this is Max-1
2830static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2831 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2832 if (!isSigned)
2833 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
2834 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
2835}
2836
2837// isMinValuePlusOne - return true if this is Min+1
2838static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2839 if (!isSigned)
2840 return C->getValue() == 1; // unsigned
2841
2842 // Calculate 1111111111000000000000
2843 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2844 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
2845}
2846
2847// isOneBitSet - Return true if there is exactly one bit set in the specified
2848// constant.
2849static bool isOneBitSet(const ConstantInt *CI) {
2850 return CI->getValue().isPowerOf2();
2851}
2852
2853// isHighOnes - Return true if the constant is of the form 1+0+.
2854// This is the same as lowones(~X).
2855static bool isHighOnes(const ConstantInt *CI) {
2856 return (~CI->getValue() + 1).isPowerOf2();
2857}
2858
2859/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
2860/// are carefully arranged to allow folding of expressions such as:
2861///
2862/// (A < B) | (A > B) --> (A != B)
2863///
2864/// Note that this is only valid if the first and second predicates have the
2865/// same sign. Is illegal to do: (A u< B) | (A s> B)
2866///
2867/// Three bits are used to represent the condition, as follows:
2868/// 0 A > B
2869/// 1 A == B
2870/// 2 A < B
2871///
2872/// <=> Value Definition
2873/// 000 0 Always false
2874/// 001 1 A > B
2875/// 010 2 A == B
2876/// 011 3 A >= B
2877/// 100 4 A < B
2878/// 101 5 A != B
2879/// 110 6 A <= B
2880/// 111 7 Always true
2881///
2882static unsigned getICmpCode(const ICmpInst *ICI) {
2883 switch (ICI->getPredicate()) {
2884 // False -> 0
2885 case ICmpInst::ICMP_UGT: return 1; // 001
2886 case ICmpInst::ICMP_SGT: return 1; // 001
2887 case ICmpInst::ICMP_EQ: return 2; // 010
2888 case ICmpInst::ICMP_UGE: return 3; // 011
2889 case ICmpInst::ICMP_SGE: return 3; // 011
2890 case ICmpInst::ICMP_ULT: return 4; // 100
2891 case ICmpInst::ICMP_SLT: return 4; // 100
2892 case ICmpInst::ICMP_NE: return 5; // 101
2893 case ICmpInst::ICMP_ULE: return 6; // 110
2894 case ICmpInst::ICMP_SLE: return 6; // 110
2895 // True -> 7
2896 default:
2897 assert(0 && "Invalid ICmp predicate!");
2898 return 0;
2899 }
2900}
2901
2902/// getICmpValue - This is the complement of getICmpCode, which turns an
2903/// opcode and two operands into either a constant true or false, or a brand
2904/// new /// ICmp instruction. The sign is passed in to determine which kind
2905/// of predicate to use in new icmp instructions.
2906static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2907 switch (code) {
2908 default: assert(0 && "Illegal ICmp code!");
2909 case 0: return ConstantInt::getFalse();
2910 case 1:
2911 if (sign)
2912 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2913 else
2914 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2915 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
2916 case 3:
2917 if (sign)
2918 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2919 else
2920 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2921 case 4:
2922 if (sign)
2923 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2924 else
2925 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2926 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
2927 case 6:
2928 if (sign)
2929 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2930 else
2931 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
2932 case 7: return ConstantInt::getTrue();
2933 }
2934}
2935
2936static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2937 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2938 (ICmpInst::isSignedPredicate(p1) &&
2939 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2940 (ICmpInst::isSignedPredicate(p2) &&
2941 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2942}
2943
2944namespace {
2945// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2946struct FoldICmpLogical {
2947 InstCombiner &IC;
2948 Value *LHS, *RHS;
2949 ICmpInst::Predicate pred;
2950 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2951 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
2952 pred(ICI->getPredicate()) {}
2953 bool shouldApply(Value *V) const {
2954 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
2955 if (PredicatesFoldable(pred, ICI->getPredicate()))
2956 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
2957 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
2958 return false;
2959 }
2960 Instruction *apply(Instruction &Log) const {
2961 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
2962 if (ICI->getOperand(0) != LHS) {
2963 assert(ICI->getOperand(1) == LHS);
2964 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
2965 }
2966
2967 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
2968 unsigned LHSCode = getICmpCode(ICI);
2969 unsigned RHSCode = getICmpCode(RHSICI);
2970 unsigned Code;
2971 switch (Log.getOpcode()) {
2972 case Instruction::And: Code = LHSCode & RHSCode; break;
2973 case Instruction::Or: Code = LHSCode | RHSCode; break;
2974 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
2975 default: assert(0 && "Illegal logical opcode!"); return 0;
2976 }
2977
2978 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
2979 ICmpInst::isSignedPredicate(ICI->getPredicate());
2980
2981 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
2982 if (Instruction *I = dyn_cast<Instruction>(RV))
2983 return I;
2984 // Otherwise, it's a constant boolean value...
2985 return IC.ReplaceInstUsesWith(Log, RV);
2986 }
2987};
2988} // end anonymous namespace
2989
2990// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
2991// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
2992// guaranteed to be a binary operator.
2993Instruction *InstCombiner::OptAndOp(Instruction *Op,
2994 ConstantInt *OpRHS,
2995 ConstantInt *AndRHS,
2996 BinaryOperator &TheAnd) {
2997 Value *X = Op->getOperand(0);
2998 Constant *Together = 0;
2999 if (!Op->isShift())
3000 Together = And(AndRHS, OpRHS);
3001
3002 switch (Op->getOpcode()) {
3003 case Instruction::Xor:
3004 if (Op->hasOneUse()) {
3005 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3006 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
3007 InsertNewInstBefore(And, TheAnd);
3008 And->takeName(Op);
3009 return BinaryOperator::createXor(And, Together);
3010 }
3011 break;
3012 case Instruction::Or:
3013 if (Together == AndRHS) // (X | C) & C --> C
3014 return ReplaceInstUsesWith(TheAnd, AndRHS);
3015
3016 if (Op->hasOneUse() && Together != OpRHS) {
3017 // (X | C1) & C2 --> (X | (C1&C2)) & C2
3018 Instruction *Or = BinaryOperator::createOr(X, Together);
3019 InsertNewInstBefore(Or, TheAnd);
3020 Or->takeName(Op);
3021 return BinaryOperator::createAnd(Or, AndRHS);
3022 }
3023 break;
3024 case Instruction::Add:
3025 if (Op->hasOneUse()) {
3026 // Adding a one to a single bit bit-field should be turned into an XOR
3027 // of the bit. First thing to check is to see if this AND is with a
3028 // single bit constant.
3029 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3030
3031 // If there is only one bit set...
3032 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3033 // Ok, at this point, we know that we are masking the result of the
3034 // ADD down to exactly one bit. If the constant we are adding has
3035 // no bits set below this bit, then we can eliminate the ADD.
3036 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3037
3038 // Check to see if any bits below the one bit set in AndRHSV are set.
3039 if ((AddRHS & (AndRHSV-1)) == 0) {
3040 // If not, the only thing that can effect the output of the AND is
3041 // the bit specified by AndRHSV. If that bit is set, the effect of
3042 // the XOR is to toggle the bit. If it is clear, then the ADD has
3043 // no effect.
3044 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3045 TheAnd.setOperand(0, X);
3046 return &TheAnd;
3047 } else {
3048 // Pull the XOR out of the AND.
3049 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
3050 InsertNewInstBefore(NewAnd, TheAnd);
3051 NewAnd->takeName(Op);
3052 return BinaryOperator::createXor(NewAnd, AndRHS);
3053 }
3054 }
3055 }
3056 }
3057 break;
3058
3059 case Instruction::Shl: {
3060 // We know that the AND will not produce any of the bits shifted in, so if
3061 // the anded constant includes them, clear them now!
3062 //
3063 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3064 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3065 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3066 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3067
3068 if (CI->getValue() == ShlMask) {
3069 // Masking out bits that the shift already masks
3070 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3071 } else if (CI != AndRHS) { // Reducing bits set in and.
3072 TheAnd.setOperand(1, CI);
3073 return &TheAnd;
3074 }
3075 break;
3076 }
3077 case Instruction::LShr:
3078 {
3079 // We know that the AND will not produce any of the bits shifted in, so if
3080 // the anded constant includes them, clear them now! This only applies to
3081 // unsigned shifts, because a signed shr may bring in set bits!
3082 //
3083 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3084 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3085 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3086 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3087
3088 if (CI->getValue() == ShrMask) {
3089 // Masking out bits that the shift already masks.
3090 return ReplaceInstUsesWith(TheAnd, Op);
3091 } else if (CI != AndRHS) {
3092 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3093 return &TheAnd;
3094 }
3095 break;
3096 }
3097 case Instruction::AShr:
3098 // Signed shr.
3099 // See if this is shifting in some sign extension, then masking it out
3100 // with an and.
3101 if (Op->hasOneUse()) {
3102 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3103 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3104 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3105 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3106 if (C == AndRHS) { // Masking out bits shifted in.
3107 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3108 // Make the argument unsigned.
3109 Value *ShVal = Op->getOperand(0);
3110 ShVal = InsertNewInstBefore(
3111 BinaryOperator::createLShr(ShVal, OpRHS,
3112 Op->getName()), TheAnd);
3113 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
3114 }
3115 }
3116 break;
3117 }
3118 return 0;
3119}
3120
3121
3122/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3123/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3124/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3125/// whether to treat the V, Lo and HI as signed or not. IB is the location to
3126/// insert new instructions.
3127Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3128 bool isSigned, bool Inside,
3129 Instruction &IB) {
3130 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3131 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3132 "Lo is not <= Hi in range emission code!");
3133
3134 if (Inside) {
3135 if (Lo == Hi) // Trivially false.
3136 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3137
3138 // V >= Min && V < Hi --> V < Hi
3139 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3140 ICmpInst::Predicate pred = (isSigned ?
3141 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3142 return new ICmpInst(pred, V, Hi);
3143 }
3144
3145 // Emit V-Lo <u Hi-Lo
3146 Constant *NegLo = ConstantExpr::getNeg(Lo);
3147 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3148 InsertNewInstBefore(Add, IB);
3149 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3150 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3151 }
3152
3153 if (Lo == Hi) // Trivially true.
3154 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3155
3156 // V < Min || V >= Hi -> V > Hi-1
3157 Hi = SubOne(cast<ConstantInt>(Hi));
3158 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3159 ICmpInst::Predicate pred = (isSigned ?
3160 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3161 return new ICmpInst(pred, V, Hi);
3162 }
3163
3164 // Emit V-Lo >u Hi-1-Lo
3165 // Note that Hi has already had one subtracted from it, above.
3166 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3167 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3168 InsertNewInstBefore(Add, IB);
3169 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3170 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3171}
3172
3173// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3174// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3175// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3176// not, since all 1s are not contiguous.
3177static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3178 const APInt& V = Val->getValue();
3179 uint32_t BitWidth = Val->getType()->getBitWidth();
3180 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3181
3182 // look for the first zero bit after the run of ones
3183 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3184 // look for the first non-zero bit
3185 ME = V.getActiveBits();
3186 return true;
3187}
3188
3189/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3190/// where isSub determines whether the operator is a sub. If we can fold one of
3191/// the following xforms:
3192///
3193/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3194/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3195/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3196///
3197/// return (A +/- B).
3198///
3199Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3200 ConstantInt *Mask, bool isSub,
3201 Instruction &I) {
3202 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3203 if (!LHSI || LHSI->getNumOperands() != 2 ||
3204 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3205
3206 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3207
3208 switch (LHSI->getOpcode()) {
3209 default: return 0;
3210 case Instruction::And:
3211 if (And(N, Mask) == Mask) {
3212 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3213 if ((Mask->getValue().countLeadingZeros() +
3214 Mask->getValue().countPopulation()) ==
3215 Mask->getValue().getBitWidth())
3216 break;
3217
3218 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3219 // part, we don't need any explicit masks to take them out of A. If that
3220 // is all N is, ignore it.
3221 uint32_t MB = 0, ME = 0;
3222 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3223 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3224 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3225 if (MaskedValueIsZero(RHS, Mask))
3226 break;
3227 }
3228 }
3229 return 0;
3230 case Instruction::Or:
3231 case Instruction::Xor:
3232 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3233 if ((Mask->getValue().countLeadingZeros() +
3234 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3235 && And(N, Mask)->isZero())
3236 break;
3237 return 0;
3238 }
3239
3240 Instruction *New;
3241 if (isSub)
3242 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3243 else
3244 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3245 return InsertNewInstBefore(New, I);
3246}
3247
3248Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3249 bool Changed = SimplifyCommutative(I);
3250 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3251
3252 if (isa<UndefValue>(Op1)) // X & undef -> 0
3253 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3254
3255 // and X, X = X
3256 if (Op0 == Op1)
3257 return ReplaceInstUsesWith(I, Op1);
3258
3259 // See if we can simplify any instructions used by the instruction whose sole
3260 // purpose is to compute bits we don't care about.
3261 if (!isa<VectorType>(I.getType())) {
3262 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3263 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3264 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3265 KnownZero, KnownOne))
3266 return &I;
3267 } else {
3268 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3269 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
3270 return ReplaceInstUsesWith(I, I.getOperand(0));
3271 } else if (isa<ConstantAggregateZero>(Op1)) {
3272 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
3273 }
3274 }
3275
3276 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3277 const APInt& AndRHSMask = AndRHS->getValue();
3278 APInt NotAndRHS(~AndRHSMask);
3279
3280 // Optimize a variety of ((val OP C1) & C2) combinations...
3281 if (isa<BinaryOperator>(Op0)) {
3282 Instruction *Op0I = cast<Instruction>(Op0);
3283 Value *Op0LHS = Op0I->getOperand(0);
3284 Value *Op0RHS = Op0I->getOperand(1);
3285 switch (Op0I->getOpcode()) {
3286 case Instruction::Xor:
3287 case Instruction::Or:
3288 // If the mask is only needed on one incoming arm, push it up.
3289 if (Op0I->hasOneUse()) {
3290 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3291 // Not masking anything out for the LHS, move to RHS.
3292 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3293 Op0RHS->getName()+".masked");
3294 InsertNewInstBefore(NewRHS, I);
3295 return BinaryOperator::create(
3296 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3297 }
3298 if (!isa<Constant>(Op0RHS) &&
3299 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3300 // Not masking anything out for the RHS, move to LHS.
3301 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3302 Op0LHS->getName()+".masked");
3303 InsertNewInstBefore(NewLHS, I);
3304 return BinaryOperator::create(
3305 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3306 }
3307 }
3308
3309 break;
3310 case Instruction::Add:
3311 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3312 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3313 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3314 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3315 return BinaryOperator::createAnd(V, AndRHS);
3316 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3317 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
3318 break;
3319
3320 case Instruction::Sub:
3321 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3322 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3323 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3324 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3325 return BinaryOperator::createAnd(V, AndRHS);
3326 break;
3327 }
3328
3329 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3330 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3331 return Res;
3332 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3333 // If this is an integer truncation or change from signed-to-unsigned, and
3334 // if the source is an and/or with immediate, transform it. This
3335 // frequently occurs for bitfield accesses.
3336 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3337 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3338 CastOp->getNumOperands() == 2)
3339 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
3340 if (CastOp->getOpcode() == Instruction::And) {
3341 // Change: and (cast (and X, C1) to T), C2
3342 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3343 // This will fold the two constants together, which may allow
3344 // other simplifications.
3345 Instruction *NewCast = CastInst::createTruncOrBitCast(
3346 CastOp->getOperand(0), I.getType(),
3347 CastOp->getName()+".shrunk");
3348 NewCast = InsertNewInstBefore(NewCast, I);
3349 // trunc_or_bitcast(C1)&C2
3350 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3351 C3 = ConstantExpr::getAnd(C3, AndRHS);
3352 return BinaryOperator::createAnd(NewCast, C3);
3353 } else if (CastOp->getOpcode() == Instruction::Or) {
3354 // Change: and (cast (or X, C1) to T), C2
3355 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3356 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3357 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3358 return ReplaceInstUsesWith(I, AndRHS);
3359 }
3360 }
3361 }
3362
3363 // Try to fold constant and into select arguments.
3364 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3365 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3366 return R;
3367 if (isa<PHINode>(Op0))
3368 if (Instruction *NV = FoldOpIntoPhi(I))
3369 return NV;
3370 }
3371
3372 Value *Op0NotVal = dyn_castNotVal(Op0);
3373 Value *Op1NotVal = dyn_castNotVal(Op1);
3374
3375 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3376 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3377
3378 // (~A & ~B) == (~(A | B)) - De Morgan's Law
3379 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3380 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3381 I.getName()+".demorgan");
3382 InsertNewInstBefore(Or, I);
3383 return BinaryOperator::createNot(Or);
3384 }
3385
3386 {
3387 Value *A = 0, *B = 0, *C = 0, *D = 0;
3388 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3389 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3390 return ReplaceInstUsesWith(I, Op1);
3391
3392 // (A|B) & ~(A&B) -> A^B
3393 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3394 if ((A == C && B == D) || (A == D && B == C))
3395 return BinaryOperator::createXor(A, B);
3396 }
3397 }
3398
3399 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3400 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3401 return ReplaceInstUsesWith(I, Op0);
3402
3403 // ~(A&B) & (A|B) -> A^B
3404 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3405 if ((A == C && B == D) || (A == D && B == C))
3406 return BinaryOperator::createXor(A, B);
3407 }
3408 }
3409
3410 if (Op0->hasOneUse() &&
3411 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3412 if (A == Op1) { // (A^B)&A -> A&(A^B)
3413 I.swapOperands(); // Simplify below
3414 std::swap(Op0, Op1);
3415 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3416 cast<BinaryOperator>(Op0)->swapOperands();
3417 I.swapOperands(); // Simplify below
3418 std::swap(Op0, Op1);
3419 }
3420 }
3421 if (Op1->hasOneUse() &&
3422 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3423 if (B == Op0) { // B&(A^B) -> B&(B^A)
3424 cast<BinaryOperator>(Op1)->swapOperands();
3425 std::swap(A, B);
3426 }
3427 if (A == Op0) { // A&(A^B) -> A & ~B
3428 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3429 InsertNewInstBefore(NotB, I);
3430 return BinaryOperator::createAnd(A, NotB);
3431 }
3432 }
3433 }
3434
3435 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3436 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3437 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3438 return R;
3439
3440 Value *LHSVal, *RHSVal;
3441 ConstantInt *LHSCst, *RHSCst;
3442 ICmpInst::Predicate LHSCC, RHSCC;
3443 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3444 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3445 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3446 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3447 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3448 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3449 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3450 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE) {
3451 // Ensure that the larger constant is on the RHS.
3452 ICmpInst::Predicate GT = ICmpInst::isSignedPredicate(LHSCC) ?
3453 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
3454 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3455 ICmpInst *LHS = cast<ICmpInst>(Op0);
3456 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3457 std::swap(LHS, RHS);
3458 std::swap(LHSCst, RHSCst);
3459 std::swap(LHSCC, RHSCC);
3460 }
3461
3462 // At this point, we know we have have two icmp instructions
3463 // comparing a value against two constants and and'ing the result
3464 // together. Because of the above check, we know that we only have
3465 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3466 // (from the FoldICmpLogical check above), that the two constants
3467 // are not equal and that the larger constant is on the RHS
3468 assert(LHSCst != RHSCst && "Compares not folded above?");
3469
3470 switch (LHSCC) {
3471 default: assert(0 && "Unknown integer condition code!");
3472 case ICmpInst::ICMP_EQ:
3473 switch (RHSCC) {
3474 default: assert(0 && "Unknown integer condition code!");
3475 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3476 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3477 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3478 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3479 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3480 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3481 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3482 return ReplaceInstUsesWith(I, LHS);
3483 }
3484 case ICmpInst::ICMP_NE:
3485 switch (RHSCC) {
3486 default: assert(0 && "Unknown integer condition code!");
3487 case ICmpInst::ICMP_ULT:
3488 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3489 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3490 break; // (X != 13 & X u< 15) -> no change
3491 case ICmpInst::ICMP_SLT:
3492 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3493 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3494 break; // (X != 13 & X s< 15) -> no change
3495 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3496 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3497 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3498 return ReplaceInstUsesWith(I, RHS);
3499 case ICmpInst::ICMP_NE:
3500 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3501 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3502 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3503 LHSVal->getName()+".off");
3504 InsertNewInstBefore(Add, I);
3505 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3506 ConstantInt::get(Add->getType(), 1));
3507 }
3508 break; // (X != 13 & X != 15) -> no change
3509 }
3510 break;
3511 case ICmpInst::ICMP_ULT:
3512 switch (RHSCC) {
3513 default: assert(0 && "Unknown integer condition code!");
3514 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3515 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3516 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3517 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3518 break;
3519 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3520 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3521 return ReplaceInstUsesWith(I, LHS);
3522 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3523 break;
3524 }
3525 break;
3526 case ICmpInst::ICMP_SLT:
3527 switch (RHSCC) {
3528 default: assert(0 && "Unknown integer condition code!");
3529 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3530 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3531 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3532 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3533 break;
3534 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3535 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3536 return ReplaceInstUsesWith(I, LHS);
3537 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3538 break;
3539 }
3540 break;
3541 case ICmpInst::ICMP_UGT:
3542 switch (RHSCC) {
3543 default: assert(0 && "Unknown integer condition code!");
3544 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3545 return ReplaceInstUsesWith(I, LHS);
3546 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3547 return ReplaceInstUsesWith(I, RHS);
3548 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3549 break;
3550 case ICmpInst::ICMP_NE:
3551 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3552 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3553 break; // (X u> 13 & X != 15) -> no change
3554 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3555 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3556 true, I);
3557 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3558 break;
3559 }
3560 break;
3561 case ICmpInst::ICMP_SGT:
3562 switch (RHSCC) {
3563 default: assert(0 && "Unknown integer condition code!");
3564 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X s> 13
3565 return ReplaceInstUsesWith(I, LHS);
3566 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3567 return ReplaceInstUsesWith(I, RHS);
3568 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3569 break;
3570 case ICmpInst::ICMP_NE:
3571 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3572 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3573 break; // (X s> 13 & X != 15) -> no change
3574 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3575 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3576 true, I);
3577 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3578 break;
3579 }
3580 break;
3581 }
3582 }
3583 }
3584
3585 // fold (and (cast A), (cast B)) -> (cast (and A, B))
3586 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3587 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3588 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3589 const Type *SrcTy = Op0C->getOperand(0)->getType();
3590 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3591 // Only do this if the casts both really cause code to be generated.
3592 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3593 I.getType(), TD) &&
3594 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3595 I.getType(), TD)) {
3596 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3597 Op1C->getOperand(0),
3598 I.getName());
3599 InsertNewInstBefore(NewOp, I);
3600 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3601 }
3602 }
3603
3604 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
3605 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3606 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3607 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
3608 SI0->getOperand(1) == SI1->getOperand(1) &&
3609 (SI0->hasOneUse() || SI1->hasOneUse())) {
3610 Instruction *NewOp =
3611 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3612 SI1->getOperand(0),
3613 SI0->getName()), I);
3614 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3615 SI1->getOperand(1));
3616 }
3617 }
3618
3619 return Changed ? &I : 0;
3620}
3621
3622/// CollectBSwapParts - Look to see if the specified value defines a single byte
3623/// in the result. If it does, and if the specified byte hasn't been filled in
3624/// yet, fill it in and return false.
3625static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3626 Instruction *I = dyn_cast<Instruction>(V);
3627 if (I == 0) return true;
3628
3629 // If this is an or instruction, it is an inner node of the bswap.
3630 if (I->getOpcode() == Instruction::Or)
3631 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3632 CollectBSwapParts(I->getOperand(1), ByteValues);
3633
3634 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
3635 // If this is a shift by a constant int, and it is "24", then its operand
3636 // defines a byte. We only handle unsigned types here.
3637 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3638 // Not shifting the entire input by N-1 bytes?
3639 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
3640 8*(ByteValues.size()-1))
3641 return true;
3642
3643 unsigned DestNo;
3644 if (I->getOpcode() == Instruction::Shl) {
3645 // X << 24 defines the top byte with the lowest of the input bytes.
3646 DestNo = ByteValues.size()-1;
3647 } else {
3648 // X >>u 24 defines the low byte with the highest of the input bytes.
3649 DestNo = 0;
3650 }
3651
3652 // If the destination byte value is already defined, the values are or'd
3653 // together, which isn't a bswap (unless it's an or of the same bits).
3654 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3655 return true;
3656 ByteValues[DestNo] = I->getOperand(0);
3657 return false;
3658 }
3659
3660 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3661 // don't have this.
3662 Value *Shift = 0, *ShiftLHS = 0;
3663 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3664 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3665 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3666 return true;
3667 Instruction *SI = cast<Instruction>(Shift);
3668
3669 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3670 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3671 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
3672 return true;
3673
3674 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3675 unsigned DestByte;
3676 if (AndAmt->getValue().getActiveBits() > 64)
3677 return true;
3678 uint64_t AndAmtVal = AndAmt->getZExtValue();
3679 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3680 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
3681 break;
3682 // Unknown mask for bswap.
3683 if (DestByte == ByteValues.size()) return true;
3684
3685 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3686 unsigned SrcByte;
3687 if (SI->getOpcode() == Instruction::Shl)
3688 SrcByte = DestByte - ShiftBytes;
3689 else
3690 SrcByte = DestByte + ShiftBytes;
3691
3692 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3693 if (SrcByte != ByteValues.size()-DestByte-1)
3694 return true;
3695
3696 // If the destination byte value is already defined, the values are or'd
3697 // together, which isn't a bswap (unless it's an or of the same bits).
3698 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3699 return true;
3700 ByteValues[DestByte] = SI->getOperand(0);
3701 return false;
3702}
3703
3704/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3705/// If so, insert the new bswap intrinsic and return it.
3706Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3707 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3708 if (!ITy || ITy->getBitWidth() % 16)
3709 return 0; // Can only bswap pairs of bytes. Can't do vectors.
3710
3711 /// ByteValues - For each byte of the result, we keep track of which value
3712 /// defines each byte.
3713 SmallVector<Value*, 8> ByteValues;
3714 ByteValues.resize(ITy->getBitWidth()/8);
3715
3716 // Try to find all the pieces corresponding to the bswap.
3717 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3718 CollectBSwapParts(I.getOperand(1), ByteValues))
3719 return 0;
3720
3721 // Check to see if all of the bytes come from the same value.
3722 Value *V = ByteValues[0];
3723 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3724
3725 // Check to make sure that all of the bytes come from the same value.
3726 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3727 if (ByteValues[i] != V)
3728 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00003729 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003730 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00003731 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003732 return new CallInst(F, V);
3733}
3734
3735
3736Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3737 bool Changed = SimplifyCommutative(I);
3738 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3739
3740 if (isa<UndefValue>(Op1)) // X | undef -> -1
3741 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3742
3743 // or X, X = X
3744 if (Op0 == Op1)
3745 return ReplaceInstUsesWith(I, Op0);
3746
3747 // See if we can simplify any instructions used by the instruction whose sole
3748 // purpose is to compute bits we don't care about.
3749 if (!isa<VectorType>(I.getType())) {
3750 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3751 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3752 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3753 KnownZero, KnownOne))
3754 return &I;
3755 } else if (isa<ConstantAggregateZero>(Op1)) {
3756 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
3757 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3758 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
3759 return ReplaceInstUsesWith(I, I.getOperand(1));
3760 }
3761
3762
3763
3764 // or X, -1 == -1
3765 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3766 ConstantInt *C1 = 0; Value *X = 0;
3767 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3768 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3769 Instruction *Or = BinaryOperator::createOr(X, RHS);
3770 InsertNewInstBefore(Or, I);
3771 Or->takeName(Op0);
3772 return BinaryOperator::createAnd(Or,
3773 ConstantInt::get(RHS->getValue() | C1->getValue()));
3774 }
3775
3776 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3777 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3778 Instruction *Or = BinaryOperator::createOr(X, RHS);
3779 InsertNewInstBefore(Or, I);
3780 Or->takeName(Op0);
3781 return BinaryOperator::createXor(Or,
3782 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
3783 }
3784
3785 // Try to fold constant and into select arguments.
3786 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3787 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3788 return R;
3789 if (isa<PHINode>(Op0))
3790 if (Instruction *NV = FoldOpIntoPhi(I))
3791 return NV;
3792 }
3793
3794 Value *A = 0, *B = 0;
3795 ConstantInt *C1 = 0, *C2 = 0;
3796
3797 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3798 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3799 return ReplaceInstUsesWith(I, Op1);
3800 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3801 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3802 return ReplaceInstUsesWith(I, Op0);
3803
3804 // (A | B) | C and A | (B | C) -> bswap if possible.
3805 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
3806 if (match(Op0, m_Or(m_Value(), m_Value())) ||
3807 match(Op1, m_Or(m_Value(), m_Value())) ||
3808 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3809 match(Op1, m_Shift(m_Value(), m_Value())))) {
3810 if (Instruction *BSwap = MatchBSwap(I))
3811 return BSwap;
3812 }
3813
3814 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3815 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3816 MaskedValueIsZero(Op1, C1->getValue())) {
3817 Instruction *NOr = BinaryOperator::createOr(A, Op1);
3818 InsertNewInstBefore(NOr, I);
3819 NOr->takeName(Op0);
3820 return BinaryOperator::createXor(NOr, C1);
3821 }
3822
3823 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3824 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3825 MaskedValueIsZero(Op0, C1->getValue())) {
3826 Instruction *NOr = BinaryOperator::createOr(A, Op0);
3827 InsertNewInstBefore(NOr, I);
3828 NOr->takeName(Op0);
3829 return BinaryOperator::createXor(NOr, C1);
3830 }
3831
3832 // (A & C)|(B & D)
3833 Value *C = 0, *D = 0;
3834 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3835 match(Op1, m_And(m_Value(B), m_Value(D)))) {
3836 Value *V1 = 0, *V2 = 0, *V3 = 0;
3837 C1 = dyn_cast<ConstantInt>(C);
3838 C2 = dyn_cast<ConstantInt>(D);
3839 if (C1 && C2) { // (A & C1)|(B & C2)
3840 // If we have: ((V + N) & C1) | (V & C2)
3841 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3842 // replace with V+N.
3843 if (C1->getValue() == ~C2->getValue()) {
3844 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
3845 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3846 // Add commutes, try both ways.
3847 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
3848 return ReplaceInstUsesWith(I, A);
3849 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
3850 return ReplaceInstUsesWith(I, A);
3851 }
3852 // Or commutes, try both ways.
3853 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
3854 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3855 // Add commutes, try both ways.
3856 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
3857 return ReplaceInstUsesWith(I, B);
3858 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
3859 return ReplaceInstUsesWith(I, B);
3860 }
3861 }
3862 V1 = 0; V2 = 0; V3 = 0;
3863 }
3864
3865 // Check to see if we have any common things being and'ed. If so, find the
3866 // terms for V1 & (V2|V3).
3867 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
3868 if (A == B) // (A & C)|(A & D) == A & (C|D)
3869 V1 = A, V2 = C, V3 = D;
3870 else if (A == D) // (A & C)|(B & A) == A & (B|C)
3871 V1 = A, V2 = B, V3 = C;
3872 else if (C == B) // (A & C)|(C & D) == C & (A|D)
3873 V1 = C, V2 = A, V3 = D;
3874 else if (C == D) // (A & C)|(B & C) == C & (A|B)
3875 V1 = C, V2 = A, V3 = B;
3876
3877 if (V1) {
3878 Value *Or =
3879 InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
3880 return BinaryOperator::createAnd(V1, Or);
3881 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003882 }
3883 }
3884
3885 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
3886 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3887 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3888 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
3889 SI0->getOperand(1) == SI1->getOperand(1) &&
3890 (SI0->hasOneUse() || SI1->hasOneUse())) {
3891 Instruction *NewOp =
3892 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3893 SI1->getOperand(0),
3894 SI0->getName()), I);
3895 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3896 SI1->getOperand(1));
3897 }
3898 }
3899
3900 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3901 if (A == Op1) // ~A | A == -1
3902 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3903 } else {
3904 A = 0;
3905 }
3906 // Note, A is still live here!
3907 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3908 if (Op0 == B)
3909 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3910
3911 // (~A | ~B) == (~(A & B)) - De Morgan's Law
3912 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3913 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3914 I.getName()+".demorgan"), I);
3915 return BinaryOperator::createNot(And);
3916 }
3917 }
3918
3919 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3920 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3921 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3922 return R;
3923
3924 Value *LHSVal, *RHSVal;
3925 ConstantInt *LHSCst, *RHSCst;
3926 ICmpInst::Predicate LHSCC, RHSCC;
3927 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3928 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3929 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
3930 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
3931 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3932 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3933 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
3934 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3935 // We can't fold (ugt x, C) | (sgt x, C2).
3936 PredicatesFoldable(LHSCC, RHSCC)) {
3937 // Ensure that the larger constant is on the RHS.
3938 ICmpInst *LHS = cast<ICmpInst>(Op0);
3939 bool NeedsSwap;
3940 if (ICmpInst::isSignedPredicate(LHSCC))
3941 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
3942 else
3943 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3944
3945 if (NeedsSwap) {
3946 std::swap(LHS, RHS);
3947 std::swap(LHSCst, RHSCst);
3948 std::swap(LHSCC, RHSCC);
3949 }
3950
3951 // At this point, we know we have have two icmp instructions
3952 // comparing a value against two constants and or'ing the result
3953 // together. Because of the above check, we know that we only have
3954 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
3955 // FoldICmpLogical check above), that the two constants are not
3956 // equal.
3957 assert(LHSCst != RHSCst && "Compares not folded above?");
3958
3959 switch (LHSCC) {
3960 default: assert(0 && "Unknown integer condition code!");
3961 case ICmpInst::ICMP_EQ:
3962 switch (RHSCC) {
3963 default: assert(0 && "Unknown integer condition code!");
3964 case ICmpInst::ICMP_EQ:
3965 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
3966 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3967 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3968 LHSVal->getName()+".off");
3969 InsertNewInstBefore(Add, I);
3970 AddCST = Subtract(AddOne(RHSCst), LHSCst);
3971 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
3972 }
3973 break; // (X == 13 | X == 15) -> no change
3974 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
3975 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
3976 break;
3977 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
3978 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
3979 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
3980 return ReplaceInstUsesWith(I, RHS);
3981 }
3982 break;
3983 case ICmpInst::ICMP_NE:
3984 switch (RHSCC) {
3985 default: assert(0 && "Unknown integer condition code!");
3986 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
3987 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
3988 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
3989 return ReplaceInstUsesWith(I, LHS);
3990 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
3991 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
3992 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
3993 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
3994 }
3995 break;
3996 case ICmpInst::ICMP_ULT:
3997 switch (RHSCC) {
3998 default: assert(0 && "Unknown integer condition code!");
3999 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4000 break;
4001 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
4002 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4003 false, I);
4004 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4005 break;
4006 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4007 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4008 return ReplaceInstUsesWith(I, RHS);
4009 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4010 break;
4011 }
4012 break;
4013 case ICmpInst::ICMP_SLT:
4014 switch (RHSCC) {
4015 default: assert(0 && "Unknown integer condition code!");
4016 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4017 break;
4018 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
4019 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4020 false, I);
4021 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4022 break;
4023 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4024 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4025 return ReplaceInstUsesWith(I, RHS);
4026 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4027 break;
4028 }
4029 break;
4030 case ICmpInst::ICMP_UGT:
4031 switch (RHSCC) {
4032 default: assert(0 && "Unknown integer condition code!");
4033 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4034 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4035 return ReplaceInstUsesWith(I, LHS);
4036 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4037 break;
4038 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4039 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4040 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4041 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4042 break;
4043 }
4044 break;
4045 case ICmpInst::ICMP_SGT:
4046 switch (RHSCC) {
4047 default: assert(0 && "Unknown integer condition code!");
4048 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4049 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4050 return ReplaceInstUsesWith(I, LHS);
4051 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4052 break;
4053 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4054 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4055 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4056 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4057 break;
4058 }
4059 break;
4060 }
4061 }
4062 }
4063
4064 // fold (or (cast A), (cast B)) -> (cast (or A, B))
4065 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4066 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4067 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4068 const Type *SrcTy = Op0C->getOperand(0)->getType();
4069 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4070 // Only do this if the casts both really cause code to be generated.
4071 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4072 I.getType(), TD) &&
4073 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4074 I.getType(), TD)) {
4075 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4076 Op1C->getOperand(0),
4077 I.getName());
4078 InsertNewInstBefore(NewOp, I);
4079 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4080 }
4081 }
4082
4083
4084 return Changed ? &I : 0;
4085}
4086
4087// XorSelf - Implements: X ^ X --> 0
4088struct XorSelf {
4089 Value *RHS;
4090 XorSelf(Value *rhs) : RHS(rhs) {}
4091 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4092 Instruction *apply(BinaryOperator &Xor) const {
4093 return &Xor;
4094 }
4095};
4096
4097
4098Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4099 bool Changed = SimplifyCommutative(I);
4100 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4101
4102 if (isa<UndefValue>(Op1))
4103 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4104
4105 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4106 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00004107 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004108 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4109 }
4110
4111 // See if we can simplify any instructions used by the instruction whose sole
4112 // purpose is to compute bits we don't care about.
4113 if (!isa<VectorType>(I.getType())) {
4114 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4115 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4116 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4117 KnownZero, KnownOne))
4118 return &I;
4119 } else if (isa<ConstantAggregateZero>(Op1)) {
4120 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
4121 }
4122
4123 // Is this a ~ operation?
4124 if (Value *NotOp = dyn_castNotVal(&I)) {
4125 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4126 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4127 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4128 if (Op0I->getOpcode() == Instruction::And ||
4129 Op0I->getOpcode() == Instruction::Or) {
4130 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4131 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4132 Instruction *NotY =
4133 BinaryOperator::createNot(Op0I->getOperand(1),
4134 Op0I->getOperand(1)->getName()+".not");
4135 InsertNewInstBefore(NotY, I);
4136 if (Op0I->getOpcode() == Instruction::And)
4137 return BinaryOperator::createOr(Op0NotVal, NotY);
4138 else
4139 return BinaryOperator::createAnd(Op0NotVal, NotY);
4140 }
4141 }
4142 }
4143 }
4144
4145
4146 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky1405e922007-08-06 20:04:16 +00004147 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4148 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4149 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004150 return new ICmpInst(ICI->getInversePredicate(),
4151 ICI->getOperand(0), ICI->getOperand(1));
4152
Nick Lewycky1405e922007-08-06 20:04:16 +00004153 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4154 return new FCmpInst(FCI->getInversePredicate(),
4155 FCI->getOperand(0), FCI->getOperand(1));
4156 }
4157
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004158 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4159 // ~(c-X) == X-c-1 == X+(-c-1)
4160 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4161 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4162 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4163 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4164 ConstantInt::get(I.getType(), 1));
4165 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
4166 }
4167
4168 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4169 if (Op0I->getOpcode() == Instruction::Add) {
4170 // ~(X-c) --> (-c-1)-X
4171 if (RHS->isAllOnesValue()) {
4172 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4173 return BinaryOperator::createSub(
4174 ConstantExpr::getSub(NegOp0CI,
4175 ConstantInt::get(I.getType(), 1)),
4176 Op0I->getOperand(0));
4177 } else if (RHS->getValue().isSignBit()) {
4178 // (X + C) ^ signbit -> (X + C + signbit)
4179 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4180 return BinaryOperator::createAdd(Op0I->getOperand(0), C);
4181
4182 }
4183 } else if (Op0I->getOpcode() == Instruction::Or) {
4184 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4185 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4186 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4187 // Anything in both C1 and C2 is known to be zero, remove it from
4188 // NewRHS.
4189 Constant *CommonBits = And(Op0CI, RHS);
4190 NewRHS = ConstantExpr::getAnd(NewRHS,
4191 ConstantExpr::getNot(CommonBits));
4192 AddToWorkList(Op0I);
4193 I.setOperand(0, Op0I->getOperand(0));
4194 I.setOperand(1, NewRHS);
4195 return &I;
4196 }
4197 }
4198 }
4199
4200 // Try to fold constant and into select arguments.
4201 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4202 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4203 return R;
4204 if (isa<PHINode>(Op0))
4205 if (Instruction *NV = FoldOpIntoPhi(I))
4206 return NV;
4207 }
4208
4209 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
4210 if (X == Op1)
4211 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4212
4213 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
4214 if (X == Op0)
4215 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4216
4217
4218 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4219 if (Op1I) {
4220 Value *A, *B;
4221 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4222 if (A == Op0) { // B^(B|A) == (A|B)^B
4223 Op1I->swapOperands();
4224 I.swapOperands();
4225 std::swap(Op0, Op1);
4226 } else if (B == Op0) { // B^(A|B) == (A|B)^B
4227 I.swapOperands(); // Simplified below.
4228 std::swap(Op0, Op1);
4229 }
4230 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4231 if (Op0 == A) // A^(A^B) == B
4232 return ReplaceInstUsesWith(I, B);
4233 else if (Op0 == B) // A^(B^A) == B
4234 return ReplaceInstUsesWith(I, A);
4235 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4236 if (A == Op0) { // A^(A&B) -> A^(B&A)
4237 Op1I->swapOperands();
4238 std::swap(A, B);
4239 }
4240 if (B == Op0) { // A^(B&A) -> (B&A)^A
4241 I.swapOperands(); // Simplified below.
4242 std::swap(Op0, Op1);
4243 }
4244 }
4245 }
4246
4247 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4248 if (Op0I) {
4249 Value *A, *B;
4250 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4251 if (A == Op1) // (B|A)^B == (A|B)^B
4252 std::swap(A, B);
4253 if (B == Op1) { // (A|B)^B == A & ~B
4254 Instruction *NotB =
4255 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4256 return BinaryOperator::createAnd(A, NotB);
4257 }
4258 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4259 if (Op1 == A) // (A^B)^A == B
4260 return ReplaceInstUsesWith(I, B);
4261 else if (Op1 == B) // (B^A)^A == B
4262 return ReplaceInstUsesWith(I, A);
4263 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4264 if (A == Op1) // (A&B)^A -> (B&A)^A
4265 std::swap(A, B);
4266 if (B == Op1 && // (B&A)^A == ~B & A
4267 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
4268 Instruction *N =
4269 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
4270 return BinaryOperator::createAnd(N, Op1);
4271 }
4272 }
4273 }
4274
4275 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4276 if (Op0I && Op1I && Op0I->isShift() &&
4277 Op0I->getOpcode() == Op1I->getOpcode() &&
4278 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4279 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4280 Instruction *NewOp =
4281 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4282 Op1I->getOperand(0),
4283 Op0I->getName()), I);
4284 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4285 Op1I->getOperand(1));
4286 }
4287
4288 if (Op0I && Op1I) {
4289 Value *A, *B, *C, *D;
4290 // (A & B)^(A | B) -> A ^ B
4291 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4292 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4293 if ((A == C && B == D) || (A == D && B == C))
4294 return BinaryOperator::createXor(A, B);
4295 }
4296 // (A | B)^(A & B) -> A ^ B
4297 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4298 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4299 if ((A == C && B == D) || (A == D && B == C))
4300 return BinaryOperator::createXor(A, B);
4301 }
4302
4303 // (A & B)^(C & D)
4304 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4305 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4306 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4307 // (X & Y)^(X & Y) -> (Y^Z) & X
4308 Value *X = 0, *Y = 0, *Z = 0;
4309 if (A == C)
4310 X = A, Y = B, Z = D;
4311 else if (A == D)
4312 X = A, Y = B, Z = C;
4313 else if (B == C)
4314 X = B, Y = A, Z = D;
4315 else if (B == D)
4316 X = B, Y = A, Z = C;
4317
4318 if (X) {
4319 Instruction *NewOp =
4320 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4321 return BinaryOperator::createAnd(NewOp, X);
4322 }
4323 }
4324 }
4325
4326 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4327 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4328 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4329 return R;
4330
4331 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
4332 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4333 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4334 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4335 const Type *SrcTy = Op0C->getOperand(0)->getType();
4336 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4337 // Only do this if the casts both really cause code to be generated.
4338 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4339 I.getType(), TD) &&
4340 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4341 I.getType(), TD)) {
4342 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4343 Op1C->getOperand(0),
4344 I.getName());
4345 InsertNewInstBefore(NewOp, I);
4346 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4347 }
4348 }
4349
4350 return Changed ? &I : 0;
4351}
4352
4353/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4354/// overflowed for this type.
4355static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4356 ConstantInt *In2, bool IsSigned = false) {
4357 Result = cast<ConstantInt>(Add(In1, In2));
4358
4359 if (IsSigned)
4360 if (In2->getValue().isNegative())
4361 return Result->getValue().sgt(In1->getValue());
4362 else
4363 return Result->getValue().slt(In1->getValue());
4364 else
4365 return Result->getValue().ult(In1->getValue());
4366}
4367
4368/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4369/// code necessary to compute the offset from the base pointer (without adding
4370/// in the base pointer). Return the result as a signed integer of intptr size.
4371static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4372 TargetData &TD = IC.getTargetData();
4373 gep_type_iterator GTI = gep_type_begin(GEP);
4374 const Type *IntPtrTy = TD.getIntPtrType();
4375 Value *Result = Constant::getNullValue(IntPtrTy);
4376
4377 // Build a mask for high order bits.
4378 unsigned IntPtrWidth = TD.getPointerSize()*8;
4379 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4380
4381 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4382 Value *Op = GEP->getOperand(i);
4383 uint64_t Size = TD.getTypeSize(GTI.getIndexedType()) & PtrSizeMask;
4384 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4385 if (OpC->isZero()) continue;
4386
4387 // Handle a struct index, which adds its field offset to the pointer.
4388 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4389 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4390
4391 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4392 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4393 else
4394 Result = IC.InsertNewInstBefore(
4395 BinaryOperator::createAdd(Result,
4396 ConstantInt::get(IntPtrTy, Size),
4397 GEP->getName()+".offs"), I);
4398 continue;
4399 }
4400
4401 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4402 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4403 Scale = ConstantExpr::getMul(OC, Scale);
4404 if (Constant *RC = dyn_cast<Constant>(Result))
4405 Result = ConstantExpr::getAdd(RC, Scale);
4406 else {
4407 // Emit an add instruction.
4408 Result = IC.InsertNewInstBefore(
4409 BinaryOperator::createAdd(Result, Scale,
4410 GEP->getName()+".offs"), I);
4411 }
4412 continue;
4413 }
4414 // Convert to correct type.
4415 if (Op->getType() != IntPtrTy) {
4416 if (Constant *OpC = dyn_cast<Constant>(Op))
4417 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4418 else
4419 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4420 Op->getName()+".c"), I);
4421 }
4422 if (Size != 1) {
4423 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4424 if (Constant *OpC = dyn_cast<Constant>(Op))
4425 Op = ConstantExpr::getMul(OpC, Scale);
4426 else // We'll let instcombine(mul) convert this to a shl if possible.
4427 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4428 GEP->getName()+".idx"), I);
4429 }
4430
4431 // Emit an add instruction.
4432 if (isa<Constant>(Op) && isa<Constant>(Result))
4433 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4434 cast<Constant>(Result));
4435 else
4436 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4437 GEP->getName()+".offs"), I);
4438 }
4439 return Result;
4440}
4441
4442/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4443/// else. At this point we know that the GEP is on the LHS of the comparison.
4444Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4445 ICmpInst::Predicate Cond,
4446 Instruction &I) {
4447 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4448
4449 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4450 if (isa<PointerType>(CI->getOperand(0)->getType()))
4451 RHS = CI->getOperand(0);
4452
4453 Value *PtrBase = GEPLHS->getOperand(0);
4454 if (PtrBase == RHS) {
4455 // As an optimization, we don't actually have to compute the actual value of
4456 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4457 // each index is zero or not.
4458 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
4459 Instruction *InVal = 0;
4460 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4461 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
4462 bool EmitIt = true;
4463 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4464 if (isa<UndefValue>(C)) // undef index -> undef.
4465 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4466 if (C->isNullValue())
4467 EmitIt = false;
4468 else if (TD->getTypeSize(GTI.getIndexedType()) == 0) {
4469 EmitIt = false; // This is indexing into a zero sized array?
4470 } else if (isa<ConstantInt>(C))
4471 return ReplaceInstUsesWith(I, // No comparison is needed here.
4472 ConstantInt::get(Type::Int1Ty,
4473 Cond == ICmpInst::ICMP_NE));
4474 }
4475
4476 if (EmitIt) {
4477 Instruction *Comp =
4478 new ICmpInst(Cond, GEPLHS->getOperand(i),
4479 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4480 if (InVal == 0)
4481 InVal = Comp;
4482 else {
4483 InVal = InsertNewInstBefore(InVal, I);
4484 InsertNewInstBefore(Comp, I);
4485 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
4486 InVal = BinaryOperator::createOr(InVal, Comp);
4487 else // True if all are equal
4488 InVal = BinaryOperator::createAnd(InVal, Comp);
4489 }
4490 }
4491 }
4492
4493 if (InVal)
4494 return InVal;
4495 else
4496 // No comparison is needed here, all indexes = 0
4497 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4498 Cond == ICmpInst::ICMP_EQ));
4499 }
4500
4501 // Only lower this if the icmp is the only user of the GEP or if we expect
4502 // the result to fold to a constant!
4503 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4504 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4505 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4506 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4507 Constant::getNullValue(Offset->getType()));
4508 }
4509 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4510 // If the base pointers are different, but the indices are the same, just
4511 // compare the base pointer.
4512 if (PtrBase != GEPRHS->getOperand(0)) {
4513 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4514 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4515 GEPRHS->getOperand(0)->getType();
4516 if (IndicesTheSame)
4517 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4518 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4519 IndicesTheSame = false;
4520 break;
4521 }
4522
4523 // If all indices are the same, just compare the base pointers.
4524 if (IndicesTheSame)
4525 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4526 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4527
4528 // Otherwise, the base pointers are different and the indices are
4529 // different, bail out.
4530 return 0;
4531 }
4532
4533 // If one of the GEPs has all zero indices, recurse.
4534 bool AllZeros = true;
4535 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4536 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4537 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4538 AllZeros = false;
4539 break;
4540 }
4541 if (AllZeros)
4542 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4543 ICmpInst::getSwappedPredicate(Cond), I);
4544
4545 // If the other GEP has all zero indices, recurse.
4546 AllZeros = true;
4547 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4548 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4549 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4550 AllZeros = false;
4551 break;
4552 }
4553 if (AllZeros)
4554 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4555
4556 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4557 // If the GEPs only differ by one index, compare it.
4558 unsigned NumDifferences = 0; // Keep track of # differences.
4559 unsigned DiffOperand = 0; // The operand that differs.
4560 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4561 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4562 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4563 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4564 // Irreconcilable differences.
4565 NumDifferences = 2;
4566 break;
4567 } else {
4568 if (NumDifferences++) break;
4569 DiffOperand = i;
4570 }
4571 }
4572
4573 if (NumDifferences == 0) // SAME GEP?
4574 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky2de09a92007-09-06 02:40:25 +00004575 ConstantInt::get(Type::Int1Ty,
4576 isTrueWhenEqual(Cond)));
4577
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004578 else if (NumDifferences == 1) {
4579 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4580 Value *RHSV = GEPRHS->getOperand(DiffOperand);
4581 // Make sure we do a signed comparison here.
4582 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4583 }
4584 }
4585
4586 // Only lower this if the icmp is the only user of the GEP or if we expect
4587 // the result to fold to a constant!
4588 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4589 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4590 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4591 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4592 Value *R = EmitGEPOffset(GEPRHS, I, *this);
4593 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4594 }
4595 }
4596 return 0;
4597}
4598
4599Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4600 bool Changed = SimplifyCompare(I);
4601 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4602
4603 // Fold trivial predicates.
4604 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4605 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4606 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4607 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4608
4609 // Simplify 'fcmp pred X, X'
4610 if (Op0 == Op1) {
4611 switch (I.getPredicate()) {
4612 default: assert(0 && "Unknown predicate!");
4613 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4614 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4615 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4616 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4617 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4618 case FCmpInst::FCMP_OLT: // True if ordered and less than
4619 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4620 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4621
4622 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4623 case FCmpInst::FCMP_ULT: // True if unordered or less than
4624 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4625 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4626 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4627 I.setPredicate(FCmpInst::FCMP_UNO);
4628 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4629 return &I;
4630
4631 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4632 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4633 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4634 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4635 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4636 I.setPredicate(FCmpInst::FCMP_ORD);
4637 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4638 return &I;
4639 }
4640 }
4641
4642 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
4643 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4644
4645 // Handle fcmp with constant RHS
4646 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4647 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4648 switch (LHSI->getOpcode()) {
4649 case Instruction::PHI:
4650 if (Instruction *NV = FoldOpIntoPhi(I))
4651 return NV;
4652 break;
4653 case Instruction::Select:
4654 // If either operand of the select is a constant, we can fold the
4655 // comparison into the select arms, which will cause one to be
4656 // constant folded and the select turned into a bitwise or.
4657 Value *Op1 = 0, *Op2 = 0;
4658 if (LHSI->hasOneUse()) {
4659 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4660 // Fold the known value into the constant operand.
4661 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4662 // Insert a new FCmp of the other select operand.
4663 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4664 LHSI->getOperand(2), RHSC,
4665 I.getName()), I);
4666 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4667 // Fold the known value into the constant operand.
4668 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4669 // Insert a new FCmp of the other select operand.
4670 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4671 LHSI->getOperand(1), RHSC,
4672 I.getName()), I);
4673 }
4674 }
4675
4676 if (Op1)
4677 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4678 break;
4679 }
4680 }
4681
4682 return Changed ? &I : 0;
4683}
4684
4685Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4686 bool Changed = SimplifyCompare(I);
4687 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4688 const Type *Ty = Op0->getType();
4689
4690 // icmp X, X
4691 if (Op0 == Op1)
4692 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4693 isTrueWhenEqual(I)));
4694
4695 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
4696 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4697
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004698 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4699 // addresses never equal each other! We already know that Op0 != Op1.
4700 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4701 isa<ConstantPointerNull>(Op0)) &&
4702 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4703 isa<ConstantPointerNull>(Op1)))
4704 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4705 !isTrueWhenEqual(I)));
4706
4707 // icmp's with boolean values can always be turned into bitwise operations
4708 if (Ty == Type::Int1Ty) {
4709 switch (I.getPredicate()) {
4710 default: assert(0 && "Invalid icmp instruction!");
4711 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
4712 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4713 InsertNewInstBefore(Xor, I);
4714 return BinaryOperator::createNot(Xor);
4715 }
4716 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
4717 return BinaryOperator::createXor(Op0, Op1);
4718
4719 case ICmpInst::ICMP_UGT:
4720 case ICmpInst::ICMP_SGT:
4721 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
4722 // FALL THROUGH
4723 case ICmpInst::ICMP_ULT:
4724 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
4725 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4726 InsertNewInstBefore(Not, I);
4727 return BinaryOperator::createAnd(Not, Op1);
4728 }
4729 case ICmpInst::ICMP_UGE:
4730 case ICmpInst::ICMP_SGE:
4731 std::swap(Op0, Op1); // Change icmp ge -> icmp le
4732 // FALL THROUGH
4733 case ICmpInst::ICMP_ULE:
4734 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
4735 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4736 InsertNewInstBefore(Not, I);
4737 return BinaryOperator::createOr(Not, Op1);
4738 }
4739 }
4740 }
4741
4742 // See if we are doing a comparison between a constant and an instruction that
4743 // can be folded into the comparison.
4744 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
4745 switch (I.getPredicate()) {
4746 default: break;
4747 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4748 if (CI->isMinValue(false))
4749 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4750 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4751 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4752 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4753 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4754 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
4755 if (CI->isMinValue(true))
4756 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
4757 ConstantInt::getAllOnesValue(Op0->getType()));
4758
4759 break;
4760
4761 case ICmpInst::ICMP_SLT:
4762 if (CI->isMinValue(true)) // A <s MIN -> FALSE
4763 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4764 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4765 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4766 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4767 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4768 break;
4769
4770 case ICmpInst::ICMP_UGT:
4771 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
4772 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4773 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4774 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4775 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4776 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4777
4778 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
4779 if (CI->isMaxValue(true))
4780 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
4781 ConstantInt::getNullValue(Op0->getType()));
4782 break;
4783
4784 case ICmpInst::ICMP_SGT:
4785 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
4786 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4787 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4788 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4789 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4790 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4791 break;
4792
4793 case ICmpInst::ICMP_ULE:
4794 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
4795 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4796 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4797 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4798 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4799 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4800 break;
4801
4802 case ICmpInst::ICMP_SLE:
4803 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
4804 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4805 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4806 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4807 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4808 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4809 break;
4810
4811 case ICmpInst::ICMP_UGE:
4812 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
4813 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4814 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4815 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4816 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4817 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4818 break;
4819
4820 case ICmpInst::ICMP_SGE:
4821 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
4822 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4823 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4824 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4825 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4826 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4827 break;
4828 }
4829
4830 // If we still have a icmp le or icmp ge instruction, turn it into the
4831 // appropriate icmp lt or icmp gt instruction. Since the border cases have
4832 // already been handled above, this requires little checking.
4833 //
4834 switch (I.getPredicate()) {
4835 default: break;
4836 case ICmpInst::ICMP_ULE:
4837 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4838 case ICmpInst::ICMP_SLE:
4839 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4840 case ICmpInst::ICMP_UGE:
4841 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4842 case ICmpInst::ICMP_SGE:
4843 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
4844 }
4845
4846 // See if we can fold the comparison based on bits known to be zero or one
4847 // in the input. If this comparison is a normal comparison, it demands all
4848 // bits, if it is a sign bit comparison, it only demands the sign bit.
4849
4850 bool UnusedBit;
4851 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
4852
4853 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
4854 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4855 if (SimplifyDemandedBits(Op0,
4856 isSignBit ? APInt::getSignBit(BitWidth)
4857 : APInt::getAllOnesValue(BitWidth),
4858 KnownZero, KnownOne, 0))
4859 return &I;
4860
4861 // Given the known and unknown bits, compute a range that the LHS could be
4862 // in.
4863 if ((KnownOne | KnownZero) != 0) {
4864 // Compute the Min, Max and RHS values based on the known bits. For the
4865 // EQ and NE we use unsigned values.
4866 APInt Min(BitWidth, 0), Max(BitWidth, 0);
4867 const APInt& RHSVal = CI->getValue();
4868 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4869 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4870 Max);
4871 } else {
4872 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4873 Max);
4874 }
4875 switch (I.getPredicate()) { // LE/GE have been folded already.
4876 default: assert(0 && "Unknown icmp opcode!");
4877 case ICmpInst::ICMP_EQ:
4878 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
4879 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4880 break;
4881 case ICmpInst::ICMP_NE:
4882 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
4883 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4884 break;
4885 case ICmpInst::ICMP_ULT:
4886 if (Max.ult(RHSVal))
4887 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4888 if (Min.uge(RHSVal))
4889 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4890 break;
4891 case ICmpInst::ICMP_UGT:
4892 if (Min.ugt(RHSVal))
4893 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4894 if (Max.ule(RHSVal))
4895 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4896 break;
4897 case ICmpInst::ICMP_SLT:
4898 if (Max.slt(RHSVal))
4899 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4900 if (Min.sgt(RHSVal))
4901 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4902 break;
4903 case ICmpInst::ICMP_SGT:
4904 if (Min.sgt(RHSVal))
4905 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4906 if (Max.sle(RHSVal))
4907 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4908 break;
4909 }
4910 }
4911
4912 // Since the RHS is a ConstantInt (CI), if the left hand side is an
4913 // instruction, see if that instruction also has constants so that the
4914 // instruction can be folded into the icmp
4915 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4916 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
4917 return Res;
4918 }
4919
4920 // Handle icmp with constant (but not simple integer constant) RHS
4921 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4922 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4923 switch (LHSI->getOpcode()) {
4924 case Instruction::GetElementPtr:
4925 if (RHSC->isNullValue()) {
4926 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
4927 bool isAllZeros = true;
4928 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
4929 if (!isa<Constant>(LHSI->getOperand(i)) ||
4930 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
4931 isAllZeros = false;
4932 break;
4933 }
4934 if (isAllZeros)
4935 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
4936 Constant::getNullValue(LHSI->getOperand(0)->getType()));
4937 }
4938 break;
4939
4940 case Instruction::PHI:
4941 if (Instruction *NV = FoldOpIntoPhi(I))
4942 return NV;
4943 break;
4944 case Instruction::Select: {
4945 // If either operand of the select is a constant, we can fold the
4946 // comparison into the select arms, which will cause one to be
4947 // constant folded and the select turned into a bitwise or.
4948 Value *Op1 = 0, *Op2 = 0;
4949 if (LHSI->hasOneUse()) {
4950 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4951 // Fold the known value into the constant operand.
4952 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
4953 // Insert a new ICmp of the other select operand.
4954 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
4955 LHSI->getOperand(2), RHSC,
4956 I.getName()), I);
4957 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4958 // Fold the known value into the constant operand.
4959 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
4960 // Insert a new ICmp of the other select operand.
4961 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
4962 LHSI->getOperand(1), RHSC,
4963 I.getName()), I);
4964 }
4965 }
4966
4967 if (Op1)
4968 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4969 break;
4970 }
4971 case Instruction::Malloc:
4972 // If we have (malloc != null), and if the malloc has a single use, we
4973 // can assume it is successful and remove the malloc.
4974 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
4975 AddToWorkList(LHSI);
4976 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4977 !isTrueWhenEqual(I)));
4978 }
4979 break;
4980 }
4981 }
4982
4983 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
4984 if (User *GEP = dyn_castGetElementPtr(Op0))
4985 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
4986 return NI;
4987 if (User *GEP = dyn_castGetElementPtr(Op1))
4988 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
4989 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
4990 return NI;
4991
4992 // Test to see if the operands of the icmp are casted versions of other
4993 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
4994 // now.
4995 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
4996 if (isa<PointerType>(Op0->getType()) &&
4997 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
4998 // We keep moving the cast from the left operand over to the right
4999 // operand, where it can often be eliminated completely.
5000 Op0 = CI->getOperand(0);
5001
5002 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5003 // so eliminate it as well.
5004 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5005 Op1 = CI2->getOperand(0);
5006
5007 // If Op1 is a constant, we can fold the cast into the constant.
5008 if (Op0->getType() != Op1->getType())
5009 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5010 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5011 } else {
5012 // Otherwise, cast the RHS right before the icmp
5013 Op1 = InsertCastBefore(Instruction::BitCast, Op1, Op0->getType(), I);
5014 }
5015 return new ICmpInst(I.getPredicate(), Op0, Op1);
5016 }
5017 }
5018
5019 if (isa<CastInst>(Op0)) {
5020 // Handle the special case of: icmp (cast bool to X), <cst>
5021 // This comes up when you have code like
5022 // int X = A < B;
5023 // if (X) ...
5024 // For generality, we handle any zero-extension of any operand comparison
5025 // with a constant or another cast from the same type.
5026 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5027 if (Instruction *R = visitICmpInstWithCastAndCast(I))
5028 return R;
5029 }
5030
5031 if (I.isEquality()) {
5032 Value *A, *B, *C, *D;
5033 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5034 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5035 Value *OtherVal = A == Op1 ? B : A;
5036 return new ICmpInst(I.getPredicate(), OtherVal,
5037 Constant::getNullValue(A->getType()));
5038 }
5039
5040 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5041 // A^c1 == C^c2 --> A == C^(c1^c2)
5042 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5043 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5044 if (Op1->hasOneUse()) {
5045 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
5046 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5047 return new ICmpInst(I.getPredicate(), A,
5048 InsertNewInstBefore(Xor, I));
5049 }
5050
5051 // A^B == A^D -> B == D
5052 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5053 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5054 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5055 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5056 }
5057 }
5058
5059 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5060 (A == Op0 || B == Op0)) {
5061 // A == (A^B) -> B == 0
5062 Value *OtherVal = A == Op0 ? B : A;
5063 return new ICmpInst(I.getPredicate(), OtherVal,
5064 Constant::getNullValue(A->getType()));
5065 }
5066 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5067 // (A-B) == A -> B == 0
5068 return new ICmpInst(I.getPredicate(), B,
5069 Constant::getNullValue(B->getType()));
5070 }
5071 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5072 // A == (A-B) -> B == 0
5073 return new ICmpInst(I.getPredicate(), B,
5074 Constant::getNullValue(B->getType()));
5075 }
5076
5077 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5078 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5079 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5080 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5081 Value *X = 0, *Y = 0, *Z = 0;
5082
5083 if (A == C) {
5084 X = B; Y = D; Z = A;
5085 } else if (A == D) {
5086 X = B; Y = C; Z = A;
5087 } else if (B == C) {
5088 X = A; Y = D; Z = B;
5089 } else if (B == D) {
5090 X = A; Y = C; Z = B;
5091 }
5092
5093 if (X) { // Build (X^Y) & Z
5094 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5095 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5096 I.setOperand(0, Op1);
5097 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5098 return &I;
5099 }
5100 }
5101 }
5102 return Changed ? &I : 0;
5103}
5104
5105
5106/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5107/// and CmpRHS are both known to be integer constants.
5108Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5109 ConstantInt *DivRHS) {
5110 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5111 const APInt &CmpRHSV = CmpRHS->getValue();
5112
5113 // FIXME: If the operand types don't match the type of the divide
5114 // then don't attempt this transform. The code below doesn't have the
5115 // logic to deal with a signed divide and an unsigned compare (and
5116 // vice versa). This is because (x /s C1) <s C2 produces different
5117 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5118 // (x /u C1) <u C2. Simply casting the operands and result won't
5119 // work. :( The if statement below tests that condition and bails
5120 // if it finds it.
5121 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5122 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5123 return 0;
5124 if (DivRHS->isZero())
5125 return 0; // The ProdOV computation fails on divide by zero.
5126
5127 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5128 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5129 // C2 (CI). By solving for X we can turn this into a range check
5130 // instead of computing a divide.
5131 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5132
5133 // Determine if the product overflows by seeing if the product is
5134 // not equal to the divide. Make sure we do the same kind of divide
5135 // as in the LHS instruction that we're folding.
5136 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5137 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5138
5139 // Get the ICmp opcode
5140 ICmpInst::Predicate Pred = ICI.getPredicate();
5141
5142 // Figure out the interval that is being checked. For example, a comparison
5143 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5144 // Compute this interval based on the constants involved and the signedness of
5145 // the compare/divide. This computes a half-open interval, keeping track of
5146 // whether either value in the interval overflows. After analysis each
5147 // overflow variable is set to 0 if it's corresponding bound variable is valid
5148 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5149 int LoOverflow = 0, HiOverflow = 0;
5150 ConstantInt *LoBound = 0, *HiBound = 0;
5151
5152
5153 if (!DivIsSigned) { // udiv
5154 // e.g. X/5 op 3 --> [15, 20)
5155 LoBound = Prod;
5156 HiOverflow = LoOverflow = ProdOV;
5157 if (!HiOverflow)
5158 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
5159 } else if (DivRHS->getValue().isPositive()) { // Divisor is > 0.
5160 if (CmpRHSV == 0) { // (X / pos) op 0
5161 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
5162 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5163 HiBound = DivRHS;
5164 } else if (CmpRHSV.isPositive()) { // (X / pos) op pos
5165 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5166 HiOverflow = LoOverflow = ProdOV;
5167 if (!HiOverflow)
5168 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5169 } else { // (X / pos) op neg
5170 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
5171 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5172 LoOverflow = AddWithOverflow(LoBound, Prod,
5173 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5174 HiBound = AddOne(Prod);
5175 HiOverflow = ProdOV ? -1 : 0;
5176 }
5177 } else { // Divisor is < 0.
5178 if (CmpRHSV == 0) { // (X / neg) op 0
5179 // e.g. X/-5 op 0 --> [-4, 5)
5180 LoBound = AddOne(DivRHS);
5181 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5182 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5183 HiOverflow = 1; // [INTMIN+1, overflow)
5184 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5185 }
5186 } else if (CmpRHSV.isPositive()) { // (X / neg) op pos
5187 // e.g. X/-5 op 3 --> [-19, -14)
5188 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5189 if (!LoOverflow)
5190 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5191 HiBound = AddOne(Prod);
5192 } else { // (X / neg) op neg
5193 // e.g. X/-5 op -3 --> [15, 20)
5194 LoBound = Prod;
5195 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
5196 HiBound = Subtract(Prod, DivRHS);
5197 }
5198
5199 // Dividing by a negative swaps the condition. LT <-> GT
5200 Pred = ICmpInst::getSwappedPredicate(Pred);
5201 }
5202
5203 Value *X = DivI->getOperand(0);
5204 switch (Pred) {
5205 default: assert(0 && "Unhandled icmp opcode!");
5206 case ICmpInst::ICMP_EQ:
5207 if (LoOverflow && HiOverflow)
5208 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5209 else if (HiOverflow)
5210 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5211 ICmpInst::ICMP_UGE, X, LoBound);
5212 else if (LoOverflow)
5213 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5214 ICmpInst::ICMP_ULT, X, HiBound);
5215 else
5216 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
5217 case ICmpInst::ICMP_NE:
5218 if (LoOverflow && HiOverflow)
5219 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5220 else if (HiOverflow)
5221 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5222 ICmpInst::ICMP_ULT, X, LoBound);
5223 else if (LoOverflow)
5224 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5225 ICmpInst::ICMP_UGE, X, HiBound);
5226 else
5227 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
5228 case ICmpInst::ICMP_ULT:
5229 case ICmpInst::ICMP_SLT:
5230 if (LoOverflow == +1) // Low bound is greater than input range.
5231 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5232 if (LoOverflow == -1) // Low bound is less than input range.
5233 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5234 return new ICmpInst(Pred, X, LoBound);
5235 case ICmpInst::ICMP_UGT:
5236 case ICmpInst::ICMP_SGT:
5237 if (HiOverflow == +1) // High bound greater than input range.
5238 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5239 else if (HiOverflow == -1) // High bound less than input range.
5240 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5241 if (Pred == ICmpInst::ICMP_UGT)
5242 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5243 else
5244 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5245 }
5246}
5247
5248
5249/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5250///
5251Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5252 Instruction *LHSI,
5253 ConstantInt *RHS) {
5254 const APInt &RHSV = RHS->getValue();
5255
5256 switch (LHSI->getOpcode()) {
5257 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
5258 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5259 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5260 // fold the xor.
5261 if (ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0 ||
5262 ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue()) {
5263 Value *CompareVal = LHSI->getOperand(0);
5264
5265 // If the sign bit of the XorCST is not set, there is no change to
5266 // the operation, just stop using the Xor.
5267 if (!XorCST->getValue().isNegative()) {
5268 ICI.setOperand(0, CompareVal);
5269 AddToWorkList(LHSI);
5270 return &ICI;
5271 }
5272
5273 // Was the old condition true if the operand is positive?
5274 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5275
5276 // If so, the new one isn't.
5277 isTrueIfPositive ^= true;
5278
5279 if (isTrueIfPositive)
5280 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5281 else
5282 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5283 }
5284 }
5285 break;
5286 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5287 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5288 LHSI->getOperand(0)->hasOneUse()) {
5289 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5290
5291 // If the LHS is an AND of a truncating cast, we can widen the
5292 // and/compare to be the input width without changing the value
5293 // produced, eliminating a cast.
5294 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5295 // We can do this transformation if either the AND constant does not
5296 // have its sign bit set or if it is an equality comparison.
5297 // Extending a relational comparison when we're checking the sign
5298 // bit would not work.
5299 if (Cast->hasOneUse() &&
5300 (ICI.isEquality() || AndCST->getValue().isPositive() &&
5301 RHSV.isPositive())) {
5302 uint32_t BitWidth =
5303 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5304 APInt NewCST = AndCST->getValue();
5305 NewCST.zext(BitWidth);
5306 APInt NewCI = RHSV;
5307 NewCI.zext(BitWidth);
5308 Instruction *NewAnd =
5309 BinaryOperator::createAnd(Cast->getOperand(0),
5310 ConstantInt::get(NewCST),LHSI->getName());
5311 InsertNewInstBefore(NewAnd, ICI);
5312 return new ICmpInst(ICI.getPredicate(), NewAnd,
5313 ConstantInt::get(NewCI));
5314 }
5315 }
5316
5317 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5318 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5319 // happens a LOT in code produced by the C front-end, for bitfield
5320 // access.
5321 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5322 if (Shift && !Shift->isShift())
5323 Shift = 0;
5324
5325 ConstantInt *ShAmt;
5326 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5327 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5328 const Type *AndTy = AndCST->getType(); // Type of the and.
5329
5330 // We can fold this as long as we can't shift unknown bits
5331 // into the mask. This can only happen with signed shift
5332 // rights, as they sign-extend.
5333 if (ShAmt) {
5334 bool CanFold = Shift->isLogicalShift();
5335 if (!CanFold) {
5336 // To test for the bad case of the signed shr, see if any
5337 // of the bits shifted in could be tested after the mask.
5338 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5339 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5340
5341 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5342 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5343 AndCST->getValue()) == 0)
5344 CanFold = true;
5345 }
5346
5347 if (CanFold) {
5348 Constant *NewCst;
5349 if (Shift->getOpcode() == Instruction::Shl)
5350 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5351 else
5352 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5353
5354 // Check to see if we are shifting out any of the bits being
5355 // compared.
5356 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5357 // If we shifted bits out, the fold is not going to work out.
5358 // As a special case, check to see if this means that the
5359 // result is always true or false now.
5360 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5361 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5362 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5363 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5364 } else {
5365 ICI.setOperand(1, NewCst);
5366 Constant *NewAndCST;
5367 if (Shift->getOpcode() == Instruction::Shl)
5368 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5369 else
5370 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5371 LHSI->setOperand(1, NewAndCST);
5372 LHSI->setOperand(0, Shift->getOperand(0));
5373 AddToWorkList(Shift); // Shift is dead.
5374 AddUsesToWorkList(ICI);
5375 return &ICI;
5376 }
5377 }
5378 }
5379
5380 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5381 // preferable because it allows the C<<Y expression to be hoisted out
5382 // of a loop if Y is invariant and X is not.
5383 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5384 ICI.isEquality() && !Shift->isArithmeticShift() &&
5385 isa<Instruction>(Shift->getOperand(0))) {
5386 // Compute C << Y.
5387 Value *NS;
5388 if (Shift->getOpcode() == Instruction::LShr) {
5389 NS = BinaryOperator::createShl(AndCST,
5390 Shift->getOperand(1), "tmp");
5391 } else {
5392 // Insert a logical shift.
5393 NS = BinaryOperator::createLShr(AndCST,
5394 Shift->getOperand(1), "tmp");
5395 }
5396 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5397
5398 // Compute X & (C << Y).
5399 Instruction *NewAnd =
5400 BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5401 InsertNewInstBefore(NewAnd, ICI);
5402
5403 ICI.setOperand(0, NewAnd);
5404 return &ICI;
5405 }
5406 }
5407 break;
5408
5409 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
5410 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5411 if (!ShAmt) break;
5412
5413 uint32_t TypeBits = RHSV.getBitWidth();
5414
5415 // Check that the shift amount is in range. If not, don't perform
5416 // undefined shifts. When the shift is visited it will be
5417 // simplified.
5418 if (ShAmt->uge(TypeBits))
5419 break;
5420
5421 if (ICI.isEquality()) {
5422 // If we are comparing against bits always shifted out, the
5423 // comparison cannot succeed.
5424 Constant *Comp =
5425 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5426 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5427 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5428 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5429 return ReplaceInstUsesWith(ICI, Cst);
5430 }
5431
5432 if (LHSI->hasOneUse()) {
5433 // Otherwise strength reduce the shift into an and.
5434 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5435 Constant *Mask =
5436 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5437
5438 Instruction *AndI =
5439 BinaryOperator::createAnd(LHSI->getOperand(0),
5440 Mask, LHSI->getName()+".mask");
5441 Value *And = InsertNewInstBefore(AndI, ICI);
5442 return new ICmpInst(ICI.getPredicate(), And,
5443 ConstantInt::get(RHSV.lshr(ShAmtVal)));
5444 }
5445 }
5446
5447 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5448 bool TrueIfSigned = false;
5449 if (LHSI->hasOneUse() &&
5450 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5451 // (X << 31) <s 0 --> (X&1) != 0
5452 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5453 (TypeBits-ShAmt->getZExtValue()-1));
5454 Instruction *AndI =
5455 BinaryOperator::createAnd(LHSI->getOperand(0),
5456 Mask, LHSI->getName()+".mask");
5457 Value *And = InsertNewInstBefore(AndI, ICI);
5458
5459 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5460 And, Constant::getNullValue(And->getType()));
5461 }
5462 break;
5463 }
5464
5465 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
5466 case Instruction::AShr: {
5467 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5468 if (!ShAmt) break;
5469
5470 if (ICI.isEquality()) {
5471 // Check that the shift amount is in range. If not, don't perform
5472 // undefined shifts. When the shift is visited it will be
5473 // simplified.
5474 uint32_t TypeBits = RHSV.getBitWidth();
5475 if (ShAmt->uge(TypeBits))
5476 break;
5477 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5478
5479 // If we are comparing against bits always shifted out, the
5480 // comparison cannot succeed.
5481 APInt Comp = RHSV << ShAmtVal;
5482 if (LHSI->getOpcode() == Instruction::LShr)
5483 Comp = Comp.lshr(ShAmtVal);
5484 else
5485 Comp = Comp.ashr(ShAmtVal);
5486
5487 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5488 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5489 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5490 return ReplaceInstUsesWith(ICI, Cst);
5491 }
5492
5493 if (LHSI->hasOneUse() || RHSV == 0) {
5494 // Otherwise strength reduce the shift into an and.
5495 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5496 Constant *Mask = ConstantInt::get(Val);
5497
5498 Instruction *AndI =
5499 BinaryOperator::createAnd(LHSI->getOperand(0),
5500 Mask, LHSI->getName()+".mask");
5501 Value *And = InsertNewInstBefore(AndI, ICI);
5502 return new ICmpInst(ICI.getPredicate(), And,
5503 ConstantExpr::getShl(RHS, ShAmt));
5504 }
5505 }
5506 break;
5507 }
5508
5509 case Instruction::SDiv:
5510 case Instruction::UDiv:
5511 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5512 // Fold this div into the comparison, producing a range check.
5513 // Determine, based on the divide type, what the range is being
5514 // checked. If there is an overflow on the low or high side, remember
5515 // it, otherwise compute the range [low, hi) bounding the new value.
5516 // See: InsertRangeTest above for the kinds of replacements possible.
5517 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
5518 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
5519 DivRHS))
5520 return R;
5521 break;
5522 }
5523
5524 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5525 if (ICI.isEquality()) {
5526 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5527
5528 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5529 // the second operand is a constant, simplify a bit.
5530 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
5531 switch (BO->getOpcode()) {
5532 case Instruction::SRem:
5533 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5534 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
5535 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
5536 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
5537 Instruction *NewRem =
5538 BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
5539 BO->getName());
5540 InsertNewInstBefore(NewRem, ICI);
5541 return new ICmpInst(ICI.getPredicate(), NewRem,
5542 Constant::getNullValue(BO->getType()));
5543 }
5544 }
5545 break;
5546 case Instruction::Add:
5547 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5548 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5549 if (BO->hasOneUse())
5550 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5551 Subtract(RHS, BOp1C));
5552 } else if (RHSV == 0) {
5553 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5554 // efficiently invertible, or if the add has just this one use.
5555 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5556
5557 if (Value *NegVal = dyn_castNegVal(BOp1))
5558 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
5559 else if (Value *NegVal = dyn_castNegVal(BOp0))
5560 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
5561 else if (BO->hasOneUse()) {
5562 Instruction *Neg = BinaryOperator::createNeg(BOp1);
5563 InsertNewInstBefore(Neg, ICI);
5564 Neg->takeName(BO);
5565 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
5566 }
5567 }
5568 break;
5569 case Instruction::Xor:
5570 // For the xor case, we can xor two constants together, eliminating
5571 // the explicit xor.
5572 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5573 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5574 ConstantExpr::getXor(RHS, BOC));
5575
5576 // FALLTHROUGH
5577 case Instruction::Sub:
5578 // Replace (([sub|xor] A, B) != 0) with (A != B)
5579 if (RHSV == 0)
5580 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5581 BO->getOperand(1));
5582 break;
5583
5584 case Instruction::Or:
5585 // If bits are being or'd in that are not present in the constant we
5586 // are comparing against, then the comparison could never succeed!
5587 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5588 Constant *NotCI = ConstantExpr::getNot(RHS);
5589 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5590 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5591 isICMP_NE));
5592 }
5593 break;
5594
5595 case Instruction::And:
5596 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5597 // If bits are being compared against that are and'd out, then the
5598 // comparison can never succeed!
5599 if ((RHSV & ~BOC->getValue()) != 0)
5600 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5601 isICMP_NE));
5602
5603 // If we have ((X & C) == C), turn it into ((X & C) != 0).
5604 if (RHS == BOC && RHSV.isPowerOf2())
5605 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5606 ICmpInst::ICMP_NE, LHSI,
5607 Constant::getNullValue(RHS->getType()));
5608
5609 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5610 if (isSignBit(BOC)) {
5611 Value *X = BO->getOperand(0);
5612 Constant *Zero = Constant::getNullValue(X->getType());
5613 ICmpInst::Predicate pred = isICMP_NE ?
5614 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5615 return new ICmpInst(pred, X, Zero);
5616 }
5617
5618 // ((X & ~7) == 0) --> X < 8
5619 if (RHSV == 0 && isHighOnes(BOC)) {
5620 Value *X = BO->getOperand(0);
5621 Constant *NegX = ConstantExpr::getNeg(BOC);
5622 ICmpInst::Predicate pred = isICMP_NE ?
5623 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5624 return new ICmpInst(pred, X, NegX);
5625 }
5626 }
5627 default: break;
5628 }
5629 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
5630 // Handle icmp {eq|ne} <intrinsic>, intcst.
5631 if (II->getIntrinsicID() == Intrinsic::bswap) {
5632 AddToWorkList(II);
5633 ICI.setOperand(0, II->getOperand(1));
5634 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
5635 return &ICI;
5636 }
5637 }
5638 } else { // Not a ICMP_EQ/ICMP_NE
5639 // If the LHS is a cast from an integral value of the same size,
5640 // then since we know the RHS is a constant, try to simlify.
5641 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
5642 Value *CastOp = Cast->getOperand(0);
5643 const Type *SrcTy = CastOp->getType();
5644 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
5645 if (SrcTy->isInteger() &&
5646 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5647 // If this is an unsigned comparison, try to make the comparison use
5648 // smaller constant values.
5649 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
5650 // X u< 128 => X s> -1
5651 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5652 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
5653 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
5654 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
5655 // X u> 127 => X s< 0
5656 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5657 Constant::getNullValue(SrcTy));
5658 }
5659 }
5660 }
5661 }
5662 return 0;
5663}
5664
5665/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5666/// We only handle extending casts so far.
5667///
5668Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5669 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
5670 Value *LHSCIOp = LHSCI->getOperand(0);
5671 const Type *SrcTy = LHSCIOp->getType();
5672 const Type *DestTy = LHSCI->getType();
5673 Value *RHSCIOp;
5674
5675 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
5676 // integer type is the same size as the pointer type.
5677 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
5678 getTargetData().getPointerSizeInBits() ==
5679 cast<IntegerType>(DestTy)->getBitWidth()) {
5680 Value *RHSOp = 0;
5681 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
5682 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
5683 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
5684 RHSOp = RHSC->getOperand(0);
5685 // If the pointer types don't match, insert a bitcast.
5686 if (LHSCIOp->getType() != RHSOp->getType())
5687 RHSOp = InsertCastBefore(Instruction::BitCast, RHSOp,
5688 LHSCIOp->getType(), ICI);
5689 }
5690
5691 if (RHSOp)
5692 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
5693 }
5694
5695 // The code below only handles extension cast instructions, so far.
5696 // Enforce this.
5697 if (LHSCI->getOpcode() != Instruction::ZExt &&
5698 LHSCI->getOpcode() != Instruction::SExt)
5699 return 0;
5700
5701 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5702 bool isSignedCmp = ICI.isSignedPredicate();
5703
5704 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
5705 // Not an extension from the same type?
5706 RHSCIOp = CI->getOperand(0);
5707 if (RHSCIOp->getType() != LHSCIOp->getType())
5708 return 0;
5709
5710 // If the signedness of the two compares doesn't agree (i.e. one is a sext
5711 // and the other is a zext), then we can't handle this.
5712 if (CI->getOpcode() != LHSCI->getOpcode())
5713 return 0;
5714
5715 // Likewise, if the signedness of the [sz]exts and the compare don't match,
5716 // then we can't handle this.
5717 if (isSignedExt != isSignedCmp && !ICI.isEquality())
5718 return 0;
5719
5720 // Okay, just insert a compare of the reduced operands now!
5721 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5722 }
5723
5724 // If we aren't dealing with a constant on the RHS, exit early
5725 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5726 if (!CI)
5727 return 0;
5728
5729 // Compute the constant that would happen if we truncated to SrcTy then
5730 // reextended to DestTy.
5731 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5732 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5733
5734 // If the re-extended constant didn't change...
5735 if (Res2 == CI) {
5736 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5737 // For example, we might have:
5738 // %A = sext short %X to uint
5739 // %B = icmp ugt uint %A, 1330
5740 // It is incorrect to transform this into
5741 // %B = icmp ugt short %X, 1330
5742 // because %A may have negative value.
5743 //
5744 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5745 // OR operation is EQ/NE.
5746 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
5747 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5748 else
5749 return 0;
5750 }
5751
5752 // The re-extended constant changed so the constant cannot be represented
5753 // in the shorter type. Consequently, we cannot emit a simple comparison.
5754
5755 // First, handle some easy cases. We know the result cannot be equal at this
5756 // point so handle the ICI.isEquality() cases
5757 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5758 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5759 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5760 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5761
5762 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5763 // should have been folded away previously and not enter in here.
5764 Value *Result;
5765 if (isSignedCmp) {
5766 // We're performing a signed comparison.
5767 if (cast<ConstantInt>(CI)->getValue().isNegative())
5768 Result = ConstantInt::getFalse(); // X < (small) --> false
5769 else
5770 Result = ConstantInt::getTrue(); // X < (large) --> true
5771 } else {
5772 // We're performing an unsigned comparison.
5773 if (isSignedExt) {
5774 // We're performing an unsigned comp with a sign extended value.
5775 // This is true if the input is >= 0. [aka >s -1]
5776 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
5777 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5778 NegOne, ICI.getName()), ICI);
5779 } else {
5780 // Unsigned extend & unsigned compare -> always true.
5781 Result = ConstantInt::getTrue();
5782 }
5783 }
5784
5785 // Finally, return the value computed.
5786 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5787 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5788 return ReplaceInstUsesWith(ICI, Result);
5789 } else {
5790 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5791 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5792 "ICmp should be folded!");
5793 if (Constant *CI = dyn_cast<Constant>(Result))
5794 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5795 else
5796 return BinaryOperator::createNot(Result);
5797 }
5798}
5799
5800Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5801 return commonShiftTransforms(I);
5802}
5803
5804Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5805 return commonShiftTransforms(I);
5806}
5807
5808Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
5809 return commonShiftTransforms(I);
5810}
5811
5812Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
5813 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
5814 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5815
5816 // shl X, 0 == X and shr X, 0 == X
5817 // shl 0, X == 0 and shr 0, X == 0
5818 if (Op1 == Constant::getNullValue(Op1->getType()) ||
5819 Op0 == Constant::getNullValue(Op0->getType()))
5820 return ReplaceInstUsesWith(I, Op0);
5821
5822 if (isa<UndefValue>(Op0)) {
5823 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
5824 return ReplaceInstUsesWith(I, Op0);
5825 else // undef << X -> 0, undef >>u X -> 0
5826 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5827 }
5828 if (isa<UndefValue>(Op1)) {
5829 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5830 return ReplaceInstUsesWith(I, Op0);
5831 else // X << undef, X >>u undef -> 0
5832 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5833 }
5834
5835 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5836 if (I.getOpcode() == Instruction::AShr)
5837 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
5838 if (CSI->isAllOnesValue())
5839 return ReplaceInstUsesWith(I, CSI);
5840
5841 // Try to fold constant and into select arguments.
5842 if (isa<Constant>(Op0))
5843 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
5844 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5845 return R;
5846
5847 // See if we can turn a signed shr into an unsigned shr.
5848 if (I.isArithmeticShift()) {
5849 if (MaskedValueIsZero(Op0,
5850 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()))) {
5851 return BinaryOperator::createLShr(Op0, Op1, I.getName());
5852 }
5853 }
5854
5855 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5856 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5857 return Res;
5858 return 0;
5859}
5860
5861Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
5862 BinaryOperator &I) {
5863 bool isLeftShift = I.getOpcode() == Instruction::Shl;
5864
5865 // See if we can simplify any instructions used by the instruction whose sole
5866 // purpose is to compute bits we don't care about.
5867 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5868 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
5869 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
5870 KnownZero, KnownOne))
5871 return &I;
5872
5873 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5874 // of a signed value.
5875 //
5876 if (Op1->uge(TypeBits)) {
5877 if (I.getOpcode() != Instruction::AShr)
5878 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5879 else {
5880 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
5881 return &I;
5882 }
5883 }
5884
5885 // ((X*C1) << C2) == (X * (C1 << C2))
5886 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
5887 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
5888 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
5889 return BinaryOperator::createMul(BO->getOperand(0),
5890 ConstantExpr::getShl(BOOp, Op1));
5891
5892 // Try to fold constant and into select arguments.
5893 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5894 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5895 return R;
5896 if (isa<PHINode>(Op0))
5897 if (Instruction *NV = FoldOpIntoPhi(I))
5898 return NV;
5899
5900 if (Op0->hasOneUse()) {
5901 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
5902 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5903 Value *V1, *V2;
5904 ConstantInt *CC;
5905 switch (Op0BO->getOpcode()) {
5906 default: break;
5907 case Instruction::Add:
5908 case Instruction::And:
5909 case Instruction::Or:
5910 case Instruction::Xor: {
5911 // These operators commute.
5912 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
5913 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
5914 match(Op0BO->getOperand(1),
5915 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5916 Instruction *YS = BinaryOperator::createShl(
5917 Op0BO->getOperand(0), Op1,
5918 Op0BO->getName());
5919 InsertNewInstBefore(YS, I); // (Y << C)
5920 Instruction *X =
5921 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
5922 Op0BO->getOperand(1)->getName());
5923 InsertNewInstBefore(X, I); // (X + (Y << C))
5924 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
5925 return BinaryOperator::createAnd(X, ConstantInt::get(
5926 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
5927 }
5928
5929 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
5930 Value *Op0BOOp1 = Op0BO->getOperand(1);
5931 if (isLeftShift && Op0BOOp1->hasOneUse() &&
5932 match(Op0BOOp1,
5933 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
5934 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
5935 V2 == Op1) {
5936 Instruction *YS = BinaryOperator::createShl(
5937 Op0BO->getOperand(0), Op1,
5938 Op0BO->getName());
5939 InsertNewInstBefore(YS, I); // (Y << C)
5940 Instruction *XM =
5941 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5942 V1->getName()+".mask");
5943 InsertNewInstBefore(XM, I); // X & (CC << C)
5944
5945 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
5946 }
5947 }
5948
5949 // FALL THROUGH.
5950 case Instruction::Sub: {
5951 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
5952 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5953 match(Op0BO->getOperand(0),
5954 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
5955 Instruction *YS = BinaryOperator::createShl(
5956 Op0BO->getOperand(1), Op1,
5957 Op0BO->getName());
5958 InsertNewInstBefore(YS, I); // (Y << C)
5959 Instruction *X =
5960 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
5961 Op0BO->getOperand(0)->getName());
5962 InsertNewInstBefore(X, I); // (X + (Y << C))
5963 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
5964 return BinaryOperator::createAnd(X, ConstantInt::get(
5965 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
5966 }
5967
5968 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
5969 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
5970 match(Op0BO->getOperand(0),
5971 m_And(m_Shr(m_Value(V1), m_Value(V2)),
5972 m_ConstantInt(CC))) && V2 == Op1 &&
5973 cast<BinaryOperator>(Op0BO->getOperand(0))
5974 ->getOperand(0)->hasOneUse()) {
5975 Instruction *YS = BinaryOperator::createShl(
5976 Op0BO->getOperand(1), Op1,
5977 Op0BO->getName());
5978 InsertNewInstBefore(YS, I); // (Y << C)
5979 Instruction *XM =
5980 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
5981 V1->getName()+".mask");
5982 InsertNewInstBefore(XM, I); // X & (CC << C)
5983
5984 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
5985 }
5986
5987 break;
5988 }
5989 }
5990
5991
5992 // If the operand is an bitwise operator with a constant RHS, and the
5993 // shift is the only use, we can pull it out of the shift.
5994 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
5995 bool isValid = true; // Valid only for And, Or, Xor
5996 bool highBitSet = false; // Transform if high bit of constant set?
5997
5998 switch (Op0BO->getOpcode()) {
5999 default: isValid = false; break; // Do not perform transform!
6000 case Instruction::Add:
6001 isValid = isLeftShift;
6002 break;
6003 case Instruction::Or:
6004 case Instruction::Xor:
6005 highBitSet = false;
6006 break;
6007 case Instruction::And:
6008 highBitSet = true;
6009 break;
6010 }
6011
6012 // If this is a signed shift right, and the high bit is modified
6013 // by the logical operation, do not perform the transformation.
6014 // The highBitSet boolean indicates the value of the high bit of
6015 // the constant which would cause it to be modified for this
6016 // operation.
6017 //
6018 if (isValid && !isLeftShift && I.getOpcode() == Instruction::AShr) {
6019 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
6020 }
6021
6022 if (isValid) {
6023 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6024
6025 Instruction *NewShift =
6026 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
6027 InsertNewInstBefore(NewShift, I);
6028 NewShift->takeName(Op0BO);
6029
6030 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6031 NewRHS);
6032 }
6033 }
6034 }
6035 }
6036
6037 // Find out if this is a shift of a shift by a constant.
6038 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6039 if (ShiftOp && !ShiftOp->isShift())
6040 ShiftOp = 0;
6041
6042 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6043 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6044 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6045 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6046 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6047 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6048 Value *X = ShiftOp->getOperand(0);
6049
6050 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
6051 if (AmtSum > TypeBits)
6052 AmtSum = TypeBits;
6053
6054 const IntegerType *Ty = cast<IntegerType>(I.getType());
6055
6056 // Check for (X << c1) << c2 and (X >> c1) >> c2
6057 if (I.getOpcode() == ShiftOp->getOpcode()) {
6058 return BinaryOperator::create(I.getOpcode(), X,
6059 ConstantInt::get(Ty, AmtSum));
6060 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6061 I.getOpcode() == Instruction::AShr) {
6062 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
6063 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6064 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6065 I.getOpcode() == Instruction::LShr) {
6066 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6067 Instruction *Shift =
6068 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6069 InsertNewInstBefore(Shift, I);
6070
6071 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6072 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6073 }
6074
6075 // Okay, if we get here, one shift must be left, and the other shift must be
6076 // right. See if the amounts are equal.
6077 if (ShiftAmt1 == ShiftAmt2) {
6078 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6079 if (I.getOpcode() == Instruction::Shl) {
6080 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
6081 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
6082 }
6083 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6084 if (I.getOpcode() == Instruction::LShr) {
6085 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
6086 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
6087 }
6088 // We can simplify ((X << C) >>s C) into a trunc + sext.
6089 // NOTE: we could do this for any C, but that would make 'unusual' integer
6090 // types. For now, just stick to ones well-supported by the code
6091 // generators.
6092 const Type *SExtType = 0;
6093 switch (Ty->getBitWidth() - ShiftAmt1) {
6094 case 1 :
6095 case 8 :
6096 case 16 :
6097 case 32 :
6098 case 64 :
6099 case 128:
6100 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6101 break;
6102 default: break;
6103 }
6104 if (SExtType) {
6105 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6106 InsertNewInstBefore(NewTrunc, I);
6107 return new SExtInst(NewTrunc, Ty);
6108 }
6109 // Otherwise, we can't handle it yet.
6110 } else if (ShiftAmt1 < ShiftAmt2) {
6111 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
6112
6113 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6114 if (I.getOpcode() == Instruction::Shl) {
6115 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6116 ShiftOp->getOpcode() == Instruction::AShr);
6117 Instruction *Shift =
6118 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6119 InsertNewInstBefore(Shift, I);
6120
6121 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6122 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6123 }
6124
6125 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
6126 if (I.getOpcode() == Instruction::LShr) {
6127 assert(ShiftOp->getOpcode() == Instruction::Shl);
6128 Instruction *Shift =
6129 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6130 InsertNewInstBefore(Shift, I);
6131
6132 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6133 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6134 }
6135
6136 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6137 } else {
6138 assert(ShiftAmt2 < ShiftAmt1);
6139 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6140
6141 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6142 if (I.getOpcode() == Instruction::Shl) {
6143 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6144 ShiftOp->getOpcode() == Instruction::AShr);
6145 Instruction *Shift =
6146 BinaryOperator::create(ShiftOp->getOpcode(), X,
6147 ConstantInt::get(Ty, ShiftDiff));
6148 InsertNewInstBefore(Shift, I);
6149
6150 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6151 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6152 }
6153
6154 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
6155 if (I.getOpcode() == Instruction::LShr) {
6156 assert(ShiftOp->getOpcode() == Instruction::Shl);
6157 Instruction *Shift =
6158 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6159 InsertNewInstBefore(Shift, I);
6160
6161 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6162 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6163 }
6164
6165 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6166 }
6167 }
6168 return 0;
6169}
6170
6171
6172/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6173/// expression. If so, decompose it, returning some value X, such that Val is
6174/// X*Scale+Offset.
6175///
6176static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6177 int &Offset) {
6178 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6179 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6180 Offset = CI->getZExtValue();
6181 Scale = 1;
6182 return ConstantInt::get(Type::Int32Ty, 0);
6183 } else if (Instruction *I = dyn_cast<Instruction>(Val)) {
6184 if (I->getNumOperands() == 2) {
6185 if (ConstantInt *CUI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6186 if (I->getOpcode() == Instruction::Shl) {
6187 // This is a value scaled by '1 << the shift amt'.
6188 Scale = 1U << CUI->getZExtValue();
6189 Offset = 0;
6190 return I->getOperand(0);
6191 } else if (I->getOpcode() == Instruction::Mul) {
6192 // This value is scaled by 'CUI'.
6193 Scale = CUI->getZExtValue();
6194 Offset = 0;
6195 return I->getOperand(0);
6196 } else if (I->getOpcode() == Instruction::Add) {
6197 // We have X+C. Check to see if we really have (X*C2)+C1,
6198 // where C1 is divisible by C2.
6199 unsigned SubScale;
6200 Value *SubVal =
6201 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6202 Offset += CUI->getZExtValue();
6203 if (SubScale > 1 && (Offset % SubScale == 0)) {
6204 Scale = SubScale;
6205 return SubVal;
6206 }
6207 }
6208 }
6209 }
6210 }
6211
6212 // Otherwise, we can't look past this.
6213 Scale = 1;
6214 Offset = 0;
6215 return Val;
6216}
6217
6218
6219/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6220/// try to eliminate the cast by moving the type information into the alloc.
6221Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6222 AllocationInst &AI) {
6223 const PointerType *PTy = cast<PointerType>(CI.getType());
6224
6225 // Remove any uses of AI that are dead.
6226 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6227
6228 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6229 Instruction *User = cast<Instruction>(*UI++);
6230 if (isInstructionTriviallyDead(User)) {
6231 while (UI != E && *UI == User)
6232 ++UI; // If this instruction uses AI more than once, don't break UI.
6233
6234 ++NumDeadInst;
6235 DOUT << "IC: DCE: " << *User;
6236 EraseInstFromFunction(*User);
6237 }
6238 }
6239
6240 // Get the type really allocated and the type casted to.
6241 const Type *AllocElTy = AI.getAllocatedType();
6242 const Type *CastElTy = PTy->getElementType();
6243 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6244
6245 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6246 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6247 if (CastElTyAlign < AllocElTyAlign) return 0;
6248
6249 // If the allocation has multiple uses, only promote it if we are strictly
6250 // increasing the alignment of the resultant allocation. If we keep it the
6251 // same, we open the door to infinite loops of various kinds.
6252 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6253
6254 uint64_t AllocElTySize = TD->getTypeSize(AllocElTy);
6255 uint64_t CastElTySize = TD->getTypeSize(CastElTy);
6256 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6257
6258 // See if we can satisfy the modulus by pulling a scale out of the array
6259 // size argument.
6260 unsigned ArraySizeScale;
6261 int ArrayOffset;
6262 Value *NumElements = // See if the array size is a decomposable linear expr.
6263 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6264
6265 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6266 // do the xform.
6267 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6268 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
6269
6270 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6271 Value *Amt = 0;
6272 if (Scale == 1) {
6273 Amt = NumElements;
6274 } else {
6275 // If the allocation size is constant, form a constant mul expression
6276 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6277 if (isa<ConstantInt>(NumElements))
6278 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6279 // otherwise multiply the amount and the number of elements
6280 else if (Scale != 1) {
6281 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6282 Amt = InsertNewInstBefore(Tmp, AI);
6283 }
6284 }
6285
6286 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6287 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
6288 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6289 Amt = InsertNewInstBefore(Tmp, AI);
6290 }
6291
6292 AllocationInst *New;
6293 if (isa<MallocInst>(AI))
6294 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6295 else
6296 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6297 InsertNewInstBefore(New, AI);
6298 New->takeName(&AI);
6299
6300 // If the allocation has multiple uses, insert a cast and change all things
6301 // that used it to use the new cast. This will also hack on CI, but it will
6302 // die soon.
6303 if (!AI.hasOneUse()) {
6304 AddUsesToWorkList(AI);
6305 // New is the allocation instruction, pointer typed. AI is the original
6306 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6307 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6308 InsertNewInstBefore(NewCast, AI);
6309 AI.replaceAllUsesWith(NewCast);
6310 }
6311 return ReplaceInstUsesWith(CI, New);
6312}
6313
6314/// CanEvaluateInDifferentType - Return true if we can take the specified value
6315/// and return it as type Ty without inserting any new casts and without
6316/// changing the computed value. This is used by code that tries to decide
6317/// whether promoting or shrinking integer operations to wider or smaller types
6318/// will allow us to eliminate a truncate or extend.
6319///
6320/// This is a truncation operation if Ty is smaller than V->getType(), or an
6321/// extension operation if Ty is larger.
6322static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattneref70bb82007-08-02 06:11:14 +00006323 unsigned CastOpc, int &NumCastsRemoved) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006324 // We can always evaluate constants in another type.
6325 if (isa<ConstantInt>(V))
6326 return true;
6327
6328 Instruction *I = dyn_cast<Instruction>(V);
6329 if (!I) return false;
6330
6331 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6332
Chris Lattneref70bb82007-08-02 06:11:14 +00006333 // If this is an extension or truncate, we can often eliminate it.
6334 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6335 // If this is a cast from the destination type, we can trivially eliminate
6336 // it, and this will remove a cast overall.
6337 if (I->getOperand(0)->getType() == Ty) {
6338 // If the first operand is itself a cast, and is eliminable, do not count
6339 // this as an eliminable cast. We would prefer to eliminate those two
6340 // casts first.
6341 if (!isa<CastInst>(I->getOperand(0)))
6342 ++NumCastsRemoved;
6343 return true;
6344 }
6345 }
6346
6347 // We can't extend or shrink something that has multiple uses: doing so would
6348 // require duplicating the instruction in general, which isn't profitable.
6349 if (!I->hasOneUse()) return false;
6350
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006351 switch (I->getOpcode()) {
6352 case Instruction::Add:
6353 case Instruction::Sub:
6354 case Instruction::And:
6355 case Instruction::Or:
6356 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006357 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00006358 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6359 NumCastsRemoved) &&
6360 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6361 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006362
6363 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006364 // If we are truncating the result of this SHL, and if it's a shift of a
6365 // constant amount, we can always perform a SHL in a smaller type.
6366 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6367 uint32_t BitWidth = Ty->getBitWidth();
6368 if (BitWidth < OrigTy->getBitWidth() &&
6369 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00006370 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6371 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006372 }
6373 break;
6374 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006375 // If this is a truncate of a logical shr, we can truncate it to a smaller
6376 // lshr iff we know that the bits we would otherwise be shifting in are
6377 // already zeros.
6378 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6379 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6380 uint32_t BitWidth = Ty->getBitWidth();
6381 if (BitWidth < OrigBitWidth &&
6382 MaskedValueIsZero(I->getOperand(0),
6383 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6384 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00006385 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6386 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006387 }
6388 }
6389 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006390 case Instruction::ZExt:
6391 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00006392 case Instruction::Trunc:
6393 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00006394 // can safely replace it. Note that replacing it does not reduce the number
6395 // of casts in the input.
6396 if (I->getOpcode() == CastOpc)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006397 return true;
Chris Lattner2799b2f2007-09-10 23:46:29 +00006398
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006399 break;
6400 default:
6401 // TODO: Can handle more cases here.
6402 break;
6403 }
6404
6405 return false;
6406}
6407
6408/// EvaluateInDifferentType - Given an expression that
6409/// CanEvaluateInDifferentType returns true for, actually insert the code to
6410/// evaluate the expression.
6411Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
6412 bool isSigned) {
6413 if (Constant *C = dyn_cast<Constant>(V))
6414 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
6415
6416 // Otherwise, it must be an instruction.
6417 Instruction *I = cast<Instruction>(V);
6418 Instruction *Res = 0;
6419 switch (I->getOpcode()) {
6420 case Instruction::Add:
6421 case Instruction::Sub:
6422 case Instruction::And:
6423 case Instruction::Or:
6424 case Instruction::Xor:
6425 case Instruction::AShr:
6426 case Instruction::LShr:
6427 case Instruction::Shl: {
6428 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
6429 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6430 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6431 LHS, RHS, I->getName());
6432 break;
6433 }
6434 case Instruction::Trunc:
6435 case Instruction::ZExt:
6436 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006437 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00006438 // just return the source. There's no need to insert it because it is not
6439 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006440 if (I->getOperand(0)->getType() == Ty)
6441 return I->getOperand(0);
6442
Chris Lattneref70bb82007-08-02 06:11:14 +00006443 // Otherwise, must be the same type of case, so just reinsert a new one.
6444 Res = CastInst::create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
6445 Ty, I->getName());
6446 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006447 default:
6448 // TODO: Can handle more cases here.
6449 assert(0 && "Unreachable!");
6450 break;
6451 }
6452
6453 return InsertNewInstBefore(Res, *I);
6454}
6455
6456/// @brief Implement the transforms common to all CastInst visitors.
6457Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
6458 Value *Src = CI.getOperand(0);
6459
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006460 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
6461 // eliminate it now.
6462 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
6463 if (Instruction::CastOps opc =
6464 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6465 // The first cast (CSrc) is eliminable so we need to fix up or replace
6466 // the second cast (CI). CSrc will then have a good chance of being dead.
6467 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
6468 }
6469 }
6470
6471 // If we are casting a select then fold the cast into the select
6472 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6473 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6474 return NV;
6475
6476 // If we are casting a PHI then fold the cast into the PHI
6477 if (isa<PHINode>(Src))
6478 if (Instruction *NV = FoldOpIntoPhi(CI))
6479 return NV;
6480
6481 return 0;
6482}
6483
6484/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
6485Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
6486 Value *Src = CI.getOperand(0);
6487
6488 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
6489 // If casting the result of a getelementptr instruction with no offset, turn
6490 // this into a cast of the original pointer!
6491 if (GEP->hasAllZeroIndices()) {
6492 // Changing the cast operand is usually not a good idea but it is safe
6493 // here because the pointer operand is being replaced with another
6494 // pointer operand so the opcode doesn't need to change.
6495 AddToWorkList(GEP);
6496 CI.setOperand(0, GEP->getOperand(0));
6497 return &CI;
6498 }
6499
6500 // If the GEP has a single use, and the base pointer is a bitcast, and the
6501 // GEP computes a constant offset, see if we can convert these three
6502 // instructions into fewer. This typically happens with unions and other
6503 // non-type-safe code.
6504 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
6505 if (GEP->hasAllConstantIndices()) {
6506 // We are guaranteed to get a constant from EmitGEPOffset.
6507 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
6508 int64_t Offset = OffsetV->getSExtValue();
6509
6510 // Get the base pointer input of the bitcast, and the type it points to.
6511 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
6512 const Type *GEPIdxTy =
6513 cast<PointerType>(OrigBase->getType())->getElementType();
6514 if (GEPIdxTy->isSized()) {
6515 SmallVector<Value*, 8> NewIndices;
6516
6517 // Start with the index over the outer type. Note that the type size
6518 // might be zero (even if the offset isn't zero) if the indexed type
6519 // is something like [0 x {int, int}]
6520 const Type *IntPtrTy = TD->getIntPtrType();
6521 int64_t FirstIdx = 0;
6522 if (int64_t TySize = TD->getTypeSize(GEPIdxTy)) {
6523 FirstIdx = Offset/TySize;
6524 Offset %= TySize;
6525
6526 // Handle silly modulus not returning values values [0..TySize).
6527 if (Offset < 0) {
6528 --FirstIdx;
6529 Offset += TySize;
6530 assert(Offset >= 0);
6531 }
6532 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
6533 }
6534
6535 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
6536
6537 // Index into the types. If we fail, set OrigBase to null.
6538 while (Offset) {
6539 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
6540 const StructLayout *SL = TD->getStructLayout(STy);
6541 if (Offset < (int64_t)SL->getSizeInBytes()) {
6542 unsigned Elt = SL->getElementContainingOffset(Offset);
6543 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
6544
6545 Offset -= SL->getElementOffset(Elt);
6546 GEPIdxTy = STy->getElementType(Elt);
6547 } else {
6548 // Otherwise, we can't index into this, bail out.
6549 Offset = 0;
6550 OrigBase = 0;
6551 }
6552 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
6553 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
6554 if (uint64_t EltSize = TD->getTypeSize(STy->getElementType())) {
6555 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
6556 Offset %= EltSize;
6557 } else {
6558 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
6559 }
6560 GEPIdxTy = STy->getElementType();
6561 } else {
6562 // Otherwise, we can't index into this, bail out.
6563 Offset = 0;
6564 OrigBase = 0;
6565 }
6566 }
6567 if (OrigBase) {
6568 // If we were able to index down into an element, create the GEP
6569 // and bitcast the result. This eliminates one bitcast, potentially
6570 // two.
David Greene393be882007-09-04 15:46:09 +00006571 Instruction *NGEP = new GetElementPtrInst(OrigBase,
6572 NewIndices.begin(),
6573 NewIndices.end(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006574 InsertNewInstBefore(NGEP, CI);
6575 NGEP->takeName(GEP);
6576
6577 if (isa<BitCastInst>(CI))
6578 return new BitCastInst(NGEP, CI.getType());
6579 assert(isa<PtrToIntInst>(CI));
6580 return new PtrToIntInst(NGEP, CI.getType());
6581 }
6582 }
6583 }
6584 }
6585 }
6586
6587 return commonCastTransforms(CI);
6588}
6589
6590
6591
6592/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6593/// integer types. This function implements the common transforms for all those
6594/// cases.
6595/// @brief Implement the transforms common to CastInst with integer operands
6596Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6597 if (Instruction *Result = commonCastTransforms(CI))
6598 return Result;
6599
6600 Value *Src = CI.getOperand(0);
6601 const Type *SrcTy = Src->getType();
6602 const Type *DestTy = CI.getType();
6603 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6604 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
6605
6606 // See if we can simplify any instructions used by the LHS whose sole
6607 // purpose is to compute bits we don't care about.
6608 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6609 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
6610 KnownZero, KnownOne))
6611 return &CI;
6612
6613 // If the source isn't an instruction or has more than one use then we
6614 // can't do anything more.
6615 Instruction *SrcI = dyn_cast<Instruction>(Src);
6616 if (!SrcI || !Src->hasOneUse())
6617 return 0;
6618
6619 // Attempt to propagate the cast into the instruction for int->int casts.
6620 int NumCastsRemoved = 0;
6621 if (!isa<BitCastInst>(CI) &&
6622 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattneref70bb82007-08-02 06:11:14 +00006623 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006624 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00006625 // eliminates the cast, so it is always a win. If this is a zero-extension,
6626 // we need to do an AND to maintain the clear top-part of the computation,
6627 // so we require that the input have eliminated at least one cast. If this
6628 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006629 // require that two casts have been eliminated.
6630 bool DoXForm;
6631 switch (CI.getOpcode()) {
6632 default:
6633 // All the others use floating point so we shouldn't actually
6634 // get here because of the check above.
6635 assert(0 && "Unknown cast type");
6636 case Instruction::Trunc:
6637 DoXForm = true;
6638 break;
6639 case Instruction::ZExt:
6640 DoXForm = NumCastsRemoved >= 1;
6641 break;
6642 case Instruction::SExt:
6643 DoXForm = NumCastsRemoved >= 2;
6644 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006645 }
6646
6647 if (DoXForm) {
6648 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6649 CI.getOpcode() == Instruction::SExt);
6650 assert(Res->getType() == DestTy);
6651 switch (CI.getOpcode()) {
6652 default: assert(0 && "Unknown cast type!");
6653 case Instruction::Trunc:
6654 case Instruction::BitCast:
6655 // Just replace this cast with the result.
6656 return ReplaceInstUsesWith(CI, Res);
6657 case Instruction::ZExt: {
6658 // We need to emit an AND to clear the high bits.
6659 assert(SrcBitSize < DestBitSize && "Not a zext?");
6660 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
6661 SrcBitSize));
6662 return BinaryOperator::createAnd(Res, C);
6663 }
6664 case Instruction::SExt:
6665 // We need to emit a cast to truncate, then a cast to sext.
6666 return CastInst::create(Instruction::SExt,
6667 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6668 CI), DestTy);
6669 }
6670 }
6671 }
6672
6673 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6674 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6675
6676 switch (SrcI->getOpcode()) {
6677 case Instruction::Add:
6678 case Instruction::Mul:
6679 case Instruction::And:
6680 case Instruction::Or:
6681 case Instruction::Xor:
6682 // If we are discarding information, rewrite.
6683 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6684 // Don't insert two casts if they cannot be eliminated. We allow
6685 // two casts to be inserted if the sizes are the same. This could
6686 // only be converting signedness, which is a noop.
6687 if (DestBitSize == SrcBitSize ||
6688 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6689 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6690 Instruction::CastOps opcode = CI.getOpcode();
6691 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6692 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6693 return BinaryOperator::create(
6694 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6695 }
6696 }
6697
6698 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6699 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6700 SrcI->getOpcode() == Instruction::Xor &&
6701 Op1 == ConstantInt::getTrue() &&
6702 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
6703 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
6704 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6705 }
6706 break;
6707 case Instruction::SDiv:
6708 case Instruction::UDiv:
6709 case Instruction::SRem:
6710 case Instruction::URem:
6711 // If we are just changing the sign, rewrite.
6712 if (DestBitSize == SrcBitSize) {
6713 // Don't insert two casts if they cannot be eliminated. We allow
6714 // two casts to be inserted if the sizes are the same. This could
6715 // only be converting signedness, which is a noop.
6716 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6717 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6718 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6719 Op0, DestTy, SrcI);
6720 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6721 Op1, DestTy, SrcI);
6722 return BinaryOperator::create(
6723 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6724 }
6725 }
6726 break;
6727
6728 case Instruction::Shl:
6729 // Allow changing the sign of the source operand. Do not allow
6730 // changing the size of the shift, UNLESS the shift amount is a
6731 // constant. We must not change variable sized shifts to a smaller
6732 // size, because it is undefined to shift more bits out than exist
6733 // in the value.
6734 if (DestBitSize == SrcBitSize ||
6735 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
6736 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6737 Instruction::BitCast : Instruction::Trunc);
6738 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6739 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6740 return BinaryOperator::createShl(Op0c, Op1c);
6741 }
6742 break;
6743 case Instruction::AShr:
6744 // If this is a signed shr, and if all bits shifted in are about to be
6745 // truncated off, turn it into an unsigned shr to allow greater
6746 // simplifications.
6747 if (DestBitSize < SrcBitSize &&
6748 isa<ConstantInt>(Op1)) {
6749 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
6750 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6751 // Insert the new logical shift right.
6752 return BinaryOperator::createLShr(Op0, Op1);
6753 }
6754 }
6755 break;
6756 }
6757 return 0;
6758}
6759
6760Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
6761 if (Instruction *Result = commonIntCastTransforms(CI))
6762 return Result;
6763
6764 Value *Src = CI.getOperand(0);
6765 const Type *Ty = CI.getType();
6766 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
6767 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
6768
6769 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6770 switch (SrcI->getOpcode()) {
6771 default: break;
6772 case Instruction::LShr:
6773 // We can shrink lshr to something smaller if we know the bits shifted in
6774 // are already zeros.
6775 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6776 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
6777
6778 // Get a mask for the bits shifting in.
6779 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
6780 Value* SrcIOp0 = SrcI->getOperand(0);
6781 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
6782 if (ShAmt >= DestBitWidth) // All zeros.
6783 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6784
6785 // Okay, we can shrink this. Truncate the input, then return a new
6786 // shift.
6787 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6788 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
6789 Ty, CI);
6790 return BinaryOperator::createLShr(V1, V2);
6791 }
6792 } else { // This is a variable shr.
6793
6794 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6795 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6796 // loop-invariant and CSE'd.
6797 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
6798 Value *One = ConstantInt::get(SrcI->getType(), 1);
6799
6800 Value *V = InsertNewInstBefore(
6801 BinaryOperator::createShl(One, SrcI->getOperand(1),
6802 "tmp"), CI);
6803 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6804 SrcI->getOperand(0),
6805 "tmp"), CI);
6806 Value *Zero = Constant::getNullValue(V->getType());
6807 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
6808 }
6809 }
6810 break;
6811 }
6812 }
6813
6814 return 0;
6815}
6816
6817Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
6818 // If one of the common conversion will work ..
6819 if (Instruction *Result = commonIntCastTransforms(CI))
6820 return Result;
6821
6822 Value *Src = CI.getOperand(0);
6823
6824 // If this is a cast of a cast
6825 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
6826 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6827 // types and if the sizes are just right we can convert this into a logical
6828 // 'and' which will be much cheaper than the pair of casts.
6829 if (isa<TruncInst>(CSrc)) {
6830 // Get the sizes of the types involved
6831 Value *A = CSrc->getOperand(0);
6832 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
6833 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6834 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
6835 // If we're actually extending zero bits and the trunc is a no-op
6836 if (MidSize < DstSize && SrcSize == DstSize) {
6837 // Replace both of the casts with an And of the type mask.
6838 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
6839 Constant *AndConst = ConstantInt::get(AndValue);
6840 Instruction *And =
6841 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
6842 // Unfortunately, if the type changed, we need to cast it back.
6843 if (And->getType() != CI.getType()) {
6844 And->setName(CSrc->getName()+".mask");
6845 InsertNewInstBefore(And, CI);
6846 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
6847 }
6848 return And;
6849 }
6850 }
6851 }
6852
6853 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
6854 // If we are just checking for a icmp eq of a single bit and zext'ing it
6855 // to an integer, then shift the bit to the appropriate place and then
6856 // cast to integer to avoid the comparison.
6857 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
6858 const APInt &Op1CV = Op1C->getValue();
6859
6860 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
6861 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
6862 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
6863 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
6864 Value *In = ICI->getOperand(0);
6865 Value *Sh = ConstantInt::get(In->getType(),
6866 In->getType()->getPrimitiveSizeInBits()-1);
6867 In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
6868 In->getName()+".lobit"),
6869 CI);
6870 if (In->getType() != CI.getType())
6871 In = CastInst::createIntegerCast(In, CI.getType(),
6872 false/*ZExt*/, "tmp", &CI);
6873
6874 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
6875 Constant *One = ConstantInt::get(In->getType(), 1);
6876 In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
6877 In->getName()+".not"),
6878 CI);
6879 }
6880
6881 return ReplaceInstUsesWith(CI, In);
6882 }
6883
6884
6885
6886 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
6887 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
6888 // zext (X == 1) to i32 --> X iff X has only the low bit set.
6889 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
6890 // zext (X != 0) to i32 --> X iff X has only the low bit set.
6891 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
6892 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
6893 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
6894 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
6895 // This only works for EQ and NE
6896 ICI->isEquality()) {
6897 // If Op1C some other power of two, convert:
6898 uint32_t BitWidth = Op1C->getType()->getBitWidth();
6899 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
6900 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
6901 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
6902
6903 APInt KnownZeroMask(~KnownZero);
6904 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
6905 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
6906 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
6907 // (X&4) == 2 --> false
6908 // (X&4) != 2 --> true
6909 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
6910 Res = ConstantExpr::getZExt(Res, CI.getType());
6911 return ReplaceInstUsesWith(CI, Res);
6912 }
6913
6914 uint32_t ShiftAmt = KnownZeroMask.logBase2();
6915 Value *In = ICI->getOperand(0);
6916 if (ShiftAmt) {
6917 // Perform a logical shr by shiftamt.
6918 // Insert the shift to put the result in the low bit.
6919 In = InsertNewInstBefore(
6920 BinaryOperator::createLShr(In,
6921 ConstantInt::get(In->getType(), ShiftAmt),
6922 In->getName()+".lobit"), CI);
6923 }
6924
6925 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
6926 Constant *One = ConstantInt::get(In->getType(), 1);
6927 In = BinaryOperator::createXor(In, One, "tmp");
6928 InsertNewInstBefore(cast<Instruction>(In), CI);
6929 }
6930
6931 if (CI.getType() == In->getType())
6932 return ReplaceInstUsesWith(CI, In);
6933 else
6934 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
6935 }
6936 }
6937 }
6938 }
6939 return 0;
6940}
6941
6942Instruction *InstCombiner::visitSExt(SExtInst &CI) {
6943 if (Instruction *I = commonIntCastTransforms(CI))
6944 return I;
6945
6946 Value *Src = CI.getOperand(0);
6947
6948 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
6949 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
6950 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
6951 // If we are just checking for a icmp eq of a single bit and zext'ing it
6952 // to an integer, then shift the bit to the appropriate place and then
6953 // cast to integer to avoid the comparison.
6954 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
6955 const APInt &Op1CV = Op1C->getValue();
6956
6957 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
6958 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
6959 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
6960 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
6961 Value *In = ICI->getOperand(0);
6962 Value *Sh = ConstantInt::get(In->getType(),
6963 In->getType()->getPrimitiveSizeInBits()-1);
6964 In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
6965 In->getName()+".lobit"),
6966 CI);
6967 if (In->getType() != CI.getType())
6968 In = CastInst::createIntegerCast(In, CI.getType(),
6969 true/*SExt*/, "tmp", &CI);
6970
6971 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
6972 In = InsertNewInstBefore(BinaryOperator::createNot(In,
6973 In->getName()+".not"), CI);
6974
6975 return ReplaceInstUsesWith(CI, In);
6976 }
6977 }
6978 }
6979
6980 return 0;
6981}
6982
6983Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
6984 return commonCastTransforms(CI);
6985}
6986
6987Instruction *InstCombiner::visitFPExt(CastInst &CI) {
6988 return commonCastTransforms(CI);
6989}
6990
6991Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
6992 return commonCastTransforms(CI);
6993}
6994
6995Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
6996 return commonCastTransforms(CI);
6997}
6998
6999Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7000 return commonCastTransforms(CI);
7001}
7002
7003Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7004 return commonCastTransforms(CI);
7005}
7006
7007Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7008 return commonPointerCastTransforms(CI);
7009}
7010
7011Instruction *InstCombiner::visitIntToPtr(CastInst &CI) {
7012 return commonCastTransforms(CI);
7013}
7014
7015Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
7016 // If the operands are integer typed then apply the integer transforms,
7017 // otherwise just apply the common ones.
7018 Value *Src = CI.getOperand(0);
7019 const Type *SrcTy = Src->getType();
7020 const Type *DestTy = CI.getType();
7021
7022 if (SrcTy->isInteger() && DestTy->isInteger()) {
7023 if (Instruction *Result = commonIntCastTransforms(CI))
7024 return Result;
7025 } else if (isa<PointerType>(SrcTy)) {
7026 if (Instruction *I = commonPointerCastTransforms(CI))
7027 return I;
7028 } else {
7029 if (Instruction *Result = commonCastTransforms(CI))
7030 return Result;
7031 }
7032
7033
7034 // Get rid of casts from one type to the same type. These are useless and can
7035 // be replaced by the operand.
7036 if (DestTy == Src->getType())
7037 return ReplaceInstUsesWith(CI, Src);
7038
7039 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7040 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7041 const Type *DstElTy = DstPTy->getElementType();
7042 const Type *SrcElTy = SrcPTy->getElementType();
7043
7044 // If we are casting a malloc or alloca to a pointer to a type of the same
7045 // size, rewrite the allocation instruction to allocate the "right" type.
7046 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7047 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7048 return V;
7049
7050 // If the source and destination are pointers, and this cast is equivalent
7051 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
7052 // This can enhance SROA and other transforms that want type-safe pointers.
7053 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7054 unsigned NumZeros = 0;
7055 while (SrcElTy != DstElTy &&
7056 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7057 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7058 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7059 ++NumZeros;
7060 }
7061
7062 // If we found a path from the src to dest, create the getelementptr now.
7063 if (SrcElTy == DstElTy) {
7064 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Chuck Rose III27d49792007-09-05 20:36:41 +00007065 return new GetElementPtrInst(Src, Idxs.begin(), Idxs.end(), "",
7066 ((Instruction*) NULL));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007067 }
7068 }
7069
7070 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7071 if (SVI->hasOneUse()) {
7072 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7073 // a bitconvert to a vector with the same # elts.
7074 if (isa<VectorType>(DestTy) &&
7075 cast<VectorType>(DestTy)->getNumElements() ==
7076 SVI->getType()->getNumElements()) {
7077 CastInst *Tmp;
7078 // If either of the operands is a cast from CI.getType(), then
7079 // evaluating the shuffle in the casted destination's type will allow
7080 // us to eliminate at least one cast.
7081 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7082 Tmp->getOperand(0)->getType() == DestTy) ||
7083 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7084 Tmp->getOperand(0)->getType() == DestTy)) {
7085 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7086 SVI->getOperand(0), DestTy, &CI);
7087 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7088 SVI->getOperand(1), DestTy, &CI);
7089 // Return a new shuffle vector. Use the same element ID's, as we
7090 // know the vector types match #elts.
7091 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
7092 }
7093 }
7094 }
7095 }
7096 return 0;
7097}
7098
7099/// GetSelectFoldableOperands - We want to turn code that looks like this:
7100/// %C = or %A, %B
7101/// %D = select %cond, %C, %A
7102/// into:
7103/// %C = select %cond, %B, 0
7104/// %D = or %A, %C
7105///
7106/// Assuming that the specified instruction is an operand to the select, return
7107/// a bitmask indicating which operands of this instruction are foldable if they
7108/// equal the other incoming value of the select.
7109///
7110static unsigned GetSelectFoldableOperands(Instruction *I) {
7111 switch (I->getOpcode()) {
7112 case Instruction::Add:
7113 case Instruction::Mul:
7114 case Instruction::And:
7115 case Instruction::Or:
7116 case Instruction::Xor:
7117 return 3; // Can fold through either operand.
7118 case Instruction::Sub: // Can only fold on the amount subtracted.
7119 case Instruction::Shl: // Can only fold on the shift amount.
7120 case Instruction::LShr:
7121 case Instruction::AShr:
7122 return 1;
7123 default:
7124 return 0; // Cannot fold
7125 }
7126}
7127
7128/// GetSelectFoldableConstant - For the same transformation as the previous
7129/// function, return the identity constant that goes into the select.
7130static Constant *GetSelectFoldableConstant(Instruction *I) {
7131 switch (I->getOpcode()) {
7132 default: assert(0 && "This cannot happen!"); abort();
7133 case Instruction::Add:
7134 case Instruction::Sub:
7135 case Instruction::Or:
7136 case Instruction::Xor:
7137 case Instruction::Shl:
7138 case Instruction::LShr:
7139 case Instruction::AShr:
7140 return Constant::getNullValue(I->getType());
7141 case Instruction::And:
7142 return Constant::getAllOnesValue(I->getType());
7143 case Instruction::Mul:
7144 return ConstantInt::get(I->getType(), 1);
7145 }
7146}
7147
7148/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7149/// have the same opcode and only one use each. Try to simplify this.
7150Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7151 Instruction *FI) {
7152 if (TI->getNumOperands() == 1) {
7153 // If this is a non-volatile load or a cast from the same type,
7154 // merge.
7155 if (TI->isCast()) {
7156 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7157 return 0;
7158 } else {
7159 return 0; // unknown unary op.
7160 }
7161
7162 // Fold this by inserting a select from the input values.
7163 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7164 FI->getOperand(0), SI.getName()+".v");
7165 InsertNewInstBefore(NewSI, SI);
7166 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
7167 TI->getType());
7168 }
7169
7170 // Only handle binary operators here.
7171 if (!isa<BinaryOperator>(TI))
7172 return 0;
7173
7174 // Figure out if the operations have any operands in common.
7175 Value *MatchOp, *OtherOpT, *OtherOpF;
7176 bool MatchIsOpZero;
7177 if (TI->getOperand(0) == FI->getOperand(0)) {
7178 MatchOp = TI->getOperand(0);
7179 OtherOpT = TI->getOperand(1);
7180 OtherOpF = FI->getOperand(1);
7181 MatchIsOpZero = true;
7182 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7183 MatchOp = TI->getOperand(1);
7184 OtherOpT = TI->getOperand(0);
7185 OtherOpF = FI->getOperand(0);
7186 MatchIsOpZero = false;
7187 } else if (!TI->isCommutative()) {
7188 return 0;
7189 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7190 MatchOp = TI->getOperand(0);
7191 OtherOpT = TI->getOperand(1);
7192 OtherOpF = FI->getOperand(0);
7193 MatchIsOpZero = true;
7194 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7195 MatchOp = TI->getOperand(1);
7196 OtherOpT = TI->getOperand(0);
7197 OtherOpF = FI->getOperand(1);
7198 MatchIsOpZero = true;
7199 } else {
7200 return 0;
7201 }
7202
7203 // If we reach here, they do have operations in common.
7204 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7205 OtherOpF, SI.getName()+".v");
7206 InsertNewInstBefore(NewSI, SI);
7207
7208 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7209 if (MatchIsOpZero)
7210 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7211 else
7212 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
7213 }
7214 assert(0 && "Shouldn't get here");
7215 return 0;
7216}
7217
7218Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
7219 Value *CondVal = SI.getCondition();
7220 Value *TrueVal = SI.getTrueValue();
7221 Value *FalseVal = SI.getFalseValue();
7222
7223 // select true, X, Y -> X
7224 // select false, X, Y -> Y
7225 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
7226 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
7227
7228 // select C, X, X -> X
7229 if (TrueVal == FalseVal)
7230 return ReplaceInstUsesWith(SI, TrueVal);
7231
7232 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7233 return ReplaceInstUsesWith(SI, FalseVal);
7234 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7235 return ReplaceInstUsesWith(SI, TrueVal);
7236 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7237 if (isa<Constant>(TrueVal))
7238 return ReplaceInstUsesWith(SI, TrueVal);
7239 else
7240 return ReplaceInstUsesWith(SI, FalseVal);
7241 }
7242
7243 if (SI.getType() == Type::Int1Ty) {
7244 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
7245 if (C->getZExtValue()) {
7246 // Change: A = select B, true, C --> A = or B, C
7247 return BinaryOperator::createOr(CondVal, FalseVal);
7248 } else {
7249 // Change: A = select B, false, C --> A = and !B, C
7250 Value *NotCond =
7251 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7252 "not."+CondVal->getName()), SI);
7253 return BinaryOperator::createAnd(NotCond, FalseVal);
7254 }
7255 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
7256 if (C->getZExtValue() == false) {
7257 // Change: A = select B, C, false --> A = and B, C
7258 return BinaryOperator::createAnd(CondVal, TrueVal);
7259 } else {
7260 // Change: A = select B, C, true --> A = or !B, C
7261 Value *NotCond =
7262 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7263 "not."+CondVal->getName()), SI);
7264 return BinaryOperator::createOr(NotCond, TrueVal);
7265 }
7266 }
7267 }
7268
7269 // Selecting between two integer constants?
7270 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7271 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
7272 // select C, 1, 0 -> zext C to int
7273 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
7274 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
7275 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
7276 // select C, 0, 1 -> zext !C to int
7277 Value *NotCond =
7278 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7279 "not."+CondVal->getName()), SI);
7280 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
7281 }
7282
7283 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
7284
7285 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
7286
7287 // (x <s 0) ? -1 : 0 -> ashr x, 31
7288 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
7289 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
7290 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
7291 // The comparison constant and the result are not neccessarily the
7292 // same width. Make an all-ones value by inserting a AShr.
7293 Value *X = IC->getOperand(0);
7294 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
7295 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7296 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7297 ShAmt, "ones");
7298 InsertNewInstBefore(SRA, SI);
7299
7300 // Finally, convert to the type of the select RHS. We figure out
7301 // if this requires a SExt, Trunc or BitCast based on the sizes.
7302 Instruction::CastOps opc = Instruction::BitCast;
7303 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
7304 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
7305 if (SRASize < SISize)
7306 opc = Instruction::SExt;
7307 else if (SRASize > SISize)
7308 opc = Instruction::Trunc;
7309 return CastInst::create(opc, SRA, SI.getType());
7310 }
7311 }
7312
7313
7314 // If one of the constants is zero (we know they can't both be) and we
7315 // have an icmp instruction with zero, and we have an 'and' with the
7316 // non-constant value, eliminate this whole mess. This corresponds to
7317 // cases like this: ((X & 27) ? 27 : 0)
7318 if (TrueValC->isZero() || FalseValC->isZero())
7319 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
7320 cast<Constant>(IC->getOperand(1))->isNullValue())
7321 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7322 if (ICA->getOpcode() == Instruction::And &&
7323 isa<ConstantInt>(ICA->getOperand(1)) &&
7324 (ICA->getOperand(1) == TrueValC ||
7325 ICA->getOperand(1) == FalseValC) &&
7326 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7327 // Okay, now we know that everything is set up, we just don't
7328 // know whether we have a icmp_ne or icmp_eq and whether the
7329 // true or false val is the zero.
7330 bool ShouldNotVal = !TrueValC->isZero();
7331 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
7332 Value *V = ICA;
7333 if (ShouldNotVal)
7334 V = InsertNewInstBefore(BinaryOperator::create(
7335 Instruction::Xor, V, ICA->getOperand(1)), SI);
7336 return ReplaceInstUsesWith(SI, V);
7337 }
7338 }
7339 }
7340
7341 // See if we are selecting two values based on a comparison of the two values.
7342 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7343 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
7344 // Transform (X == Y) ? X : Y -> Y
7345 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
7346 return ReplaceInstUsesWith(SI, FalseVal);
7347 // Transform (X != Y) ? X : Y -> X
7348 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7349 return ReplaceInstUsesWith(SI, TrueVal);
7350 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7351
7352 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
7353 // Transform (X == Y) ? Y : X -> X
7354 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ)
7355 return ReplaceInstUsesWith(SI, FalseVal);
7356 // Transform (X != Y) ? Y : X -> Y
7357 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7358 return ReplaceInstUsesWith(SI, TrueVal);
7359 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7360 }
7361 }
7362
7363 // See if we are selecting two values based on a comparison of the two values.
7364 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7365 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7366 // Transform (X == Y) ? X : Y -> Y
7367 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7368 return ReplaceInstUsesWith(SI, FalseVal);
7369 // Transform (X != Y) ? X : Y -> X
7370 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7371 return ReplaceInstUsesWith(SI, TrueVal);
7372 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7373
7374 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7375 // Transform (X == Y) ? Y : X -> X
7376 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7377 return ReplaceInstUsesWith(SI, FalseVal);
7378 // Transform (X != Y) ? Y : X -> Y
7379 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7380 return ReplaceInstUsesWith(SI, TrueVal);
7381 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7382 }
7383 }
7384
7385 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7386 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7387 if (TI->hasOneUse() && FI->hasOneUse()) {
7388 Instruction *AddOp = 0, *SubOp = 0;
7389
7390 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7391 if (TI->getOpcode() == FI->getOpcode())
7392 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7393 return IV;
7394
7395 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
7396 // even legal for FP.
7397 if (TI->getOpcode() == Instruction::Sub &&
7398 FI->getOpcode() == Instruction::Add) {
7399 AddOp = FI; SubOp = TI;
7400 } else if (FI->getOpcode() == Instruction::Sub &&
7401 TI->getOpcode() == Instruction::Add) {
7402 AddOp = TI; SubOp = FI;
7403 }
7404
7405 if (AddOp) {
7406 Value *OtherAddOp = 0;
7407 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7408 OtherAddOp = AddOp->getOperand(1);
7409 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7410 OtherAddOp = AddOp->getOperand(0);
7411 }
7412
7413 if (OtherAddOp) {
7414 // So at this point we know we have (Y -> OtherAddOp):
7415 // select C, (add X, Y), (sub X, Z)
7416 Value *NegVal; // Compute -Z
7417 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7418 NegVal = ConstantExpr::getNeg(C);
7419 } else {
7420 NegVal = InsertNewInstBefore(
7421 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
7422 }
7423
7424 Value *NewTrueOp = OtherAddOp;
7425 Value *NewFalseOp = NegVal;
7426 if (AddOp != TI)
7427 std::swap(NewTrueOp, NewFalseOp);
7428 Instruction *NewSel =
7429 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7430
7431 NewSel = InsertNewInstBefore(NewSel, SI);
7432 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
7433 }
7434 }
7435 }
7436
7437 // See if we can fold the select into one of our operands.
7438 if (SI.getType()->isInteger()) {
7439 // See the comment above GetSelectFoldableOperands for a description of the
7440 // transformation we are doing here.
7441 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7442 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7443 !isa<Constant>(FalseVal))
7444 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7445 unsigned OpToFold = 0;
7446 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7447 OpToFold = 1;
7448 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7449 OpToFold = 2;
7450 }
7451
7452 if (OpToFold) {
7453 Constant *C = GetSelectFoldableConstant(TVI);
7454 Instruction *NewSel =
7455 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
7456 InsertNewInstBefore(NewSel, SI);
7457 NewSel->takeName(TVI);
7458 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7459 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
7460 else {
7461 assert(0 && "Unknown instruction!!");
7462 }
7463 }
7464 }
7465
7466 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7467 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7468 !isa<Constant>(TrueVal))
7469 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7470 unsigned OpToFold = 0;
7471 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7472 OpToFold = 1;
7473 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7474 OpToFold = 2;
7475 }
7476
7477 if (OpToFold) {
7478 Constant *C = GetSelectFoldableConstant(FVI);
7479 Instruction *NewSel =
7480 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
7481 InsertNewInstBefore(NewSel, SI);
7482 NewSel->takeName(FVI);
7483 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7484 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
7485 else
7486 assert(0 && "Unknown instruction!!");
7487 }
7488 }
7489 }
7490
7491 if (BinaryOperator::isNot(CondVal)) {
7492 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7493 SI.setOperand(1, FalseVal);
7494 SI.setOperand(2, TrueVal);
7495 return &SI;
7496 }
7497
7498 return 0;
7499}
7500
Chris Lattner47cf3452007-08-09 19:05:49 +00007501/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
7502/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
7503/// and it is more than the alignment of the ultimate object, see if we can
7504/// increase the alignment of the ultimate object, making this check succeed.
7505static unsigned GetOrEnforceKnownAlignment(Value *V, TargetData *TD,
7506 unsigned PrefAlign = 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007507 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7508 unsigned Align = GV->getAlignment();
7509 if (Align == 0 && TD)
7510 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattner47cf3452007-08-09 19:05:49 +00007511
7512 // If there is a large requested alignment and we can, bump up the alignment
7513 // of the global.
7514 if (PrefAlign > Align && GV->hasInitializer()) {
7515 GV->setAlignment(PrefAlign);
7516 Align = PrefAlign;
7517 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007518 return Align;
7519 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7520 unsigned Align = AI->getAlignment();
7521 if (Align == 0 && TD) {
7522 if (isa<AllocaInst>(AI))
7523 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
7524 else if (isa<MallocInst>(AI)) {
7525 // Malloc returns maximally aligned memory.
7526 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
7527 Align =
7528 std::max(Align,
7529 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
7530 Align =
7531 std::max(Align,
7532 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
7533 }
7534 }
Chris Lattner47cf3452007-08-09 19:05:49 +00007535
7536 // If there is a requested alignment and if this is an alloca, round up. We
7537 // don't do this for malloc, because some systems can't respect the request.
7538 if (PrefAlign > Align && isa<AllocaInst>(AI)) {
7539 AI->setAlignment(PrefAlign);
7540 Align = PrefAlign;
7541 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007542 return Align;
7543 } else if (isa<BitCastInst>(V) ||
7544 (isa<ConstantExpr>(V) &&
7545 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner47cf3452007-08-09 19:05:49 +00007546 return GetOrEnforceKnownAlignment(cast<User>(V)->getOperand(0),
7547 TD, PrefAlign);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007548 } else if (User *GEPI = dyn_castGetElementPtr(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007549 // If all indexes are zero, it is just the alignment of the base pointer.
7550 bool AllZeroOperands = true;
7551 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7552 if (!isa<Constant>(GEPI->getOperand(i)) ||
7553 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7554 AllZeroOperands = false;
7555 break;
7556 }
Chris Lattner47cf3452007-08-09 19:05:49 +00007557
7558 if (AllZeroOperands) {
7559 // Treat this like a bitcast.
7560 return GetOrEnforceKnownAlignment(GEPI->getOperand(0), TD, PrefAlign);
7561 }
7562
7563 unsigned BaseAlignment = GetOrEnforceKnownAlignment(GEPI->getOperand(0),TD);
7564 if (BaseAlignment == 0) return 0;
7565
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007566 // Otherwise, if the base alignment is >= the alignment we expect for the
7567 // base pointer type, then we know that the resultant pointer is aligned at
7568 // least as much as its type requires.
7569 if (!TD) return 0;
7570
7571 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
7572 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Lauro Ramos Venancio55da3352007-07-31 20:13:21 +00007573 unsigned Align = TD->getABITypeAlignment(PtrTy->getElementType());
7574 if (Align <= BaseAlignment) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007575 const Type *GEPTy = GEPI->getType();
7576 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Lauro Ramos Venancio55da3352007-07-31 20:13:21 +00007577 Align = std::min(Align, (unsigned)
7578 TD->getABITypeAlignment(GEPPtrTy->getElementType()));
7579 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007580 }
7581 return 0;
7582 }
7583 return 0;
7584}
7585
7586
7587/// visitCallInst - CallInst simplification. This mostly only handles folding
7588/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
7589/// the heavy lifting.
7590///
7591Instruction *InstCombiner::visitCallInst(CallInst &CI) {
7592 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7593 if (!II) return visitCallSite(&CI);
7594
7595 // Intrinsics cannot occur in an invoke, so handle them here instead of in
7596 // visitCallSite.
7597 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
7598 bool Changed = false;
7599
7600 // memmove/cpy/set of zero bytes is a noop.
7601 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7602 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7603
7604 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
7605 if (CI->getZExtValue() == 1) {
7606 // Replace the instruction with just byte operations. We would
7607 // transform other cases to loads/stores, but we don't know if
7608 // alignment is sufficient.
7609 }
7610 }
7611
7612 // If we have a memmove and the source operation is a constant global,
7613 // then the source and dest pointers can't alias, so we can change this
7614 // into a call to memcpy.
7615 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(II)) {
7616 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7617 if (GVSrc->isConstant()) {
7618 Module *M = CI.getParent()->getParent()->getParent();
7619 const char *Name;
7620 if (CI.getCalledFunction()->getFunctionType()->getParamType(2) ==
7621 Type::Int32Ty)
7622 Name = "llvm.memcpy.i32";
7623 else
7624 Name = "llvm.memcpy.i64";
7625 Constant *MemCpy = M->getOrInsertFunction(Name,
7626 CI.getCalledFunction()->getFunctionType());
7627 CI.setOperand(0, MemCpy);
7628 Changed = true;
7629 }
7630 }
7631
7632 // If we can determine a pointer alignment that is bigger than currently
7633 // set, update the alignment.
7634 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattner47cf3452007-08-09 19:05:49 +00007635 unsigned Alignment1 = GetOrEnforceKnownAlignment(MI->getOperand(1), TD);
7636 unsigned Alignment2 = GetOrEnforceKnownAlignment(MI->getOperand(2), TD);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007637 unsigned Align = std::min(Alignment1, Alignment2);
7638 if (MI->getAlignment()->getZExtValue() < Align) {
7639 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Align));
7640 Changed = true;
7641 }
7642 } else if (isa<MemSetInst>(MI)) {
Chris Lattner47cf3452007-08-09 19:05:49 +00007643 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest(), TD);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007644 if (MI->getAlignment()->getZExtValue() < Alignment) {
7645 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
7646 Changed = true;
7647 }
7648 }
7649
7650 if (Changed) return II;
7651 } else {
7652 switch (II->getIntrinsicID()) {
7653 default: break;
7654 case Intrinsic::ppc_altivec_lvx:
7655 case Intrinsic::ppc_altivec_lvxl:
7656 case Intrinsic::x86_sse_loadu_ps:
7657 case Intrinsic::x86_sse2_loadu_pd:
7658 case Intrinsic::x86_sse2_loadu_dq:
7659 // Turn PPC lvx -> load if the pointer is known aligned.
7660 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattner47cf3452007-08-09 19:05:49 +00007661 if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007662 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7663 PointerType::get(II->getType()), CI);
7664 return new LoadInst(Ptr);
7665 }
7666 break;
7667 case Intrinsic::ppc_altivec_stvx:
7668 case Intrinsic::ppc_altivec_stvxl:
7669 // Turn stvx -> store if the pointer is known aligned.
Chris Lattner47cf3452007-08-09 19:05:49 +00007670 if (GetOrEnforceKnownAlignment(II->getOperand(2), TD, 16) >= 16) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007671 const Type *OpPtrTy = PointerType::get(II->getOperand(1)->getType());
7672 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(2),
7673 OpPtrTy, CI);
7674 return new StoreInst(II->getOperand(1), Ptr);
7675 }
7676 break;
7677 case Intrinsic::x86_sse_storeu_ps:
7678 case Intrinsic::x86_sse2_storeu_pd:
7679 case Intrinsic::x86_sse2_storeu_dq:
7680 case Intrinsic::x86_sse2_storel_dq:
7681 // Turn X86 storeu -> store if the pointer is known aligned.
Chris Lattner47cf3452007-08-09 19:05:49 +00007682 if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007683 const Type *OpPtrTy = PointerType::get(II->getOperand(2)->getType());
7684 Value *Ptr = InsertCastBefore(Instruction::BitCast, II->getOperand(1),
7685 OpPtrTy, CI);
7686 return new StoreInst(II->getOperand(2), Ptr);
7687 }
7688 break;
7689
7690 case Intrinsic::x86_sse_cvttss2si: {
7691 // These intrinsics only demands the 0th element of its input vector. If
7692 // we can simplify the input based on that, do so now.
7693 uint64_t UndefElts;
7694 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7695 UndefElts)) {
7696 II->setOperand(1, V);
7697 return II;
7698 }
7699 break;
7700 }
7701
7702 case Intrinsic::ppc_altivec_vperm:
7703 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
7704 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
7705 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
7706
7707 // Check that all of the elements are integer constants or undefs.
7708 bool AllEltsOk = true;
7709 for (unsigned i = 0; i != 16; ++i) {
7710 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
7711 !isa<UndefValue>(Mask->getOperand(i))) {
7712 AllEltsOk = false;
7713 break;
7714 }
7715 }
7716
7717 if (AllEltsOk) {
7718 // Cast the input vectors to byte vectors.
7719 Value *Op0 = InsertCastBefore(Instruction::BitCast,
7720 II->getOperand(1), Mask->getType(), CI);
7721 Value *Op1 = InsertCastBefore(Instruction::BitCast,
7722 II->getOperand(2), Mask->getType(), CI);
7723 Value *Result = UndefValue::get(Op0->getType());
7724
7725 // Only extract each element once.
7726 Value *ExtractedElts[32];
7727 memset(ExtractedElts, 0, sizeof(ExtractedElts));
7728
7729 for (unsigned i = 0; i != 16; ++i) {
7730 if (isa<UndefValue>(Mask->getOperand(i)))
7731 continue;
7732 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
7733 Idx &= 31; // Match the hardware behavior.
7734
7735 if (ExtractedElts[Idx] == 0) {
7736 Instruction *Elt =
7737 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
7738 InsertNewInstBefore(Elt, CI);
7739 ExtractedElts[Idx] = Elt;
7740 }
7741
7742 // Insert this value into the result vector.
7743 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
7744 InsertNewInstBefore(cast<Instruction>(Result), CI);
7745 }
7746 return CastInst::create(Instruction::BitCast, Result, CI.getType());
7747 }
7748 }
7749 break;
7750
7751 case Intrinsic::stackrestore: {
7752 // If the save is right next to the restore, remove the restore. This can
7753 // happen when variable allocas are DCE'd.
7754 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
7755 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
7756 BasicBlock::iterator BI = SS;
7757 if (&*++BI == II)
7758 return EraseInstFromFunction(CI);
7759 }
7760 }
7761
7762 // If the stack restore is in a return/unwind block and if there are no
7763 // allocas or calls between the restore and the return, nuke the restore.
7764 TerminatorInst *TI = II->getParent()->getTerminator();
7765 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
7766 BasicBlock::iterator BI = II;
7767 bool CannotRemove = false;
7768 for (++BI; &*BI != TI; ++BI) {
7769 if (isa<AllocaInst>(BI) ||
7770 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
7771 CannotRemove = true;
7772 break;
7773 }
7774 }
7775 if (!CannotRemove)
7776 return EraseInstFromFunction(CI);
7777 }
7778 break;
7779 }
7780 }
7781 }
7782
7783 return visitCallSite(II);
7784}
7785
7786// InvokeInst simplification
7787//
7788Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
7789 return visitCallSite(&II);
7790}
7791
7792// visitCallSite - Improvements for call and invoke instructions.
7793//
7794Instruction *InstCombiner::visitCallSite(CallSite CS) {
7795 bool Changed = false;
7796
7797 // If the callee is a constexpr cast of a function, attempt to move the cast
7798 // to the arguments of the call/invoke.
7799 if (transformConstExprCastCall(CS)) return 0;
7800
7801 Value *Callee = CS.getCalledValue();
7802
7803 if (Function *CalleeF = dyn_cast<Function>(Callee))
7804 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
7805 Instruction *OldCall = CS.getInstruction();
7806 // If the call and callee calling conventions don't match, this call must
7807 // be unreachable, as the call is undefined.
7808 new StoreInst(ConstantInt::getTrue(),
7809 UndefValue::get(PointerType::get(Type::Int1Ty)), OldCall);
7810 if (!OldCall->use_empty())
7811 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
7812 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
7813 return EraseInstFromFunction(*OldCall);
7814 return 0;
7815 }
7816
7817 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
7818 // This instruction is not reachable, just remove it. We insert a store to
7819 // undef so that we know that this code is not reachable, despite the fact
7820 // that we can't modify the CFG here.
7821 new StoreInst(ConstantInt::getTrue(),
7822 UndefValue::get(PointerType::get(Type::Int1Ty)),
7823 CS.getInstruction());
7824
7825 if (!CS.getInstruction()->use_empty())
7826 CS.getInstruction()->
7827 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
7828
7829 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
7830 // Don't break the CFG, insert a dummy cond branch.
7831 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
7832 ConstantInt::getTrue(), II);
7833 }
7834 return EraseInstFromFunction(*CS.getInstruction());
7835 }
7836
7837 const PointerType *PTy = cast<PointerType>(Callee->getType());
7838 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
7839 if (FTy->isVarArg()) {
7840 // See if we can optimize any arguments passed through the varargs area of
7841 // the call.
7842 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
7843 E = CS.arg_end(); I != E; ++I)
7844 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
7845 // If this cast does not effect the value passed through the varargs
7846 // area, we can eliminate the use of the cast.
7847 Value *Op = CI->getOperand(0);
7848 if (CI->isLosslessCast()) {
7849 *I = Op;
7850 Changed = true;
7851 }
7852 }
7853 }
7854
Duncan Sandscf7ecaa2007-09-11 14:35:41 +00007855 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee)) {
7856 IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0));
7857 if (In && In->getIntrinsicID() == Intrinsic::init_trampoline) {
7858 Function *NestF =
7859 cast<Function>(IntrinsicInst::StripPointerCasts(In->getOperand(2)));
7860 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
7861 const FunctionType *NestFTy =
7862 cast<FunctionType>(NestFPTy->getElementType());
7863
7864 if (const ParamAttrsList *NestAttrs = NestFTy->getParamAttrs()) {
7865 unsigned NestIdx = 1;
7866 const Type *NestTy = 0;
Chris Lattner087ea3b2007-09-14 03:07:24 +00007867 uint16_t NestAttr = 0;
Duncan Sandscf7ecaa2007-09-11 14:35:41 +00007868
7869 Instruction *Caller = CS.getInstruction();
7870
7871 // Look for a parameter marked with the 'nest' attribute.
7872 for (FunctionType::param_iterator I = NestFTy->param_begin(),
7873 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
7874 if (NestAttrs->paramHasAttr(NestIdx, ParamAttr::Nest)) {
7875 // Record the parameter type and any other attributes.
7876 NestTy = *I;
7877 NestAttr = NestAttrs->getParamAttrs(NestIdx);
7878 break;
7879 }
7880
7881 if (NestTy) {
7882 std::vector<Value*> NewArgs;
7883 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
7884
7885 // Insert the nest argument into the call argument list, which may
7886 // mean appending it.
7887 {
7888 unsigned Idx = 1;
7889 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
7890 do {
7891 if (Idx == NestIdx) {
7892 // Add the chain argument.
7893 Value *NestVal = In->getOperand(3);
7894 if (NestVal->getType() != NestTy)
7895 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
7896 NewArgs.push_back(NestVal);
7897 }
7898
7899 if (I == E)
7900 break;
7901
7902 // Add the original argument.
7903 NewArgs.push_back(*I);
7904
7905 ++Idx, ++I;
7906 } while (1);
7907 }
7908
7909 // The trampoline may have been bitcast to a bogus type (FTy).
7910 // Handle this by synthesizing a new function type, equal to FTy
7911 // with the chain parameter inserted. Likewise for attributes.
7912
7913 const ParamAttrsList *Attrs = FTy->getParamAttrs();
7914 std::vector<const Type*> NewTypes;
7915 ParamAttrsVector NewAttrs;
7916 NewTypes.reserve(FTy->getNumParams()+1);
7917
7918 // Add any function result attributes.
7919 uint16_t Attr = Attrs ? Attrs->getParamAttrs(0) : 0;
7920 if (Attr)
7921 NewAttrs.push_back (ParamAttrsWithIndex::get(0, Attr));
7922
7923 // Insert the chain's type into the list of parameter types, which may
7924 // mean appending it. Likewise for the chain's attributes.
7925 {
7926 unsigned Idx = 1;
7927 FunctionType::param_iterator I = FTy->param_begin(),
7928 E = FTy->param_end();
7929
7930 do {
7931 if (Idx == NestIdx) {
7932 // Add the chain's type and attributes.
7933 NewTypes.push_back(NestTy);
7934 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
7935 }
7936
7937 if (I == E)
7938 break;
7939
7940 // Add the original type and attributes.
7941 NewTypes.push_back(*I);
7942 Attr = Attrs ? Attrs->getParamAttrs(Idx) : 0;
7943 if (Attr)
7944 NewAttrs.push_back
7945 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
7946
7947 ++Idx, ++I;
7948 } while (1);
7949 }
7950
7951 // Replace the trampoline call with a direct call. Let the generic
7952 // code sort out any function type mismatches.
7953 FunctionType *NewFTy =
7954 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg(),
7955 ParamAttrsList::get(NewAttrs));
7956 Constant *NewCallee = NestF->getType() == PointerType::get(NewFTy) ?
7957 NestF : ConstantExpr::getBitCast(NestF, PointerType::get(NewFTy));
7958
7959 Instruction *NewCaller;
7960 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
7961 NewCaller = new InvokeInst(NewCallee, II->getNormalDest(),
7962 II->getUnwindDest(), NewArgs.begin(),
7963 NewArgs.end(), Caller->getName(),
7964 Caller);
7965 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
7966 } else {
7967 NewCaller = new CallInst(NewCallee, NewArgs.begin(), NewArgs.end(),
7968 Caller->getName(), Caller);
7969 if (cast<CallInst>(Caller)->isTailCall())
7970 cast<CallInst>(NewCaller)->setTailCall();
7971 cast<CallInst>(NewCaller)->
7972 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
7973 }
7974 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
7975 Caller->replaceAllUsesWith(NewCaller);
7976 Caller->eraseFromParent();
7977 RemoveFromWorkList(Caller);
7978 return 0;
7979 }
7980 }
7981
7982 // Replace the trampoline call with a direct call. Since there is no
7983 // 'nest' parameter, there is no need to adjust the argument list. Let
7984 // the generic code sort out any function type mismatches.
7985 Constant *NewCallee = NestF->getType() == PTy ?
7986 NestF : ConstantExpr::getBitCast(NestF, PTy);
7987 CS.setCalledFunction(NewCallee);
7988 Changed = true;
7989 }
7990 }
7991
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007992 return Changed ? CS.getInstruction() : 0;
7993}
7994
7995// transformConstExprCastCall - If the callee is a constexpr cast of a function,
7996// attempt to move the cast to the arguments of the call/invoke.
7997//
7998bool InstCombiner::transformConstExprCastCall(CallSite CS) {
7999 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8000 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
8001 if (CE->getOpcode() != Instruction::BitCast ||
8002 !isa<Function>(CE->getOperand(0)))
8003 return false;
8004 Function *Callee = cast<Function>(CE->getOperand(0));
8005 Instruction *Caller = CS.getInstruction();
8006
8007 // Okay, this is a cast from a function to a different type. Unless doing so
8008 // would cause a type conversion of one of our arguments, change this call to
8009 // be a direct call with arguments casted to the appropriate types.
8010 //
8011 const FunctionType *FT = Callee->getFunctionType();
8012 const Type *OldRetTy = Caller->getType();
8013
8014 const FunctionType *ActualFT =
8015 cast<FunctionType>(cast<PointerType>(CE->getType())->getElementType());
8016
8017 // If the parameter attributes don't match up, don't do the xform. We don't
8018 // want to lose an sret attribute or something.
8019 if (FT->getParamAttrs() != ActualFT->getParamAttrs())
8020 return false;
8021
8022 // Check to see if we are changing the return type...
8023 if (OldRetTy != FT->getReturnType()) {
8024 if (Callee->isDeclaration() && !Caller->use_empty() &&
8025 // Conversion is ok if changing from pointer to int of same size.
8026 !(isa<PointerType>(FT->getReturnType()) &&
8027 TD->getIntPtrType() == OldRetTy))
8028 return false; // Cannot transform this return value.
8029
8030 // If the callsite is an invoke instruction, and the return value is used by
8031 // a PHI node in a successor, we cannot change the return type of the call
8032 // because there is no place to put the cast instruction (without breaking
8033 // the critical edge). Bail out in this case.
8034 if (!Caller->use_empty())
8035 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8036 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8037 UI != E; ++UI)
8038 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8039 if (PN->getParent() == II->getNormalDest() ||
8040 PN->getParent() == II->getUnwindDest())
8041 return false;
8042 }
8043
8044 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8045 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
8046
8047 CallSite::arg_iterator AI = CS.arg_begin();
8048 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8049 const Type *ParamTy = FT->getParamType(i);
8050 const Type *ActTy = (*AI)->getType();
8051 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
8052 //Some conversions are safe even if we do not have a body.
8053 //Either we can cast directly, or we can upconvert the argument
8054 bool isConvertible = ActTy == ParamTy ||
8055 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
8056 (ParamTy->isInteger() && ActTy->isInteger() &&
8057 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8058 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
8059 && c->getValue().isStrictlyPositive());
8060 if (Callee->isDeclaration() && !isConvertible) return false;
8061
8062 // Most other conversions can be done if we have a body, even if these
8063 // lose information, e.g. int->short.
8064 // Some conversions cannot be done at all, e.g. float to pointer.
8065 // Logic here parallels CastInst::getCastOpcode (the design there
8066 // requires legality checks like this be done before calling it).
8067 if (ParamTy->isInteger()) {
8068 if (const VectorType *VActTy = dyn_cast<VectorType>(ActTy)) {
8069 if (VActTy->getBitWidth() != ParamTy->getPrimitiveSizeInBits())
8070 return false;
8071 }
8072 if (!ActTy->isInteger() && !ActTy->isFloatingPoint() &&
8073 !isa<PointerType>(ActTy))
8074 return false;
8075 } else if (ParamTy->isFloatingPoint()) {
8076 if (const VectorType *VActTy = dyn_cast<VectorType>(ActTy)) {
8077 if (VActTy->getBitWidth() != ParamTy->getPrimitiveSizeInBits())
8078 return false;
8079 }
8080 if (!ActTy->isInteger() && !ActTy->isFloatingPoint())
8081 return false;
8082 } else if (const VectorType *VParamTy = dyn_cast<VectorType>(ParamTy)) {
8083 if (const VectorType *VActTy = dyn_cast<VectorType>(ActTy)) {
8084 if (VActTy->getBitWidth() != VParamTy->getBitWidth())
8085 return false;
8086 }
8087 if (VParamTy->getBitWidth() != ActTy->getPrimitiveSizeInBits())
8088 return false;
8089 } else if (isa<PointerType>(ParamTy)) {
8090 if (!ActTy->isInteger() && !isa<PointerType>(ActTy))
8091 return false;
8092 } else {
8093 return false;
8094 }
8095 }
8096
8097 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
8098 Callee->isDeclaration())
8099 return false; // Do not delete arguments unless we have a function body...
8100
8101 // Okay, we decided that this is a safe thing to do: go ahead and start
8102 // inserting cast instructions as necessary...
8103 std::vector<Value*> Args;
8104 Args.reserve(NumActualArgs);
8105
8106 AI = CS.arg_begin();
8107 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8108 const Type *ParamTy = FT->getParamType(i);
8109 if ((*AI)->getType() == ParamTy) {
8110 Args.push_back(*AI);
8111 } else {
8112 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
8113 false, ParamTy, false);
8114 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
8115 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
8116 }
8117 }
8118
8119 // If the function takes more arguments than the call was taking, add them
8120 // now...
8121 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8122 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8123
8124 // If we are removing arguments to the function, emit an obnoxious warning...
8125 if (FT->getNumParams() < NumActualArgs)
8126 if (!FT->isVarArg()) {
8127 cerr << "WARNING: While resolving call to function '"
8128 << Callee->getName() << "' arguments were dropped!\n";
8129 } else {
8130 // Add all of the arguments in their promoted form to the arg list...
8131 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8132 const Type *PTy = getPromotedType((*AI)->getType());
8133 if (PTy != (*AI)->getType()) {
8134 // Must promote to pass through va_arg area!
8135 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
8136 PTy, false);
8137 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
8138 InsertNewInstBefore(Cast, *Caller);
8139 Args.push_back(Cast);
8140 } else {
8141 Args.push_back(*AI);
8142 }
8143 }
8144 }
8145
8146 if (FT->getReturnType() == Type::VoidTy)
8147 Caller->setName(""); // Void type should not have a name.
8148
8149 Instruction *NC;
8150 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8151 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
David Greene8278ef52007-08-27 19:04:21 +00008152 Args.begin(), Args.end(), Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +00008153 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008154 } else {
Chris Lattner03dc7d72007-08-02 16:53:43 +00008155 NC = new CallInst(Callee, Args.begin(), Args.end(),
8156 Caller->getName(), Caller);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008157 if (cast<CallInst>(Caller)->isTailCall())
8158 cast<CallInst>(NC)->setTailCall();
8159 cast<CallInst>(NC)->setCallingConv(cast<CallInst>(Caller)->getCallingConv());
8160 }
8161
8162 // Insert a cast of the return type as necessary.
8163 Value *NV = NC;
8164 if (Caller->getType() != NV->getType() && !Caller->use_empty()) {
8165 if (NV->getType() != Type::VoidTy) {
8166 const Type *CallerTy = Caller->getType();
8167 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
8168 CallerTy, false);
8169 NV = NC = CastInst::create(opcode, NC, CallerTy, "tmp");
8170
8171 // If this is an invoke instruction, we should insert it after the first
8172 // non-phi, instruction in the normal successor block.
8173 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8174 BasicBlock::iterator I = II->getNormalDest()->begin();
8175 while (isa<PHINode>(I)) ++I;
8176 InsertNewInstBefore(NC, *I);
8177 } else {
8178 // Otherwise, it's a call, just insert cast right after the call instr
8179 InsertNewInstBefore(NC, *Caller);
8180 }
8181 AddUsersToWorkList(*Caller);
8182 } else {
8183 NV = UndefValue::get(Caller->getType());
8184 }
8185 }
8186
8187 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8188 Caller->replaceAllUsesWith(NV);
8189 Caller->eraseFromParent();
8190 RemoveFromWorkList(Caller);
8191 return true;
8192}
8193
8194/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
8195/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
8196/// and a single binop.
8197Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
8198 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8199 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
8200 isa<CmpInst>(FirstInst));
8201 unsigned Opc = FirstInst->getOpcode();
8202 Value *LHSVal = FirstInst->getOperand(0);
8203 Value *RHSVal = FirstInst->getOperand(1);
8204
8205 const Type *LHSType = LHSVal->getType();
8206 const Type *RHSType = RHSVal->getType();
8207
8208 // Scan to see if all operands are the same opcode, all have one use, and all
8209 // kill their operands (i.e. the operands have one use).
8210 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
8211 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
8212 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
8213 // Verify type of the LHS matches so we don't fold cmp's of different
8214 // types or GEP's with different index types.
8215 I->getOperand(0)->getType() != LHSType ||
8216 I->getOperand(1)->getType() != RHSType)
8217 return 0;
8218
8219 // If they are CmpInst instructions, check their predicates
8220 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
8221 if (cast<CmpInst>(I)->getPredicate() !=
8222 cast<CmpInst>(FirstInst)->getPredicate())
8223 return 0;
8224
8225 // Keep track of which operand needs a phi node.
8226 if (I->getOperand(0) != LHSVal) LHSVal = 0;
8227 if (I->getOperand(1) != RHSVal) RHSVal = 0;
8228 }
8229
8230 // Otherwise, this is safe to transform, determine if it is profitable.
8231
8232 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
8233 // Indexes are often folded into load/store instructions, so we don't want to
8234 // hide them behind a phi.
8235 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
8236 return 0;
8237
8238 Value *InLHS = FirstInst->getOperand(0);
8239 Value *InRHS = FirstInst->getOperand(1);
8240 PHINode *NewLHS = 0, *NewRHS = 0;
8241 if (LHSVal == 0) {
8242 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
8243 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
8244 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
8245 InsertNewInstBefore(NewLHS, PN);
8246 LHSVal = NewLHS;
8247 }
8248
8249 if (RHSVal == 0) {
8250 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
8251 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
8252 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
8253 InsertNewInstBefore(NewRHS, PN);
8254 RHSVal = NewRHS;
8255 }
8256
8257 // Add all operands to the new PHIs.
8258 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8259 if (NewLHS) {
8260 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8261 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
8262 }
8263 if (NewRHS) {
8264 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
8265 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
8266 }
8267 }
8268
8269 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
8270 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
8271 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8272 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
8273 RHSVal);
8274 else {
8275 assert(isa<GetElementPtrInst>(FirstInst));
8276 return new GetElementPtrInst(LHSVal, RHSVal);
8277 }
8278}
8279
8280/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
8281/// of the block that defines it. This means that it must be obvious the value
8282/// of the load is not changed from the point of the load to the end of the
8283/// block it is in.
8284///
8285/// Finally, it is safe, but not profitable, to sink a load targetting a
8286/// non-address-taken alloca. Doing so will cause us to not promote the alloca
8287/// to a register.
8288static bool isSafeToSinkLoad(LoadInst *L) {
8289 BasicBlock::iterator BBI = L, E = L->getParent()->end();
8290
8291 for (++BBI; BBI != E; ++BBI)
8292 if (BBI->mayWriteToMemory())
8293 return false;
8294
8295 // Check for non-address taken alloca. If not address-taken already, it isn't
8296 // profitable to do this xform.
8297 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
8298 bool isAddressTaken = false;
8299 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8300 UI != E; ++UI) {
8301 if (isa<LoadInst>(UI)) continue;
8302 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8303 // If storing TO the alloca, then the address isn't taken.
8304 if (SI->getOperand(1) == AI) continue;
8305 }
8306 isAddressTaken = true;
8307 break;
8308 }
8309
8310 if (!isAddressTaken)
8311 return false;
8312 }
8313
8314 return true;
8315}
8316
8317
8318// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
8319// operator and they all are only used by the PHI, PHI together their
8320// inputs, and do the operation once, to the result of the PHI.
8321Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
8322 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8323
8324 // Scan the instruction, looking for input operations that can be folded away.
8325 // If all input operands to the phi are the same instruction (e.g. a cast from
8326 // the same type or "+42") we can pull the operation through the PHI, reducing
8327 // code size and simplifying code.
8328 Constant *ConstantOp = 0;
8329 const Type *CastSrcTy = 0;
8330 bool isVolatile = false;
8331 if (isa<CastInst>(FirstInst)) {
8332 CastSrcTy = FirstInst->getOperand(0)->getType();
8333 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
8334 // Can fold binop, compare or shift here if the RHS is a constant,
8335 // otherwise call FoldPHIArgBinOpIntoPHI.
8336 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
8337 if (ConstantOp == 0)
8338 return FoldPHIArgBinOpIntoPHI(PN);
8339 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
8340 isVolatile = LI->isVolatile();
8341 // We can't sink the load if the loaded value could be modified between the
8342 // load and the PHI.
8343 if (LI->getParent() != PN.getIncomingBlock(0) ||
8344 !isSafeToSinkLoad(LI))
8345 return 0;
8346 } else if (isa<GetElementPtrInst>(FirstInst)) {
8347 if (FirstInst->getNumOperands() == 2)
8348 return FoldPHIArgBinOpIntoPHI(PN);
8349 // Can't handle general GEPs yet.
8350 return 0;
8351 } else {
8352 return 0; // Cannot fold this operation.
8353 }
8354
8355 // Check to see if all arguments are the same operation.
8356 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8357 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
8358 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
8359 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
8360 return 0;
8361 if (CastSrcTy) {
8362 if (I->getOperand(0)->getType() != CastSrcTy)
8363 return 0; // Cast operation must match.
8364 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8365 // We can't sink the load if the loaded value could be modified between
8366 // the load and the PHI.
8367 if (LI->isVolatile() != isVolatile ||
8368 LI->getParent() != PN.getIncomingBlock(i) ||
8369 !isSafeToSinkLoad(LI))
8370 return 0;
8371 } else if (I->getOperand(1) != ConstantOp) {
8372 return 0;
8373 }
8374 }
8375
8376 // Okay, they are all the same operation. Create a new PHI node of the
8377 // correct type, and PHI together all of the LHS's of the instructions.
8378 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
8379 PN.getName()+".in");
8380 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
8381
8382 Value *InVal = FirstInst->getOperand(0);
8383 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
8384
8385 // Add all operands to the new PHI.
8386 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8387 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8388 if (NewInVal != InVal)
8389 InVal = 0;
8390 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
8391 }
8392
8393 Value *PhiVal;
8394 if (InVal) {
8395 // The new PHI unions all of the same values together. This is really
8396 // common, so we handle it intelligently here for compile-time speed.
8397 PhiVal = InVal;
8398 delete NewPN;
8399 } else {
8400 InsertNewInstBefore(NewPN, PN);
8401 PhiVal = NewPN;
8402 }
8403
8404 // Insert and return the new operation.
8405 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
8406 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
8407 else if (isa<LoadInst>(FirstInst))
8408 return new LoadInst(PhiVal, "", isVolatile);
8409 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
8410 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
8411 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8412 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
8413 PhiVal, ConstantOp);
8414 else
8415 assert(0 && "Unknown operation");
8416 return 0;
8417}
8418
8419/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
8420/// that is dead.
8421static bool DeadPHICycle(PHINode *PN,
8422 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
8423 if (PN->use_empty()) return true;
8424 if (!PN->hasOneUse()) return false;
8425
8426 // Remember this node, and if we find the cycle, return.
8427 if (!PotentiallyDeadPHIs.insert(PN))
8428 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +00008429
8430 // Don't scan crazily complex things.
8431 if (PotentiallyDeadPHIs.size() == 16)
8432 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008433
8434 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
8435 return DeadPHICycle(PU, PotentiallyDeadPHIs);
8436
8437 return false;
8438}
8439
8440// PHINode simplification
8441//
8442Instruction *InstCombiner::visitPHINode(PHINode &PN) {
8443 // If LCSSA is around, don't mess with Phi nodes
8444 if (MustPreserveLCSSA) return 0;
8445
8446 if (Value *V = PN.hasConstantValue())
8447 return ReplaceInstUsesWith(PN, V);
8448
8449 // If all PHI operands are the same operation, pull them through the PHI,
8450 // reducing code size.
8451 if (isa<Instruction>(PN.getIncomingValue(0)) &&
8452 PN.getIncomingValue(0)->hasOneUse())
8453 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
8454 return Result;
8455
8456 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
8457 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
8458 // PHI)... break the cycle.
8459 if (PN.hasOneUse()) {
8460 Instruction *PHIUser = cast<Instruction>(PN.use_back());
8461 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
8462 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
8463 PotentiallyDeadPHIs.insert(&PN);
8464 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
8465 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8466 }
8467
8468 // If this phi has a single use, and if that use just computes a value for
8469 // the next iteration of a loop, delete the phi. This occurs with unused
8470 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
8471 // common case here is good because the only other things that catch this
8472 // are induction variable analysis (sometimes) and ADCE, which is only run
8473 // late.
8474 if (PHIUser->hasOneUse() &&
8475 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
8476 PHIUser->use_back() == &PN) {
8477 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8478 }
8479 }
8480
8481 return 0;
8482}
8483
8484static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
8485 Instruction *InsertPoint,
8486 InstCombiner *IC) {
8487 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
8488 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
8489 // We must cast correctly to the pointer type. Ensure that we
8490 // sign extend the integer value if it is smaller as this is
8491 // used for address computation.
8492 Instruction::CastOps opcode =
8493 (VTySize < PtrSize ? Instruction::SExt :
8494 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
8495 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
8496}
8497
8498
8499Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
8500 Value *PtrOp = GEP.getOperand(0);
8501 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
8502 // If so, eliminate the noop.
8503 if (GEP.getNumOperands() == 1)
8504 return ReplaceInstUsesWith(GEP, PtrOp);
8505
8506 if (isa<UndefValue>(GEP.getOperand(0)))
8507 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
8508
8509 bool HasZeroPointerIndex = false;
8510 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
8511 HasZeroPointerIndex = C->isNullValue();
8512
8513 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
8514 return ReplaceInstUsesWith(GEP, PtrOp);
8515
8516 // Eliminate unneeded casts for indices.
8517 bool MadeChange = false;
8518
8519 gep_type_iterator GTI = gep_type_begin(GEP);
8520 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
8521 if (isa<SequentialType>(*GTI)) {
8522 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
8523 if (CI->getOpcode() == Instruction::ZExt ||
8524 CI->getOpcode() == Instruction::SExt) {
8525 const Type *SrcTy = CI->getOperand(0)->getType();
8526 // We can eliminate a cast from i32 to i64 iff the target
8527 // is a 32-bit pointer target.
8528 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
8529 MadeChange = true;
8530 GEP.setOperand(i, CI->getOperand(0));
8531 }
8532 }
8533 }
8534 // If we are using a wider index than needed for this platform, shrink it
8535 // to what we need. If the incoming value needs a cast instruction,
8536 // insert it. This explicit cast can make subsequent optimizations more
8537 // obvious.
8538 Value *Op = GEP.getOperand(i);
8539 if (TD->getTypeSize(Op->getType()) > TD->getPointerSize())
8540 if (Constant *C = dyn_cast<Constant>(Op)) {
8541 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
8542 MadeChange = true;
8543 } else {
8544 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
8545 GEP);
8546 GEP.setOperand(i, Op);
8547 MadeChange = true;
8548 }
8549 }
8550 }
8551 if (MadeChange) return &GEP;
8552
8553 // If this GEP instruction doesn't move the pointer, and if the input operand
8554 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
8555 // real input to the dest type.
8556 if (GEP.hasAllZeroIndices() && isa<BitCastInst>(GEP.getOperand(0)))
8557 return new BitCastInst(cast<BitCastInst>(GEP.getOperand(0))->getOperand(0),
8558 GEP.getType());
8559
8560 // Combine Indices - If the source pointer to this getelementptr instruction
8561 // is a getelementptr instruction, combine the indices of the two
8562 // getelementptr instructions into a single instruction.
8563 //
8564 SmallVector<Value*, 8> SrcGEPOperands;
8565 if (User *Src = dyn_castGetElementPtr(PtrOp))
8566 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
8567
8568 if (!SrcGEPOperands.empty()) {
8569 // Note that if our source is a gep chain itself that we wait for that
8570 // chain to be resolved before we perform this transformation. This
8571 // avoids us creating a TON of code in some cases.
8572 //
8573 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
8574 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
8575 return 0; // Wait until our source is folded to completion.
8576
8577 SmallVector<Value*, 8> Indices;
8578
8579 // Find out whether the last index in the source GEP is a sequential idx.
8580 bool EndsWithSequential = false;
8581 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
8582 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
8583 EndsWithSequential = !isa<StructType>(*I);
8584
8585 // Can we combine the two pointer arithmetics offsets?
8586 if (EndsWithSequential) {
8587 // Replace: gep (gep %P, long B), long A, ...
8588 // With: T = long A+B; gep %P, T, ...
8589 //
8590 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
8591 if (SO1 == Constant::getNullValue(SO1->getType())) {
8592 Sum = GO1;
8593 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
8594 Sum = SO1;
8595 } else {
8596 // If they aren't the same type, convert both to an integer of the
8597 // target's pointer size.
8598 if (SO1->getType() != GO1->getType()) {
8599 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
8600 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
8601 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
8602 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
8603 } else {
8604 unsigned PS = TD->getPointerSize();
8605 if (TD->getTypeSize(SO1->getType()) == PS) {
8606 // Convert GO1 to SO1's type.
8607 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
8608
8609 } else if (TD->getTypeSize(GO1->getType()) == PS) {
8610 // Convert SO1 to GO1's type.
8611 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
8612 } else {
8613 const Type *PT = TD->getIntPtrType();
8614 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
8615 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
8616 }
8617 }
8618 }
8619 if (isa<Constant>(SO1) && isa<Constant>(GO1))
8620 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
8621 else {
8622 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
8623 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
8624 }
8625 }
8626
8627 // Recycle the GEP we already have if possible.
8628 if (SrcGEPOperands.size() == 2) {
8629 GEP.setOperand(0, SrcGEPOperands[0]);
8630 GEP.setOperand(1, Sum);
8631 return &GEP;
8632 } else {
8633 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8634 SrcGEPOperands.end()-1);
8635 Indices.push_back(Sum);
8636 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
8637 }
8638 } else if (isa<Constant>(*GEP.idx_begin()) &&
8639 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
8640 SrcGEPOperands.size() != 1) {
8641 // Otherwise we can do the fold if the first index of the GEP is a zero
8642 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
8643 SrcGEPOperands.end());
8644 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
8645 }
8646
8647 if (!Indices.empty())
David Greene393be882007-09-04 15:46:09 +00008648 return new GetElementPtrInst(SrcGEPOperands[0], Indices.begin(),
8649 Indices.end(), GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008650
8651 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
8652 // GEP of global variable. If all of the indices for this GEP are
8653 // constants, we can promote this to a constexpr instead of an instruction.
8654
8655 // Scan for nonconstants...
8656 SmallVector<Constant*, 8> Indices;
8657 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
8658 for (; I != E && isa<Constant>(*I); ++I)
8659 Indices.push_back(cast<Constant>(*I));
8660
8661 if (I == E) { // If they are all constants...
8662 Constant *CE = ConstantExpr::getGetElementPtr(GV,
8663 &Indices[0],Indices.size());
8664
8665 // Replace all uses of the GEP with the new constexpr...
8666 return ReplaceInstUsesWith(GEP, CE);
8667 }
8668 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
8669 if (!isa<PointerType>(X->getType())) {
8670 // Not interesting. Source pointer must be a cast from pointer.
8671 } else if (HasZeroPointerIndex) {
8672 // transform: GEP (cast [10 x ubyte]* X to [0 x ubyte]*), long 0, ...
8673 // into : GEP [10 x ubyte]* X, long 0, ...
8674 //
8675 // This occurs when the program declares an array extern like "int X[];"
8676 //
8677 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
8678 const PointerType *XTy = cast<PointerType>(X->getType());
8679 if (const ArrayType *XATy =
8680 dyn_cast<ArrayType>(XTy->getElementType()))
8681 if (const ArrayType *CATy =
8682 dyn_cast<ArrayType>(CPTy->getElementType()))
8683 if (CATy->getElementType() == XATy->getElementType()) {
8684 // At this point, we know that the cast source type is a pointer
8685 // to an array of the same type as the destination pointer
8686 // array. Because the array type is never stepped over (there
8687 // is a leading zero) we can fold the cast into this GEP.
8688 GEP.setOperand(0, X);
8689 return &GEP;
8690 }
8691 } else if (GEP.getNumOperands() == 2) {
8692 // Transform things like:
8693 // %t = getelementptr ubyte* cast ([2 x int]* %str to uint*), uint %V
8694 // into: %t1 = getelementptr [2 x int*]* %str, int 0, uint %V; cast
8695 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
8696 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
8697 if (isa<ArrayType>(SrcElTy) &&
8698 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
8699 TD->getTypeSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +00008700 Value *Idx[2];
8701 Idx[0] = Constant::getNullValue(Type::Int32Ty);
8702 Idx[1] = GEP.getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008703 Value *V = InsertNewInstBefore(
David Greene393be882007-09-04 15:46:09 +00008704 new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName()), GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008705 // V and GEP are both pointer types --> BitCast
8706 return new BitCastInst(V, GEP.getType());
8707 }
8708
8709 // Transform things like:
8710 // getelementptr sbyte* cast ([100 x double]* X to sbyte*), int %tmp
8711 // (where tmp = 8*tmp2) into:
8712 // getelementptr [100 x double]* %arr, int 0, int %tmp.2
8713
8714 if (isa<ArrayType>(SrcElTy) &&
8715 (ResElTy == Type::Int8Ty || ResElTy == Type::Int8Ty)) {
8716 uint64_t ArrayEltSize =
8717 TD->getTypeSize(cast<ArrayType>(SrcElTy)->getElementType());
8718
8719 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
8720 // allow either a mul, shift, or constant here.
8721 Value *NewIdx = 0;
8722 ConstantInt *Scale = 0;
8723 if (ArrayEltSize == 1) {
8724 NewIdx = GEP.getOperand(1);
8725 Scale = ConstantInt::get(NewIdx->getType(), 1);
8726 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
8727 NewIdx = ConstantInt::get(CI->getType(), 1);
8728 Scale = CI;
8729 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
8730 if (Inst->getOpcode() == Instruction::Shl &&
8731 isa<ConstantInt>(Inst->getOperand(1))) {
8732 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
8733 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
8734 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
8735 NewIdx = Inst->getOperand(0);
8736 } else if (Inst->getOpcode() == Instruction::Mul &&
8737 isa<ConstantInt>(Inst->getOperand(1))) {
8738 Scale = cast<ConstantInt>(Inst->getOperand(1));
8739 NewIdx = Inst->getOperand(0);
8740 }
8741 }
8742
8743 // If the index will be to exactly the right offset with the scale taken
8744 // out, perform the transformation.
8745 if (Scale && Scale->getZExtValue() % ArrayEltSize == 0) {
8746 if (isa<ConstantInt>(Scale))
8747 Scale = ConstantInt::get(Scale->getType(),
8748 Scale->getZExtValue() / ArrayEltSize);
8749 if (Scale->getZExtValue() != 1) {
8750 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
8751 true /*SExt*/);
8752 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
8753 NewIdx = InsertNewInstBefore(Sc, GEP);
8754 }
8755
8756 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +00008757 Value *Idx[2];
8758 Idx[0] = Constant::getNullValue(Type::Int32Ty);
8759 Idx[1] = NewIdx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008760 Instruction *NewGEP =
David Greene393be882007-09-04 15:46:09 +00008761 new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008762 NewGEP = InsertNewInstBefore(NewGEP, GEP);
8763 // The NewGEP must be pointer typed, so must the old one -> BitCast
8764 return new BitCastInst(NewGEP, GEP.getType());
8765 }
8766 }
8767 }
8768 }
8769
8770 return 0;
8771}
8772
8773Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
8774 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
8775 if (AI.isArrayAllocation()) // Check C != 1
8776 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
8777 const Type *NewTy =
8778 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
8779 AllocationInst *New = 0;
8780
8781 // Create and insert the replacement instruction...
8782 if (isa<MallocInst>(AI))
8783 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
8784 else {
8785 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
8786 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
8787 }
8788
8789 InsertNewInstBefore(New, AI);
8790
8791 // Scan to the end of the allocation instructions, to skip over a block of
8792 // allocas if possible...
8793 //
8794 BasicBlock::iterator It = New;
8795 while (isa<AllocationInst>(*It)) ++It;
8796
8797 // Now that I is pointing to the first non-allocation-inst in the block,
8798 // insert our getelementptr instruction...
8799 //
8800 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greene393be882007-09-04 15:46:09 +00008801 Value *Idx[2];
8802 Idx[0] = NullIdx;
8803 Idx[1] = NullIdx;
8804 Value *V = new GetElementPtrInst(New, Idx, Idx + 2,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008805 New->getName()+".sub", It);
8806
8807 // Now make everything use the getelementptr instead of the original
8808 // allocation.
8809 return ReplaceInstUsesWith(AI, V);
8810 } else if (isa<UndefValue>(AI.getArraySize())) {
8811 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8812 }
8813
8814 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
8815 // Note that we only do this for alloca's, because malloc should allocate and
8816 // return a unique pointer, even for a zero byte allocation.
8817 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
8818 TD->getTypeSize(AI.getAllocatedType()) == 0)
8819 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
8820
8821 return 0;
8822}
8823
8824Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
8825 Value *Op = FI.getOperand(0);
8826
8827 // free undef -> unreachable.
8828 if (isa<UndefValue>(Op)) {
8829 // Insert a new store to null because we cannot modify the CFG here.
8830 new StoreInst(ConstantInt::getTrue(),
8831 UndefValue::get(PointerType::get(Type::Int1Ty)), &FI);
8832 return EraseInstFromFunction(FI);
8833 }
8834
8835 // If we have 'free null' delete the instruction. This can happen in stl code
8836 // when lots of inlining happens.
8837 if (isa<ConstantPointerNull>(Op))
8838 return EraseInstFromFunction(FI);
8839
8840 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
8841 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
8842 FI.setOperand(0, CI->getOperand(0));
8843 return &FI;
8844 }
8845
8846 // Change free (gep X, 0,0,0,0) into free(X)
8847 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
8848 if (GEPI->hasAllZeroIndices()) {
8849 AddToWorkList(GEPI);
8850 FI.setOperand(0, GEPI->getOperand(0));
8851 return &FI;
8852 }
8853 }
8854
8855 // Change free(malloc) into nothing, if the malloc has a single use.
8856 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
8857 if (MI->hasOneUse()) {
8858 EraseInstFromFunction(FI);
8859 return EraseInstFromFunction(*MI);
8860 }
8861
8862 return 0;
8863}
8864
8865
8866/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
8867static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI) {
8868 User *CI = cast<User>(LI.getOperand(0));
8869 Value *CastOp = CI->getOperand(0);
8870
8871 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
8872 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
8873 const Type *SrcPTy = SrcTy->getElementType();
8874
8875 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
8876 isa<VectorType>(DestPTy)) {
8877 // If the source is an array, the code below will not succeed. Check to
8878 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
8879 // constants.
8880 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
8881 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
8882 if (ASrcTy->getNumElements() != 0) {
8883 Value *Idxs[2];
8884 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
8885 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
8886 SrcTy = cast<PointerType>(CastOp->getType());
8887 SrcPTy = SrcTy->getElementType();
8888 }
8889
8890 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
8891 isa<VectorType>(SrcPTy)) &&
8892 // Do not allow turning this into a load of an integer, which is then
8893 // casted to a pointer, this pessimizes pointer analysis a lot.
8894 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
8895 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
8896 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
8897
8898 // Okay, we are casting from one integer or pointer type to another of
8899 // the same size. Instead of casting the pointer before the load, cast
8900 // the result of the loaded value.
8901 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
8902 CI->getName(),
8903 LI.isVolatile()),LI);
8904 // Now cast the result of the load.
8905 return new BitCastInst(NewLoad, LI.getType());
8906 }
8907 }
8908 }
8909 return 0;
8910}
8911
8912/// isSafeToLoadUnconditionally - Return true if we know that executing a load
8913/// from this value cannot trap. If it is not obviously safe to load from the
8914/// specified pointer, we do a quick local scan of the basic block containing
8915/// ScanFrom, to determine if the address is already accessed.
8916static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
8917 // If it is an alloca or global variable, it is always safe to load from.
8918 if (isa<AllocaInst>(V) || isa<GlobalVariable>(V)) return true;
8919
8920 // Otherwise, be a little bit agressive by scanning the local block where we
8921 // want to check to see if the pointer is already being loaded or stored
8922 // from/to. If so, the previous load or store would have already trapped,
8923 // so there is no harm doing an extra load (also, CSE will later eliminate
8924 // the load entirely).
8925 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
8926
8927 while (BBI != E) {
8928 --BBI;
8929
8930 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
8931 if (LI->getOperand(0) == V) return true;
8932 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8933 if (SI->getOperand(1) == V) return true;
8934
8935 }
8936 return false;
8937}
8938
Chris Lattner0270a112007-08-11 18:48:48 +00008939/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
8940/// until we find the underlying object a pointer is referring to or something
8941/// we don't understand. Note that the returned pointer may be offset from the
8942/// input, because we ignore GEP indices.
8943static Value *GetUnderlyingObject(Value *Ptr) {
8944 while (1) {
8945 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
8946 if (CE->getOpcode() == Instruction::BitCast ||
8947 CE->getOpcode() == Instruction::GetElementPtr)
8948 Ptr = CE->getOperand(0);
8949 else
8950 return Ptr;
8951 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
8952 Ptr = BCI->getOperand(0);
8953 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
8954 Ptr = GEP->getOperand(0);
8955 } else {
8956 return Ptr;
8957 }
8958 }
8959}
8960
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008961Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
8962 Value *Op = LI.getOperand(0);
8963
Dan Gohman5c4d0e12007-07-20 16:34:21 +00008964 // Attempt to improve the alignment.
Chris Lattner47cf3452007-08-09 19:05:49 +00008965 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op, TD);
Dan Gohman5c4d0e12007-07-20 16:34:21 +00008966 if (KnownAlign > LI.getAlignment())
8967 LI.setAlignment(KnownAlign);
8968
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008969 // load (cast X) --> cast (load X) iff safe
8970 if (isa<CastInst>(Op))
8971 if (Instruction *Res = InstCombineLoadCast(*this, LI))
8972 return Res;
8973
8974 // None of the following transforms are legal for volatile loads.
8975 if (LI.isVolatile()) return 0;
8976
8977 if (&LI.getParent()->front() != &LI) {
8978 BasicBlock::iterator BBI = &LI; --BBI;
8979 // If the instruction immediately before this is a store to the same
8980 // address, do a simple form of store->load forwarding.
8981 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
8982 if (SI->getOperand(1) == LI.getOperand(0))
8983 return ReplaceInstUsesWith(LI, SI->getOperand(0));
8984 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
8985 if (LIB->getOperand(0) == LI.getOperand(0))
8986 return ReplaceInstUsesWith(LI, LIB);
8987 }
8988
8989 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op))
8990 if (isa<ConstantPointerNull>(GEPI->getOperand(0))) {
8991 // Insert a new store to null instruction before the load to indicate
8992 // that this code is not reachable. We do this instead of inserting
8993 // an unreachable instruction directly because we cannot modify the
8994 // CFG.
8995 new StoreInst(UndefValue::get(LI.getType()),
8996 Constant::getNullValue(Op->getType()), &LI);
8997 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
8998 }
8999
9000 if (Constant *C = dyn_cast<Constant>(Op)) {
9001 // load null/undef -> undef
9002 if ((C->isNullValue() || isa<UndefValue>(C))) {
9003 // Insert a new store to null instruction before the load to indicate that
9004 // this code is not reachable. We do this instead of inserting an
9005 // unreachable instruction directly because we cannot modify the CFG.
9006 new StoreInst(UndefValue::get(LI.getType()),
9007 Constant::getNullValue(Op->getType()), &LI);
9008 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9009 }
9010
9011 // Instcombine load (constant global) into the value loaded.
9012 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
9013 if (GV->isConstant() && !GV->isDeclaration())
9014 return ReplaceInstUsesWith(LI, GV->getInitializer());
9015
9016 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
9017 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
9018 if (CE->getOpcode() == Instruction::GetElementPtr) {
9019 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
9020 if (GV->isConstant() && !GV->isDeclaration())
9021 if (Constant *V =
9022 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
9023 return ReplaceInstUsesWith(LI, V);
9024 if (CE->getOperand(0)->isNullValue()) {
9025 // Insert a new store to null instruction before the load to indicate
9026 // that this code is not reachable. We do this instead of inserting
9027 // an unreachable instruction directly because we cannot modify the
9028 // CFG.
9029 new StoreInst(UndefValue::get(LI.getType()),
9030 Constant::getNullValue(Op->getType()), &LI);
9031 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9032 }
9033
9034 } else if (CE->isCast()) {
9035 if (Instruction *Res = InstCombineLoadCast(*this, LI))
9036 return Res;
9037 }
9038 }
Chris Lattner0270a112007-08-11 18:48:48 +00009039
9040 // If this load comes from anywhere in a constant global, and if the global
9041 // is all undef or zero, we know what it loads.
9042 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
9043 if (GV->isConstant() && GV->hasInitializer()) {
9044 if (GV->getInitializer()->isNullValue())
9045 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
9046 else if (isa<UndefValue>(GV->getInitializer()))
9047 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9048 }
9049 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009050
9051 if (Op->hasOneUse()) {
9052 // Change select and PHI nodes to select values instead of addresses: this
9053 // helps alias analysis out a lot, allows many others simplifications, and
9054 // exposes redundancy in the code.
9055 //
9056 // Note that we cannot do the transformation unless we know that the
9057 // introduced loads cannot trap! Something like this is valid as long as
9058 // the condition is always false: load (select bool %C, int* null, int* %G),
9059 // but it would not be valid if we transformed it to load from null
9060 // unconditionally.
9061 //
9062 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
9063 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
9064 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
9065 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
9066 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
9067 SI->getOperand(1)->getName()+".val"), LI);
9068 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
9069 SI->getOperand(2)->getName()+".val"), LI);
9070 return new SelectInst(SI->getCondition(), V1, V2);
9071 }
9072
9073 // load (select (cond, null, P)) -> load P
9074 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
9075 if (C->isNullValue()) {
9076 LI.setOperand(0, SI->getOperand(2));
9077 return &LI;
9078 }
9079
9080 // load (select (cond, P, null)) -> load P
9081 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
9082 if (C->isNullValue()) {
9083 LI.setOperand(0, SI->getOperand(1));
9084 return &LI;
9085 }
9086 }
9087 }
9088 return 0;
9089}
9090
9091/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
9092/// when possible.
9093static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
9094 User *CI = cast<User>(SI.getOperand(1));
9095 Value *CastOp = CI->getOperand(0);
9096
9097 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9098 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9099 const Type *SrcPTy = SrcTy->getElementType();
9100
9101 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
9102 // If the source is an array, the code below will not succeed. Check to
9103 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9104 // constants.
9105 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9106 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9107 if (ASrcTy->getNumElements() != 0) {
9108 Value* Idxs[2];
9109 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9110 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
9111 SrcTy = cast<PointerType>(CastOp->getType());
9112 SrcPTy = SrcTy->getElementType();
9113 }
9114
9115 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
9116 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9117 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
9118
9119 // Okay, we are casting from one integer or pointer type to another of
9120 // the same size. Instead of casting the pointer before
9121 // the store, cast the value to be stored.
9122 Value *NewCast;
9123 Value *SIOp0 = SI.getOperand(0);
9124 Instruction::CastOps opcode = Instruction::BitCast;
9125 const Type* CastSrcTy = SIOp0->getType();
9126 const Type* CastDstTy = SrcPTy;
9127 if (isa<PointerType>(CastDstTy)) {
9128 if (CastSrcTy->isInteger())
9129 opcode = Instruction::IntToPtr;
9130 } else if (isa<IntegerType>(CastDstTy)) {
9131 if (isa<PointerType>(SIOp0->getType()))
9132 opcode = Instruction::PtrToInt;
9133 }
9134 if (Constant *C = dyn_cast<Constant>(SIOp0))
9135 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
9136 else
9137 NewCast = IC.InsertNewInstBefore(
9138 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
9139 SI);
9140 return new StoreInst(NewCast, CastOp);
9141 }
9142 }
9143 }
9144 return 0;
9145}
9146
9147Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
9148 Value *Val = SI.getOperand(0);
9149 Value *Ptr = SI.getOperand(1);
9150
9151 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
9152 EraseInstFromFunction(SI);
9153 ++NumCombined;
9154 return 0;
9155 }
9156
9157 // If the RHS is an alloca with a single use, zapify the store, making the
9158 // alloca dead.
9159 if (Ptr->hasOneUse()) {
9160 if (isa<AllocaInst>(Ptr)) {
9161 EraseInstFromFunction(SI);
9162 ++NumCombined;
9163 return 0;
9164 }
9165
9166 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
9167 if (isa<AllocaInst>(GEP->getOperand(0)) &&
9168 GEP->getOperand(0)->hasOneUse()) {
9169 EraseInstFromFunction(SI);
9170 ++NumCombined;
9171 return 0;
9172 }
9173 }
9174
Dan Gohman5c4d0e12007-07-20 16:34:21 +00009175 // Attempt to improve the alignment.
Chris Lattner47cf3452007-08-09 19:05:49 +00009176 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr, TD);
Dan Gohman5c4d0e12007-07-20 16:34:21 +00009177 if (KnownAlign > SI.getAlignment())
9178 SI.setAlignment(KnownAlign);
9179
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009180 // Do really simple DSE, to catch cases where there are several consequtive
9181 // stores to the same location, separated by a few arithmetic operations. This
9182 // situation often occurs with bitfield accesses.
9183 BasicBlock::iterator BBI = &SI;
9184 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
9185 --ScanInsts) {
9186 --BBI;
9187
9188 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
9189 // Prev store isn't volatile, and stores to the same location?
9190 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
9191 ++NumDeadStore;
9192 ++BBI;
9193 EraseInstFromFunction(*PrevSI);
9194 continue;
9195 }
9196 break;
9197 }
9198
9199 // If this is a load, we have to stop. However, if the loaded value is from
9200 // the pointer we're loading and is producing the pointer we're storing,
9201 // then *this* store is dead (X = load P; store X -> P).
9202 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattner24905f72007-09-07 05:33:03 +00009203 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009204 EraseInstFromFunction(SI);
9205 ++NumCombined;
9206 return 0;
9207 }
9208 // Otherwise, this is a load from some other location. Stores before it
9209 // may not be dead.
9210 break;
9211 }
9212
9213 // Don't skip over loads or things that can modify memory.
9214 if (BBI->mayWriteToMemory())
9215 break;
9216 }
9217
9218
9219 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
9220
9221 // store X, null -> turns into 'unreachable' in SimplifyCFG
9222 if (isa<ConstantPointerNull>(Ptr)) {
9223 if (!isa<UndefValue>(Val)) {
9224 SI.setOperand(0, UndefValue::get(Val->getType()));
9225 if (Instruction *U = dyn_cast<Instruction>(Val))
9226 AddToWorkList(U); // Dropped a use.
9227 ++NumCombined;
9228 }
9229 return 0; // Do not modify these!
9230 }
9231
9232 // store undef, Ptr -> noop
9233 if (isa<UndefValue>(Val)) {
9234 EraseInstFromFunction(SI);
9235 ++NumCombined;
9236 return 0;
9237 }
9238
9239 // If the pointer destination is a cast, see if we can fold the cast into the
9240 // source instead.
9241 if (isa<CastInst>(Ptr))
9242 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9243 return Res;
9244 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
9245 if (CE->isCast())
9246 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9247 return Res;
9248
9249
9250 // If this store is the last instruction in the basic block, and if the block
9251 // ends with an unconditional branch, try to move it to the successor block.
9252 BBI = &SI; ++BBI;
9253 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
9254 if (BI->isUnconditional())
9255 if (SimplifyStoreAtEndOfBlock(SI))
9256 return 0; // xform done!
9257
9258 return 0;
9259}
9260
9261/// SimplifyStoreAtEndOfBlock - Turn things like:
9262/// if () { *P = v1; } else { *P = v2 }
9263/// into a phi node with a store in the successor.
9264///
9265/// Simplify things like:
9266/// *P = v1; if () { *P = v2; }
9267/// into a phi node with a store in the successor.
9268///
9269bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
9270 BasicBlock *StoreBB = SI.getParent();
9271
9272 // Check to see if the successor block has exactly two incoming edges. If
9273 // so, see if the other predecessor contains a store to the same location.
9274 // if so, insert a PHI node (if needed) and move the stores down.
9275 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
9276
9277 // Determine whether Dest has exactly two predecessors and, if so, compute
9278 // the other predecessor.
9279 pred_iterator PI = pred_begin(DestBB);
9280 BasicBlock *OtherBB = 0;
9281 if (*PI != StoreBB)
9282 OtherBB = *PI;
9283 ++PI;
9284 if (PI == pred_end(DestBB))
9285 return false;
9286
9287 if (*PI != StoreBB) {
9288 if (OtherBB)
9289 return false;
9290 OtherBB = *PI;
9291 }
9292 if (++PI != pred_end(DestBB))
9293 return false;
9294
9295
9296 // Verify that the other block ends in a branch and is not otherwise empty.
9297 BasicBlock::iterator BBI = OtherBB->getTerminator();
9298 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
9299 if (!OtherBr || BBI == OtherBB->begin())
9300 return false;
9301
9302 // If the other block ends in an unconditional branch, check for the 'if then
9303 // else' case. there is an instruction before the branch.
9304 StoreInst *OtherStore = 0;
9305 if (OtherBr->isUnconditional()) {
9306 // If this isn't a store, or isn't a store to the same location, bail out.
9307 --BBI;
9308 OtherStore = dyn_cast<StoreInst>(BBI);
9309 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
9310 return false;
9311 } else {
9312 // Otherwise, the other block ended with a conditional branch. If one of the
9313 // destinations is StoreBB, then we have the if/then case.
9314 if (OtherBr->getSuccessor(0) != StoreBB &&
9315 OtherBr->getSuccessor(1) != StoreBB)
9316 return false;
9317
9318 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
9319 // if/then triangle. See if there is a store to the same ptr as SI that
9320 // lives in OtherBB.
9321 for (;; --BBI) {
9322 // Check to see if we find the matching store.
9323 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
9324 if (OtherStore->getOperand(1) != SI.getOperand(1))
9325 return false;
9326 break;
9327 }
9328 // If we find something that may be using the stored value, or if we run
9329 // out of instructions, we can't do the xform.
9330 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
9331 BBI == OtherBB->begin())
9332 return false;
9333 }
9334
9335 // In order to eliminate the store in OtherBr, we have to
9336 // make sure nothing reads the stored value in StoreBB.
9337 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
9338 // FIXME: This should really be AA driven.
9339 if (isa<LoadInst>(I) || I->mayWriteToMemory())
9340 return false;
9341 }
9342 }
9343
9344 // Insert a PHI node now if we need it.
9345 Value *MergedVal = OtherStore->getOperand(0);
9346 if (MergedVal != SI.getOperand(0)) {
9347 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
9348 PN->reserveOperandSpace(2);
9349 PN->addIncoming(SI.getOperand(0), SI.getParent());
9350 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
9351 MergedVal = InsertNewInstBefore(PN, DestBB->front());
9352 }
9353
9354 // Advance to a place where it is safe to insert the new store and
9355 // insert it.
9356 BBI = DestBB->begin();
9357 while (isa<PHINode>(BBI)) ++BBI;
9358 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
9359 OtherStore->isVolatile()), *BBI);
9360
9361 // Nuke the old stores.
9362 EraseInstFromFunction(SI);
9363 EraseInstFromFunction(*OtherStore);
9364 ++NumCombined;
9365 return true;
9366}
9367
9368
9369Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
9370 // Change br (not X), label True, label False to: br X, label False, True
9371 Value *X = 0;
9372 BasicBlock *TrueDest;
9373 BasicBlock *FalseDest;
9374 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
9375 !isa<Constant>(X)) {
9376 // Swap Destinations and condition...
9377 BI.setCondition(X);
9378 BI.setSuccessor(0, FalseDest);
9379 BI.setSuccessor(1, TrueDest);
9380 return &BI;
9381 }
9382
9383 // Cannonicalize fcmp_one -> fcmp_oeq
9384 FCmpInst::Predicate FPred; Value *Y;
9385 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
9386 TrueDest, FalseDest)))
9387 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
9388 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
9389 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
9390 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
9391 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
9392 NewSCC->takeName(I);
9393 // Swap Destinations and condition...
9394 BI.setCondition(NewSCC);
9395 BI.setSuccessor(0, FalseDest);
9396 BI.setSuccessor(1, TrueDest);
9397 RemoveFromWorkList(I);
9398 I->eraseFromParent();
9399 AddToWorkList(NewSCC);
9400 return &BI;
9401 }
9402
9403 // Cannonicalize icmp_ne -> icmp_eq
9404 ICmpInst::Predicate IPred;
9405 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
9406 TrueDest, FalseDest)))
9407 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
9408 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
9409 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
9410 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
9411 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
9412 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
9413 NewSCC->takeName(I);
9414 // Swap Destinations and condition...
9415 BI.setCondition(NewSCC);
9416 BI.setSuccessor(0, FalseDest);
9417 BI.setSuccessor(1, TrueDest);
9418 RemoveFromWorkList(I);
9419 I->eraseFromParent();;
9420 AddToWorkList(NewSCC);
9421 return &BI;
9422 }
9423
9424 return 0;
9425}
9426
9427Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
9428 Value *Cond = SI.getCondition();
9429 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
9430 if (I->getOpcode() == Instruction::Add)
9431 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
9432 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
9433 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
9434 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
9435 AddRHS));
9436 SI.setOperand(0, I->getOperand(0));
9437 AddToWorkList(I);
9438 return &SI;
9439 }
9440 }
9441 return 0;
9442}
9443
9444/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
9445/// is to leave as a vector operation.
9446static bool CheapToScalarize(Value *V, bool isConstant) {
9447 if (isa<ConstantAggregateZero>(V))
9448 return true;
9449 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
9450 if (isConstant) return true;
9451 // If all elts are the same, we can extract.
9452 Constant *Op0 = C->getOperand(0);
9453 for (unsigned i = 1; i < C->getNumOperands(); ++i)
9454 if (C->getOperand(i) != Op0)
9455 return false;
9456 return true;
9457 }
9458 Instruction *I = dyn_cast<Instruction>(V);
9459 if (!I) return false;
9460
9461 // Insert element gets simplified to the inserted element or is deleted if
9462 // this is constant idx extract element and its a constant idx insertelt.
9463 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
9464 isa<ConstantInt>(I->getOperand(2)))
9465 return true;
9466 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
9467 return true;
9468 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
9469 if (BO->hasOneUse() &&
9470 (CheapToScalarize(BO->getOperand(0), isConstant) ||
9471 CheapToScalarize(BO->getOperand(1), isConstant)))
9472 return true;
9473 if (CmpInst *CI = dyn_cast<CmpInst>(I))
9474 if (CI->hasOneUse() &&
9475 (CheapToScalarize(CI->getOperand(0), isConstant) ||
9476 CheapToScalarize(CI->getOperand(1), isConstant)))
9477 return true;
9478
9479 return false;
9480}
9481
9482/// Read and decode a shufflevector mask.
9483///
9484/// It turns undef elements into values that are larger than the number of
9485/// elements in the input.
9486static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
9487 unsigned NElts = SVI->getType()->getNumElements();
9488 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
9489 return std::vector<unsigned>(NElts, 0);
9490 if (isa<UndefValue>(SVI->getOperand(2)))
9491 return std::vector<unsigned>(NElts, 2*NElts);
9492
9493 std::vector<unsigned> Result;
9494 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
9495 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
9496 if (isa<UndefValue>(CP->getOperand(i)))
9497 Result.push_back(NElts*2); // undef -> 8
9498 else
9499 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
9500 return Result;
9501}
9502
9503/// FindScalarElement - Given a vector and an element number, see if the scalar
9504/// value is already around as a register, for example if it were inserted then
9505/// extracted from the vector.
9506static Value *FindScalarElement(Value *V, unsigned EltNo) {
9507 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
9508 const VectorType *PTy = cast<VectorType>(V->getType());
9509 unsigned Width = PTy->getNumElements();
9510 if (EltNo >= Width) // Out of range access.
9511 return UndefValue::get(PTy->getElementType());
9512
9513 if (isa<UndefValue>(V))
9514 return UndefValue::get(PTy->getElementType());
9515 else if (isa<ConstantAggregateZero>(V))
9516 return Constant::getNullValue(PTy->getElementType());
9517 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
9518 return CP->getOperand(EltNo);
9519 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
9520 // If this is an insert to a variable element, we don't know what it is.
9521 if (!isa<ConstantInt>(III->getOperand(2)))
9522 return 0;
9523 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
9524
9525 // If this is an insert to the element we are looking for, return the
9526 // inserted value.
9527 if (EltNo == IIElt)
9528 return III->getOperand(1);
9529
9530 // Otherwise, the insertelement doesn't modify the value, recurse on its
9531 // vector input.
9532 return FindScalarElement(III->getOperand(0), EltNo);
9533 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
9534 unsigned InEl = getShuffleMask(SVI)[EltNo];
9535 if (InEl < Width)
9536 return FindScalarElement(SVI->getOperand(0), InEl);
9537 else if (InEl < Width*2)
9538 return FindScalarElement(SVI->getOperand(1), InEl - Width);
9539 else
9540 return UndefValue::get(PTy->getElementType());
9541 }
9542
9543 // Otherwise, we don't know.
9544 return 0;
9545}
9546
9547Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
9548
9549 // If vector val is undef, replace extract with scalar undef.
9550 if (isa<UndefValue>(EI.getOperand(0)))
9551 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9552
9553 // If vector val is constant 0, replace extract with scalar 0.
9554 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
9555 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
9556
9557 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
9558 // If vector val is constant with uniform operands, replace EI
9559 // with that operand
9560 Constant *op0 = C->getOperand(0);
9561 for (unsigned i = 1; i < C->getNumOperands(); ++i)
9562 if (C->getOperand(i) != op0) {
9563 op0 = 0;
9564 break;
9565 }
9566 if (op0)
9567 return ReplaceInstUsesWith(EI, op0);
9568 }
9569
9570 // If extracting a specified index from the vector, see if we can recursively
9571 // find a previously computed scalar that was inserted into the vector.
9572 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
9573 unsigned IndexVal = IdxC->getZExtValue();
9574 unsigned VectorWidth =
9575 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
9576
9577 // If this is extracting an invalid index, turn this into undef, to avoid
9578 // crashing the code below.
9579 if (IndexVal >= VectorWidth)
9580 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9581
9582 // This instruction only demands the single element from the input vector.
9583 // If the input vector has a single use, simplify it based on this use
9584 // property.
9585 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
9586 uint64_t UndefElts;
9587 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
9588 1 << IndexVal,
9589 UndefElts)) {
9590 EI.setOperand(0, V);
9591 return &EI;
9592 }
9593 }
9594
9595 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
9596 return ReplaceInstUsesWith(EI, Elt);
9597
9598 // If the this extractelement is directly using a bitcast from a vector of
9599 // the same number of elements, see if we can find the source element from
9600 // it. In this case, we will end up needing to bitcast the scalars.
9601 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
9602 if (const VectorType *VT =
9603 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
9604 if (VT->getNumElements() == VectorWidth)
9605 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
9606 return new BitCastInst(Elt, EI.getType());
9607 }
9608 }
9609
9610 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
9611 if (I->hasOneUse()) {
9612 // Push extractelement into predecessor operation if legal and
9613 // profitable to do so
9614 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
9615 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
9616 if (CheapToScalarize(BO, isConstantElt)) {
9617 ExtractElementInst *newEI0 =
9618 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
9619 EI.getName()+".lhs");
9620 ExtractElementInst *newEI1 =
9621 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
9622 EI.getName()+".rhs");
9623 InsertNewInstBefore(newEI0, EI);
9624 InsertNewInstBefore(newEI1, EI);
9625 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
9626 }
9627 } else if (isa<LoadInst>(I)) {
9628 Value *Ptr = InsertCastBefore(Instruction::BitCast, I->getOperand(0),
9629 PointerType::get(EI.getType()), EI);
9630 GetElementPtrInst *GEP =
9631 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
9632 InsertNewInstBefore(GEP, EI);
9633 return new LoadInst(GEP);
9634 }
9635 }
9636 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
9637 // Extracting the inserted element?
9638 if (IE->getOperand(2) == EI.getOperand(1))
9639 return ReplaceInstUsesWith(EI, IE->getOperand(1));
9640 // If the inserted and extracted elements are constants, they must not
9641 // be the same value, extract from the pre-inserted value instead.
9642 if (isa<Constant>(IE->getOperand(2)) &&
9643 isa<Constant>(EI.getOperand(1))) {
9644 AddUsesToWorkList(EI);
9645 EI.setOperand(0, IE->getOperand(0));
9646 return &EI;
9647 }
9648 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
9649 // If this is extracting an element from a shufflevector, figure out where
9650 // it came from and extract from the appropriate input element instead.
9651 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
9652 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
9653 Value *Src;
9654 if (SrcIdx < SVI->getType()->getNumElements())
9655 Src = SVI->getOperand(0);
9656 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
9657 SrcIdx -= SVI->getType()->getNumElements();
9658 Src = SVI->getOperand(1);
9659 } else {
9660 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
9661 }
9662 return new ExtractElementInst(Src, SrcIdx);
9663 }
9664 }
9665 }
9666 return 0;
9667}
9668
9669/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
9670/// elements from either LHS or RHS, return the shuffle mask and true.
9671/// Otherwise, return false.
9672static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
9673 std::vector<Constant*> &Mask) {
9674 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
9675 "Invalid CollectSingleShuffleElements");
9676 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
9677
9678 if (isa<UndefValue>(V)) {
9679 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
9680 return true;
9681 } else if (V == LHS) {
9682 for (unsigned i = 0; i != NumElts; ++i)
9683 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
9684 return true;
9685 } else if (V == RHS) {
9686 for (unsigned i = 0; i != NumElts; ++i)
9687 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
9688 return true;
9689 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9690 // If this is an insert of an extract from some other vector, include it.
9691 Value *VecOp = IEI->getOperand(0);
9692 Value *ScalarOp = IEI->getOperand(1);
9693 Value *IdxOp = IEI->getOperand(2);
9694
9695 if (!isa<ConstantInt>(IdxOp))
9696 return false;
9697 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
9698
9699 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
9700 // Okay, we can handle this if the vector we are insertinting into is
9701 // transitively ok.
9702 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9703 // If so, update the mask to reflect the inserted undef.
9704 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
9705 return true;
9706 }
9707 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
9708 if (isa<ConstantInt>(EI->getOperand(1)) &&
9709 EI->getOperand(0)->getType() == V->getType()) {
9710 unsigned ExtractedIdx =
9711 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9712
9713 // This must be extracting from either LHS or RHS.
9714 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
9715 // Okay, we can handle this if the vector we are insertinting into is
9716 // transitively ok.
9717 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
9718 // If so, update the mask to reflect the inserted value.
9719 if (EI->getOperand(0) == LHS) {
9720 Mask[InsertedIdx & (NumElts-1)] =
9721 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
9722 } else {
9723 assert(EI->getOperand(0) == RHS);
9724 Mask[InsertedIdx & (NumElts-1)] =
9725 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
9726
9727 }
9728 return true;
9729 }
9730 }
9731 }
9732 }
9733 }
9734 // TODO: Handle shufflevector here!
9735
9736 return false;
9737}
9738
9739/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
9740/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
9741/// that computes V and the LHS value of the shuffle.
9742static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
9743 Value *&RHS) {
9744 assert(isa<VectorType>(V->getType()) &&
9745 (RHS == 0 || V->getType() == RHS->getType()) &&
9746 "Invalid shuffle!");
9747 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
9748
9749 if (isa<UndefValue>(V)) {
9750 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
9751 return V;
9752 } else if (isa<ConstantAggregateZero>(V)) {
9753 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
9754 return V;
9755 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
9756 // If this is an insert of an extract from some other vector, include it.
9757 Value *VecOp = IEI->getOperand(0);
9758 Value *ScalarOp = IEI->getOperand(1);
9759 Value *IdxOp = IEI->getOperand(2);
9760
9761 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9762 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9763 EI->getOperand(0)->getType() == V->getType()) {
9764 unsigned ExtractedIdx =
9765 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9766 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
9767
9768 // Either the extracted from or inserted into vector must be RHSVec,
9769 // otherwise we'd end up with a shuffle of three inputs.
9770 if (EI->getOperand(0) == RHS || RHS == 0) {
9771 RHS = EI->getOperand(0);
9772 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
9773 Mask[InsertedIdx & (NumElts-1)] =
9774 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
9775 return V;
9776 }
9777
9778 if (VecOp == RHS) {
9779 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
9780 // Everything but the extracted element is replaced with the RHS.
9781 for (unsigned i = 0; i != NumElts; ++i) {
9782 if (i != InsertedIdx)
9783 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
9784 }
9785 return V;
9786 }
9787
9788 // If this insertelement is a chain that comes from exactly these two
9789 // vectors, return the vector and the effective shuffle.
9790 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
9791 return EI->getOperand(0);
9792
9793 }
9794 }
9795 }
9796 // TODO: Handle shufflevector here!
9797
9798 // Otherwise, can't do anything fancy. Return an identity vector.
9799 for (unsigned i = 0; i != NumElts; ++i)
9800 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
9801 return V;
9802}
9803
9804Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
9805 Value *VecOp = IE.getOperand(0);
9806 Value *ScalarOp = IE.getOperand(1);
9807 Value *IdxOp = IE.getOperand(2);
9808
9809 // Inserting an undef or into an undefined place, remove this.
9810 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
9811 ReplaceInstUsesWith(IE, VecOp);
9812
9813 // If the inserted element was extracted from some other vector, and if the
9814 // indexes are constant, try to turn this into a shufflevector operation.
9815 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
9816 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
9817 EI->getOperand(0)->getType() == IE.getType()) {
9818 unsigned NumVectorElts = IE.getType()->getNumElements();
9819 unsigned ExtractedIdx =
9820 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
9821 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
9822
9823 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
9824 return ReplaceInstUsesWith(IE, VecOp);
9825
9826 if (InsertedIdx >= NumVectorElts) // Out of range insert.
9827 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
9828
9829 // If we are extracting a value from a vector, then inserting it right
9830 // back into the same place, just use the input vector.
9831 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
9832 return ReplaceInstUsesWith(IE, VecOp);
9833
9834 // We could theoretically do this for ANY input. However, doing so could
9835 // turn chains of insertelement instructions into a chain of shufflevector
9836 // instructions, and right now we do not merge shufflevectors. As such,
9837 // only do this in a situation where it is clear that there is benefit.
9838 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
9839 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
9840 // the values of VecOp, except then one read from EIOp0.
9841 // Build a new shuffle mask.
9842 std::vector<Constant*> Mask;
9843 if (isa<UndefValue>(VecOp))
9844 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
9845 else {
9846 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
9847 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
9848 NumVectorElts));
9849 }
9850 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
9851 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
9852 ConstantVector::get(Mask));
9853 }
9854
9855 // If this insertelement isn't used by some other insertelement, turn it
9856 // (and any insertelements it points to), into one big shuffle.
9857 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
9858 std::vector<Constant*> Mask;
9859 Value *RHS = 0;
9860 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
9861 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
9862 // We now have a shuffle of LHS, RHS, Mask.
9863 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
9864 }
9865 }
9866 }
9867
9868 return 0;
9869}
9870
9871
9872Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
9873 Value *LHS = SVI.getOperand(0);
9874 Value *RHS = SVI.getOperand(1);
9875 std::vector<unsigned> Mask = getShuffleMask(&SVI);
9876
9877 bool MadeChange = false;
9878
9879 // Undefined shuffle mask -> undefined value.
9880 if (isa<UndefValue>(SVI.getOperand(2)))
9881 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
9882
9883 // If we have shuffle(x, undef, mask) and any elements of mask refer to
9884 // the undef, change them to undefs.
9885 if (isa<UndefValue>(SVI.getOperand(1))) {
9886 // Scan to see if there are any references to the RHS. If so, replace them
9887 // with undef element refs and set MadeChange to true.
9888 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9889 if (Mask[i] >= e && Mask[i] != 2*e) {
9890 Mask[i] = 2*e;
9891 MadeChange = true;
9892 }
9893 }
9894
9895 if (MadeChange) {
9896 // Remap any references to RHS to use LHS.
9897 std::vector<Constant*> Elts;
9898 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9899 if (Mask[i] == 2*e)
9900 Elts.push_back(UndefValue::get(Type::Int32Ty));
9901 else
9902 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9903 }
9904 SVI.setOperand(2, ConstantVector::get(Elts));
9905 }
9906 }
9907
9908 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
9909 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
9910 if (LHS == RHS || isa<UndefValue>(LHS)) {
9911 if (isa<UndefValue>(LHS) && LHS == RHS) {
9912 // shuffle(undef,undef,mask) -> undef.
9913 return ReplaceInstUsesWith(SVI, LHS);
9914 }
9915
9916 // Remap any references to RHS to use LHS.
9917 std::vector<Constant*> Elts;
9918 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9919 if (Mask[i] >= 2*e)
9920 Elts.push_back(UndefValue::get(Type::Int32Ty));
9921 else {
9922 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
9923 (Mask[i] < e && isa<UndefValue>(LHS)))
9924 Mask[i] = 2*e; // Turn into undef.
9925 else
9926 Mask[i] &= (e-1); // Force to LHS.
9927 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
9928 }
9929 }
9930 SVI.setOperand(0, SVI.getOperand(1));
9931 SVI.setOperand(1, UndefValue::get(RHS->getType()));
9932 SVI.setOperand(2, ConstantVector::get(Elts));
9933 LHS = SVI.getOperand(0);
9934 RHS = SVI.getOperand(1);
9935 MadeChange = true;
9936 }
9937
9938 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
9939 bool isLHSID = true, isRHSID = true;
9940
9941 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
9942 if (Mask[i] >= e*2) continue; // Ignore undef values.
9943 // Is this an identity shuffle of the LHS value?
9944 isLHSID &= (Mask[i] == i);
9945
9946 // Is this an identity shuffle of the RHS value?
9947 isRHSID &= (Mask[i]-e == i);
9948 }
9949
9950 // Eliminate identity shuffles.
9951 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
9952 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
9953
9954 // If the LHS is a shufflevector itself, see if we can combine it with this
9955 // one without producing an unusual shuffle. Here we are really conservative:
9956 // we are absolutely afraid of producing a shuffle mask not in the input
9957 // program, because the code gen may not be smart enough to turn a merged
9958 // shuffle into two specific shuffles: it may produce worse code. As such,
9959 // we only merge two shuffles if the result is one of the two input shuffle
9960 // masks. In this case, merging the shuffles just removes one instruction,
9961 // which we know is safe. This is good for things like turning:
9962 // (splat(splat)) -> splat.
9963 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
9964 if (isa<UndefValue>(RHS)) {
9965 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
9966
9967 std::vector<unsigned> NewMask;
9968 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
9969 if (Mask[i] >= 2*e)
9970 NewMask.push_back(2*e);
9971 else
9972 NewMask.push_back(LHSMask[Mask[i]]);
9973
9974 // If the result mask is equal to the src shuffle or this shuffle mask, do
9975 // the replacement.
9976 if (NewMask == LHSMask || NewMask == Mask) {
9977 std::vector<Constant*> Elts;
9978 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
9979 if (NewMask[i] >= e*2) {
9980 Elts.push_back(UndefValue::get(Type::Int32Ty));
9981 } else {
9982 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
9983 }
9984 }
9985 return new ShuffleVectorInst(LHSSVI->getOperand(0),
9986 LHSSVI->getOperand(1),
9987 ConstantVector::get(Elts));
9988 }
9989 }
9990 }
9991
9992 return MadeChange ? &SVI : 0;
9993}
9994
9995
9996
9997
9998/// TryToSinkInstruction - Try to move the specified instruction from its
9999/// current block into the beginning of DestBlock, which can only happen if it's
10000/// safe to move the instruction past all of the instructions between it and the
10001/// end of its block.
10002static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
10003 assert(I->hasOneUse() && "Invariants didn't hold!");
10004
10005 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
10006 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
10007
10008 // Do not sink alloca instructions out of the entry block.
10009 if (isa<AllocaInst>(I) && I->getParent() ==
10010 &DestBlock->getParent()->getEntryBlock())
10011 return false;
10012
10013 // We can only sink load instructions if there is nothing between the load and
10014 // the end of block that could change the value.
10015 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10016 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
10017 Scan != E; ++Scan)
10018 if (Scan->mayWriteToMemory())
10019 return false;
10020 }
10021
10022 BasicBlock::iterator InsertPos = DestBlock->begin();
10023 while (isa<PHINode>(InsertPos)) ++InsertPos;
10024
10025 I->moveBefore(InsertPos);
10026 ++NumSunkInst;
10027 return true;
10028}
10029
10030
10031/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
10032/// all reachable code to the worklist.
10033///
10034/// This has a couple of tricks to make the code faster and more powerful. In
10035/// particular, we constant fold and DCE instructions as we go, to avoid adding
10036/// them to the worklist (this significantly speeds up instcombine on code where
10037/// many instructions are dead or constant). Additionally, if we find a branch
10038/// whose condition is a known constant, we only visit the reachable successors.
10039///
10040static void AddReachableCodeToWorklist(BasicBlock *BB,
10041 SmallPtrSet<BasicBlock*, 64> &Visited,
10042 InstCombiner &IC,
10043 const TargetData *TD) {
10044 std::vector<BasicBlock*> Worklist;
10045 Worklist.push_back(BB);
10046
10047 while (!Worklist.empty()) {
10048 BB = Worklist.back();
10049 Worklist.pop_back();
10050
10051 // We have now visited this block! If we've already been here, ignore it.
10052 if (!Visited.insert(BB)) continue;
10053
10054 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
10055 Instruction *Inst = BBI++;
10056
10057 // DCE instruction if trivially dead.
10058 if (isInstructionTriviallyDead(Inst)) {
10059 ++NumDeadInst;
10060 DOUT << "IC: DCE: " << *Inst;
10061 Inst->eraseFromParent();
10062 continue;
10063 }
10064
10065 // ConstantProp instruction if trivially constant.
10066 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
10067 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
10068 Inst->replaceAllUsesWith(C);
10069 ++NumConstProp;
10070 Inst->eraseFromParent();
10071 continue;
10072 }
Chris Lattnere0f462d2007-07-20 22:06:41 +000010073
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010074 IC.AddToWorkList(Inst);
10075 }
10076
10077 // Recursively visit successors. If this is a branch or switch on a
10078 // constant, only visit the reachable successor.
10079 TerminatorInst *TI = BB->getTerminator();
10080 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
10081 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
10082 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
10083 Worklist.push_back(BI->getSuccessor(!CondVal));
10084 continue;
10085 }
10086 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
10087 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
10088 // See if this is an explicit destination.
10089 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
10090 if (SI->getCaseValue(i) == Cond) {
10091 Worklist.push_back(SI->getSuccessor(i));
10092 continue;
10093 }
10094
10095 // Otherwise it is the default destination.
10096 Worklist.push_back(SI->getSuccessor(0));
10097 continue;
10098 }
10099 }
10100
10101 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
10102 Worklist.push_back(TI->getSuccessor(i));
10103 }
10104}
10105
10106bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
10107 bool Changed = false;
10108 TD = &getAnalysis<TargetData>();
10109
10110 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
10111 << F.getNameStr() << "\n");
10112
10113 {
10114 // Do a depth-first traversal of the function, populate the worklist with
10115 // the reachable instructions. Ignore blocks that are not reachable. Keep
10116 // track of which blocks we visit.
10117 SmallPtrSet<BasicBlock*, 64> Visited;
10118 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
10119
10120 // Do a quick scan over the function. If we find any blocks that are
10121 // unreachable, remove any instructions inside of them. This prevents
10122 // the instcombine code from having to deal with some bad special cases.
10123 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
10124 if (!Visited.count(BB)) {
10125 Instruction *Term = BB->getTerminator();
10126 while (Term != BB->begin()) { // Remove instrs bottom-up
10127 BasicBlock::iterator I = Term; --I;
10128
10129 DOUT << "IC: DCE: " << *I;
10130 ++NumDeadInst;
10131
10132 if (!I->use_empty())
10133 I->replaceAllUsesWith(UndefValue::get(I->getType()));
10134 I->eraseFromParent();
10135 }
10136 }
10137 }
10138
10139 while (!Worklist.empty()) {
10140 Instruction *I = RemoveOneFromWorkList();
10141 if (I == 0) continue; // skip null values.
10142
10143 // Check to see if we can DCE the instruction.
10144 if (isInstructionTriviallyDead(I)) {
10145 // Add operands to the worklist.
10146 if (I->getNumOperands() < 4)
10147 AddUsesToWorkList(*I);
10148 ++NumDeadInst;
10149
10150 DOUT << "IC: DCE: " << *I;
10151
10152 I->eraseFromParent();
10153 RemoveFromWorkList(I);
10154 continue;
10155 }
10156
10157 // Instruction isn't dead, see if we can constant propagate it.
10158 if (Constant *C = ConstantFoldInstruction(I, TD)) {
10159 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
10160
10161 // Add operands to the worklist.
10162 AddUsesToWorkList(*I);
10163 ReplaceInstUsesWith(*I, C);
10164
10165 ++NumConstProp;
10166 I->eraseFromParent();
10167 RemoveFromWorkList(I);
10168 continue;
10169 }
10170
10171 // See if we can trivially sink this instruction to a successor basic block.
10172 if (I->hasOneUse()) {
10173 BasicBlock *BB = I->getParent();
10174 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
10175 if (UserParent != BB) {
10176 bool UserIsSuccessor = false;
10177 // See if the user is one of our successors.
10178 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
10179 if (*SI == UserParent) {
10180 UserIsSuccessor = true;
10181 break;
10182 }
10183
10184 // If the user is one of our immediate successors, and if that successor
10185 // only has us as a predecessors (we'd have to split the critical edge
10186 // otherwise), we can keep going.
10187 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
10188 next(pred_begin(UserParent)) == pred_end(UserParent))
10189 // Okay, the CFG is simple enough, try to sink this instruction.
10190 Changed |= TryToSinkInstruction(I, UserParent);
10191 }
10192 }
10193
10194 // Now that we have an instruction, try combining it to simplify it...
10195#ifndef NDEBUG
10196 std::string OrigI;
10197#endif
10198 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
10199 if (Instruction *Result = visit(*I)) {
10200 ++NumCombined;
10201 // Should we replace the old instruction with a new one?
10202 if (Result != I) {
10203 DOUT << "IC: Old = " << *I
10204 << " New = " << *Result;
10205
10206 // Everything uses the new instruction now.
10207 I->replaceAllUsesWith(Result);
10208
10209 // Push the new instruction and any users onto the worklist.
10210 AddToWorkList(Result);
10211 AddUsersToWorkList(*Result);
10212
10213 // Move the name to the new instruction first.
10214 Result->takeName(I);
10215
10216 // Insert the new instruction into the basic block...
10217 BasicBlock *InstParent = I->getParent();
10218 BasicBlock::iterator InsertPos = I;
10219
10220 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
10221 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
10222 ++InsertPos;
10223
10224 InstParent->getInstList().insert(InsertPos, Result);
10225
10226 // Make sure that we reprocess all operands now that we reduced their
10227 // use counts.
10228 AddUsesToWorkList(*I);
10229
10230 // Instructions can end up on the worklist more than once. Make sure
10231 // we do not process an instruction that has been deleted.
10232 RemoveFromWorkList(I);
10233
10234 // Erase the old instruction.
10235 InstParent->getInstList().erase(I);
10236 } else {
10237#ifndef NDEBUG
10238 DOUT << "IC: Mod = " << OrigI
10239 << " New = " << *I;
10240#endif
10241
10242 // If the instruction was modified, it's possible that it is now dead.
10243 // if so, remove it.
10244 if (isInstructionTriviallyDead(I)) {
10245 // Make sure we process all operands now that we are reducing their
10246 // use counts.
10247 AddUsesToWorkList(*I);
10248
10249 // Instructions may end up in the worklist more than once. Erase all
10250 // occurrences of this instruction.
10251 RemoveFromWorkList(I);
10252 I->eraseFromParent();
10253 } else {
10254 AddToWorkList(I);
10255 AddUsersToWorkList(*I);
10256 }
10257 }
10258 Changed = true;
10259 }
10260 }
10261
10262 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnerb933ea62007-08-05 08:47:58 +000010263
10264 // Do an explicit clear, this shrinks the map if needed.
10265 WorklistMap.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010266 return Changed;
10267}
10268
10269
10270bool InstCombiner::runOnFunction(Function &F) {
10271 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
10272
10273 bool EverMadeChange = false;
10274
10275 // Iterate while there is work to do.
10276 unsigned Iteration = 0;
10277 while (DoOneIteration(F, Iteration++))
10278 EverMadeChange = true;
10279 return EverMadeChange;
10280}
10281
10282FunctionPass *llvm::createInstructionCombiningPass() {
10283 return new InstCombiner();
10284}
10285