blob: d17035c161ee59b3505cee059a1dca58ee254c04 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- InstructionCombining.cpp - Combine multiple instructions -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
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);
Chris Lattner7c1626482008-01-08 07:23:51 +0000213 Instruction *visitIntToPtr(IntToPtrInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000214 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);
Duncan Sands74833f22007-09-17 10:26:40 +0000238 Instruction *transformCallThroughTrampoline(CallSite CS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000239
240 public:
241 // InsertNewInstBefore - insert an instruction New before instruction Old
242 // in the program. Add the new instruction to the worklist.
243 //
244 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
245 assert(New && New->getParent() == 0 &&
246 "New instruction already inserted into a basic block!");
247 BasicBlock *BB = Old.getParent();
248 BB->getInstList().insert(&Old, New); // Insert inst
249 AddToWorkList(New);
250 return New;
251 }
252
253 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
254 /// This also adds the cast to the worklist. Finally, this returns the
255 /// cast.
256 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
257 Instruction &Pos) {
258 if (V->getType() == Ty) return V;
259
260 if (Constant *CV = dyn_cast<Constant>(V))
261 return ConstantExpr::getCast(opc, CV, Ty);
262
263 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
264 AddToWorkList(C);
265 return C;
266 }
Chris Lattner13c2d6e2008-01-13 22:23:22 +0000267
268 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
269 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
270 }
271
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000272
273 // ReplaceInstUsesWith - This method is to be used when an instruction is
274 // found to be dead, replacable with another preexisting expression. Here
275 // we add all uses of I to the worklist, replace all uses of I with the new
276 // value, then return I, so that the inst combiner will know that I was
277 // modified.
278 //
279 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
280 AddUsersToWorkList(I); // Add all modified instrs to worklist
281 if (&I != V) {
282 I.replaceAllUsesWith(V);
283 return &I;
284 } else {
285 // If we are replacing the instruction with itself, this must be in a
286 // segment of unreachable code, so just clobber the instruction.
287 I.replaceAllUsesWith(UndefValue::get(I.getType()));
288 return &I;
289 }
290 }
291
292 // UpdateValueUsesWith - This method is to be used when an value is
293 // found to be replacable with another preexisting expression or was
294 // updated. Here we add all uses of I to the worklist, replace all uses of
295 // I with the new value (unless the instruction was just updated), then
296 // return true, so that the inst combiner will know that I was modified.
297 //
298 bool UpdateValueUsesWith(Value *Old, Value *New) {
299 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
300 if (Old != New)
301 Old->replaceAllUsesWith(New);
302 if (Instruction *I = dyn_cast<Instruction>(Old))
303 AddToWorkList(I);
304 if (Instruction *I = dyn_cast<Instruction>(New))
305 AddToWorkList(I);
306 return true;
307 }
308
309 // EraseInstFromFunction - When dealing with an instruction that has side
310 // effects or produces a void value, we can't rely on DCE to delete the
311 // instruction. Instead, visit methods should return the value returned by
312 // this function.
313 Instruction *EraseInstFromFunction(Instruction &I) {
314 assert(I.use_empty() && "Cannot erase instruction that is used!");
315 AddUsesToWorkList(I);
316 RemoveFromWorkList(&I);
317 I.eraseFromParent();
318 return 0; // Don't do anything with FI
319 }
320
321 private:
322 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
323 /// InsertBefore instruction. This is specialized a bit to avoid inserting
324 /// casts that are known to not do anything...
325 ///
326 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
327 Value *V, const Type *DestTy,
328 Instruction *InsertBefore);
329
330 /// SimplifyCommutative - This performs a few simplifications for
331 /// commutative operators.
332 bool SimplifyCommutative(BinaryOperator &I);
333
334 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
335 /// most-complex to least-complex order.
336 bool SimplifyCompare(CmpInst &I);
337
338 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
339 /// on the demanded bits.
340 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
341 APInt& KnownZero, APInt& KnownOne,
342 unsigned Depth = 0);
343
344 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
345 uint64_t &UndefElts, unsigned Depth = 0);
346
347 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
348 // PHI node as operand #0, see if we can fold the instruction into the PHI
349 // (which is only possible if all operands to the PHI are constants).
350 Instruction *FoldOpIntoPhi(Instruction &I);
351
352 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
353 // operator and they all are only used by the PHI, PHI together their
354 // inputs, and do the operation once, to the result of the PHI.
355 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
356 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
357
358
359 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
360 ConstantInt *AndRHS, BinaryOperator &TheAnd);
361
362 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
363 bool isSub, Instruction &I);
364 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
365 bool isSigned, bool Inside, Instruction &IB);
366 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
367 Instruction *MatchBSwap(BinaryOperator &I);
368 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000369 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
370
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000371
372 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
373 };
374
375 char InstCombiner::ID = 0;
376 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
377}
378
379// getComplexity: Assign a complexity or rank value to LLVM Values...
380// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
381static unsigned getComplexity(Value *V) {
382 if (isa<Instruction>(V)) {
383 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
384 return 3;
385 return 4;
386 }
387 if (isa<Argument>(V)) return 3;
388 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
389}
390
391// isOnlyUse - Return true if this instruction will be deleted if we stop using
392// it.
393static bool isOnlyUse(Value *V) {
394 return V->hasOneUse() || isa<Constant>(V);
395}
396
397// getPromotedType - Return the specified type promoted as it would be to pass
398// though a va_arg area...
399static const Type *getPromotedType(const Type *Ty) {
400 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
401 if (ITy->getBitWidth() < 32)
402 return Type::Int32Ty;
403 }
404 return Ty;
405}
406
407/// getBitCastOperand - If the specified operand is a CastInst or a constant
408/// expression bitcast, return the operand value, otherwise return null.
409static Value *getBitCastOperand(Value *V) {
410 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
411 return I->getOperand(0);
412 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
413 if (CE->getOpcode() == Instruction::BitCast)
414 return CE->getOperand(0);
415 return 0;
416}
417
418/// This function is a wrapper around CastInst::isEliminableCastPair. It
419/// simply extracts arguments and returns what that function returns.
420static Instruction::CastOps
421isEliminableCastPair(
422 const CastInst *CI, ///< The first cast instruction
423 unsigned opcode, ///< The opcode of the second cast instruction
424 const Type *DstTy, ///< The target type for the second cast instruction
425 TargetData *TD ///< The target data for pointer size
426) {
427
428 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
429 const Type *MidTy = CI->getType(); // B from above
430
431 // Get the opcodes of the two Cast instructions
432 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
433 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
434
435 return Instruction::CastOps(
436 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
437 DstTy, TD->getIntPtrType()));
438}
439
440/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
441/// in any code being generated. It does not require codegen if V is simple
442/// enough or if the cast can be folded into other casts.
443static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
444 const Type *Ty, TargetData *TD) {
445 if (V->getType() == Ty || isa<Constant>(V)) return false;
446
447 // If this is another cast that can be eliminated, it isn't codegen either.
448 if (const CastInst *CI = dyn_cast<CastInst>(V))
449 if (isEliminableCastPair(CI, opcode, Ty, TD))
450 return false;
451 return true;
452}
453
454/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
455/// InsertBefore instruction. This is specialized a bit to avoid inserting
456/// casts that are known to not do anything...
457///
458Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
459 Value *V, const Type *DestTy,
460 Instruction *InsertBefore) {
461 if (V->getType() == DestTy) return V;
462 if (Constant *C = dyn_cast<Constant>(V))
463 return ConstantExpr::getCast(opcode, C, DestTy);
464
465 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
466}
467
468// SimplifyCommutative - This performs a few simplifications for commutative
469// operators:
470//
471// 1. Order operands such that they are listed from right (least complex) to
472// left (most complex). This puts constants before unary operators before
473// binary operators.
474//
475// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
476// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
477//
478bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
479 bool Changed = false;
480 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
481 Changed = !I.swapOperands();
482
483 if (!I.isAssociative()) return Changed;
484 Instruction::BinaryOps Opcode = I.getOpcode();
485 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
486 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
487 if (isa<Constant>(I.getOperand(1))) {
488 Constant *Folded = ConstantExpr::get(I.getOpcode(),
489 cast<Constant>(I.getOperand(1)),
490 cast<Constant>(Op->getOperand(1)));
491 I.setOperand(0, Op->getOperand(0));
492 I.setOperand(1, Folded);
493 return true;
494 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
495 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
496 isOnlyUse(Op) && isOnlyUse(Op1)) {
497 Constant *C1 = cast<Constant>(Op->getOperand(1));
498 Constant *C2 = cast<Constant>(Op1->getOperand(1));
499
500 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
501 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
502 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
503 Op1->getOperand(0),
504 Op1->getName(), &I);
505 AddToWorkList(New);
506 I.setOperand(0, New);
507 I.setOperand(1, Folded);
508 return true;
509 }
510 }
511 return Changed;
512}
513
514/// SimplifyCompare - For a CmpInst this function just orders the operands
515/// so that theyare listed from right (least complex) to left (most complex).
516/// This puts constants before unary operators before binary operators.
517bool InstCombiner::SimplifyCompare(CmpInst &I) {
518 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
519 return false;
520 I.swapOperands();
521 // Compare instructions are not associative so there's nothing else we can do.
522 return true;
523}
524
525// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
526// if the LHS is a constant zero (which is the 'negate' form).
527//
528static inline Value *dyn_castNegVal(Value *V) {
529 if (BinaryOperator::isNeg(V))
530 return BinaryOperator::getNegArgument(V);
531
532 // Constants can be considered to be negated values if they can be folded.
533 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
534 return ConstantExpr::getNeg(C);
535 return 0;
536}
537
538static inline Value *dyn_castNotVal(Value *V) {
539 if (BinaryOperator::isNot(V))
540 return BinaryOperator::getNotArgument(V);
541
542 // Constants can be considered to be not'ed values...
543 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
544 return ConstantInt::get(~C->getValue());
545 return 0;
546}
547
548// dyn_castFoldableMul - If this value is a multiply that can be folded into
549// other computations (because it has a constant operand), return the
550// non-constant operand of the multiply, and set CST to point to the multiplier.
551// Otherwise, return null.
552//
553static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
554 if (V->hasOneUse() && V->getType()->isInteger())
555 if (Instruction *I = dyn_cast<Instruction>(V)) {
556 if (I->getOpcode() == Instruction::Mul)
557 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
558 return I->getOperand(0);
559 if (I->getOpcode() == Instruction::Shl)
560 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
561 // The multiplier is really 1 << CST.
562 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
563 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
564 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
565 return I->getOperand(0);
566 }
567 }
568 return 0;
569}
570
571/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
572/// expression, return it.
573static User *dyn_castGetElementPtr(Value *V) {
574 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
575 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
576 if (CE->getOpcode() == Instruction::GetElementPtr)
577 return cast<User>(V);
578 return false;
579}
580
581/// AddOne - Add one to a ConstantInt
582static ConstantInt *AddOne(ConstantInt *C) {
583 APInt Val(C->getValue());
584 return ConstantInt::get(++Val);
585}
586/// SubOne - Subtract one from a ConstantInt
587static ConstantInt *SubOne(ConstantInt *C) {
588 APInt Val(C->getValue());
589 return ConstantInt::get(--Val);
590}
591/// Add - Add two ConstantInts together
592static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
593 return ConstantInt::get(C1->getValue() + C2->getValue());
594}
595/// And - Bitwise AND two ConstantInts together
596static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
597 return ConstantInt::get(C1->getValue() & C2->getValue());
598}
599/// Subtract - Subtract one ConstantInt from another
600static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
601 return ConstantInt::get(C1->getValue() - C2->getValue());
602}
603/// Multiply - Multiply two ConstantInts together
604static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
605 return ConstantInt::get(C1->getValue() * C2->getValue());
606}
607
608/// ComputeMaskedBits - Determine which of the bits specified in Mask are
609/// known to be either zero or one and return them in the KnownZero/KnownOne
610/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
611/// processing.
612/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
613/// we cannot optimize based on the assumption that it is zero without changing
614/// it to be an explicit zero. If we don't change it to zero, other code could
615/// optimized based on the contradictory assumption that it is non-zero.
616/// Because instcombine aggressively folds operations with undef args anyway,
617/// this won't lose us code quality.
618static void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
619 APInt& KnownOne, unsigned Depth = 0) {
620 assert(V && "No Value?");
621 assert(Depth <= 6 && "Limit Search Depth");
622 uint32_t BitWidth = Mask.getBitWidth();
623 assert(cast<IntegerType>(V->getType())->getBitWidth() == BitWidth &&
624 KnownZero.getBitWidth() == BitWidth &&
625 KnownOne.getBitWidth() == BitWidth &&
626 "V, Mask, KnownOne and KnownZero should have same BitWidth");
627 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
628 // We know all of the bits for a constant!
629 KnownOne = CI->getValue() & Mask;
630 KnownZero = ~KnownOne & Mask;
631 return;
632 }
633
634 if (Depth == 6 || Mask == 0)
635 return; // Limit search depth.
636
637 Instruction *I = dyn_cast<Instruction>(V);
638 if (!I) return;
639
640 KnownZero.clear(); KnownOne.clear(); // Don't know anything.
641 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
642
643 switch (I->getOpcode()) {
644 case Instruction::And: {
645 // If either the LHS or the RHS are Zero, the result is zero.
646 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
647 APInt Mask2(Mask & ~KnownZero);
648 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
649 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
650 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
651
652 // Output known-1 bits are only known if set in both the LHS & RHS.
653 KnownOne &= KnownOne2;
654 // Output known-0 are known to be clear if zero in either the LHS | RHS.
655 KnownZero |= KnownZero2;
656 return;
657 }
658 case Instruction::Or: {
659 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
660 APInt Mask2(Mask & ~KnownOne);
661 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
662 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
663 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
664
665 // Output known-0 bits are only known if clear in both the LHS & RHS.
666 KnownZero &= KnownZero2;
667 // Output known-1 are known to be set if set in either the LHS | RHS.
668 KnownOne |= KnownOne2;
669 return;
670 }
671 case Instruction::Xor: {
672 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
673 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
674 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
675 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
676
677 // Output known-0 bits are known if clear or set in both the LHS & RHS.
678 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
679 // Output known-1 are known to be set if set in only one of the LHS, RHS.
680 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
681 KnownZero = KnownZeroOut;
682 return;
683 }
684 case Instruction::Select:
685 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
686 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
687 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
688 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
689
690 // Only known if known in both the LHS and RHS.
691 KnownOne &= KnownOne2;
692 KnownZero &= KnownZero2;
693 return;
694 case Instruction::FPTrunc:
695 case Instruction::FPExt:
696 case Instruction::FPToUI:
697 case Instruction::FPToSI:
698 case Instruction::SIToFP:
699 case Instruction::PtrToInt:
700 case Instruction::UIToFP:
701 case Instruction::IntToPtr:
702 return; // Can't work with floating point or pointers
703 case Instruction::Trunc: {
704 // All these have integer operands
705 uint32_t SrcBitWidth =
706 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
707 APInt MaskIn(Mask);
708 MaskIn.zext(SrcBitWidth);
709 KnownZero.zext(SrcBitWidth);
710 KnownOne.zext(SrcBitWidth);
711 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
712 KnownZero.trunc(BitWidth);
713 KnownOne.trunc(BitWidth);
714 return;
715 }
716 case Instruction::BitCast: {
717 const Type *SrcTy = I->getOperand(0)->getType();
718 if (SrcTy->isInteger()) {
719 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
720 return;
721 }
722 break;
723 }
724 case Instruction::ZExt: {
725 // Compute the bits in the result that are not present in the input.
726 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
727 uint32_t SrcBitWidth = SrcTy->getBitWidth();
728
729 APInt MaskIn(Mask);
730 MaskIn.trunc(SrcBitWidth);
731 KnownZero.trunc(SrcBitWidth);
732 KnownOne.trunc(SrcBitWidth);
733 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
734 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
735 // The top bits are known to be zero.
736 KnownZero.zext(BitWidth);
737 KnownOne.zext(BitWidth);
738 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
739 return;
740 }
741 case Instruction::SExt: {
742 // Compute the bits in the result that are not present in the input.
743 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
744 uint32_t SrcBitWidth = SrcTy->getBitWidth();
745
746 APInt MaskIn(Mask);
747 MaskIn.trunc(SrcBitWidth);
748 KnownZero.trunc(SrcBitWidth);
749 KnownOne.trunc(SrcBitWidth);
750 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
751 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
752 KnownZero.zext(BitWidth);
753 KnownOne.zext(BitWidth);
754
755 // If the sign bit of the input is known set or clear, then we know the
756 // top bits of the result.
757 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
758 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
759 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
760 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
761 return;
762 }
763 case Instruction::Shl:
764 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
765 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
766 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
767 APInt Mask2(Mask.lshr(ShiftAmt));
768 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
769 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
770 KnownZero <<= ShiftAmt;
771 KnownOne <<= ShiftAmt;
772 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
773 return;
774 }
775 break;
776 case Instruction::LShr:
777 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
778 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
779 // Compute the new bits that are at the top now.
780 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
781
782 // Unsigned shift right.
783 APInt Mask2(Mask.shl(ShiftAmt));
784 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
785 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
786 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
787 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
788 // high bits known zero.
789 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
790 return;
791 }
792 break;
793 case Instruction::AShr:
794 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
795 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
796 // Compute the new bits that are at the top now.
797 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
798
799 // Signed shift right.
800 APInt Mask2(Mask.shl(ShiftAmt));
801 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
802 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
803 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
804 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
805
806 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
807 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
808 KnownZero |= HighBits;
809 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
810 KnownOne |= HighBits;
811 return;
812 }
813 break;
814 }
815}
816
817/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
818/// this predicate to simplify operations downstream. Mask is known to be zero
819/// for bits that V cannot have.
820static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
821 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
822 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
823 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
824 return (KnownZero & Mask) == Mask;
825}
826
827/// ShrinkDemandedConstant - Check to see if the specified operand of the
828/// specified instruction is a constant integer. If so, check to see if there
829/// are any bits set in the constant that are not demanded. If so, shrink the
830/// constant and return true.
831static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
832 APInt Demanded) {
833 assert(I && "No instruction?");
834 assert(OpNo < I->getNumOperands() && "Operand index too large");
835
836 // If the operand is not a constant integer, nothing to do.
837 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
838 if (!OpC) return false;
839
840 // If there are no bits set that aren't demanded, nothing to do.
841 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
842 if ((~Demanded & OpC->getValue()) == 0)
843 return false;
844
845 // This instruction is producing bits that are not demanded. Shrink the RHS.
846 Demanded &= OpC->getValue();
847 I->setOperand(OpNo, ConstantInt::get(Demanded));
848 return true;
849}
850
851// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
852// set of known zero and one bits, compute the maximum and minimum values that
853// could have the specified known zero and known one bits, returning them in
854// min/max.
855static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
856 const APInt& KnownZero,
857 const APInt& KnownOne,
858 APInt& Min, APInt& Max) {
859 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
860 assert(KnownZero.getBitWidth() == BitWidth &&
861 KnownOne.getBitWidth() == BitWidth &&
862 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
863 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
864 APInt UnknownBits = ~(KnownZero|KnownOne);
865
866 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
867 // bit if it is unknown.
868 Min = KnownOne;
869 Max = KnownOne|UnknownBits;
870
871 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
872 Min.set(BitWidth-1);
873 Max.clear(BitWidth-1);
874 }
875}
876
877// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
878// a set of known zero and one bits, compute the maximum and minimum values that
879// could have the specified known zero and known one bits, returning them in
880// min/max.
881static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnerb933ea62007-08-05 08:47:58 +0000882 const APInt &KnownZero,
883 const APInt &KnownOne,
884 APInt &Min, APInt &Max) {
885 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000886 assert(KnownZero.getBitWidth() == BitWidth &&
887 KnownOne.getBitWidth() == BitWidth &&
888 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
889 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
890 APInt UnknownBits = ~(KnownZero|KnownOne);
891
892 // The minimum value is when the unknown bits are all zeros.
893 Min = KnownOne;
894 // The maximum value is when the unknown bits are all ones.
895 Max = KnownOne|UnknownBits;
896}
897
898/// SimplifyDemandedBits - This function attempts to replace V with a simpler
899/// value based on the demanded bits. When this function is called, it is known
900/// that only the bits set in DemandedMask of the result of V are ever used
901/// downstream. Consequently, depending on the mask and V, it may be possible
902/// to replace V with a constant or one of its operands. In such cases, this
903/// function does the replacement and returns true. In all other cases, it
904/// returns false after analyzing the expression and setting KnownOne and known
905/// to be one in the expression. KnownZero contains all the bits that are known
906/// to be zero in the expression. These are provided to potentially allow the
907/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
908/// the expression. KnownOne and KnownZero always follow the invariant that
909/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
910/// the bits in KnownOne and KnownZero may only be accurate for those bits set
911/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
912/// and KnownOne must all be the same.
913bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
914 APInt& KnownZero, APInt& KnownOne,
915 unsigned Depth) {
916 assert(V != 0 && "Null pointer of Value???");
917 assert(Depth <= 6 && "Limit Search Depth");
918 uint32_t BitWidth = DemandedMask.getBitWidth();
919 const IntegerType *VTy = cast<IntegerType>(V->getType());
920 assert(VTy->getBitWidth() == BitWidth &&
921 KnownZero.getBitWidth() == BitWidth &&
922 KnownOne.getBitWidth() == BitWidth &&
923 "Value *V, DemandedMask, KnownZero and KnownOne \
924 must have same BitWidth");
925 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
926 // We know all of the bits for a constant!
927 KnownOne = CI->getValue() & DemandedMask;
928 KnownZero = ~KnownOne & DemandedMask;
929 return false;
930 }
931
932 KnownZero.clear();
933 KnownOne.clear();
934 if (!V->hasOneUse()) { // Other users may use these bits.
935 if (Depth != 0) { // Not at the root.
936 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
937 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
938 return false;
939 }
940 // If this is the root being simplified, allow it to have multiple uses,
941 // just set the DemandedMask to all bits.
942 DemandedMask = APInt::getAllOnesValue(BitWidth);
943 } else if (DemandedMask == 0) { // Not demanding any bits from V.
944 if (V != UndefValue::get(VTy))
945 return UpdateValueUsesWith(V, UndefValue::get(VTy));
946 return false;
947 } else if (Depth == 6) { // Limit search depth.
948 return false;
949 }
950
951 Instruction *I = dyn_cast<Instruction>(V);
952 if (!I) return false; // Only analyze instructions.
953
954 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
955 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
956 switch (I->getOpcode()) {
957 default: break;
958 case Instruction::And:
959 // If either the LHS or the RHS are Zero, the result is zero.
960 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
961 RHSKnownZero, RHSKnownOne, Depth+1))
962 return true;
963 assert((RHSKnownZero & RHSKnownOne) == 0 &&
964 "Bits known to be one AND zero?");
965
966 // If something is known zero on the RHS, the bits aren't demanded on the
967 // LHS.
968 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
969 LHSKnownZero, LHSKnownOne, Depth+1))
970 return true;
971 assert((LHSKnownZero & LHSKnownOne) == 0 &&
972 "Bits known to be one AND zero?");
973
974 // If all of the demanded bits are known 1 on one side, return the other.
975 // These bits cannot contribute to the result of the 'and'.
976 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
977 (DemandedMask & ~LHSKnownZero))
978 return UpdateValueUsesWith(I, I->getOperand(0));
979 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
980 (DemandedMask & ~RHSKnownZero))
981 return UpdateValueUsesWith(I, I->getOperand(1));
982
983 // If all of the demanded bits in the inputs are known zeros, return zero.
984 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
985 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
986
987 // If the RHS is a constant, see if we can simplify it.
988 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
989 return UpdateValueUsesWith(I, I);
990
991 // Output known-1 bits are only known if set in both the LHS & RHS.
992 RHSKnownOne &= LHSKnownOne;
993 // Output known-0 are known to be clear if zero in either the LHS | RHS.
994 RHSKnownZero |= LHSKnownZero;
995 break;
996 case Instruction::Or:
997 // If either the LHS or the RHS are One, the result is One.
998 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
999 RHSKnownZero, RHSKnownOne, Depth+1))
1000 return true;
1001 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1002 "Bits known to be one AND zero?");
1003 // If something is known one on the RHS, the bits aren't demanded on the
1004 // LHS.
1005 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1006 LHSKnownZero, LHSKnownOne, Depth+1))
1007 return true;
1008 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1009 "Bits known to be one AND zero?");
1010
1011 // If all of the demanded bits are known zero on one side, return the other.
1012 // These bits cannot contribute to the result of the 'or'.
1013 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1014 (DemandedMask & ~LHSKnownOne))
1015 return UpdateValueUsesWith(I, I->getOperand(0));
1016 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1017 (DemandedMask & ~RHSKnownOne))
1018 return UpdateValueUsesWith(I, I->getOperand(1));
1019
1020 // If all of the potentially set bits on one side are known to be set on
1021 // the other side, just use the 'other' side.
1022 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1023 (DemandedMask & (~RHSKnownZero)))
1024 return UpdateValueUsesWith(I, I->getOperand(0));
1025 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1026 (DemandedMask & (~LHSKnownZero)))
1027 return UpdateValueUsesWith(I, I->getOperand(1));
1028
1029 // If the RHS is a constant, see if we can simplify it.
1030 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1031 return UpdateValueUsesWith(I, I);
1032
1033 // Output known-0 bits are only known if clear in both the LHS & RHS.
1034 RHSKnownZero &= LHSKnownZero;
1035 // Output known-1 are known to be set if set in either the LHS | RHS.
1036 RHSKnownOne |= LHSKnownOne;
1037 break;
1038 case Instruction::Xor: {
1039 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1040 RHSKnownZero, RHSKnownOne, Depth+1))
1041 return true;
1042 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1043 "Bits known to be one AND zero?");
1044 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1045 LHSKnownZero, LHSKnownOne, Depth+1))
1046 return true;
1047 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1048 "Bits known to be one AND zero?");
1049
1050 // If all of the demanded bits are known zero on one side, return the other.
1051 // These bits cannot contribute to the result of the 'xor'.
1052 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1053 return UpdateValueUsesWith(I, I->getOperand(0));
1054 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1055 return UpdateValueUsesWith(I, I->getOperand(1));
1056
1057 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1058 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1059 (RHSKnownOne & LHSKnownOne);
1060 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1061 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1062 (RHSKnownOne & LHSKnownZero);
1063
1064 // If all of the demanded bits are known to be zero on one side or the
1065 // other, turn this into an *inclusive* or.
1066 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1067 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1068 Instruction *Or =
1069 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1070 I->getName());
1071 InsertNewInstBefore(Or, *I);
1072 return UpdateValueUsesWith(I, Or);
1073 }
1074
1075 // If all of the demanded bits on one side are known, and all of the set
1076 // bits on that side are also known to be set on the other side, turn this
1077 // into an AND, as we know the bits will be cleared.
1078 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1079 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1080 // all known
1081 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1082 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1083 Instruction *And =
1084 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1085 InsertNewInstBefore(And, *I);
1086 return UpdateValueUsesWith(I, And);
1087 }
1088 }
1089
1090 // If the RHS is a constant, see if we can simplify it.
1091 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1092 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1093 return UpdateValueUsesWith(I, I);
1094
1095 RHSKnownZero = KnownZeroOut;
1096 RHSKnownOne = KnownOneOut;
1097 break;
1098 }
1099 case Instruction::Select:
1100 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1101 RHSKnownZero, RHSKnownOne, Depth+1))
1102 return true;
1103 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1104 LHSKnownZero, LHSKnownOne, Depth+1))
1105 return true;
1106 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1107 "Bits known to be one AND zero?");
1108 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1109 "Bits known to be one AND zero?");
1110
1111 // If the operands are constants, see if we can simplify them.
1112 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1113 return UpdateValueUsesWith(I, I);
1114 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1115 return UpdateValueUsesWith(I, I);
1116
1117 // Only known if known in both the LHS and RHS.
1118 RHSKnownOne &= LHSKnownOne;
1119 RHSKnownZero &= LHSKnownZero;
1120 break;
1121 case Instruction::Trunc: {
1122 uint32_t truncBf =
1123 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1124 DemandedMask.zext(truncBf);
1125 RHSKnownZero.zext(truncBf);
1126 RHSKnownOne.zext(truncBf);
1127 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1128 RHSKnownZero, RHSKnownOne, Depth+1))
1129 return true;
1130 DemandedMask.trunc(BitWidth);
1131 RHSKnownZero.trunc(BitWidth);
1132 RHSKnownOne.trunc(BitWidth);
1133 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1134 "Bits known to be one AND zero?");
1135 break;
1136 }
1137 case Instruction::BitCast:
1138 if (!I->getOperand(0)->getType()->isInteger())
1139 return false;
1140
1141 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1142 RHSKnownZero, RHSKnownOne, Depth+1))
1143 return true;
1144 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1145 "Bits known to be one AND zero?");
1146 break;
1147 case Instruction::ZExt: {
1148 // Compute the bits in the result that are not present in the input.
1149 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1150 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1151
1152 DemandedMask.trunc(SrcBitWidth);
1153 RHSKnownZero.trunc(SrcBitWidth);
1154 RHSKnownOne.trunc(SrcBitWidth);
1155 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1156 RHSKnownZero, RHSKnownOne, Depth+1))
1157 return true;
1158 DemandedMask.zext(BitWidth);
1159 RHSKnownZero.zext(BitWidth);
1160 RHSKnownOne.zext(BitWidth);
1161 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1162 "Bits known to be one AND zero?");
1163 // The top bits are known to be zero.
1164 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1165 break;
1166 }
1167 case Instruction::SExt: {
1168 // Compute the bits in the result that are not present in the input.
1169 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1170 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1171
1172 APInt InputDemandedBits = DemandedMask &
1173 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1174
1175 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1176 // If any of the sign extended bits are demanded, we know that the sign
1177 // bit is demanded.
1178 if ((NewBits & DemandedMask) != 0)
1179 InputDemandedBits.set(SrcBitWidth-1);
1180
1181 InputDemandedBits.trunc(SrcBitWidth);
1182 RHSKnownZero.trunc(SrcBitWidth);
1183 RHSKnownOne.trunc(SrcBitWidth);
1184 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1185 RHSKnownZero, RHSKnownOne, Depth+1))
1186 return true;
1187 InputDemandedBits.zext(BitWidth);
1188 RHSKnownZero.zext(BitWidth);
1189 RHSKnownOne.zext(BitWidth);
1190 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1191 "Bits known to be one AND zero?");
1192
1193 // If the sign bit of the input is known set or clear, then we know the
1194 // top bits of the result.
1195
1196 // If the input sign bit is known zero, or if the NewBits are not demanded
1197 // convert this into a zero extension.
1198 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1199 {
1200 // Convert to ZExt cast
1201 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1202 return UpdateValueUsesWith(I, NewCast);
1203 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1204 RHSKnownOne |= NewBits;
1205 }
1206 break;
1207 }
1208 case Instruction::Add: {
1209 // Figure out what the input bits are. If the top bits of the and result
1210 // are not demanded, then the add doesn't demand them from its input
1211 // either.
1212 uint32_t NLZ = DemandedMask.countLeadingZeros();
1213
1214 // If there is a constant on the RHS, there are a variety of xformations
1215 // we can do.
1216 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1217 // If null, this should be simplified elsewhere. Some of the xforms here
1218 // won't work if the RHS is zero.
1219 if (RHS->isZero())
1220 break;
1221
1222 // If the top bit of the output is demanded, demand everything from the
1223 // input. Otherwise, we demand all the input bits except NLZ top bits.
1224 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1225
1226 // Find information about known zero/one bits in the input.
1227 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1228 LHSKnownZero, LHSKnownOne, Depth+1))
1229 return true;
1230
1231 // If the RHS of the add has bits set that can't affect the input, reduce
1232 // the constant.
1233 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1234 return UpdateValueUsesWith(I, I);
1235
1236 // Avoid excess work.
1237 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1238 break;
1239
1240 // Turn it into OR if input bits are zero.
1241 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1242 Instruction *Or =
1243 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1244 I->getName());
1245 InsertNewInstBefore(Or, *I);
1246 return UpdateValueUsesWith(I, Or);
1247 }
1248
1249 // We can say something about the output known-zero and known-one bits,
1250 // depending on potential carries from the input constant and the
1251 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1252 // bits set and the RHS constant is 0x01001, then we know we have a known
1253 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1254
1255 // To compute this, we first compute the potential carry bits. These are
1256 // the bits which may be modified. I'm not aware of a better way to do
1257 // this scan.
1258 const APInt& RHSVal = RHS->getValue();
1259 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1260
1261 // Now that we know which bits have carries, compute the known-1/0 sets.
1262
1263 // Bits are known one if they are known zero in one operand and one in the
1264 // other, and there is no input carry.
1265 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1266 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1267
1268 // Bits are known zero if they are known zero in both operands and there
1269 // is no input carry.
1270 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1271 } else {
1272 // If the high-bits of this ADD are not demanded, then it does not demand
1273 // the high bits of its LHS or RHS.
1274 if (DemandedMask[BitWidth-1] == 0) {
1275 // Right fill the mask of bits for this ADD to demand the most
1276 // significant bit and all those below it.
1277 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1278 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1279 LHSKnownZero, LHSKnownOne, Depth+1))
1280 return true;
1281 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1282 LHSKnownZero, LHSKnownOne, Depth+1))
1283 return true;
1284 }
1285 }
1286 break;
1287 }
1288 case Instruction::Sub:
1289 // If the high-bits of this SUB are not demanded, then it does not demand
1290 // the high bits of its LHS or RHS.
1291 if (DemandedMask[BitWidth-1] == 0) {
1292 // Right fill the mask of bits for this SUB to demand the most
1293 // significant bit and all those below it.
1294 uint32_t NLZ = DemandedMask.countLeadingZeros();
1295 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1296 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1297 LHSKnownZero, LHSKnownOne, Depth+1))
1298 return true;
1299 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1300 LHSKnownZero, LHSKnownOne, Depth+1))
1301 return true;
1302 }
1303 break;
1304 case Instruction::Shl:
1305 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1306 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1307 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1308 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1309 RHSKnownZero, RHSKnownOne, Depth+1))
1310 return true;
1311 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1312 "Bits known to be one AND zero?");
1313 RHSKnownZero <<= ShiftAmt;
1314 RHSKnownOne <<= ShiftAmt;
1315 // low bits known zero.
1316 if (ShiftAmt)
1317 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1318 }
1319 break;
1320 case Instruction::LShr:
1321 // For a logical shift right
1322 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1323 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1324
1325 // Unsigned shift right.
1326 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1327 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1328 RHSKnownZero, RHSKnownOne, Depth+1))
1329 return true;
1330 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1331 "Bits known to be one AND zero?");
1332 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1333 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1334 if (ShiftAmt) {
1335 // Compute the new bits that are at the top now.
1336 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1337 RHSKnownZero |= HighBits; // high bits known zero.
1338 }
1339 }
1340 break;
1341 case Instruction::AShr:
1342 // If this is an arithmetic shift right and only the low-bit is set, we can
1343 // always convert this into a logical shr, even if the shift amount is
1344 // variable. The low bit of the shift cannot be an input sign bit unless
1345 // the shift amount is >= the size of the datatype, which is undefined.
1346 if (DemandedMask == 1) {
1347 // Perform the logical shift right.
1348 Value *NewVal = BinaryOperator::createLShr(
1349 I->getOperand(0), I->getOperand(1), I->getName());
1350 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1351 return UpdateValueUsesWith(I, NewVal);
1352 }
1353
1354 // If the sign bit is the only bit demanded by this ashr, then there is no
1355 // need to do it, the shift doesn't change the high bit.
1356 if (DemandedMask.isSignBit())
1357 return UpdateValueUsesWith(I, I->getOperand(0));
1358
1359 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1360 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1361
1362 // Signed shift right.
1363 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1364 // If any of the "high bits" are demanded, we should set the sign bit as
1365 // demanded.
1366 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1367 DemandedMaskIn.set(BitWidth-1);
1368 if (SimplifyDemandedBits(I->getOperand(0),
1369 DemandedMaskIn,
1370 RHSKnownZero, RHSKnownOne, Depth+1))
1371 return true;
1372 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1373 "Bits known to be one AND zero?");
1374 // Compute the new bits that are at the top now.
1375 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1376 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1377 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1378
1379 // Handle the sign bits.
1380 APInt SignBit(APInt::getSignBit(BitWidth));
1381 // Adjust to where it is now in the mask.
1382 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1383
1384 // If the input sign bit is known to be zero, or if none of the top bits
1385 // are demanded, turn this into an unsigned shift right.
1386 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
1387 (HighBits & ~DemandedMask) == HighBits) {
1388 // Perform the logical shift right.
1389 Value *NewVal = BinaryOperator::createLShr(
1390 I->getOperand(0), SA, I->getName());
1391 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1392 return UpdateValueUsesWith(I, NewVal);
1393 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1394 RHSKnownOne |= HighBits;
1395 }
1396 }
1397 break;
1398 }
1399
1400 // If the client is only demanding bits that we know, return the known
1401 // constant.
1402 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1403 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1404 return false;
1405}
1406
1407
1408/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1409/// 64 or fewer elements. DemandedElts contains the set of elements that are
1410/// actually used by the caller. This method analyzes which elements of the
1411/// operand are undef and returns that information in UndefElts.
1412///
1413/// If the information about demanded elements can be used to simplify the
1414/// operation, the operation is simplified, then the resultant value is
1415/// returned. This returns null if no change was made.
1416Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1417 uint64_t &UndefElts,
1418 unsigned Depth) {
1419 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1420 assert(VWidth <= 64 && "Vector too wide to analyze!");
1421 uint64_t EltMask = ~0ULL >> (64-VWidth);
1422 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1423 "Invalid DemandedElts!");
1424
1425 if (isa<UndefValue>(V)) {
1426 // If the entire vector is undefined, just return this info.
1427 UndefElts = EltMask;
1428 return 0;
1429 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1430 UndefElts = EltMask;
1431 return UndefValue::get(V->getType());
1432 }
1433
1434 UndefElts = 0;
1435 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1436 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1437 Constant *Undef = UndefValue::get(EltTy);
1438
1439 std::vector<Constant*> Elts;
1440 for (unsigned i = 0; i != VWidth; ++i)
1441 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1442 Elts.push_back(Undef);
1443 UndefElts |= (1ULL << i);
1444 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1445 Elts.push_back(Undef);
1446 UndefElts |= (1ULL << i);
1447 } else { // Otherwise, defined.
1448 Elts.push_back(CP->getOperand(i));
1449 }
1450
1451 // If we changed the constant, return it.
1452 Constant *NewCP = ConstantVector::get(Elts);
1453 return NewCP != CP ? NewCP : 0;
1454 } else if (isa<ConstantAggregateZero>(V)) {
1455 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1456 // set to undef.
1457 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1458 Constant *Zero = Constant::getNullValue(EltTy);
1459 Constant *Undef = UndefValue::get(EltTy);
1460 std::vector<Constant*> Elts;
1461 for (unsigned i = 0; i != VWidth; ++i)
1462 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1463 UndefElts = DemandedElts ^ EltMask;
1464 return ConstantVector::get(Elts);
1465 }
1466
1467 if (!V->hasOneUse()) { // Other users may use these bits.
1468 if (Depth != 0) { // Not at the root.
1469 // TODO: Just compute the UndefElts information recursively.
1470 return false;
1471 }
1472 return false;
1473 } else if (Depth == 10) { // Limit search depth.
1474 return false;
1475 }
1476
1477 Instruction *I = dyn_cast<Instruction>(V);
1478 if (!I) return false; // Only analyze instructions.
1479
1480 bool MadeChange = false;
1481 uint64_t UndefElts2;
1482 Value *TmpV;
1483 switch (I->getOpcode()) {
1484 default: break;
1485
1486 case Instruction::InsertElement: {
1487 // If this is a variable index, we don't know which element it overwrites.
1488 // demand exactly the same input as we produce.
1489 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1490 if (Idx == 0) {
1491 // Note that we can't propagate undef elt info, because we don't know
1492 // which elt is getting updated.
1493 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1494 UndefElts2, Depth+1);
1495 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1496 break;
1497 }
1498
1499 // If this is inserting an element that isn't demanded, remove this
1500 // insertelement.
1501 unsigned IdxNo = Idx->getZExtValue();
1502 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1503 return AddSoonDeadInstToWorklist(*I, 0);
1504
1505 // Otherwise, the element inserted overwrites whatever was there, so the
1506 // input demanded set is simpler than the output set.
1507 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1508 DemandedElts & ~(1ULL << IdxNo),
1509 UndefElts, Depth+1);
1510 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1511
1512 // The inserted element is defined.
1513 UndefElts |= 1ULL << IdxNo;
1514 break;
1515 }
1516 case Instruction::BitCast: {
1517 // Vector->vector casts only.
1518 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1519 if (!VTy) break;
1520 unsigned InVWidth = VTy->getNumElements();
1521 uint64_t InputDemandedElts = 0;
1522 unsigned Ratio;
1523
1524 if (VWidth == InVWidth) {
1525 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1526 // elements as are demanded of us.
1527 Ratio = 1;
1528 InputDemandedElts = DemandedElts;
1529 } else if (VWidth > InVWidth) {
1530 // Untested so far.
1531 break;
1532
1533 // If there are more elements in the result than there are in the source,
1534 // then an input element is live if any of the corresponding output
1535 // elements are live.
1536 Ratio = VWidth/InVWidth;
1537 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1538 if (DemandedElts & (1ULL << OutIdx))
1539 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1540 }
1541 } else {
1542 // Untested so far.
1543 break;
1544
1545 // If there are more elements in the source than there are in the result,
1546 // then an input element is live if the corresponding output element is
1547 // live.
1548 Ratio = InVWidth/VWidth;
1549 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1550 if (DemandedElts & (1ULL << InIdx/Ratio))
1551 InputDemandedElts |= 1ULL << InIdx;
1552 }
1553
1554 // div/rem demand all inputs, because they don't want divide by zero.
1555 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1556 UndefElts2, Depth+1);
1557 if (TmpV) {
1558 I->setOperand(0, TmpV);
1559 MadeChange = true;
1560 }
1561
1562 UndefElts = UndefElts2;
1563 if (VWidth > InVWidth) {
1564 assert(0 && "Unimp");
1565 // If there are more elements in the result than there are in the source,
1566 // then an output element is undef if the corresponding input element is
1567 // undef.
1568 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1569 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1570 UndefElts |= 1ULL << OutIdx;
1571 } else if (VWidth < InVWidth) {
1572 assert(0 && "Unimp");
1573 // If there are more elements in the source than there are in the result,
1574 // then a result element is undef if all of the corresponding input
1575 // elements are undef.
1576 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1577 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1578 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1579 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1580 }
1581 break;
1582 }
1583 case Instruction::And:
1584 case Instruction::Or:
1585 case Instruction::Xor:
1586 case Instruction::Add:
1587 case Instruction::Sub:
1588 case Instruction::Mul:
1589 // div/rem demand all inputs, because they don't want divide by zero.
1590 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1591 UndefElts, Depth+1);
1592 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1593 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1594 UndefElts2, Depth+1);
1595 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1596
1597 // Output elements are undefined if both are undefined. Consider things
1598 // like undef&0. The result is known zero, not undef.
1599 UndefElts &= UndefElts2;
1600 break;
1601
1602 case Instruction::Call: {
1603 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1604 if (!II) break;
1605 switch (II->getIntrinsicID()) {
1606 default: break;
1607
1608 // Binary vector operations that work column-wise. A dest element is a
1609 // function of the corresponding input elements from the two inputs.
1610 case Intrinsic::x86_sse_sub_ss:
1611 case Intrinsic::x86_sse_mul_ss:
1612 case Intrinsic::x86_sse_min_ss:
1613 case Intrinsic::x86_sse_max_ss:
1614 case Intrinsic::x86_sse2_sub_sd:
1615 case Intrinsic::x86_sse2_mul_sd:
1616 case Intrinsic::x86_sse2_min_sd:
1617 case Intrinsic::x86_sse2_max_sd:
1618 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1619 UndefElts, Depth+1);
1620 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1621 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1622 UndefElts2, Depth+1);
1623 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1624
1625 // If only the low elt is demanded and this is a scalarizable intrinsic,
1626 // scalarize it now.
1627 if (DemandedElts == 1) {
1628 switch (II->getIntrinsicID()) {
1629 default: break;
1630 case Intrinsic::x86_sse_sub_ss:
1631 case Intrinsic::x86_sse_mul_ss:
1632 case Intrinsic::x86_sse2_sub_sd:
1633 case Intrinsic::x86_sse2_mul_sd:
1634 // TODO: Lower MIN/MAX/ABS/etc
1635 Value *LHS = II->getOperand(1);
1636 Value *RHS = II->getOperand(2);
1637 // Extract the element as scalars.
1638 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1639 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1640
1641 switch (II->getIntrinsicID()) {
1642 default: assert(0 && "Case stmts out of sync!");
1643 case Intrinsic::x86_sse_sub_ss:
1644 case Intrinsic::x86_sse2_sub_sd:
1645 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1646 II->getName()), *II);
1647 break;
1648 case Intrinsic::x86_sse_mul_ss:
1649 case Intrinsic::x86_sse2_mul_sd:
1650 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1651 II->getName()), *II);
1652 break;
1653 }
1654
1655 Instruction *New =
1656 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1657 II->getName());
1658 InsertNewInstBefore(New, *II);
1659 AddSoonDeadInstToWorklist(*II, 0);
1660 return New;
1661 }
1662 }
1663
1664 // Output elements are undefined if both are undefined. Consider things
1665 // like undef&0. The result is known zero, not undef.
1666 UndefElts &= UndefElts2;
1667 break;
1668 }
1669 break;
1670 }
1671 }
1672 return MadeChange ? I : 0;
1673}
1674
Nick Lewycky2de09a92007-09-06 02:40:25 +00001675/// @returns true if the specified compare predicate is
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001676/// true when both operands are equal...
Nick Lewycky2de09a92007-09-06 02:40:25 +00001677/// @brief Determine if the icmp Predicate is true when both operands are equal
1678static bool isTrueWhenEqual(ICmpInst::Predicate pred) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001679 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1680 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1681 pred == ICmpInst::ICMP_SLE;
1682}
1683
Nick Lewycky2de09a92007-09-06 02:40:25 +00001684/// @returns true if the specified compare instruction is
1685/// true when both operands are equal...
1686/// @brief Determine if the ICmpInst returns true when both operands are equal
1687static bool isTrueWhenEqual(ICmpInst &ICI) {
1688 return isTrueWhenEqual(ICI.getPredicate());
1689}
1690
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001691/// AssociativeOpt - Perform an optimization on an associative operator. This
1692/// function is designed to check a chain of associative operators for a
1693/// potential to apply a certain optimization. Since the optimization may be
1694/// applicable if the expression was reassociated, this checks the chain, then
1695/// reassociates the expression as necessary to expose the optimization
1696/// opportunity. This makes use of a special Functor, which must define
1697/// 'shouldApply' and 'apply' methods.
1698///
1699template<typename Functor>
1700Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1701 unsigned Opcode = Root.getOpcode();
1702 Value *LHS = Root.getOperand(0);
1703
1704 // Quick check, see if the immediate LHS matches...
1705 if (F.shouldApply(LHS))
1706 return F.apply(Root);
1707
1708 // Otherwise, if the LHS is not of the same opcode as the root, return.
1709 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1710 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1711 // Should we apply this transform to the RHS?
1712 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1713
1714 // If not to the RHS, check to see if we should apply to the LHS...
1715 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1716 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1717 ShouldApply = true;
1718 }
1719
1720 // If the functor wants to apply the optimization to the RHS of LHSI,
1721 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1722 if (ShouldApply) {
1723 BasicBlock *BB = Root.getParent();
1724
1725 // Now all of the instructions are in the current basic block, go ahead
1726 // and perform the reassociation.
1727 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1728
1729 // First move the selected RHS to the LHS of the root...
1730 Root.setOperand(0, LHSI->getOperand(1));
1731
1732 // Make what used to be the LHS of the root be the user of the root...
1733 Value *ExtraOperand = TmpLHSI->getOperand(1);
1734 if (&Root == TmpLHSI) {
1735 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1736 return 0;
1737 }
1738 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1739 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1740 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1741 BasicBlock::iterator ARI = &Root; ++ARI;
1742 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1743 ARI = Root;
1744
1745 // Now propagate the ExtraOperand down the chain of instructions until we
1746 // get to LHSI.
1747 while (TmpLHSI != LHSI) {
1748 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1749 // Move the instruction to immediately before the chain we are
1750 // constructing to avoid breaking dominance properties.
1751 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1752 BB->getInstList().insert(ARI, NextLHSI);
1753 ARI = NextLHSI;
1754
1755 Value *NextOp = NextLHSI->getOperand(1);
1756 NextLHSI->setOperand(1, ExtraOperand);
1757 TmpLHSI = NextLHSI;
1758 ExtraOperand = NextOp;
1759 }
1760
1761 // Now that the instructions are reassociated, have the functor perform
1762 // the transformation...
1763 return F.apply(Root);
1764 }
1765
1766 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1767 }
1768 return 0;
1769}
1770
1771
1772// AddRHS - Implements: X + X --> X << 1
1773struct AddRHS {
1774 Value *RHS;
1775 AddRHS(Value *rhs) : RHS(rhs) {}
1776 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1777 Instruction *apply(BinaryOperator &Add) const {
1778 return BinaryOperator::createShl(Add.getOperand(0),
1779 ConstantInt::get(Add.getType(), 1));
1780 }
1781};
1782
1783// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1784// iff C1&C2 == 0
1785struct AddMaskingAnd {
1786 Constant *C2;
1787 AddMaskingAnd(Constant *c) : C2(c) {}
1788 bool shouldApply(Value *LHS) const {
1789 ConstantInt *C1;
1790 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1791 ConstantExpr::getAnd(C1, C2)->isNullValue();
1792 }
1793 Instruction *apply(BinaryOperator &Add) const {
1794 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1795 }
1796};
1797
1798static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1799 InstCombiner *IC) {
1800 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1801 if (Constant *SOC = dyn_cast<Constant>(SO))
1802 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1803
1804 return IC->InsertNewInstBefore(CastInst::create(
1805 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1806 }
1807
1808 // Figure out if the constant is the left or the right argument.
1809 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1810 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1811
1812 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1813 if (ConstIsRHS)
1814 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1815 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1816 }
1817
1818 Value *Op0 = SO, *Op1 = ConstOperand;
1819 if (!ConstIsRHS)
1820 std::swap(Op0, Op1);
1821 Instruction *New;
1822 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1823 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1824 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1825 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1826 SO->getName()+".cmp");
1827 else {
1828 assert(0 && "Unknown binary instruction type!");
1829 abort();
1830 }
1831 return IC->InsertNewInstBefore(New, I);
1832}
1833
1834// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1835// constant as the other operand, try to fold the binary operator into the
1836// select arguments. This also works for Cast instructions, which obviously do
1837// not have a second operand.
1838static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1839 InstCombiner *IC) {
1840 // Don't modify shared select instructions
1841 if (!SI->hasOneUse()) return 0;
1842 Value *TV = SI->getOperand(1);
1843 Value *FV = SI->getOperand(2);
1844
1845 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1846 // Bool selects with constant operands can be folded to logical ops.
1847 if (SI->getType() == Type::Int1Ty) return 0;
1848
1849 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1850 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1851
1852 return new SelectInst(SI->getCondition(), SelectTrueVal,
1853 SelectFalseVal);
1854 }
1855 return 0;
1856}
1857
1858
1859/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1860/// node as operand #0, see if we can fold the instruction into the PHI (which
1861/// is only possible if all operands to the PHI are constants).
1862Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1863 PHINode *PN = cast<PHINode>(I.getOperand(0));
1864 unsigned NumPHIValues = PN->getNumIncomingValues();
1865 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1866
1867 // Check to see if all of the operands of the PHI are constants. If there is
1868 // one non-constant value, remember the BB it is. If there is more than one
1869 // or if *it* is a PHI, bail out.
1870 BasicBlock *NonConstBB = 0;
1871 for (unsigned i = 0; i != NumPHIValues; ++i)
1872 if (!isa<Constant>(PN->getIncomingValue(i))) {
1873 if (NonConstBB) return 0; // More than one non-const value.
1874 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1875 NonConstBB = PN->getIncomingBlock(i);
1876
1877 // If the incoming non-constant value is in I's block, we have an infinite
1878 // loop.
1879 if (NonConstBB == I.getParent())
1880 return 0;
1881 }
1882
1883 // If there is exactly one non-constant value, we can insert a copy of the
1884 // operation in that block. However, if this is a critical edge, we would be
1885 // inserting the computation one some other paths (e.g. inside a loop). Only
1886 // do this if the pred block is unconditionally branching into the phi block.
1887 if (NonConstBB) {
1888 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1889 if (!BI || !BI->isUnconditional()) return 0;
1890 }
1891
1892 // Okay, we can do the transformation: create the new PHI node.
1893 PHINode *NewPN = new PHINode(I.getType(), "");
1894 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1895 InsertNewInstBefore(NewPN, *PN);
1896 NewPN->takeName(PN);
1897
1898 // Next, add all of the operands to the PHI.
1899 if (I.getNumOperands() == 2) {
1900 Constant *C = cast<Constant>(I.getOperand(1));
1901 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00001902 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001903 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1904 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1905 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1906 else
1907 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1908 } else {
1909 assert(PN->getIncomingBlock(i) == NonConstBB);
1910 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1911 InV = BinaryOperator::create(BO->getOpcode(),
1912 PN->getIncomingValue(i), C, "phitmp",
1913 NonConstBB->getTerminator());
1914 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1915 InV = CmpInst::create(CI->getOpcode(),
1916 CI->getPredicate(),
1917 PN->getIncomingValue(i), C, "phitmp",
1918 NonConstBB->getTerminator());
1919 else
1920 assert(0 && "Unknown binop!");
1921
1922 AddToWorkList(cast<Instruction>(InV));
1923 }
1924 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1925 }
1926 } else {
1927 CastInst *CI = cast<CastInst>(&I);
1928 const Type *RetTy = CI->getType();
1929 for (unsigned i = 0; i != NumPHIValues; ++i) {
1930 Value *InV;
1931 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1932 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1933 } else {
1934 assert(PN->getIncomingBlock(i) == NonConstBB);
1935 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1936 I.getType(), "phitmp",
1937 NonConstBB->getTerminator());
1938 AddToWorkList(cast<Instruction>(InV));
1939 }
1940 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1941 }
1942 }
1943 return ReplaceInstUsesWith(I, NewPN);
1944}
1945
1946Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1947 bool Changed = SimplifyCommutative(I);
1948 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1949
1950 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1951 // X + undef -> undef
1952 if (isa<UndefValue>(RHS))
1953 return ReplaceInstUsesWith(I, RHS);
1954
1955 // X + 0 --> X
1956 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1957 if (RHSC->isNullValue())
1958 return ReplaceInstUsesWith(I, LHS);
1959 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen2fc20782007-09-14 22:26:36 +00001960 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1961 (I.getType())->getValueAPF()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001962 return ReplaceInstUsesWith(I, LHS);
1963 }
1964
1965 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1966 // X + (signbit) --> X ^ signbit
1967 const APInt& Val = CI->getValue();
1968 uint32_t BitWidth = Val.getBitWidth();
1969 if (Val == APInt::getSignBit(BitWidth))
1970 return BinaryOperator::createXor(LHS, RHS);
1971
1972 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1973 // (X & 254)+1 -> (X&254)|1
1974 if (!isa<VectorType>(I.getType())) {
1975 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1976 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1977 KnownZero, KnownOne))
1978 return &I;
1979 }
1980 }
1981
1982 if (isa<PHINode>(LHS))
1983 if (Instruction *NV = FoldOpIntoPhi(I))
1984 return NV;
1985
1986 ConstantInt *XorRHS = 0;
1987 Value *XorLHS = 0;
1988 if (isa<ConstantInt>(RHSC) &&
1989 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
1990 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
1991 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
1992
1993 uint32_t Size = TySizeBits / 2;
1994 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
1995 APInt CFF80Val(-C0080Val);
1996 do {
1997 if (TySizeBits > Size) {
1998 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
1999 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2000 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2001 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2002 // This is a sign extend if the top bits are known zero.
2003 if (!MaskedValueIsZero(XorLHS,
2004 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2005 Size = 0; // Not a sign ext, but can't be any others either.
2006 break;
2007 }
2008 }
2009 Size >>= 1;
2010 C0080Val = APIntOps::lshr(C0080Val, Size);
2011 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2012 } while (Size >= 1);
2013
2014 // FIXME: This shouldn't be necessary. When the backends can handle types
2015 // with funny bit widths then this whole cascade of if statements should
2016 // be removed. It is just here to get the size of the "middle" type back
2017 // up to something that the back ends can handle.
2018 const Type *MiddleType = 0;
2019 switch (Size) {
2020 default: break;
2021 case 32: MiddleType = Type::Int32Ty; break;
2022 case 16: MiddleType = Type::Int16Ty; break;
2023 case 8: MiddleType = Type::Int8Ty; break;
2024 }
2025 if (MiddleType) {
2026 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2027 InsertNewInstBefore(NewTrunc, I);
2028 return new SExtInst(NewTrunc, I.getType(), I.getName());
2029 }
2030 }
2031 }
2032
2033 // X + X --> X << 1
2034 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
2035 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2036
2037 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2038 if (RHSI->getOpcode() == Instruction::Sub)
2039 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2040 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2041 }
2042 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2043 if (LHSI->getOpcode() == Instruction::Sub)
2044 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2045 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2046 }
2047 }
2048
2049 // -A + B --> B - A
2050 if (Value *V = dyn_castNegVal(LHS))
2051 return BinaryOperator::createSub(RHS, V);
2052
2053 // A + -B --> A - B
2054 if (!isa<Constant>(RHS))
2055 if (Value *V = dyn_castNegVal(RHS))
2056 return BinaryOperator::createSub(LHS, V);
2057
2058
2059 ConstantInt *C2;
2060 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2061 if (X == RHS) // X*C + X --> X * (C+1)
2062 return BinaryOperator::createMul(RHS, AddOne(C2));
2063
2064 // X*C1 + X*C2 --> X * (C1+C2)
2065 ConstantInt *C1;
2066 if (X == dyn_castFoldableMul(RHS, C1))
2067 return BinaryOperator::createMul(X, Add(C1, C2));
2068 }
2069
2070 // X + X*C --> X * (C+1)
2071 if (dyn_castFoldableMul(RHS, C2) == LHS)
2072 return BinaryOperator::createMul(LHS, AddOne(C2));
2073
2074 // X + ~X --> -1 since ~X = -X-1
2075 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2076 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2077
2078
2079 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2080 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2081 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2082 return R;
2083
2084 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2085 Value *X = 0;
2086 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2087 return BinaryOperator::createSub(SubOne(CRHS), X);
2088
2089 // (X & FF00) + xx00 -> (X+xx00) & FF00
2090 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2091 Constant *Anded = And(CRHS, C2);
2092 if (Anded == CRHS) {
2093 // See if all bits from the first bit set in the Add RHS up are included
2094 // in the mask. First, get the rightmost bit.
2095 const APInt& AddRHSV = CRHS->getValue();
2096
2097 // Form a mask of all bits from the lowest bit added through the top.
2098 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2099
2100 // See if the and mask includes all of these bits.
2101 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2102
2103 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2104 // Okay, the xform is safe. Insert the new add pronto.
2105 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2106 LHS->getName()), I);
2107 return BinaryOperator::createAnd(NewAdd, C2);
2108 }
2109 }
2110 }
2111
2112 // Try to fold constant add into select arguments.
2113 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2114 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2115 return R;
2116 }
2117
2118 // add (cast *A to intptrtype) B ->
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002119 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002120 {
2121 CastInst *CI = dyn_cast<CastInst>(LHS);
2122 Value *Other = RHS;
2123 if (!CI) {
2124 CI = dyn_cast<CastInst>(RHS);
2125 Other = LHS;
2126 }
2127 if (CI && CI->getType()->isSized() &&
2128 (CI->getType()->getPrimitiveSizeInBits() ==
2129 TD->getIntPtrType()->getPrimitiveSizeInBits())
2130 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00002131 unsigned AS =
2132 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +00002133 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2134 PointerType::get(Type::Int8Ty, AS), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002135 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
2136 return new PtrToIntInst(I2, CI->getType());
2137 }
2138 }
Christopher Lamb244ec282007-12-18 09:34:41 +00002139
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002140 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb244ec282007-12-18 09:34:41 +00002141 {
2142 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2143 Value *Other = RHS;
2144 if (!SI) {
2145 SI = dyn_cast<SelectInst>(RHS);
2146 Other = LHS;
2147 }
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002148 if (SI && SI->hasOneUse()) {
Christopher Lamb244ec282007-12-18 09:34:41 +00002149 Value *TV = SI->getTrueValue();
2150 Value *FV = SI->getFalseValue();
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002151 Value *A, *N;
Christopher Lamb244ec282007-12-18 09:34:41 +00002152
2153 // Can we fold the add into the argument of the select?
2154 // We check both true and false select arguments for a matching subtract.
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002155 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2156 A == Other) // Fold the add into the true select value.
2157 return new SelectInst(SI->getCondition(), N, A);
2158 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2159 A == Other) // Fold the add into the false select value.
2160 return new SelectInst(SI->getCondition(), A, N);
Christopher Lamb244ec282007-12-18 09:34:41 +00002161 }
2162 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002163
2164 return Changed ? &I : 0;
2165}
2166
2167// isSignBit - Return true if the value represented by the constant only has the
2168// highest order bit set.
2169static bool isSignBit(ConstantInt *CI) {
2170 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
2171 return CI->getValue() == APInt::getSignBit(NumBits);
2172}
2173
2174Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2175 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2176
2177 if (Op0 == Op1) // sub X, X -> 0
2178 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2179
2180 // If this is a 'B = x-(-A)', change to B = x+A...
2181 if (Value *V = dyn_castNegVal(Op1))
2182 return BinaryOperator::createAdd(Op0, V);
2183
2184 if (isa<UndefValue>(Op0))
2185 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2186 if (isa<UndefValue>(Op1))
2187 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2188
2189 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2190 // Replace (-1 - A) with (~A)...
2191 if (C->isAllOnesValue())
2192 return BinaryOperator::createNot(Op1);
2193
2194 // C - ~X == X + (1+C)
2195 Value *X = 0;
2196 if (match(Op1, m_Not(m_Value(X))))
2197 return BinaryOperator::createAdd(X, AddOne(C));
2198
2199 // -(X >>u 31) -> (X >>s 31)
2200 // -(X >>s 31) -> (X >>u 31)
2201 if (C->isZero()) {
2202 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
2203 if (SI->getOpcode() == Instruction::LShr) {
2204 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2205 // Check to see if we are shifting out everything but the sign bit.
2206 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2207 SI->getType()->getPrimitiveSizeInBits()-1) {
2208 // Ok, the transformation is safe. Insert AShr.
2209 return BinaryOperator::create(Instruction::AShr,
2210 SI->getOperand(0), CU, SI->getName());
2211 }
2212 }
2213 }
2214 else if (SI->getOpcode() == Instruction::AShr) {
2215 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2216 // Check to see if we are shifting out everything but the sign bit.
2217 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2218 SI->getType()->getPrimitiveSizeInBits()-1) {
2219 // Ok, the transformation is safe. Insert LShr.
2220 return BinaryOperator::createLShr(
2221 SI->getOperand(0), CU, SI->getName());
2222 }
2223 }
2224 }
2225 }
2226
2227 // Try to fold constant sub into select arguments.
2228 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2229 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2230 return R;
2231
2232 if (isa<PHINode>(Op0))
2233 if (Instruction *NV = FoldOpIntoPhi(I))
2234 return NV;
2235 }
2236
2237 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2238 if (Op1I->getOpcode() == Instruction::Add &&
2239 !Op0->getType()->isFPOrFPVector()) {
2240 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2241 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
2242 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2243 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2244 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2245 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2246 // C1-(X+C2) --> (C1-C2)-X
2247 return BinaryOperator::createSub(Subtract(CI1, CI2),
2248 Op1I->getOperand(0));
2249 }
2250 }
2251
2252 if (Op1I->hasOneUse()) {
2253 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2254 // is not used by anyone else...
2255 //
2256 if (Op1I->getOpcode() == Instruction::Sub &&
2257 !Op1I->getType()->isFPOrFPVector()) {
2258 // Swap the two operands of the subexpr...
2259 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2260 Op1I->setOperand(0, IIOp1);
2261 Op1I->setOperand(1, IIOp0);
2262
2263 // Create the new top level add instruction...
2264 return BinaryOperator::createAdd(Op0, Op1);
2265 }
2266
2267 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2268 //
2269 if (Op1I->getOpcode() == Instruction::And &&
2270 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2271 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2272
2273 Value *NewNot =
2274 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2275 return BinaryOperator::createAnd(Op0, NewNot);
2276 }
2277
2278 // 0 - (X sdiv C) -> (X sdiv -C)
2279 if (Op1I->getOpcode() == Instruction::SDiv)
2280 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2281 if (CSI->isZero())
2282 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2283 return BinaryOperator::createSDiv(Op1I->getOperand(0),
2284 ConstantExpr::getNeg(DivRHS));
2285
2286 // X - X*C --> X * (1-C)
2287 ConstantInt *C2 = 0;
2288 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2289 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2290 return BinaryOperator::createMul(Op0, CP1);
2291 }
Dan Gohmanda338742007-09-17 17:31:57 +00002292
2293 // X - ((X / Y) * Y) --> X % Y
2294 if (Op1I->getOpcode() == Instruction::Mul)
2295 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2296 if (Op0 == I->getOperand(0) &&
2297 Op1I->getOperand(1) == I->getOperand(1)) {
2298 if (I->getOpcode() == Instruction::SDiv)
2299 return BinaryOperator::createSRem(Op0, Op1I->getOperand(1));
2300 if (I->getOpcode() == Instruction::UDiv)
2301 return BinaryOperator::createURem(Op0, Op1I->getOperand(1));
2302 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002303 }
2304 }
2305
2306 if (!Op0->getType()->isFPOrFPVector())
2307 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2308 if (Op0I->getOpcode() == Instruction::Add) {
2309 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2310 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2311 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2312 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2313 } else if (Op0I->getOpcode() == Instruction::Sub) {
2314 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2315 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2316 }
2317
2318 ConstantInt *C1;
2319 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2320 if (X == Op1) // X*C - X --> X * (C-1)
2321 return BinaryOperator::createMul(Op1, SubOne(C1));
2322
2323 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2324 if (X == dyn_castFoldableMul(Op1, C2))
2325 return BinaryOperator::createMul(Op1, Subtract(C1, C2));
2326 }
2327 return 0;
2328}
2329
2330/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2331/// comparison only checks the sign bit. If it only checks the sign bit, set
2332/// TrueIfSigned if the result of the comparison is true when the input value is
2333/// signed.
2334static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2335 bool &TrueIfSigned) {
2336 switch (pred) {
2337 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2338 TrueIfSigned = true;
2339 return RHS->isZero();
2340 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2341 TrueIfSigned = true;
2342 return RHS->isAllOnesValue();
2343 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2344 TrueIfSigned = false;
2345 return RHS->isAllOnesValue();
2346 case ICmpInst::ICMP_UGT:
2347 // True if LHS u> RHS and RHS == high-bit-mask - 1
2348 TrueIfSigned = true;
2349 return RHS->getValue() ==
2350 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2351 case ICmpInst::ICMP_UGE:
2352 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2353 TrueIfSigned = true;
2354 return RHS->getValue() ==
2355 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
2356 default:
2357 return false;
2358 }
2359}
2360
2361Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2362 bool Changed = SimplifyCommutative(I);
2363 Value *Op0 = I.getOperand(0);
2364
2365 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2366 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2367
2368 // Simplify mul instructions with a constant RHS...
2369 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2370 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2371
2372 // ((X << C1)*C2) == (X * (C2 << C1))
2373 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2374 if (SI->getOpcode() == Instruction::Shl)
2375 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2376 return BinaryOperator::createMul(SI->getOperand(0),
2377 ConstantExpr::getShl(CI, ShOp));
2378
2379 if (CI->isZero())
2380 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2381 if (CI->equalsInt(1)) // X * 1 == X
2382 return ReplaceInstUsesWith(I, Op0);
2383 if (CI->isAllOnesValue()) // X * -1 == 0 - X
2384 return BinaryOperator::createNeg(Op0, I.getName());
2385
2386 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2387 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
2388 return BinaryOperator::createShl(Op0,
2389 ConstantInt::get(Op0->getType(), Val.logBase2()));
2390 }
2391 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2392 if (Op1F->isNullValue())
2393 return ReplaceInstUsesWith(I, Op1);
2394
2395 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2396 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen2fc20782007-09-14 22:26:36 +00002397 // We need a better interface for long double here.
2398 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2399 if (Op1F->isExactlyValue(1.0))
2400 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002401 }
2402
2403 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2404 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2405 isa<ConstantInt>(Op0I->getOperand(1))) {
2406 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2407 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2408 Op1, "tmp");
2409 InsertNewInstBefore(Add, I);
2410 Value *C1C2 = ConstantExpr::getMul(Op1,
2411 cast<Constant>(Op0I->getOperand(1)));
2412 return BinaryOperator::createAdd(Add, C1C2);
2413
2414 }
2415
2416 // Try to fold constant mul into select arguments.
2417 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2418 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2419 return R;
2420
2421 if (isa<PHINode>(Op0))
2422 if (Instruction *NV = FoldOpIntoPhi(I))
2423 return NV;
2424 }
2425
2426 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2427 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2428 return BinaryOperator::createMul(Op0v, Op1v);
2429
2430 // If one of the operands of the multiply is a cast from a boolean value, then
2431 // we know the bool is either zero or one, so this is a 'masking' multiply.
2432 // See if we can simplify things based on how the boolean was originally
2433 // formed.
2434 CastInst *BoolCast = 0;
2435 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2436 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2437 BoolCast = CI;
2438 if (!BoolCast)
2439 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2440 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2441 BoolCast = CI;
2442 if (BoolCast) {
2443 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2444 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2445 const Type *SCOpTy = SCIOp0->getType();
2446 bool TIS = false;
2447
2448 // If the icmp is true iff the sign bit of X is set, then convert this
2449 // multiply into a shift/and combination.
2450 if (isa<ConstantInt>(SCIOp1) &&
2451 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2452 TIS) {
2453 // Shift the X value right to turn it into "all signbits".
2454 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2455 SCOpTy->getPrimitiveSizeInBits()-1);
2456 Value *V =
2457 InsertNewInstBefore(
2458 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
2459 BoolCast->getOperand(0)->getName()+
2460 ".mask"), I);
2461
2462 // If the multiply type is not the same as the source type, sign extend
2463 // or truncate to the multiply type.
2464 if (I.getType() != V->getType()) {
2465 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2466 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2467 Instruction::CastOps opcode =
2468 (SrcBits == DstBits ? Instruction::BitCast :
2469 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2470 V = InsertCastBefore(opcode, V, I.getType(), I);
2471 }
2472
2473 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2474 return BinaryOperator::createAnd(V, OtherOp);
2475 }
2476 }
2477 }
2478
2479 return Changed ? &I : 0;
2480}
2481
2482/// This function implements the transforms on div instructions that work
2483/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2484/// used by the visitors to those instructions.
2485/// @brief Transforms common to all three div instructions
2486Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2487 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2488
2489 // undef / X -> 0
2490 if (isa<UndefValue>(Op0))
2491 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2492
2493 // X / undef -> undef
2494 if (isa<UndefValue>(Op1))
2495 return ReplaceInstUsesWith(I, Op1);
2496
2497 // Handle cases involving: div X, (select Cond, Y, Z)
2498 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2499 // div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in the
2500 // same basic block, then we replace the select with Y, and the condition
2501 // of the select with false (if the cond value is in the same BB). If the
2502 // select has uses other than the div, this allows them to be simplified
2503 // also. Note that div X, Y is just as good as div X, 0 (undef)
2504 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2505 if (ST->isNullValue()) {
2506 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2507 if (CondI && CondI->getParent() == I.getParent())
2508 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2509 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2510 I.setOperand(1, SI->getOperand(2));
2511 else
2512 UpdateValueUsesWith(SI, SI->getOperand(2));
2513 return &I;
2514 }
2515
2516 // Likewise for: div X, (Cond ? Y : 0) -> div X, Y
2517 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2518 if (ST->isNullValue()) {
2519 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2520 if (CondI && CondI->getParent() == I.getParent())
2521 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2522 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2523 I.setOperand(1, SI->getOperand(1));
2524 else
2525 UpdateValueUsesWith(SI, SI->getOperand(1));
2526 return &I;
2527 }
2528 }
2529
2530 return 0;
2531}
2532
2533/// This function implements the transforms common to both integer division
2534/// instructions (udiv and sdiv). It is called by the visitors to those integer
2535/// division instructions.
2536/// @brief Common integer divide transforms
2537Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2538 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2539
2540 if (Instruction *Common = commonDivTransforms(I))
2541 return Common;
2542
2543 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2544 // div X, 1 == X
2545 if (RHS->equalsInt(1))
2546 return ReplaceInstUsesWith(I, Op0);
2547
2548 // (X / C1) / C2 -> X / (C1*C2)
2549 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2550 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2551 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2552 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2553 Multiply(RHS, LHSRHS));
2554 }
2555
2556 if (!RHS->isZero()) { // avoid X udiv 0
2557 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2558 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2559 return R;
2560 if (isa<PHINode>(Op0))
2561 if (Instruction *NV = FoldOpIntoPhi(I))
2562 return NV;
2563 }
2564 }
2565
2566 // 0 / X == 0, we don't need to preserve faults!
2567 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2568 if (LHS->equalsInt(0))
2569 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2570
2571 return 0;
2572}
2573
2574Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2575 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2576
2577 // Handle the integer div common cases
2578 if (Instruction *Common = commonIDivTransforms(I))
2579 return Common;
2580
2581 // X udiv C^2 -> X >> C
2582 // Check to see if this is an unsigned division with an exact power of 2,
2583 // if so, convert to a right shift.
2584 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2585 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
2586 return BinaryOperator::createLShr(Op0,
2587 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2588 }
2589
2590 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2591 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2592 if (RHSI->getOpcode() == Instruction::Shl &&
2593 isa<ConstantInt>(RHSI->getOperand(0))) {
2594 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2595 if (C1.isPowerOf2()) {
2596 Value *N = RHSI->getOperand(1);
2597 const Type *NTy = N->getType();
2598 if (uint32_t C2 = C1.logBase2()) {
2599 Constant *C2V = ConstantInt::get(NTy, C2);
2600 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
2601 }
2602 return BinaryOperator::createLShr(Op0, N);
2603 }
2604 }
2605 }
2606
2607 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2608 // where C1&C2 are powers of two.
2609 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2610 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2611 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2612 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2613 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2614 // Compute the shift amounts
2615 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2616 // Construct the "on true" case of the select
2617 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2618 Instruction *TSI = BinaryOperator::createLShr(
2619 Op0, TC, SI->getName()+".t");
2620 TSI = InsertNewInstBefore(TSI, I);
2621
2622 // Construct the "on false" case of the select
2623 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2624 Instruction *FSI = BinaryOperator::createLShr(
2625 Op0, FC, SI->getName()+".f");
2626 FSI = InsertNewInstBefore(FSI, I);
2627
2628 // construct the select instruction and return it.
2629 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2630 }
2631 }
2632 return 0;
2633}
2634
2635Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2636 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2637
2638 // Handle the integer div common cases
2639 if (Instruction *Common = commonIDivTransforms(I))
2640 return Common;
2641
2642 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2643 // sdiv X, -1 == -X
2644 if (RHS->isAllOnesValue())
2645 return BinaryOperator::createNeg(Op0);
2646
2647 // -X/C -> X/-C
2648 if (Value *LHSNeg = dyn_castNegVal(Op0))
2649 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2650 }
2651
2652 // If the sign bits of both operands are zero (i.e. we can prove they are
2653 // unsigned inputs), turn this into a udiv.
2654 if (I.getType()->isInteger()) {
2655 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2656 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmandb3dd962007-11-05 23:16:33 +00002657 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002658 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2659 }
2660 }
2661
2662 return 0;
2663}
2664
2665Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2666 return commonDivTransforms(I);
2667}
2668
2669/// GetFactor - If we can prove that the specified value is at least a multiple
2670/// of some factor, return that factor.
2671static Constant *GetFactor(Value *V) {
2672 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2673 return CI;
2674
2675 // Unless we can be tricky, we know this is a multiple of 1.
2676 Constant *Result = ConstantInt::get(V->getType(), 1);
2677
2678 Instruction *I = dyn_cast<Instruction>(V);
2679 if (!I) return Result;
2680
2681 if (I->getOpcode() == Instruction::Mul) {
2682 // Handle multiplies by a constant, etc.
2683 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2684 GetFactor(I->getOperand(1)));
2685 } else if (I->getOpcode() == Instruction::Shl) {
2686 // (X<<C) -> X * (1 << C)
2687 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2688 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2689 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2690 }
2691 } else if (I->getOpcode() == Instruction::And) {
2692 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2693 // X & 0xFFF0 is known to be a multiple of 16.
2694 uint32_t Zeros = RHS->getValue().countTrailingZeros();
Chris Lattnera03930e2007-11-23 22:35:18 +00002695 if (Zeros != V->getType()->getPrimitiveSizeInBits())// don't shift by "32"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002696 return ConstantExpr::getShl(Result,
2697 ConstantInt::get(Result->getType(), Zeros));
2698 }
2699 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2700 // Only handle int->int casts.
2701 if (!CI->isIntegerCast())
2702 return Result;
2703 Value *Op = CI->getOperand(0);
2704 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
2705 }
2706 return Result;
2707}
2708
2709/// This function implements the transforms on rem instructions that work
2710/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2711/// is used by the visitors to those instructions.
2712/// @brief Transforms common to all three rem instructions
2713Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2714 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2715
2716 // 0 % X == 0, we don't need to preserve faults!
2717 if (Constant *LHS = dyn_cast<Constant>(Op0))
2718 if (LHS->isNullValue())
2719 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2720
2721 if (isa<UndefValue>(Op0)) // undef % X -> 0
2722 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2723 if (isa<UndefValue>(Op1))
2724 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2725
2726 // Handle cases involving: rem X, (select Cond, Y, Z)
2727 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2728 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2729 // the same basic block, then we replace the select with Y, and the
2730 // condition of the select with false (if the cond value is in the same
2731 // BB). If the select has uses other than the div, this allows them to be
2732 // simplified also.
2733 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2734 if (ST->isNullValue()) {
2735 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2736 if (CondI && CondI->getParent() == I.getParent())
2737 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2738 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2739 I.setOperand(1, SI->getOperand(2));
2740 else
2741 UpdateValueUsesWith(SI, SI->getOperand(2));
2742 return &I;
2743 }
2744 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2745 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2746 if (ST->isNullValue()) {
2747 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2748 if (CondI && CondI->getParent() == I.getParent())
2749 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2750 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2751 I.setOperand(1, SI->getOperand(1));
2752 else
2753 UpdateValueUsesWith(SI, SI->getOperand(1));
2754 return &I;
2755 }
2756 }
2757
2758 return 0;
2759}
2760
2761/// This function implements the transforms common to both integer remainder
2762/// instructions (urem and srem). It is called by the visitors to those integer
2763/// remainder instructions.
2764/// @brief Common integer remainder transforms
2765Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2766 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2767
2768 if (Instruction *common = commonRemTransforms(I))
2769 return common;
2770
2771 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2772 // X % 0 == undef, we don't need to preserve faults!
2773 if (RHS->equalsInt(0))
2774 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2775
2776 if (RHS->equalsInt(1)) // X % 1 == 0
2777 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2778
2779 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2780 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2781 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2782 return R;
2783 } else if (isa<PHINode>(Op0I)) {
2784 if (Instruction *NV = FoldOpIntoPhi(I))
2785 return NV;
2786 }
2787 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2788 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
2789 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2790 }
2791 }
2792
2793 return 0;
2794}
2795
2796Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2797 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2798
2799 if (Instruction *common = commonIRemTransforms(I))
2800 return common;
2801
2802 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2803 // X urem C^2 -> X and C
2804 // Check to see if this is an unsigned remainder with an exact power of 2,
2805 // if so, convert to a bitwise and.
2806 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2807 if (C->getValue().isPowerOf2())
2808 return BinaryOperator::createAnd(Op0, SubOne(C));
2809 }
2810
2811 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2812 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2813 if (RHSI->getOpcode() == Instruction::Shl &&
2814 isa<ConstantInt>(RHSI->getOperand(0))) {
2815 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
2816 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2817 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2818 "tmp"), I);
2819 return BinaryOperator::createAnd(Op0, Add);
2820 }
2821 }
2822 }
2823
2824 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2825 // where C1&C2 are powers of two.
2826 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2827 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2828 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2829 // STO == 0 and SFO == 0 handled above.
2830 if ((STO->getValue().isPowerOf2()) &&
2831 (SFO->getValue().isPowerOf2())) {
2832 Value *TrueAnd = InsertNewInstBefore(
2833 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2834 Value *FalseAnd = InsertNewInstBefore(
2835 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2836 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2837 }
2838 }
2839 }
2840
2841 return 0;
2842}
2843
2844Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2845 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2846
Dan Gohmandb3dd962007-11-05 23:16:33 +00002847 // Handle the integer rem common cases
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002848 if (Instruction *common = commonIRemTransforms(I))
2849 return common;
2850
2851 if (Value *RHSNeg = dyn_castNegVal(Op1))
2852 if (!isa<ConstantInt>(RHSNeg) ||
2853 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
2854 // X % -Y -> X % Y
2855 AddUsesToWorkList(I);
2856 I.setOperand(1, RHSNeg);
2857 return &I;
2858 }
2859
Dan Gohmandb3dd962007-11-05 23:16:33 +00002860 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002861 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00002862 if (I.getType()->isInteger()) {
2863 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2864 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2865 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2866 return BinaryOperator::createURem(Op0, Op1, I.getName());
2867 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002868 }
2869
2870 return 0;
2871}
2872
2873Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2874 return commonRemTransforms(I);
2875}
2876
2877// isMaxValueMinusOne - return true if this is Max-1
2878static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2879 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2880 if (!isSigned)
2881 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
2882 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
2883}
2884
2885// isMinValuePlusOne - return true if this is Min+1
2886static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2887 if (!isSigned)
2888 return C->getValue() == 1; // unsigned
2889
2890 // Calculate 1111111111000000000000
2891 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2892 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
2893}
2894
2895// isOneBitSet - Return true if there is exactly one bit set in the specified
2896// constant.
2897static bool isOneBitSet(const ConstantInt *CI) {
2898 return CI->getValue().isPowerOf2();
2899}
2900
2901// isHighOnes - Return true if the constant is of the form 1+0+.
2902// This is the same as lowones(~X).
2903static bool isHighOnes(const ConstantInt *CI) {
2904 return (~CI->getValue() + 1).isPowerOf2();
2905}
2906
2907/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
2908/// are carefully arranged to allow folding of expressions such as:
2909///
2910/// (A < B) | (A > B) --> (A != B)
2911///
2912/// Note that this is only valid if the first and second predicates have the
2913/// same sign. Is illegal to do: (A u< B) | (A s> B)
2914///
2915/// Three bits are used to represent the condition, as follows:
2916/// 0 A > B
2917/// 1 A == B
2918/// 2 A < B
2919///
2920/// <=> Value Definition
2921/// 000 0 Always false
2922/// 001 1 A > B
2923/// 010 2 A == B
2924/// 011 3 A >= B
2925/// 100 4 A < B
2926/// 101 5 A != B
2927/// 110 6 A <= B
2928/// 111 7 Always true
2929///
2930static unsigned getICmpCode(const ICmpInst *ICI) {
2931 switch (ICI->getPredicate()) {
2932 // False -> 0
2933 case ICmpInst::ICMP_UGT: return 1; // 001
2934 case ICmpInst::ICMP_SGT: return 1; // 001
2935 case ICmpInst::ICMP_EQ: return 2; // 010
2936 case ICmpInst::ICMP_UGE: return 3; // 011
2937 case ICmpInst::ICMP_SGE: return 3; // 011
2938 case ICmpInst::ICMP_ULT: return 4; // 100
2939 case ICmpInst::ICMP_SLT: return 4; // 100
2940 case ICmpInst::ICMP_NE: return 5; // 101
2941 case ICmpInst::ICMP_ULE: return 6; // 110
2942 case ICmpInst::ICMP_SLE: return 6; // 110
2943 // True -> 7
2944 default:
2945 assert(0 && "Invalid ICmp predicate!");
2946 return 0;
2947 }
2948}
2949
2950/// getICmpValue - This is the complement of getICmpCode, which turns an
2951/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00002952/// new ICmp instruction. The sign is passed in to determine which kind
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002953/// of predicate to use in new icmp instructions.
2954static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2955 switch (code) {
2956 default: assert(0 && "Illegal ICmp code!");
2957 case 0: return ConstantInt::getFalse();
2958 case 1:
2959 if (sign)
2960 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2961 else
2962 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2963 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
2964 case 3:
2965 if (sign)
2966 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2967 else
2968 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2969 case 4:
2970 if (sign)
2971 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2972 else
2973 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2974 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
2975 case 6:
2976 if (sign)
2977 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2978 else
2979 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
2980 case 7: return ConstantInt::getTrue();
2981 }
2982}
2983
2984static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2985 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2986 (ICmpInst::isSignedPredicate(p1) &&
2987 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2988 (ICmpInst::isSignedPredicate(p2) &&
2989 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2990}
2991
2992namespace {
2993// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2994struct FoldICmpLogical {
2995 InstCombiner &IC;
2996 Value *LHS, *RHS;
2997 ICmpInst::Predicate pred;
2998 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
2999 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3000 pred(ICI->getPredicate()) {}
3001 bool shouldApply(Value *V) const {
3002 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3003 if (PredicatesFoldable(pred, ICI->getPredicate()))
3004 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
3005 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
3006 return false;
3007 }
3008 Instruction *apply(Instruction &Log) const {
3009 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3010 if (ICI->getOperand(0) != LHS) {
3011 assert(ICI->getOperand(1) == LHS);
3012 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3013 }
3014
3015 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3016 unsigned LHSCode = getICmpCode(ICI);
3017 unsigned RHSCode = getICmpCode(RHSICI);
3018 unsigned Code;
3019 switch (Log.getOpcode()) {
3020 case Instruction::And: Code = LHSCode & RHSCode; break;
3021 case Instruction::Or: Code = LHSCode | RHSCode; break;
3022 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3023 default: assert(0 && "Illegal logical opcode!"); return 0;
3024 }
3025
3026 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3027 ICmpInst::isSignedPredicate(ICI->getPredicate());
3028
3029 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3030 if (Instruction *I = dyn_cast<Instruction>(RV))
3031 return I;
3032 // Otherwise, it's a constant boolean value...
3033 return IC.ReplaceInstUsesWith(Log, RV);
3034 }
3035};
3036} // end anonymous namespace
3037
3038// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3039// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3040// guaranteed to be a binary operator.
3041Instruction *InstCombiner::OptAndOp(Instruction *Op,
3042 ConstantInt *OpRHS,
3043 ConstantInt *AndRHS,
3044 BinaryOperator &TheAnd) {
3045 Value *X = Op->getOperand(0);
3046 Constant *Together = 0;
3047 if (!Op->isShift())
3048 Together = And(AndRHS, OpRHS);
3049
3050 switch (Op->getOpcode()) {
3051 case Instruction::Xor:
3052 if (Op->hasOneUse()) {
3053 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3054 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
3055 InsertNewInstBefore(And, TheAnd);
3056 And->takeName(Op);
3057 return BinaryOperator::createXor(And, Together);
3058 }
3059 break;
3060 case Instruction::Or:
3061 if (Together == AndRHS) // (X | C) & C --> C
3062 return ReplaceInstUsesWith(TheAnd, AndRHS);
3063
3064 if (Op->hasOneUse() && Together != OpRHS) {
3065 // (X | C1) & C2 --> (X | (C1&C2)) & C2
3066 Instruction *Or = BinaryOperator::createOr(X, Together);
3067 InsertNewInstBefore(Or, TheAnd);
3068 Or->takeName(Op);
3069 return BinaryOperator::createAnd(Or, AndRHS);
3070 }
3071 break;
3072 case Instruction::Add:
3073 if (Op->hasOneUse()) {
3074 // Adding a one to a single bit bit-field should be turned into an XOR
3075 // of the bit. First thing to check is to see if this AND is with a
3076 // single bit constant.
3077 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3078
3079 // If there is only one bit set...
3080 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3081 // Ok, at this point, we know that we are masking the result of the
3082 // ADD down to exactly one bit. If the constant we are adding has
3083 // no bits set below this bit, then we can eliminate the ADD.
3084 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3085
3086 // Check to see if any bits below the one bit set in AndRHSV are set.
3087 if ((AddRHS & (AndRHSV-1)) == 0) {
3088 // If not, the only thing that can effect the output of the AND is
3089 // the bit specified by AndRHSV. If that bit is set, the effect of
3090 // the XOR is to toggle the bit. If it is clear, then the ADD has
3091 // no effect.
3092 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3093 TheAnd.setOperand(0, X);
3094 return &TheAnd;
3095 } else {
3096 // Pull the XOR out of the AND.
3097 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
3098 InsertNewInstBefore(NewAnd, TheAnd);
3099 NewAnd->takeName(Op);
3100 return BinaryOperator::createXor(NewAnd, AndRHS);
3101 }
3102 }
3103 }
3104 }
3105 break;
3106
3107 case Instruction::Shl: {
3108 // We know that the AND will not produce any of the bits shifted in, so if
3109 // the anded constant includes them, clear them now!
3110 //
3111 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3112 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3113 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3114 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3115
3116 if (CI->getValue() == ShlMask) {
3117 // Masking out bits that the shift already masks
3118 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3119 } else if (CI != AndRHS) { // Reducing bits set in and.
3120 TheAnd.setOperand(1, CI);
3121 return &TheAnd;
3122 }
3123 break;
3124 }
3125 case Instruction::LShr:
3126 {
3127 // We know that the AND will not produce any of the bits shifted in, so if
3128 // the anded constant includes them, clear them now! This only applies to
3129 // unsigned shifts, because a signed shr may bring in set bits!
3130 //
3131 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3132 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3133 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3134 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3135
3136 if (CI->getValue() == ShrMask) {
3137 // Masking out bits that the shift already masks.
3138 return ReplaceInstUsesWith(TheAnd, Op);
3139 } else if (CI != AndRHS) {
3140 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3141 return &TheAnd;
3142 }
3143 break;
3144 }
3145 case Instruction::AShr:
3146 // Signed shr.
3147 // See if this is shifting in some sign extension, then masking it out
3148 // with an and.
3149 if (Op->hasOneUse()) {
3150 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3151 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3152 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3153 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3154 if (C == AndRHS) { // Masking out bits shifted in.
3155 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3156 // Make the argument unsigned.
3157 Value *ShVal = Op->getOperand(0);
3158 ShVal = InsertNewInstBefore(
3159 BinaryOperator::createLShr(ShVal, OpRHS,
3160 Op->getName()), TheAnd);
3161 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
3162 }
3163 }
3164 break;
3165 }
3166 return 0;
3167}
3168
3169
3170/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3171/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3172/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3173/// whether to treat the V, Lo and HI as signed or not. IB is the location to
3174/// insert new instructions.
3175Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3176 bool isSigned, bool Inside,
3177 Instruction &IB) {
3178 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3179 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3180 "Lo is not <= Hi in range emission code!");
3181
3182 if (Inside) {
3183 if (Lo == Hi) // Trivially false.
3184 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3185
3186 // V >= Min && V < Hi --> V < Hi
3187 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3188 ICmpInst::Predicate pred = (isSigned ?
3189 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3190 return new ICmpInst(pred, V, Hi);
3191 }
3192
3193 // Emit V-Lo <u Hi-Lo
3194 Constant *NegLo = ConstantExpr::getNeg(Lo);
3195 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3196 InsertNewInstBefore(Add, IB);
3197 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3198 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3199 }
3200
3201 if (Lo == Hi) // Trivially true.
3202 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3203
3204 // V < Min || V >= Hi -> V > Hi-1
3205 Hi = SubOne(cast<ConstantInt>(Hi));
3206 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3207 ICmpInst::Predicate pred = (isSigned ?
3208 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3209 return new ICmpInst(pred, V, Hi);
3210 }
3211
3212 // Emit V-Lo >u Hi-1-Lo
3213 // Note that Hi has already had one subtracted from it, above.
3214 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3215 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3216 InsertNewInstBefore(Add, IB);
3217 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3218 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3219}
3220
3221// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3222// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3223// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3224// not, since all 1s are not contiguous.
3225static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3226 const APInt& V = Val->getValue();
3227 uint32_t BitWidth = Val->getType()->getBitWidth();
3228 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3229
3230 // look for the first zero bit after the run of ones
3231 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3232 // look for the first non-zero bit
3233 ME = V.getActiveBits();
3234 return true;
3235}
3236
3237/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3238/// where isSub determines whether the operator is a sub. If we can fold one of
3239/// the following xforms:
3240///
3241/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3242/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3243/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3244///
3245/// return (A +/- B).
3246///
3247Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3248 ConstantInt *Mask, bool isSub,
3249 Instruction &I) {
3250 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3251 if (!LHSI || LHSI->getNumOperands() != 2 ||
3252 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3253
3254 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3255
3256 switch (LHSI->getOpcode()) {
3257 default: return 0;
3258 case Instruction::And:
3259 if (And(N, Mask) == Mask) {
3260 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3261 if ((Mask->getValue().countLeadingZeros() +
3262 Mask->getValue().countPopulation()) ==
3263 Mask->getValue().getBitWidth())
3264 break;
3265
3266 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3267 // part, we don't need any explicit masks to take them out of A. If that
3268 // is all N is, ignore it.
3269 uint32_t MB = 0, ME = 0;
3270 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3271 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3272 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3273 if (MaskedValueIsZero(RHS, Mask))
3274 break;
3275 }
3276 }
3277 return 0;
3278 case Instruction::Or:
3279 case Instruction::Xor:
3280 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3281 if ((Mask->getValue().countLeadingZeros() +
3282 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3283 && And(N, Mask)->isZero())
3284 break;
3285 return 0;
3286 }
3287
3288 Instruction *New;
3289 if (isSub)
3290 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3291 else
3292 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3293 return InsertNewInstBefore(New, I);
3294}
3295
3296Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3297 bool Changed = SimplifyCommutative(I);
3298 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3299
3300 if (isa<UndefValue>(Op1)) // X & undef -> 0
3301 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3302
3303 // and X, X = X
3304 if (Op0 == Op1)
3305 return ReplaceInstUsesWith(I, Op1);
3306
3307 // See if we can simplify any instructions used by the instruction whose sole
3308 // purpose is to compute bits we don't care about.
3309 if (!isa<VectorType>(I.getType())) {
3310 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3311 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3312 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3313 KnownZero, KnownOne))
3314 return &I;
3315 } else {
3316 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3317 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
3318 return ReplaceInstUsesWith(I, I.getOperand(0));
3319 } else if (isa<ConstantAggregateZero>(Op1)) {
3320 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
3321 }
3322 }
3323
3324 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3325 const APInt& AndRHSMask = AndRHS->getValue();
3326 APInt NotAndRHS(~AndRHSMask);
3327
3328 // Optimize a variety of ((val OP C1) & C2) combinations...
3329 if (isa<BinaryOperator>(Op0)) {
3330 Instruction *Op0I = cast<Instruction>(Op0);
3331 Value *Op0LHS = Op0I->getOperand(0);
3332 Value *Op0RHS = Op0I->getOperand(1);
3333 switch (Op0I->getOpcode()) {
3334 case Instruction::Xor:
3335 case Instruction::Or:
3336 // If the mask is only needed on one incoming arm, push it up.
3337 if (Op0I->hasOneUse()) {
3338 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3339 // Not masking anything out for the LHS, move to RHS.
3340 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3341 Op0RHS->getName()+".masked");
3342 InsertNewInstBefore(NewRHS, I);
3343 return BinaryOperator::create(
3344 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3345 }
3346 if (!isa<Constant>(Op0RHS) &&
3347 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3348 // Not masking anything out for the RHS, move to LHS.
3349 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3350 Op0LHS->getName()+".masked");
3351 InsertNewInstBefore(NewLHS, I);
3352 return BinaryOperator::create(
3353 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3354 }
3355 }
3356
3357 break;
3358 case Instruction::Add:
3359 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3360 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3361 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3362 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3363 return BinaryOperator::createAnd(V, AndRHS);
3364 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3365 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
3366 break;
3367
3368 case Instruction::Sub:
3369 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3370 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3371 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3372 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3373 return BinaryOperator::createAnd(V, AndRHS);
3374 break;
3375 }
3376
3377 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3378 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3379 return Res;
3380 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3381 // If this is an integer truncation or change from signed-to-unsigned, and
3382 // if the source is an and/or with immediate, transform it. This
3383 // frequently occurs for bitfield accesses.
3384 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3385 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3386 CastOp->getNumOperands() == 2)
3387 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
3388 if (CastOp->getOpcode() == Instruction::And) {
3389 // Change: and (cast (and X, C1) to T), C2
3390 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3391 // This will fold the two constants together, which may allow
3392 // other simplifications.
3393 Instruction *NewCast = CastInst::createTruncOrBitCast(
3394 CastOp->getOperand(0), I.getType(),
3395 CastOp->getName()+".shrunk");
3396 NewCast = InsertNewInstBefore(NewCast, I);
3397 // trunc_or_bitcast(C1)&C2
3398 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3399 C3 = ConstantExpr::getAnd(C3, AndRHS);
3400 return BinaryOperator::createAnd(NewCast, C3);
3401 } else if (CastOp->getOpcode() == Instruction::Or) {
3402 // Change: and (cast (or X, C1) to T), C2
3403 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3404 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3405 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3406 return ReplaceInstUsesWith(I, AndRHS);
3407 }
3408 }
3409 }
3410
3411 // Try to fold constant and into select arguments.
3412 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3413 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3414 return R;
3415 if (isa<PHINode>(Op0))
3416 if (Instruction *NV = FoldOpIntoPhi(I))
3417 return NV;
3418 }
3419
3420 Value *Op0NotVal = dyn_castNotVal(Op0);
3421 Value *Op1NotVal = dyn_castNotVal(Op1);
3422
3423 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3424 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3425
3426 // (~A & ~B) == (~(A | B)) - De Morgan's Law
3427 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3428 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3429 I.getName()+".demorgan");
3430 InsertNewInstBefore(Or, I);
3431 return BinaryOperator::createNot(Or);
3432 }
3433
3434 {
3435 Value *A = 0, *B = 0, *C = 0, *D = 0;
3436 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3437 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3438 return ReplaceInstUsesWith(I, Op1);
3439
3440 // (A|B) & ~(A&B) -> A^B
3441 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3442 if ((A == C && B == D) || (A == D && B == C))
3443 return BinaryOperator::createXor(A, B);
3444 }
3445 }
3446
3447 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3448 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3449 return ReplaceInstUsesWith(I, Op0);
3450
3451 // ~(A&B) & (A|B) -> A^B
3452 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3453 if ((A == C && B == D) || (A == D && B == C))
3454 return BinaryOperator::createXor(A, B);
3455 }
3456 }
3457
3458 if (Op0->hasOneUse() &&
3459 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3460 if (A == Op1) { // (A^B)&A -> A&(A^B)
3461 I.swapOperands(); // Simplify below
3462 std::swap(Op0, Op1);
3463 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3464 cast<BinaryOperator>(Op0)->swapOperands();
3465 I.swapOperands(); // Simplify below
3466 std::swap(Op0, Op1);
3467 }
3468 }
3469 if (Op1->hasOneUse() &&
3470 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3471 if (B == Op0) { // B&(A^B) -> B&(B^A)
3472 cast<BinaryOperator>(Op1)->swapOperands();
3473 std::swap(A, B);
3474 }
3475 if (A == Op0) { // A&(A^B) -> A & ~B
3476 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3477 InsertNewInstBefore(NotB, I);
3478 return BinaryOperator::createAnd(A, NotB);
3479 }
3480 }
3481 }
3482
3483 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3484 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3485 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3486 return R;
3487
3488 Value *LHSVal, *RHSVal;
3489 ConstantInt *LHSCst, *RHSCst;
3490 ICmpInst::Predicate LHSCC, RHSCC;
3491 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3492 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3493 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3494 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3495 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3496 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3497 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner205ad1d2007-11-22 23:47:13 +00003498 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3499
3500 // Don't try to fold ICMP_SLT + ICMP_ULT.
3501 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3502 ICmpInst::isSignedPredicate(LHSCC) ==
3503 ICmpInst::isSignedPredicate(RHSCC))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003504 // Ensure that the larger constant is on the RHS.
Chris Lattnerda628ca2008-01-13 20:59:02 +00003505 ICmpInst::Predicate GT;
3506 if (ICmpInst::isSignedPredicate(LHSCC) ||
3507 (ICmpInst::isEquality(LHSCC) &&
3508 ICmpInst::isSignedPredicate(RHSCC)))
3509 GT = ICmpInst::ICMP_SGT;
3510 else
3511 GT = ICmpInst::ICMP_UGT;
3512
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003513 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3514 ICmpInst *LHS = cast<ICmpInst>(Op0);
3515 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3516 std::swap(LHS, RHS);
3517 std::swap(LHSCst, RHSCst);
3518 std::swap(LHSCC, RHSCC);
3519 }
3520
3521 // At this point, we know we have have two icmp instructions
3522 // comparing a value against two constants and and'ing the result
3523 // together. Because of the above check, we know that we only have
3524 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3525 // (from the FoldICmpLogical check above), that the two constants
3526 // are not equal and that the larger constant is on the RHS
3527 assert(LHSCst != RHSCst && "Compares not folded above?");
3528
3529 switch (LHSCC) {
3530 default: assert(0 && "Unknown integer condition code!");
3531 case ICmpInst::ICMP_EQ:
3532 switch (RHSCC) {
3533 default: assert(0 && "Unknown integer condition code!");
3534 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3535 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3536 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3537 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3538 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3539 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3540 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3541 return ReplaceInstUsesWith(I, LHS);
3542 }
3543 case ICmpInst::ICMP_NE:
3544 switch (RHSCC) {
3545 default: assert(0 && "Unknown integer condition code!");
3546 case ICmpInst::ICMP_ULT:
3547 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3548 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3549 break; // (X != 13 & X u< 15) -> no change
3550 case ICmpInst::ICMP_SLT:
3551 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3552 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3553 break; // (X != 13 & X s< 15) -> no change
3554 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3555 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3556 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3557 return ReplaceInstUsesWith(I, RHS);
3558 case ICmpInst::ICMP_NE:
3559 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3560 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3561 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3562 LHSVal->getName()+".off");
3563 InsertNewInstBefore(Add, I);
3564 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3565 ConstantInt::get(Add->getType(), 1));
3566 }
3567 break; // (X != 13 & X != 15) -> no change
3568 }
3569 break;
3570 case ICmpInst::ICMP_ULT:
3571 switch (RHSCC) {
3572 default: assert(0 && "Unknown integer condition code!");
3573 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3574 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3575 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3576 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3577 break;
3578 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3579 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3580 return ReplaceInstUsesWith(I, LHS);
3581 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3582 break;
3583 }
3584 break;
3585 case ICmpInst::ICMP_SLT:
3586 switch (RHSCC) {
3587 default: assert(0 && "Unknown integer condition code!");
3588 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3589 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3590 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3591 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3592 break;
3593 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3594 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3595 return ReplaceInstUsesWith(I, LHS);
3596 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3597 break;
3598 }
3599 break;
3600 case ICmpInst::ICMP_UGT:
3601 switch (RHSCC) {
3602 default: assert(0 && "Unknown integer condition code!");
3603 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3604 return ReplaceInstUsesWith(I, LHS);
3605 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3606 return ReplaceInstUsesWith(I, RHS);
3607 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3608 break;
3609 case ICmpInst::ICMP_NE:
3610 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3611 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3612 break; // (X u> 13 & X != 15) -> no change
3613 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3614 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3615 true, I);
3616 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3617 break;
3618 }
3619 break;
3620 case ICmpInst::ICMP_SGT:
3621 switch (RHSCC) {
3622 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerab0fc252007-11-16 06:04:17 +00003623 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003624 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3625 return ReplaceInstUsesWith(I, RHS);
3626 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3627 break;
3628 case ICmpInst::ICMP_NE:
3629 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3630 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3631 break; // (X s> 13 & X != 15) -> no change
3632 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3633 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3634 true, I);
3635 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3636 break;
3637 }
3638 break;
3639 }
3640 }
3641 }
3642
3643 // fold (and (cast A), (cast B)) -> (cast (and A, B))
3644 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3645 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3646 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3647 const Type *SrcTy = Op0C->getOperand(0)->getType();
3648 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3649 // Only do this if the casts both really cause code to be generated.
3650 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3651 I.getType(), TD) &&
3652 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3653 I.getType(), TD)) {
3654 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3655 Op1C->getOperand(0),
3656 I.getName());
3657 InsertNewInstBefore(NewOp, I);
3658 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3659 }
3660 }
3661
3662 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
3663 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3664 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3665 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
3666 SI0->getOperand(1) == SI1->getOperand(1) &&
3667 (SI0->hasOneUse() || SI1->hasOneUse())) {
3668 Instruction *NewOp =
3669 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3670 SI1->getOperand(0),
3671 SI0->getName()), I);
3672 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3673 SI1->getOperand(1));
3674 }
3675 }
3676
Chris Lattner91882432007-10-24 05:38:08 +00003677 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3678 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3679 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3680 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3681 RHS->getPredicate() == FCmpInst::FCMP_ORD)
3682 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3683 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3684 // If either of the constants are nans, then the whole thing returns
3685 // false.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00003686 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00003687 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3688 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3689 RHS->getOperand(0));
3690 }
3691 }
3692 }
3693
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003694 return Changed ? &I : 0;
3695}
3696
3697/// CollectBSwapParts - Look to see if the specified value defines a single byte
3698/// in the result. If it does, and if the specified byte hasn't been filled in
3699/// yet, fill it in and return false.
3700static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3701 Instruction *I = dyn_cast<Instruction>(V);
3702 if (I == 0) return true;
3703
3704 // If this is an or instruction, it is an inner node of the bswap.
3705 if (I->getOpcode() == Instruction::Or)
3706 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3707 CollectBSwapParts(I->getOperand(1), ByteValues);
3708
3709 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
3710 // If this is a shift by a constant int, and it is "24", then its operand
3711 // defines a byte. We only handle unsigned types here.
3712 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3713 // Not shifting the entire input by N-1 bytes?
3714 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
3715 8*(ByteValues.size()-1))
3716 return true;
3717
3718 unsigned DestNo;
3719 if (I->getOpcode() == Instruction::Shl) {
3720 // X << 24 defines the top byte with the lowest of the input bytes.
3721 DestNo = ByteValues.size()-1;
3722 } else {
3723 // X >>u 24 defines the low byte with the highest of the input bytes.
3724 DestNo = 0;
3725 }
3726
3727 // If the destination byte value is already defined, the values are or'd
3728 // together, which isn't a bswap (unless it's an or of the same bits).
3729 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3730 return true;
3731 ByteValues[DestNo] = I->getOperand(0);
3732 return false;
3733 }
3734
3735 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3736 // don't have this.
3737 Value *Shift = 0, *ShiftLHS = 0;
3738 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3739 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3740 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3741 return true;
3742 Instruction *SI = cast<Instruction>(Shift);
3743
3744 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3745 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3746 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
3747 return true;
3748
3749 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3750 unsigned DestByte;
3751 if (AndAmt->getValue().getActiveBits() > 64)
3752 return true;
3753 uint64_t AndAmtVal = AndAmt->getZExtValue();
3754 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3755 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
3756 break;
3757 // Unknown mask for bswap.
3758 if (DestByte == ByteValues.size()) return true;
3759
3760 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3761 unsigned SrcByte;
3762 if (SI->getOpcode() == Instruction::Shl)
3763 SrcByte = DestByte - ShiftBytes;
3764 else
3765 SrcByte = DestByte + ShiftBytes;
3766
3767 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3768 if (SrcByte != ByteValues.size()-DestByte-1)
3769 return true;
3770
3771 // If the destination byte value is already defined, the values are or'd
3772 // together, which isn't a bswap (unless it's an or of the same bits).
3773 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3774 return true;
3775 ByteValues[DestByte] = SI->getOperand(0);
3776 return false;
3777}
3778
3779/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3780/// If so, insert the new bswap intrinsic and return it.
3781Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3782 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3783 if (!ITy || ITy->getBitWidth() % 16)
3784 return 0; // Can only bswap pairs of bytes. Can't do vectors.
3785
3786 /// ByteValues - For each byte of the result, we keep track of which value
3787 /// defines each byte.
3788 SmallVector<Value*, 8> ByteValues;
3789 ByteValues.resize(ITy->getBitWidth()/8);
3790
3791 // Try to find all the pieces corresponding to the bswap.
3792 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3793 CollectBSwapParts(I.getOperand(1), ByteValues))
3794 return 0;
3795
3796 // Check to see if all of the bytes come from the same value.
3797 Value *V = ByteValues[0];
3798 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3799
3800 // Check to make sure that all of the bytes come from the same value.
3801 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3802 if (ByteValues[i] != V)
3803 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00003804 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003805 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00003806 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003807 return new CallInst(F, V);
3808}
3809
3810
3811Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3812 bool Changed = SimplifyCommutative(I);
3813 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3814
3815 if (isa<UndefValue>(Op1)) // X | undef -> -1
3816 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3817
3818 // or X, X = X
3819 if (Op0 == Op1)
3820 return ReplaceInstUsesWith(I, Op0);
3821
3822 // See if we can simplify any instructions used by the instruction whose sole
3823 // purpose is to compute bits we don't care about.
3824 if (!isa<VectorType>(I.getType())) {
3825 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3826 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3827 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3828 KnownZero, KnownOne))
3829 return &I;
3830 } else if (isa<ConstantAggregateZero>(Op1)) {
3831 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
3832 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3833 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
3834 return ReplaceInstUsesWith(I, I.getOperand(1));
3835 }
3836
3837
3838
3839 // or X, -1 == -1
3840 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3841 ConstantInt *C1 = 0; Value *X = 0;
3842 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3843 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3844 Instruction *Or = BinaryOperator::createOr(X, RHS);
3845 InsertNewInstBefore(Or, I);
3846 Or->takeName(Op0);
3847 return BinaryOperator::createAnd(Or,
3848 ConstantInt::get(RHS->getValue() | C1->getValue()));
3849 }
3850
3851 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3852 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3853 Instruction *Or = BinaryOperator::createOr(X, RHS);
3854 InsertNewInstBefore(Or, I);
3855 Or->takeName(Op0);
3856 return BinaryOperator::createXor(Or,
3857 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
3858 }
3859
3860 // Try to fold constant and into select arguments.
3861 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3862 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3863 return R;
3864 if (isa<PHINode>(Op0))
3865 if (Instruction *NV = FoldOpIntoPhi(I))
3866 return NV;
3867 }
3868
3869 Value *A = 0, *B = 0;
3870 ConstantInt *C1 = 0, *C2 = 0;
3871
3872 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3873 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3874 return ReplaceInstUsesWith(I, Op1);
3875 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3876 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3877 return ReplaceInstUsesWith(I, Op0);
3878
3879 // (A | B) | C and A | (B | C) -> bswap if possible.
3880 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
3881 if (match(Op0, m_Or(m_Value(), m_Value())) ||
3882 match(Op1, m_Or(m_Value(), m_Value())) ||
3883 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3884 match(Op1, m_Shift(m_Value(), m_Value())))) {
3885 if (Instruction *BSwap = MatchBSwap(I))
3886 return BSwap;
3887 }
3888
3889 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3890 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3891 MaskedValueIsZero(Op1, C1->getValue())) {
3892 Instruction *NOr = BinaryOperator::createOr(A, Op1);
3893 InsertNewInstBefore(NOr, I);
3894 NOr->takeName(Op0);
3895 return BinaryOperator::createXor(NOr, C1);
3896 }
3897
3898 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3899 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3900 MaskedValueIsZero(Op0, C1->getValue())) {
3901 Instruction *NOr = BinaryOperator::createOr(A, Op0);
3902 InsertNewInstBefore(NOr, I);
3903 NOr->takeName(Op0);
3904 return BinaryOperator::createXor(NOr, C1);
3905 }
3906
3907 // (A & C)|(B & D)
3908 Value *C = 0, *D = 0;
3909 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3910 match(Op1, m_And(m_Value(B), m_Value(D)))) {
3911 Value *V1 = 0, *V2 = 0, *V3 = 0;
3912 C1 = dyn_cast<ConstantInt>(C);
3913 C2 = dyn_cast<ConstantInt>(D);
3914 if (C1 && C2) { // (A & C1)|(B & C2)
3915 // If we have: ((V + N) & C1) | (V & C2)
3916 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3917 // replace with V+N.
3918 if (C1->getValue() == ~C2->getValue()) {
3919 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
3920 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3921 // Add commutes, try both ways.
3922 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
3923 return ReplaceInstUsesWith(I, A);
3924 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
3925 return ReplaceInstUsesWith(I, A);
3926 }
3927 // Or commutes, try both ways.
3928 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
3929 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3930 // Add commutes, try both ways.
3931 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
3932 return ReplaceInstUsesWith(I, B);
3933 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
3934 return ReplaceInstUsesWith(I, B);
3935 }
3936 }
3937 V1 = 0; V2 = 0; V3 = 0;
3938 }
3939
3940 // Check to see if we have any common things being and'ed. If so, find the
3941 // terms for V1 & (V2|V3).
3942 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
3943 if (A == B) // (A & C)|(A & D) == A & (C|D)
3944 V1 = A, V2 = C, V3 = D;
3945 else if (A == D) // (A & C)|(B & A) == A & (B|C)
3946 V1 = A, V2 = B, V3 = C;
3947 else if (C == B) // (A & C)|(C & D) == C & (A|D)
3948 V1 = C, V2 = A, V3 = D;
3949 else if (C == D) // (A & C)|(B & C) == C & (A|B)
3950 V1 = C, V2 = A, V3 = B;
3951
3952 if (V1) {
3953 Value *Or =
3954 InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
3955 return BinaryOperator::createAnd(V1, Or);
3956 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003957 }
3958 }
3959
3960 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
3961 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3962 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3963 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
3964 SI0->getOperand(1) == SI1->getOperand(1) &&
3965 (SI0->hasOneUse() || SI1->hasOneUse())) {
3966 Instruction *NewOp =
3967 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3968 SI1->getOperand(0),
3969 SI0->getName()), I);
3970 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3971 SI1->getOperand(1));
3972 }
3973 }
3974
3975 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3976 if (A == Op1) // ~A | A == -1
3977 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3978 } else {
3979 A = 0;
3980 }
3981 // Note, A is still live here!
3982 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3983 if (Op0 == B)
3984 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3985
3986 // (~A | ~B) == (~(A & B)) - De Morgan's Law
3987 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3988 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3989 I.getName()+".demorgan"), I);
3990 return BinaryOperator::createNot(And);
3991 }
3992 }
3993
3994 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3995 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3996 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3997 return R;
3998
3999 Value *LHSVal, *RHSVal;
4000 ConstantInt *LHSCst, *RHSCst;
4001 ICmpInst::Predicate LHSCC, RHSCC;
4002 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4003 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4004 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4005 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4006 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4007 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4008 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4009 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4010 // We can't fold (ugt x, C) | (sgt x, C2).
4011 PredicatesFoldable(LHSCC, RHSCC)) {
4012 // Ensure that the larger constant is on the RHS.
4013 ICmpInst *LHS = cast<ICmpInst>(Op0);
4014 bool NeedsSwap;
4015 if (ICmpInst::isSignedPredicate(LHSCC))
4016 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4017 else
4018 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4019
4020 if (NeedsSwap) {
4021 std::swap(LHS, RHS);
4022 std::swap(LHSCst, RHSCst);
4023 std::swap(LHSCC, RHSCC);
4024 }
4025
4026 // At this point, we know we have have two icmp instructions
4027 // comparing a value against two constants and or'ing the result
4028 // together. Because of the above check, we know that we only have
4029 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4030 // FoldICmpLogical check above), that the two constants are not
4031 // equal.
4032 assert(LHSCst != RHSCst && "Compares not folded above?");
4033
4034 switch (LHSCC) {
4035 default: assert(0 && "Unknown integer condition code!");
4036 case ICmpInst::ICMP_EQ:
4037 switch (RHSCC) {
4038 default: assert(0 && "Unknown integer condition code!");
4039 case ICmpInst::ICMP_EQ:
4040 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4041 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4042 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4043 LHSVal->getName()+".off");
4044 InsertNewInstBefore(Add, I);
4045 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4046 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4047 }
4048 break; // (X == 13 | X == 15) -> no change
4049 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4050 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4051 break;
4052 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4053 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4054 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4055 return ReplaceInstUsesWith(I, RHS);
4056 }
4057 break;
4058 case ICmpInst::ICMP_NE:
4059 switch (RHSCC) {
4060 default: assert(0 && "Unknown integer condition code!");
4061 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4062 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4063 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4064 return ReplaceInstUsesWith(I, LHS);
4065 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4066 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4067 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4068 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4069 }
4070 break;
4071 case ICmpInst::ICMP_ULT:
4072 switch (RHSCC) {
4073 default: assert(0 && "Unknown integer condition code!");
4074 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4075 break;
4076 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner26376862007-11-01 02:18:41 +00004077 // If RHSCst is [us]MAXINT, it is always false. Not handling
4078 // this can cause overflow.
4079 if (RHSCst->isMaxValue(false))
4080 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004081 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4082 false, I);
4083 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4084 break;
4085 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4086 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4087 return ReplaceInstUsesWith(I, RHS);
4088 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4089 break;
4090 }
4091 break;
4092 case ICmpInst::ICMP_SLT:
4093 switch (RHSCC) {
4094 default: assert(0 && "Unknown integer condition code!");
4095 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4096 break;
4097 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner26376862007-11-01 02:18:41 +00004098 // If RHSCst is [us]MAXINT, it is always false. Not handling
4099 // this can cause overflow.
4100 if (RHSCst->isMaxValue(true))
4101 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004102 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4103 false, I);
4104 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4105 break;
4106 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4107 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4108 return ReplaceInstUsesWith(I, RHS);
4109 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4110 break;
4111 }
4112 break;
4113 case ICmpInst::ICMP_UGT:
4114 switch (RHSCC) {
4115 default: assert(0 && "Unknown integer condition code!");
4116 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4117 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4118 return ReplaceInstUsesWith(I, LHS);
4119 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4120 break;
4121 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4122 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4123 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4124 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4125 break;
4126 }
4127 break;
4128 case ICmpInst::ICMP_SGT:
4129 switch (RHSCC) {
4130 default: assert(0 && "Unknown integer condition code!");
4131 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4132 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4133 return ReplaceInstUsesWith(I, LHS);
4134 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4135 break;
4136 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4137 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4138 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4139 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4140 break;
4141 }
4142 break;
4143 }
4144 }
4145 }
4146
4147 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004148 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004149 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4150 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4151 const Type *SrcTy = Op0C->getOperand(0)->getType();
4152 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4153 // Only do this if the casts both really cause code to be generated.
4154 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4155 I.getType(), TD) &&
4156 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4157 I.getType(), TD)) {
4158 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4159 Op1C->getOperand(0),
4160 I.getName());
4161 InsertNewInstBefore(NewOp, I);
4162 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4163 }
4164 }
Chris Lattner91882432007-10-24 05:38:08 +00004165 }
4166
4167
4168 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4169 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4170 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4171 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4172 RHS->getPredicate() == FCmpInst::FCMP_UNO)
4173 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4174 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4175 // If either of the constants are nans, then the whole thing returns
4176 // true.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00004177 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00004178 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4179
4180 // Otherwise, no need to compare the two constants, compare the
4181 // rest.
4182 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4183 RHS->getOperand(0));
4184 }
4185 }
4186 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004187
4188 return Changed ? &I : 0;
4189}
4190
4191// XorSelf - Implements: X ^ X --> 0
4192struct XorSelf {
4193 Value *RHS;
4194 XorSelf(Value *rhs) : RHS(rhs) {}
4195 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4196 Instruction *apply(BinaryOperator &Xor) const {
4197 return &Xor;
4198 }
4199};
4200
4201
4202Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4203 bool Changed = SimplifyCommutative(I);
4204 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4205
4206 if (isa<UndefValue>(Op1))
4207 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4208
4209 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4210 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00004211 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004212 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4213 }
4214
4215 // See if we can simplify any instructions used by the instruction whose sole
4216 // purpose is to compute bits we don't care about.
4217 if (!isa<VectorType>(I.getType())) {
4218 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4219 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4220 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4221 KnownZero, KnownOne))
4222 return &I;
4223 } else if (isa<ConstantAggregateZero>(Op1)) {
4224 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
4225 }
4226
4227 // Is this a ~ operation?
4228 if (Value *NotOp = dyn_castNotVal(&I)) {
4229 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4230 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4231 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4232 if (Op0I->getOpcode() == Instruction::And ||
4233 Op0I->getOpcode() == Instruction::Or) {
4234 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4235 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4236 Instruction *NotY =
4237 BinaryOperator::createNot(Op0I->getOperand(1),
4238 Op0I->getOperand(1)->getName()+".not");
4239 InsertNewInstBefore(NotY, I);
4240 if (Op0I->getOpcode() == Instruction::And)
4241 return BinaryOperator::createOr(Op0NotVal, NotY);
4242 else
4243 return BinaryOperator::createAnd(Op0NotVal, NotY);
4244 }
4245 }
4246 }
4247 }
4248
4249
4250 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky1405e922007-08-06 20:04:16 +00004251 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4252 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4253 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004254 return new ICmpInst(ICI->getInversePredicate(),
4255 ICI->getOperand(0), ICI->getOperand(1));
4256
Nick Lewycky1405e922007-08-06 20:04:16 +00004257 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4258 return new FCmpInst(FCI->getInversePredicate(),
4259 FCI->getOperand(0), FCI->getOperand(1));
4260 }
4261
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004262 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4263 // ~(c-X) == X-c-1 == X+(-c-1)
4264 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4265 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4266 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4267 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4268 ConstantInt::get(I.getType(), 1));
4269 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
4270 }
4271
4272 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4273 if (Op0I->getOpcode() == Instruction::Add) {
4274 // ~(X-c) --> (-c-1)-X
4275 if (RHS->isAllOnesValue()) {
4276 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4277 return BinaryOperator::createSub(
4278 ConstantExpr::getSub(NegOp0CI,
4279 ConstantInt::get(I.getType(), 1)),
4280 Op0I->getOperand(0));
4281 } else if (RHS->getValue().isSignBit()) {
4282 // (X + C) ^ signbit -> (X + C + signbit)
4283 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4284 return BinaryOperator::createAdd(Op0I->getOperand(0), C);
4285
4286 }
4287 } else if (Op0I->getOpcode() == Instruction::Or) {
4288 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4289 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4290 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4291 // Anything in both C1 and C2 is known to be zero, remove it from
4292 // NewRHS.
4293 Constant *CommonBits = And(Op0CI, RHS);
4294 NewRHS = ConstantExpr::getAnd(NewRHS,
4295 ConstantExpr::getNot(CommonBits));
4296 AddToWorkList(Op0I);
4297 I.setOperand(0, Op0I->getOperand(0));
4298 I.setOperand(1, NewRHS);
4299 return &I;
4300 }
4301 }
4302 }
4303
4304 // Try to fold constant and into select arguments.
4305 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4306 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4307 return R;
4308 if (isa<PHINode>(Op0))
4309 if (Instruction *NV = FoldOpIntoPhi(I))
4310 return NV;
4311 }
4312
4313 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
4314 if (X == Op1)
4315 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4316
4317 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
4318 if (X == Op0)
4319 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4320
4321
4322 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4323 if (Op1I) {
4324 Value *A, *B;
4325 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4326 if (A == Op0) { // B^(B|A) == (A|B)^B
4327 Op1I->swapOperands();
4328 I.swapOperands();
4329 std::swap(Op0, Op1);
4330 } else if (B == Op0) { // B^(A|B) == (A|B)^B
4331 I.swapOperands(); // Simplified below.
4332 std::swap(Op0, Op1);
4333 }
4334 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4335 if (Op0 == A) // A^(A^B) == B
4336 return ReplaceInstUsesWith(I, B);
4337 else if (Op0 == B) // A^(B^A) == B
4338 return ReplaceInstUsesWith(I, A);
4339 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4340 if (A == Op0) { // A^(A&B) -> A^(B&A)
4341 Op1I->swapOperands();
4342 std::swap(A, B);
4343 }
4344 if (B == Op0) { // A^(B&A) -> (B&A)^A
4345 I.swapOperands(); // Simplified below.
4346 std::swap(Op0, Op1);
4347 }
4348 }
4349 }
4350
4351 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4352 if (Op0I) {
4353 Value *A, *B;
4354 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4355 if (A == Op1) // (B|A)^B == (A|B)^B
4356 std::swap(A, B);
4357 if (B == Op1) { // (A|B)^B == A & ~B
4358 Instruction *NotB =
4359 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4360 return BinaryOperator::createAnd(A, NotB);
4361 }
4362 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4363 if (Op1 == A) // (A^B)^A == B
4364 return ReplaceInstUsesWith(I, B);
4365 else if (Op1 == B) // (B^A)^A == B
4366 return ReplaceInstUsesWith(I, A);
4367 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4368 if (A == Op1) // (A&B)^A -> (B&A)^A
4369 std::swap(A, B);
4370 if (B == Op1 && // (B&A)^A == ~B & A
4371 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
4372 Instruction *N =
4373 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
4374 return BinaryOperator::createAnd(N, Op1);
4375 }
4376 }
4377 }
4378
4379 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4380 if (Op0I && Op1I && Op0I->isShift() &&
4381 Op0I->getOpcode() == Op1I->getOpcode() &&
4382 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4383 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4384 Instruction *NewOp =
4385 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4386 Op1I->getOperand(0),
4387 Op0I->getName()), I);
4388 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4389 Op1I->getOperand(1));
4390 }
4391
4392 if (Op0I && Op1I) {
4393 Value *A, *B, *C, *D;
4394 // (A & B)^(A | B) -> A ^ B
4395 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4396 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4397 if ((A == C && B == D) || (A == D && B == C))
4398 return BinaryOperator::createXor(A, B);
4399 }
4400 // (A | B)^(A & B) -> A ^ B
4401 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4402 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4403 if ((A == C && B == D) || (A == D && B == C))
4404 return BinaryOperator::createXor(A, B);
4405 }
4406
4407 // (A & B)^(C & D)
4408 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4409 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4410 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4411 // (X & Y)^(X & Y) -> (Y^Z) & X
4412 Value *X = 0, *Y = 0, *Z = 0;
4413 if (A == C)
4414 X = A, Y = B, Z = D;
4415 else if (A == D)
4416 X = A, Y = B, Z = C;
4417 else if (B == C)
4418 X = B, Y = A, Z = D;
4419 else if (B == D)
4420 X = B, Y = A, Z = C;
4421
4422 if (X) {
4423 Instruction *NewOp =
4424 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4425 return BinaryOperator::createAnd(NewOp, X);
4426 }
4427 }
4428 }
4429
4430 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4431 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4432 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4433 return R;
4434
4435 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004436 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004437 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4438 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4439 const Type *SrcTy = Op0C->getOperand(0)->getType();
4440 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4441 // Only do this if the casts both really cause code to be generated.
4442 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4443 I.getType(), TD) &&
4444 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4445 I.getType(), TD)) {
4446 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4447 Op1C->getOperand(0),
4448 I.getName());
4449 InsertNewInstBefore(NewOp, I);
4450 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4451 }
4452 }
Chris Lattner91882432007-10-24 05:38:08 +00004453 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004454 return Changed ? &I : 0;
4455}
4456
4457/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4458/// overflowed for this type.
4459static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4460 ConstantInt *In2, bool IsSigned = false) {
4461 Result = cast<ConstantInt>(Add(In1, In2));
4462
4463 if (IsSigned)
4464 if (In2->getValue().isNegative())
4465 return Result->getValue().sgt(In1->getValue());
4466 else
4467 return Result->getValue().slt(In1->getValue());
4468 else
4469 return Result->getValue().ult(In1->getValue());
4470}
4471
4472/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4473/// code necessary to compute the offset from the base pointer (without adding
4474/// in the base pointer). Return the result as a signed integer of intptr size.
4475static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4476 TargetData &TD = IC.getTargetData();
4477 gep_type_iterator GTI = gep_type_begin(GEP);
4478 const Type *IntPtrTy = TD.getIntPtrType();
4479 Value *Result = Constant::getNullValue(IntPtrTy);
4480
4481 // Build a mask for high order bits.
4482 unsigned IntPtrWidth = TD.getPointerSize()*8;
4483 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4484
4485 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4486 Value *Op = GEP->getOperand(i);
Duncan Sandsf99fdc62007-11-01 20:53:16 +00004487 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004488 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4489 if (OpC->isZero()) continue;
4490
4491 // Handle a struct index, which adds its field offset to the pointer.
4492 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4493 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4494
4495 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4496 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4497 else
4498 Result = IC.InsertNewInstBefore(
4499 BinaryOperator::createAdd(Result,
4500 ConstantInt::get(IntPtrTy, Size),
4501 GEP->getName()+".offs"), I);
4502 continue;
4503 }
4504
4505 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4506 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4507 Scale = ConstantExpr::getMul(OC, Scale);
4508 if (Constant *RC = dyn_cast<Constant>(Result))
4509 Result = ConstantExpr::getAdd(RC, Scale);
4510 else {
4511 // Emit an add instruction.
4512 Result = IC.InsertNewInstBefore(
4513 BinaryOperator::createAdd(Result, Scale,
4514 GEP->getName()+".offs"), I);
4515 }
4516 continue;
4517 }
4518 // Convert to correct type.
4519 if (Op->getType() != IntPtrTy) {
4520 if (Constant *OpC = dyn_cast<Constant>(Op))
4521 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4522 else
4523 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4524 Op->getName()+".c"), I);
4525 }
4526 if (Size != 1) {
4527 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4528 if (Constant *OpC = dyn_cast<Constant>(Op))
4529 Op = ConstantExpr::getMul(OpC, Scale);
4530 else // We'll let instcombine(mul) convert this to a shl if possible.
4531 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4532 GEP->getName()+".idx"), I);
4533 }
4534
4535 // Emit an add instruction.
4536 if (isa<Constant>(Op) && isa<Constant>(Result))
4537 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4538 cast<Constant>(Result));
4539 else
4540 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4541 GEP->getName()+".offs"), I);
4542 }
4543 return Result;
4544}
4545
4546/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4547/// else. At this point we know that the GEP is on the LHS of the comparison.
4548Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4549 ICmpInst::Predicate Cond,
4550 Instruction &I) {
4551 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4552
4553 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4554 if (isa<PointerType>(CI->getOperand(0)->getType()))
4555 RHS = CI->getOperand(0);
4556
4557 Value *PtrBase = GEPLHS->getOperand(0);
4558 if (PtrBase == RHS) {
4559 // As an optimization, we don't actually have to compute the actual value of
4560 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4561 // each index is zero or not.
4562 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
4563 Instruction *InVal = 0;
4564 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4565 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
4566 bool EmitIt = true;
4567 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4568 if (isa<UndefValue>(C)) // undef index -> undef.
4569 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4570 if (C->isNullValue())
4571 EmitIt = false;
Duncan Sandsf99fdc62007-11-01 20:53:16 +00004572 else if (TD->getABITypeSize(GTI.getIndexedType()) == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004573 EmitIt = false; // This is indexing into a zero sized array?
4574 } else if (isa<ConstantInt>(C))
4575 return ReplaceInstUsesWith(I, // No comparison is needed here.
4576 ConstantInt::get(Type::Int1Ty,
4577 Cond == ICmpInst::ICMP_NE));
4578 }
4579
4580 if (EmitIt) {
4581 Instruction *Comp =
4582 new ICmpInst(Cond, GEPLHS->getOperand(i),
4583 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4584 if (InVal == 0)
4585 InVal = Comp;
4586 else {
4587 InVal = InsertNewInstBefore(InVal, I);
4588 InsertNewInstBefore(Comp, I);
4589 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
4590 InVal = BinaryOperator::createOr(InVal, Comp);
4591 else // True if all are equal
4592 InVal = BinaryOperator::createAnd(InVal, Comp);
4593 }
4594 }
4595 }
4596
4597 if (InVal)
4598 return InVal;
4599 else
4600 // No comparison is needed here, all indexes = 0
4601 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4602 Cond == ICmpInst::ICMP_EQ));
4603 }
4604
4605 // Only lower this if the icmp is the only user of the GEP or if we expect
4606 // the result to fold to a constant!
4607 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4608 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4609 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4610 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4611 Constant::getNullValue(Offset->getType()));
4612 }
4613 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4614 // If the base pointers are different, but the indices are the same, just
4615 // compare the base pointer.
4616 if (PtrBase != GEPRHS->getOperand(0)) {
4617 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4618 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4619 GEPRHS->getOperand(0)->getType();
4620 if (IndicesTheSame)
4621 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4622 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4623 IndicesTheSame = false;
4624 break;
4625 }
4626
4627 // If all indices are the same, just compare the base pointers.
4628 if (IndicesTheSame)
4629 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4630 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4631
4632 // Otherwise, the base pointers are different and the indices are
4633 // different, bail out.
4634 return 0;
4635 }
4636
4637 // If one of the GEPs has all zero indices, recurse.
4638 bool AllZeros = true;
4639 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4640 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4641 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4642 AllZeros = false;
4643 break;
4644 }
4645 if (AllZeros)
4646 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4647 ICmpInst::getSwappedPredicate(Cond), I);
4648
4649 // If the other GEP has all zero indices, recurse.
4650 AllZeros = true;
4651 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4652 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4653 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4654 AllZeros = false;
4655 break;
4656 }
4657 if (AllZeros)
4658 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4659
4660 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4661 // If the GEPs only differ by one index, compare it.
4662 unsigned NumDifferences = 0; // Keep track of # differences.
4663 unsigned DiffOperand = 0; // The operand that differs.
4664 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4665 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4666 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4667 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4668 // Irreconcilable differences.
4669 NumDifferences = 2;
4670 break;
4671 } else {
4672 if (NumDifferences++) break;
4673 DiffOperand = i;
4674 }
4675 }
4676
4677 if (NumDifferences == 0) // SAME GEP?
4678 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky2de09a92007-09-06 02:40:25 +00004679 ConstantInt::get(Type::Int1Ty,
4680 isTrueWhenEqual(Cond)));
4681
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004682 else if (NumDifferences == 1) {
4683 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4684 Value *RHSV = GEPRHS->getOperand(DiffOperand);
4685 // Make sure we do a signed comparison here.
4686 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4687 }
4688 }
4689
4690 // Only lower this if the icmp is the only user of the GEP or if we expect
4691 // the result to fold to a constant!
4692 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4693 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4694 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4695 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4696 Value *R = EmitGEPOffset(GEPRHS, I, *this);
4697 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4698 }
4699 }
4700 return 0;
4701}
4702
4703Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4704 bool Changed = SimplifyCompare(I);
4705 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4706
4707 // Fold trivial predicates.
4708 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4709 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4710 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4711 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4712
4713 // Simplify 'fcmp pred X, X'
4714 if (Op0 == Op1) {
4715 switch (I.getPredicate()) {
4716 default: assert(0 && "Unknown predicate!");
4717 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4718 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4719 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4720 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4721 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4722 case FCmpInst::FCMP_OLT: // True if ordered and less than
4723 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4724 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4725
4726 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4727 case FCmpInst::FCMP_ULT: // True if unordered or less than
4728 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4729 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4730 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4731 I.setPredicate(FCmpInst::FCMP_UNO);
4732 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4733 return &I;
4734
4735 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4736 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4737 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4738 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4739 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4740 I.setPredicate(FCmpInst::FCMP_ORD);
4741 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4742 return &I;
4743 }
4744 }
4745
4746 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
4747 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4748
4749 // Handle fcmp with constant RHS
4750 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4751 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4752 switch (LHSI->getOpcode()) {
4753 case Instruction::PHI:
4754 if (Instruction *NV = FoldOpIntoPhi(I))
4755 return NV;
4756 break;
4757 case Instruction::Select:
4758 // If either operand of the select is a constant, we can fold the
4759 // comparison into the select arms, which will cause one to be
4760 // constant folded and the select turned into a bitwise or.
4761 Value *Op1 = 0, *Op2 = 0;
4762 if (LHSI->hasOneUse()) {
4763 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4764 // Fold the known value into the constant operand.
4765 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4766 // Insert a new FCmp of the other select operand.
4767 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4768 LHSI->getOperand(2), RHSC,
4769 I.getName()), I);
4770 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4771 // Fold the known value into the constant operand.
4772 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4773 // Insert a new FCmp of the other select operand.
4774 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4775 LHSI->getOperand(1), RHSC,
4776 I.getName()), I);
4777 }
4778 }
4779
4780 if (Op1)
4781 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4782 break;
4783 }
4784 }
4785
4786 return Changed ? &I : 0;
4787}
4788
4789Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4790 bool Changed = SimplifyCompare(I);
4791 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4792 const Type *Ty = Op0->getType();
4793
4794 // icmp X, X
4795 if (Op0 == Op1)
4796 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4797 isTrueWhenEqual(I)));
4798
4799 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
4800 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lambf78cd322007-12-18 21:32:20 +00004801
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004802 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4803 // addresses never equal each other! We already know that Op0 != Op1.
4804 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4805 isa<ConstantPointerNull>(Op0)) &&
4806 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4807 isa<ConstantPointerNull>(Op1)))
4808 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4809 !isTrueWhenEqual(I)));
4810
4811 // icmp's with boolean values can always be turned into bitwise operations
4812 if (Ty == Type::Int1Ty) {
4813 switch (I.getPredicate()) {
4814 default: assert(0 && "Invalid icmp instruction!");
4815 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
4816 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4817 InsertNewInstBefore(Xor, I);
4818 return BinaryOperator::createNot(Xor);
4819 }
4820 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
4821 return BinaryOperator::createXor(Op0, Op1);
4822
4823 case ICmpInst::ICMP_UGT:
4824 case ICmpInst::ICMP_SGT:
4825 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
4826 // FALL THROUGH
4827 case ICmpInst::ICMP_ULT:
4828 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
4829 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4830 InsertNewInstBefore(Not, I);
4831 return BinaryOperator::createAnd(Not, Op1);
4832 }
4833 case ICmpInst::ICMP_UGE:
4834 case ICmpInst::ICMP_SGE:
4835 std::swap(Op0, Op1); // Change icmp ge -> icmp le
4836 // FALL THROUGH
4837 case ICmpInst::ICMP_ULE:
4838 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
4839 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4840 InsertNewInstBefore(Not, I);
4841 return BinaryOperator::createOr(Not, Op1);
4842 }
4843 }
4844 }
4845
4846 // See if we are doing a comparison between a constant and an instruction that
4847 // can be folded into the comparison.
4848 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lambfa6b3102007-12-20 07:21:11 +00004849 Value *A, *B;
4850
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00004851 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
4852 if (I.isEquality() && CI->isNullValue() &&
4853 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
4854 // (icmp cond A B) if cond is equality
4855 return new ICmpInst(I.getPredicate(), A, B);
Owen Anderson42f61ed2007-12-28 07:42:12 +00004856 }
Christopher Lambfa6b3102007-12-20 07:21:11 +00004857
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004858 switch (I.getPredicate()) {
4859 default: break;
4860 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4861 if (CI->isMinValue(false))
4862 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4863 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4864 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4865 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4866 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4867 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
4868 if (CI->isMinValue(true))
4869 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
4870 ConstantInt::getAllOnesValue(Op0->getType()));
4871
4872 break;
4873
4874 case ICmpInst::ICMP_SLT:
4875 if (CI->isMinValue(true)) // A <s MIN -> FALSE
4876 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4877 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4878 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4879 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4880 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4881 break;
4882
4883 case ICmpInst::ICMP_UGT:
4884 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
4885 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4886 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4887 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4888 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4889 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4890
4891 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
4892 if (CI->isMaxValue(true))
4893 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
4894 ConstantInt::getNullValue(Op0->getType()));
4895 break;
4896
4897 case ICmpInst::ICMP_SGT:
4898 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
4899 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4900 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4901 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4902 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4903 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4904 break;
4905
4906 case ICmpInst::ICMP_ULE:
4907 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
4908 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4909 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4910 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4911 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4912 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4913 break;
4914
4915 case ICmpInst::ICMP_SLE:
4916 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
4917 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4918 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4919 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4920 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4921 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4922 break;
4923
4924 case ICmpInst::ICMP_UGE:
4925 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
4926 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4927 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4928 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4929 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4930 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4931 break;
4932
4933 case ICmpInst::ICMP_SGE:
4934 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
4935 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4936 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4937 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4938 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4939 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4940 break;
4941 }
4942
4943 // If we still have a icmp le or icmp ge instruction, turn it into the
4944 // appropriate icmp lt or icmp gt instruction. Since the border cases have
4945 // already been handled above, this requires little checking.
4946 //
4947 switch (I.getPredicate()) {
4948 default: break;
4949 case ICmpInst::ICMP_ULE:
4950 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4951 case ICmpInst::ICMP_SLE:
4952 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4953 case ICmpInst::ICMP_UGE:
4954 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4955 case ICmpInst::ICMP_SGE:
4956 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
4957 }
4958
4959 // See if we can fold the comparison based on bits known to be zero or one
4960 // in the input. If this comparison is a normal comparison, it demands all
4961 // bits, if it is a sign bit comparison, it only demands the sign bit.
4962
4963 bool UnusedBit;
4964 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
4965
4966 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
4967 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4968 if (SimplifyDemandedBits(Op0,
4969 isSignBit ? APInt::getSignBit(BitWidth)
4970 : APInt::getAllOnesValue(BitWidth),
4971 KnownZero, KnownOne, 0))
4972 return &I;
4973
4974 // Given the known and unknown bits, compute a range that the LHS could be
4975 // in.
4976 if ((KnownOne | KnownZero) != 0) {
4977 // Compute the Min, Max and RHS values based on the known bits. For the
4978 // EQ and NE we use unsigned values.
4979 APInt Min(BitWidth, 0), Max(BitWidth, 0);
4980 const APInt& RHSVal = CI->getValue();
4981 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4982 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4983 Max);
4984 } else {
4985 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4986 Max);
4987 }
4988 switch (I.getPredicate()) { // LE/GE have been folded already.
4989 default: assert(0 && "Unknown icmp opcode!");
4990 case ICmpInst::ICMP_EQ:
4991 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
4992 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4993 break;
4994 case ICmpInst::ICMP_NE:
4995 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
4996 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4997 break;
4998 case ICmpInst::ICMP_ULT:
4999 if (Max.ult(RHSVal))
5000 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5001 if (Min.uge(RHSVal))
5002 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5003 break;
5004 case ICmpInst::ICMP_UGT:
5005 if (Min.ugt(RHSVal))
5006 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5007 if (Max.ule(RHSVal))
5008 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5009 break;
5010 case ICmpInst::ICMP_SLT:
5011 if (Max.slt(RHSVal))
5012 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5013 if (Min.sgt(RHSVal))
5014 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5015 break;
5016 case ICmpInst::ICMP_SGT:
5017 if (Min.sgt(RHSVal))
5018 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5019 if (Max.sle(RHSVal))
5020 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5021 break;
5022 }
5023 }
5024
5025 // Since the RHS is a ConstantInt (CI), if the left hand side is an
5026 // instruction, see if that instruction also has constants so that the
5027 // instruction can be folded into the icmp
5028 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5029 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5030 return Res;
5031 }
5032
5033 // Handle icmp with constant (but not simple integer constant) RHS
5034 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5035 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5036 switch (LHSI->getOpcode()) {
5037 case Instruction::GetElementPtr:
5038 if (RHSC->isNullValue()) {
5039 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5040 bool isAllZeros = true;
5041 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5042 if (!isa<Constant>(LHSI->getOperand(i)) ||
5043 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5044 isAllZeros = false;
5045 break;
5046 }
5047 if (isAllZeros)
5048 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5049 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5050 }
5051 break;
5052
5053 case Instruction::PHI:
5054 if (Instruction *NV = FoldOpIntoPhi(I))
5055 return NV;
5056 break;
5057 case Instruction::Select: {
5058 // If either operand of the select is a constant, we can fold the
5059 // comparison into the select arms, which will cause one to be
5060 // constant folded and the select turned into a bitwise or.
5061 Value *Op1 = 0, *Op2 = 0;
5062 if (LHSI->hasOneUse()) {
5063 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5064 // Fold the known value into the constant operand.
5065 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5066 // Insert a new ICmp of the other select operand.
5067 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5068 LHSI->getOperand(2), RHSC,
5069 I.getName()), I);
5070 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5071 // Fold the known value into the constant operand.
5072 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5073 // Insert a new ICmp of the other select operand.
5074 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5075 LHSI->getOperand(1), RHSC,
5076 I.getName()), I);
5077 }
5078 }
5079
5080 if (Op1)
5081 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5082 break;
5083 }
5084 case Instruction::Malloc:
5085 // If we have (malloc != null), and if the malloc has a single use, we
5086 // can assume it is successful and remove the malloc.
5087 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5088 AddToWorkList(LHSI);
5089 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5090 !isTrueWhenEqual(I)));
5091 }
5092 break;
5093 }
5094 }
5095
5096 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5097 if (User *GEP = dyn_castGetElementPtr(Op0))
5098 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5099 return NI;
5100 if (User *GEP = dyn_castGetElementPtr(Op1))
5101 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5102 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5103 return NI;
5104
5105 // Test to see if the operands of the icmp are casted versions of other
5106 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5107 // now.
5108 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5109 if (isa<PointerType>(Op0->getType()) &&
5110 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
5111 // We keep moving the cast from the left operand over to the right
5112 // operand, where it can often be eliminated completely.
5113 Op0 = CI->getOperand(0);
5114
5115 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5116 // so eliminate it as well.
5117 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5118 Op1 = CI2->getOperand(0);
5119
5120 // If Op1 is a constant, we can fold the cast into the constant.
5121 if (Op0->getType() != Op1->getType())
5122 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5123 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5124 } else {
5125 // Otherwise, cast the RHS right before the icmp
Chris Lattner13c2d6e2008-01-13 22:23:22 +00005126 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005127 }
5128 return new ICmpInst(I.getPredicate(), Op0, Op1);
5129 }
5130 }
5131
5132 if (isa<CastInst>(Op0)) {
5133 // Handle the special case of: icmp (cast bool to X), <cst>
5134 // This comes up when you have code like
5135 // int X = A < B;
5136 // if (X) ...
5137 // For generality, we handle any zero-extension of any operand comparison
5138 // with a constant or another cast from the same type.
5139 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5140 if (Instruction *R = visitICmpInstWithCastAndCast(I))
5141 return R;
5142 }
5143
5144 if (I.isEquality()) {
5145 Value *A, *B, *C, *D;
5146 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5147 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5148 Value *OtherVal = A == Op1 ? B : A;
5149 return new ICmpInst(I.getPredicate(), OtherVal,
5150 Constant::getNullValue(A->getType()));
5151 }
5152
5153 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5154 // A^c1 == C^c2 --> A == C^(c1^c2)
5155 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5156 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5157 if (Op1->hasOneUse()) {
5158 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
5159 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5160 return new ICmpInst(I.getPredicate(), A,
5161 InsertNewInstBefore(Xor, I));
5162 }
5163
5164 // A^B == A^D -> B == D
5165 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5166 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5167 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5168 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5169 }
5170 }
5171
5172 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5173 (A == Op0 || B == Op0)) {
5174 // A == (A^B) -> B == 0
5175 Value *OtherVal = A == Op0 ? B : A;
5176 return new ICmpInst(I.getPredicate(), OtherVal,
5177 Constant::getNullValue(A->getType()));
5178 }
5179 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5180 // (A-B) == A -> B == 0
5181 return new ICmpInst(I.getPredicate(), B,
5182 Constant::getNullValue(B->getType()));
5183 }
5184 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5185 // A == (A-B) -> B == 0
5186 return new ICmpInst(I.getPredicate(), B,
5187 Constant::getNullValue(B->getType()));
5188 }
5189
5190 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5191 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5192 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5193 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5194 Value *X = 0, *Y = 0, *Z = 0;
5195
5196 if (A == C) {
5197 X = B; Y = D; Z = A;
5198 } else if (A == D) {
5199 X = B; Y = C; Z = A;
5200 } else if (B == C) {
5201 X = A; Y = D; Z = B;
5202 } else if (B == D) {
5203 X = A; Y = C; Z = B;
5204 }
5205
5206 if (X) { // Build (X^Y) & Z
5207 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5208 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5209 I.setOperand(0, Op1);
5210 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5211 return &I;
5212 }
5213 }
5214 }
5215 return Changed ? &I : 0;
5216}
5217
5218
5219/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5220/// and CmpRHS are both known to be integer constants.
5221Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5222 ConstantInt *DivRHS) {
5223 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5224 const APInt &CmpRHSV = CmpRHS->getValue();
5225
5226 // FIXME: If the operand types don't match the type of the divide
5227 // then don't attempt this transform. The code below doesn't have the
5228 // logic to deal with a signed divide and an unsigned compare (and
5229 // vice versa). This is because (x /s C1) <s C2 produces different
5230 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5231 // (x /u C1) <u C2. Simply casting the operands and result won't
5232 // work. :( The if statement below tests that condition and bails
5233 // if it finds it.
5234 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5235 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5236 return 0;
5237 if (DivRHS->isZero())
5238 return 0; // The ProdOV computation fails on divide by zero.
5239
5240 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5241 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5242 // C2 (CI). By solving for X we can turn this into a range check
5243 // instead of computing a divide.
5244 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5245
5246 // Determine if the product overflows by seeing if the product is
5247 // not equal to the divide. Make sure we do the same kind of divide
5248 // as in the LHS instruction that we're folding.
5249 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5250 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5251
5252 // Get the ICmp opcode
5253 ICmpInst::Predicate Pred = ICI.getPredicate();
5254
5255 // Figure out the interval that is being checked. For example, a comparison
5256 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5257 // Compute this interval based on the constants involved and the signedness of
5258 // the compare/divide. This computes a half-open interval, keeping track of
5259 // whether either value in the interval overflows. After analysis each
5260 // overflow variable is set to 0 if it's corresponding bound variable is valid
5261 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5262 int LoOverflow = 0, HiOverflow = 0;
5263 ConstantInt *LoBound = 0, *HiBound = 0;
5264
5265
5266 if (!DivIsSigned) { // udiv
5267 // e.g. X/5 op 3 --> [15, 20)
5268 LoBound = Prod;
5269 HiOverflow = LoOverflow = ProdOV;
5270 if (!HiOverflow)
5271 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
5272 } else if (DivRHS->getValue().isPositive()) { // Divisor is > 0.
5273 if (CmpRHSV == 0) { // (X / pos) op 0
5274 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
5275 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5276 HiBound = DivRHS;
5277 } else if (CmpRHSV.isPositive()) { // (X / pos) op pos
5278 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5279 HiOverflow = LoOverflow = ProdOV;
5280 if (!HiOverflow)
5281 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5282 } else { // (X / pos) op neg
5283 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
5284 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5285 LoOverflow = AddWithOverflow(LoBound, Prod,
5286 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5287 HiBound = AddOne(Prod);
5288 HiOverflow = ProdOV ? -1 : 0;
5289 }
5290 } else { // Divisor is < 0.
5291 if (CmpRHSV == 0) { // (X / neg) op 0
5292 // e.g. X/-5 op 0 --> [-4, 5)
5293 LoBound = AddOne(DivRHS);
5294 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5295 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5296 HiOverflow = 1; // [INTMIN+1, overflow)
5297 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5298 }
5299 } else if (CmpRHSV.isPositive()) { // (X / neg) op pos
5300 // e.g. X/-5 op 3 --> [-19, -14)
5301 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5302 if (!LoOverflow)
5303 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5304 HiBound = AddOne(Prod);
5305 } else { // (X / neg) op neg
5306 // e.g. X/-5 op -3 --> [15, 20)
5307 LoBound = Prod;
5308 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
5309 HiBound = Subtract(Prod, DivRHS);
5310 }
5311
5312 // Dividing by a negative swaps the condition. LT <-> GT
5313 Pred = ICmpInst::getSwappedPredicate(Pred);
5314 }
5315
5316 Value *X = DivI->getOperand(0);
5317 switch (Pred) {
5318 default: assert(0 && "Unhandled icmp opcode!");
5319 case ICmpInst::ICMP_EQ:
5320 if (LoOverflow && HiOverflow)
5321 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5322 else if (HiOverflow)
5323 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5324 ICmpInst::ICMP_UGE, X, LoBound);
5325 else if (LoOverflow)
5326 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5327 ICmpInst::ICMP_ULT, X, HiBound);
5328 else
5329 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
5330 case ICmpInst::ICMP_NE:
5331 if (LoOverflow && HiOverflow)
5332 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5333 else if (HiOverflow)
5334 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5335 ICmpInst::ICMP_ULT, X, LoBound);
5336 else if (LoOverflow)
5337 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5338 ICmpInst::ICMP_UGE, X, HiBound);
5339 else
5340 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
5341 case ICmpInst::ICMP_ULT:
5342 case ICmpInst::ICMP_SLT:
5343 if (LoOverflow == +1) // Low bound is greater than input range.
5344 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5345 if (LoOverflow == -1) // Low bound is less than input range.
5346 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5347 return new ICmpInst(Pred, X, LoBound);
5348 case ICmpInst::ICMP_UGT:
5349 case ICmpInst::ICMP_SGT:
5350 if (HiOverflow == +1) // High bound greater than input range.
5351 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5352 else if (HiOverflow == -1) // High bound less than input range.
5353 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5354 if (Pred == ICmpInst::ICMP_UGT)
5355 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5356 else
5357 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5358 }
5359}
5360
5361
5362/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5363///
5364Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5365 Instruction *LHSI,
5366 ConstantInt *RHS) {
5367 const APInt &RHSV = RHS->getValue();
5368
5369 switch (LHSI->getOpcode()) {
5370 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
5371 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5372 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5373 // fold the xor.
5374 if (ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0 ||
5375 ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue()) {
5376 Value *CompareVal = LHSI->getOperand(0);
5377
5378 // If the sign bit of the XorCST is not set, there is no change to
5379 // the operation, just stop using the Xor.
5380 if (!XorCST->getValue().isNegative()) {
5381 ICI.setOperand(0, CompareVal);
5382 AddToWorkList(LHSI);
5383 return &ICI;
5384 }
5385
5386 // Was the old condition true if the operand is positive?
5387 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5388
5389 // If so, the new one isn't.
5390 isTrueIfPositive ^= true;
5391
5392 if (isTrueIfPositive)
5393 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5394 else
5395 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5396 }
5397 }
5398 break;
5399 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5400 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5401 LHSI->getOperand(0)->hasOneUse()) {
5402 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5403
5404 // If the LHS is an AND of a truncating cast, we can widen the
5405 // and/compare to be the input width without changing the value
5406 // produced, eliminating a cast.
5407 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5408 // We can do this transformation if either the AND constant does not
5409 // have its sign bit set or if it is an equality comparison.
5410 // Extending a relational comparison when we're checking the sign
5411 // bit would not work.
5412 if (Cast->hasOneUse() &&
5413 (ICI.isEquality() || AndCST->getValue().isPositive() &&
5414 RHSV.isPositive())) {
5415 uint32_t BitWidth =
5416 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5417 APInt NewCST = AndCST->getValue();
5418 NewCST.zext(BitWidth);
5419 APInt NewCI = RHSV;
5420 NewCI.zext(BitWidth);
5421 Instruction *NewAnd =
5422 BinaryOperator::createAnd(Cast->getOperand(0),
5423 ConstantInt::get(NewCST),LHSI->getName());
5424 InsertNewInstBefore(NewAnd, ICI);
5425 return new ICmpInst(ICI.getPredicate(), NewAnd,
5426 ConstantInt::get(NewCI));
5427 }
5428 }
5429
5430 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5431 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5432 // happens a LOT in code produced by the C front-end, for bitfield
5433 // access.
5434 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5435 if (Shift && !Shift->isShift())
5436 Shift = 0;
5437
5438 ConstantInt *ShAmt;
5439 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5440 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5441 const Type *AndTy = AndCST->getType(); // Type of the and.
5442
5443 // We can fold this as long as we can't shift unknown bits
5444 // into the mask. This can only happen with signed shift
5445 // rights, as they sign-extend.
5446 if (ShAmt) {
5447 bool CanFold = Shift->isLogicalShift();
5448 if (!CanFold) {
5449 // To test for the bad case of the signed shr, see if any
5450 // of the bits shifted in could be tested after the mask.
5451 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5452 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5453
5454 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5455 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5456 AndCST->getValue()) == 0)
5457 CanFold = true;
5458 }
5459
5460 if (CanFold) {
5461 Constant *NewCst;
5462 if (Shift->getOpcode() == Instruction::Shl)
5463 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5464 else
5465 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5466
5467 // Check to see if we are shifting out any of the bits being
5468 // compared.
5469 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5470 // If we shifted bits out, the fold is not going to work out.
5471 // As a special case, check to see if this means that the
5472 // result is always true or false now.
5473 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5474 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5475 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5476 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5477 } else {
5478 ICI.setOperand(1, NewCst);
5479 Constant *NewAndCST;
5480 if (Shift->getOpcode() == Instruction::Shl)
5481 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5482 else
5483 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5484 LHSI->setOperand(1, NewAndCST);
5485 LHSI->setOperand(0, Shift->getOperand(0));
5486 AddToWorkList(Shift); // Shift is dead.
5487 AddUsesToWorkList(ICI);
5488 return &ICI;
5489 }
5490 }
5491 }
5492
5493 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5494 // preferable because it allows the C<<Y expression to be hoisted out
5495 // of a loop if Y is invariant and X is not.
5496 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5497 ICI.isEquality() && !Shift->isArithmeticShift() &&
5498 isa<Instruction>(Shift->getOperand(0))) {
5499 // Compute C << Y.
5500 Value *NS;
5501 if (Shift->getOpcode() == Instruction::LShr) {
5502 NS = BinaryOperator::createShl(AndCST,
5503 Shift->getOperand(1), "tmp");
5504 } else {
5505 // Insert a logical shift.
5506 NS = BinaryOperator::createLShr(AndCST,
5507 Shift->getOperand(1), "tmp");
5508 }
5509 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5510
5511 // Compute X & (C << Y).
5512 Instruction *NewAnd =
5513 BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5514 InsertNewInstBefore(NewAnd, ICI);
5515
5516 ICI.setOperand(0, NewAnd);
5517 return &ICI;
5518 }
5519 }
5520 break;
5521
5522 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
5523 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5524 if (!ShAmt) break;
5525
5526 uint32_t TypeBits = RHSV.getBitWidth();
5527
5528 // Check that the shift amount is in range. If not, don't perform
5529 // undefined shifts. When the shift is visited it will be
5530 // simplified.
5531 if (ShAmt->uge(TypeBits))
5532 break;
5533
5534 if (ICI.isEquality()) {
5535 // If we are comparing against bits always shifted out, the
5536 // comparison cannot succeed.
5537 Constant *Comp =
5538 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5539 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5540 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5541 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5542 return ReplaceInstUsesWith(ICI, Cst);
5543 }
5544
5545 if (LHSI->hasOneUse()) {
5546 // Otherwise strength reduce the shift into an and.
5547 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5548 Constant *Mask =
5549 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5550
5551 Instruction *AndI =
5552 BinaryOperator::createAnd(LHSI->getOperand(0),
5553 Mask, LHSI->getName()+".mask");
5554 Value *And = InsertNewInstBefore(AndI, ICI);
5555 return new ICmpInst(ICI.getPredicate(), And,
5556 ConstantInt::get(RHSV.lshr(ShAmtVal)));
5557 }
5558 }
5559
5560 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5561 bool TrueIfSigned = false;
5562 if (LHSI->hasOneUse() &&
5563 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5564 // (X << 31) <s 0 --> (X&1) != 0
5565 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5566 (TypeBits-ShAmt->getZExtValue()-1));
5567 Instruction *AndI =
5568 BinaryOperator::createAnd(LHSI->getOperand(0),
5569 Mask, LHSI->getName()+".mask");
5570 Value *And = InsertNewInstBefore(AndI, ICI);
5571
5572 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5573 And, Constant::getNullValue(And->getType()));
5574 }
5575 break;
5576 }
5577
5578 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
5579 case Instruction::AShr: {
5580 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5581 if (!ShAmt) break;
5582
5583 if (ICI.isEquality()) {
5584 // Check that the shift amount is in range. If not, don't perform
5585 // undefined shifts. When the shift is visited it will be
5586 // simplified.
5587 uint32_t TypeBits = RHSV.getBitWidth();
5588 if (ShAmt->uge(TypeBits))
5589 break;
5590 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5591
5592 // If we are comparing against bits always shifted out, the
5593 // comparison cannot succeed.
5594 APInt Comp = RHSV << ShAmtVal;
5595 if (LHSI->getOpcode() == Instruction::LShr)
5596 Comp = Comp.lshr(ShAmtVal);
5597 else
5598 Comp = Comp.ashr(ShAmtVal);
5599
5600 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5601 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5602 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5603 return ReplaceInstUsesWith(ICI, Cst);
5604 }
5605
5606 if (LHSI->hasOneUse() || RHSV == 0) {
5607 // Otherwise strength reduce the shift into an and.
5608 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5609 Constant *Mask = ConstantInt::get(Val);
5610
5611 Instruction *AndI =
5612 BinaryOperator::createAnd(LHSI->getOperand(0),
5613 Mask, LHSI->getName()+".mask");
5614 Value *And = InsertNewInstBefore(AndI, ICI);
5615 return new ICmpInst(ICI.getPredicate(), And,
5616 ConstantExpr::getShl(RHS, ShAmt));
5617 }
5618 }
5619 break;
5620 }
5621
5622 case Instruction::SDiv:
5623 case Instruction::UDiv:
5624 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5625 // Fold this div into the comparison, producing a range check.
5626 // Determine, based on the divide type, what the range is being
5627 // checked. If there is an overflow on the low or high side, remember
5628 // it, otherwise compute the range [low, hi) bounding the new value.
5629 // See: InsertRangeTest above for the kinds of replacements possible.
5630 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
5631 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
5632 DivRHS))
5633 return R;
5634 break;
5635 }
5636
5637 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5638 if (ICI.isEquality()) {
5639 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5640
5641 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5642 // the second operand is a constant, simplify a bit.
5643 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
5644 switch (BO->getOpcode()) {
5645 case Instruction::SRem:
5646 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5647 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
5648 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
5649 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
5650 Instruction *NewRem =
5651 BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
5652 BO->getName());
5653 InsertNewInstBefore(NewRem, ICI);
5654 return new ICmpInst(ICI.getPredicate(), NewRem,
5655 Constant::getNullValue(BO->getType()));
5656 }
5657 }
5658 break;
5659 case Instruction::Add:
5660 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5661 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5662 if (BO->hasOneUse())
5663 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5664 Subtract(RHS, BOp1C));
5665 } else if (RHSV == 0) {
5666 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5667 // efficiently invertible, or if the add has just this one use.
5668 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5669
5670 if (Value *NegVal = dyn_castNegVal(BOp1))
5671 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
5672 else if (Value *NegVal = dyn_castNegVal(BOp0))
5673 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
5674 else if (BO->hasOneUse()) {
5675 Instruction *Neg = BinaryOperator::createNeg(BOp1);
5676 InsertNewInstBefore(Neg, ICI);
5677 Neg->takeName(BO);
5678 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
5679 }
5680 }
5681 break;
5682 case Instruction::Xor:
5683 // For the xor case, we can xor two constants together, eliminating
5684 // the explicit xor.
5685 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5686 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5687 ConstantExpr::getXor(RHS, BOC));
5688
5689 // FALLTHROUGH
5690 case Instruction::Sub:
5691 // Replace (([sub|xor] A, B) != 0) with (A != B)
5692 if (RHSV == 0)
5693 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5694 BO->getOperand(1));
5695 break;
5696
5697 case Instruction::Or:
5698 // If bits are being or'd in that are not present in the constant we
5699 // are comparing against, then the comparison could never succeed!
5700 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5701 Constant *NotCI = ConstantExpr::getNot(RHS);
5702 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5703 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5704 isICMP_NE));
5705 }
5706 break;
5707
5708 case Instruction::And:
5709 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5710 // If bits are being compared against that are and'd out, then the
5711 // comparison can never succeed!
5712 if ((RHSV & ~BOC->getValue()) != 0)
5713 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5714 isICMP_NE));
5715
5716 // If we have ((X & C) == C), turn it into ((X & C) != 0).
5717 if (RHS == BOC && RHSV.isPowerOf2())
5718 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5719 ICmpInst::ICMP_NE, LHSI,
5720 Constant::getNullValue(RHS->getType()));
5721
5722 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5723 if (isSignBit(BOC)) {
5724 Value *X = BO->getOperand(0);
5725 Constant *Zero = Constant::getNullValue(X->getType());
5726 ICmpInst::Predicate pred = isICMP_NE ?
5727 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5728 return new ICmpInst(pred, X, Zero);
5729 }
5730
5731 // ((X & ~7) == 0) --> X < 8
5732 if (RHSV == 0 && isHighOnes(BOC)) {
5733 Value *X = BO->getOperand(0);
5734 Constant *NegX = ConstantExpr::getNeg(BOC);
5735 ICmpInst::Predicate pred = isICMP_NE ?
5736 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5737 return new ICmpInst(pred, X, NegX);
5738 }
5739 }
5740 default: break;
5741 }
5742 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
5743 // Handle icmp {eq|ne} <intrinsic>, intcst.
5744 if (II->getIntrinsicID() == Intrinsic::bswap) {
5745 AddToWorkList(II);
5746 ICI.setOperand(0, II->getOperand(1));
5747 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
5748 return &ICI;
5749 }
5750 }
5751 } else { // Not a ICMP_EQ/ICMP_NE
5752 // If the LHS is a cast from an integral value of the same size,
5753 // then since we know the RHS is a constant, try to simlify.
5754 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
5755 Value *CastOp = Cast->getOperand(0);
5756 const Type *SrcTy = CastOp->getType();
5757 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
5758 if (SrcTy->isInteger() &&
5759 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5760 // If this is an unsigned comparison, try to make the comparison use
5761 // smaller constant values.
5762 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
5763 // X u< 128 => X s> -1
5764 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5765 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
5766 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
5767 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
5768 // X u> 127 => X s< 0
5769 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5770 Constant::getNullValue(SrcTy));
5771 }
5772 }
5773 }
5774 }
5775 return 0;
5776}
5777
5778/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5779/// We only handle extending casts so far.
5780///
5781Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5782 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
5783 Value *LHSCIOp = LHSCI->getOperand(0);
5784 const Type *SrcTy = LHSCIOp->getType();
5785 const Type *DestTy = LHSCI->getType();
5786 Value *RHSCIOp;
5787
5788 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
5789 // integer type is the same size as the pointer type.
5790 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
5791 getTargetData().getPointerSizeInBits() ==
5792 cast<IntegerType>(DestTy)->getBitWidth()) {
5793 Value *RHSOp = 0;
5794 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
5795 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
5796 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
5797 RHSOp = RHSC->getOperand(0);
5798 // If the pointer types don't match, insert a bitcast.
5799 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner13c2d6e2008-01-13 22:23:22 +00005800 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005801 }
5802
5803 if (RHSOp)
5804 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
5805 }
5806
5807 // The code below only handles extension cast instructions, so far.
5808 // Enforce this.
5809 if (LHSCI->getOpcode() != Instruction::ZExt &&
5810 LHSCI->getOpcode() != Instruction::SExt)
5811 return 0;
5812
5813 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5814 bool isSignedCmp = ICI.isSignedPredicate();
5815
5816 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
5817 // Not an extension from the same type?
5818 RHSCIOp = CI->getOperand(0);
5819 if (RHSCIOp->getType() != LHSCIOp->getType())
5820 return 0;
5821
5822 // If the signedness of the two compares doesn't agree (i.e. one is a sext
5823 // and the other is a zext), then we can't handle this.
5824 if (CI->getOpcode() != LHSCI->getOpcode())
5825 return 0;
5826
5827 // Likewise, if the signedness of the [sz]exts and the compare don't match,
5828 // then we can't handle this.
5829 if (isSignedExt != isSignedCmp && !ICI.isEquality())
5830 return 0;
5831
5832 // Okay, just insert a compare of the reduced operands now!
5833 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5834 }
5835
5836 // If we aren't dealing with a constant on the RHS, exit early
5837 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5838 if (!CI)
5839 return 0;
5840
5841 // Compute the constant that would happen if we truncated to SrcTy then
5842 // reextended to DestTy.
5843 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5844 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5845
5846 // If the re-extended constant didn't change...
5847 if (Res2 == CI) {
5848 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5849 // For example, we might have:
5850 // %A = sext short %X to uint
5851 // %B = icmp ugt uint %A, 1330
5852 // It is incorrect to transform this into
5853 // %B = icmp ugt short %X, 1330
5854 // because %A may have negative value.
5855 //
5856 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5857 // OR operation is EQ/NE.
5858 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
5859 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5860 else
5861 return 0;
5862 }
5863
5864 // The re-extended constant changed so the constant cannot be represented
5865 // in the shorter type. Consequently, we cannot emit a simple comparison.
5866
5867 // First, handle some easy cases. We know the result cannot be equal at this
5868 // point so handle the ICI.isEquality() cases
5869 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5870 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5871 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5872 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5873
5874 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5875 // should have been folded away previously and not enter in here.
5876 Value *Result;
5877 if (isSignedCmp) {
5878 // We're performing a signed comparison.
5879 if (cast<ConstantInt>(CI)->getValue().isNegative())
5880 Result = ConstantInt::getFalse(); // X < (small) --> false
5881 else
5882 Result = ConstantInt::getTrue(); // X < (large) --> true
5883 } else {
5884 // We're performing an unsigned comparison.
5885 if (isSignedExt) {
5886 // We're performing an unsigned comp with a sign extended value.
5887 // This is true if the input is >= 0. [aka >s -1]
5888 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
5889 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5890 NegOne, ICI.getName()), ICI);
5891 } else {
5892 // Unsigned extend & unsigned compare -> always true.
5893 Result = ConstantInt::getTrue();
5894 }
5895 }
5896
5897 // Finally, return the value computed.
5898 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5899 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5900 return ReplaceInstUsesWith(ICI, Result);
5901 } else {
5902 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5903 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5904 "ICmp should be folded!");
5905 if (Constant *CI = dyn_cast<Constant>(Result))
5906 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5907 else
5908 return BinaryOperator::createNot(Result);
5909 }
5910}
5911
5912Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5913 return commonShiftTransforms(I);
5914}
5915
5916Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5917 return commonShiftTransforms(I);
5918}
5919
5920Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00005921 if (Instruction *R = commonShiftTransforms(I))
5922 return R;
5923
5924 Value *Op0 = I.getOperand(0);
5925
5926 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5927 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
5928 if (CSI->isAllOnesValue())
5929 return ReplaceInstUsesWith(I, CSI);
5930
5931 // See if we can turn a signed shr into an unsigned shr.
5932 if (MaskedValueIsZero(Op0,
5933 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
5934 return BinaryOperator::createLShr(Op0, I.getOperand(1));
5935
5936 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005937}
5938
5939Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
5940 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
5941 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5942
5943 // shl X, 0 == X and shr X, 0 == X
5944 // shl 0, X == 0 and shr 0, X == 0
5945 if (Op1 == Constant::getNullValue(Op1->getType()) ||
5946 Op0 == Constant::getNullValue(Op0->getType()))
5947 return ReplaceInstUsesWith(I, Op0);
5948
5949 if (isa<UndefValue>(Op0)) {
5950 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
5951 return ReplaceInstUsesWith(I, Op0);
5952 else // undef << X -> 0, undef >>u X -> 0
5953 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5954 }
5955 if (isa<UndefValue>(Op1)) {
5956 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5957 return ReplaceInstUsesWith(I, Op0);
5958 else // X << undef, X >>u undef -> 0
5959 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5960 }
5961
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005962 // Try to fold constant and into select arguments.
5963 if (isa<Constant>(Op0))
5964 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
5965 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5966 return R;
5967
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005968 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5969 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5970 return Res;
5971 return 0;
5972}
5973
5974Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
5975 BinaryOperator &I) {
5976 bool isLeftShift = I.getOpcode() == Instruction::Shl;
5977
5978 // See if we can simplify any instructions used by the instruction whose sole
5979 // purpose is to compute bits we don't care about.
5980 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5981 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
5982 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
5983 KnownZero, KnownOne))
5984 return &I;
5985
5986 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5987 // of a signed value.
5988 //
5989 if (Op1->uge(TypeBits)) {
5990 if (I.getOpcode() != Instruction::AShr)
5991 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5992 else {
5993 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
5994 return &I;
5995 }
5996 }
5997
5998 // ((X*C1) << C2) == (X * (C1 << C2))
5999 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6000 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6001 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6002 return BinaryOperator::createMul(BO->getOperand(0),
6003 ConstantExpr::getShl(BOOp, Op1));
6004
6005 // Try to fold constant and into select arguments.
6006 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6007 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6008 return R;
6009 if (isa<PHINode>(Op0))
6010 if (Instruction *NV = FoldOpIntoPhi(I))
6011 return NV;
6012
Chris Lattnerc6d1f642007-12-22 09:07:47 +00006013 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6014 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6015 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6016 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6017 // place. Don't try to do this transformation in this case. Also, we
6018 // require that the input operand is a shift-by-constant so that we have
6019 // confidence that the shifts will get folded together. We could do this
6020 // xform in more cases, but it is unlikely to be profitable.
6021 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6022 isa<ConstantInt>(TrOp->getOperand(1))) {
6023 // Okay, we'll do this xform. Make the shift of shift.
6024 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6025 Instruction *NSh = BinaryOperator::create(I.getOpcode(), TrOp, ShAmt,
6026 I.getName());
6027 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6028
6029 // For logical shifts, the truncation has the effect of making the high
6030 // part of the register be zeros. Emulate this by inserting an AND to
6031 // clear the top bits as needed. This 'and' will usually be zapped by
6032 // other xforms later if dead.
6033 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6034 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6035 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6036
6037 // The mask we constructed says what the trunc would do if occurring
6038 // between the shifts. We want to know the effect *after* the second
6039 // shift. We know that it is a logical shift by a constant, so adjust the
6040 // mask as appropriate.
6041 if (I.getOpcode() == Instruction::Shl)
6042 MaskV <<= Op1->getZExtValue();
6043 else {
6044 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6045 MaskV = MaskV.lshr(Op1->getZExtValue());
6046 }
6047
6048 Instruction *And = BinaryOperator::createAnd(NSh, ConstantInt::get(MaskV),
6049 TI->getName());
6050 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6051
6052 // Return the value truncated to the interesting size.
6053 return new TruncInst(And, I.getType());
6054 }
6055 }
6056
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006057 if (Op0->hasOneUse()) {
6058 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6059 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6060 Value *V1, *V2;
6061 ConstantInt *CC;
6062 switch (Op0BO->getOpcode()) {
6063 default: break;
6064 case Instruction::Add:
6065 case Instruction::And:
6066 case Instruction::Or:
6067 case Instruction::Xor: {
6068 // These operators commute.
6069 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
6070 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6071 match(Op0BO->getOperand(1),
6072 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6073 Instruction *YS = BinaryOperator::createShl(
6074 Op0BO->getOperand(0), Op1,
6075 Op0BO->getName());
6076 InsertNewInstBefore(YS, I); // (Y << C)
6077 Instruction *X =
6078 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
6079 Op0BO->getOperand(1)->getName());
6080 InsertNewInstBefore(X, I); // (X + (Y << C))
6081 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6082 return BinaryOperator::createAnd(X, ConstantInt::get(
6083 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6084 }
6085
6086 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
6087 Value *Op0BOOp1 = Op0BO->getOperand(1);
6088 if (isLeftShift && Op0BOOp1->hasOneUse() &&
6089 match(Op0BOOp1,
6090 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6091 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6092 V2 == Op1) {
6093 Instruction *YS = BinaryOperator::createShl(
6094 Op0BO->getOperand(0), Op1,
6095 Op0BO->getName());
6096 InsertNewInstBefore(YS, I); // (Y << C)
6097 Instruction *XM =
6098 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
6099 V1->getName()+".mask");
6100 InsertNewInstBefore(XM, I); // X & (CC << C)
6101
6102 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6103 }
6104 }
6105
6106 // FALL THROUGH.
6107 case Instruction::Sub: {
6108 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6109 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6110 match(Op0BO->getOperand(0),
6111 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6112 Instruction *YS = BinaryOperator::createShl(
6113 Op0BO->getOperand(1), Op1,
6114 Op0BO->getName());
6115 InsertNewInstBefore(YS, I); // (Y << C)
6116 Instruction *X =
6117 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
6118 Op0BO->getOperand(0)->getName());
6119 InsertNewInstBefore(X, I); // (X + (Y << C))
6120 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6121 return BinaryOperator::createAnd(X, ConstantInt::get(
6122 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6123 }
6124
6125 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
6126 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6127 match(Op0BO->getOperand(0),
6128 m_And(m_Shr(m_Value(V1), m_Value(V2)),
6129 m_ConstantInt(CC))) && V2 == Op1 &&
6130 cast<BinaryOperator>(Op0BO->getOperand(0))
6131 ->getOperand(0)->hasOneUse()) {
6132 Instruction *YS = BinaryOperator::createShl(
6133 Op0BO->getOperand(1), Op1,
6134 Op0BO->getName());
6135 InsertNewInstBefore(YS, I); // (Y << C)
6136 Instruction *XM =
6137 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
6138 V1->getName()+".mask");
6139 InsertNewInstBefore(XM, I); // X & (CC << C)
6140
6141 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
6142 }
6143
6144 break;
6145 }
6146 }
6147
6148
6149 // If the operand is an bitwise operator with a constant RHS, and the
6150 // shift is the only use, we can pull it out of the shift.
6151 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6152 bool isValid = true; // Valid only for And, Or, Xor
6153 bool highBitSet = false; // Transform if high bit of constant set?
6154
6155 switch (Op0BO->getOpcode()) {
6156 default: isValid = false; break; // Do not perform transform!
6157 case Instruction::Add:
6158 isValid = isLeftShift;
6159 break;
6160 case Instruction::Or:
6161 case Instruction::Xor:
6162 highBitSet = false;
6163 break;
6164 case Instruction::And:
6165 highBitSet = true;
6166 break;
6167 }
6168
6169 // If this is a signed shift right, and the high bit is modified
6170 // by the logical operation, do not perform the transformation.
6171 // The highBitSet boolean indicates the value of the high bit of
6172 // the constant which would cause it to be modified for this
6173 // operation.
6174 //
Chris Lattner15b76e32007-12-06 06:25:04 +00006175 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006176 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006177
6178 if (isValid) {
6179 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6180
6181 Instruction *NewShift =
6182 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
6183 InsertNewInstBefore(NewShift, I);
6184 NewShift->takeName(Op0BO);
6185
6186 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6187 NewRHS);
6188 }
6189 }
6190 }
6191 }
6192
6193 // Find out if this is a shift of a shift by a constant.
6194 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6195 if (ShiftOp && !ShiftOp->isShift())
6196 ShiftOp = 0;
6197
6198 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6199 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6200 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6201 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6202 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6203 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6204 Value *X = ShiftOp->getOperand(0);
6205
6206 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
6207 if (AmtSum > TypeBits)
6208 AmtSum = TypeBits;
6209
6210 const IntegerType *Ty = cast<IntegerType>(I.getType());
6211
6212 // Check for (X << c1) << c2 and (X >> c1) >> c2
6213 if (I.getOpcode() == ShiftOp->getOpcode()) {
6214 return BinaryOperator::create(I.getOpcode(), X,
6215 ConstantInt::get(Ty, AmtSum));
6216 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6217 I.getOpcode() == Instruction::AShr) {
6218 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
6219 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6220 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6221 I.getOpcode() == Instruction::LShr) {
6222 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6223 Instruction *Shift =
6224 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6225 InsertNewInstBefore(Shift, I);
6226
6227 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6228 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6229 }
6230
6231 // Okay, if we get here, one shift must be left, and the other shift must be
6232 // right. See if the amounts are equal.
6233 if (ShiftAmt1 == ShiftAmt2) {
6234 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6235 if (I.getOpcode() == Instruction::Shl) {
6236 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
6237 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
6238 }
6239 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6240 if (I.getOpcode() == Instruction::LShr) {
6241 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
6242 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
6243 }
6244 // We can simplify ((X << C) >>s C) into a trunc + sext.
6245 // NOTE: we could do this for any C, but that would make 'unusual' integer
6246 // types. For now, just stick to ones well-supported by the code
6247 // generators.
6248 const Type *SExtType = 0;
6249 switch (Ty->getBitWidth() - ShiftAmt1) {
6250 case 1 :
6251 case 8 :
6252 case 16 :
6253 case 32 :
6254 case 64 :
6255 case 128:
6256 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6257 break;
6258 default: break;
6259 }
6260 if (SExtType) {
6261 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6262 InsertNewInstBefore(NewTrunc, I);
6263 return new SExtInst(NewTrunc, Ty);
6264 }
6265 // Otherwise, we can't handle it yet.
6266 } else if (ShiftAmt1 < ShiftAmt2) {
6267 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
6268
6269 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6270 if (I.getOpcode() == Instruction::Shl) {
6271 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6272 ShiftOp->getOpcode() == Instruction::AShr);
6273 Instruction *Shift =
6274 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6275 InsertNewInstBefore(Shift, I);
6276
6277 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6278 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6279 }
6280
6281 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
6282 if (I.getOpcode() == Instruction::LShr) {
6283 assert(ShiftOp->getOpcode() == Instruction::Shl);
6284 Instruction *Shift =
6285 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6286 InsertNewInstBefore(Shift, I);
6287
6288 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6289 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6290 }
6291
6292 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6293 } else {
6294 assert(ShiftAmt2 < ShiftAmt1);
6295 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6296
6297 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6298 if (I.getOpcode() == Instruction::Shl) {
6299 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6300 ShiftOp->getOpcode() == Instruction::AShr);
6301 Instruction *Shift =
6302 BinaryOperator::create(ShiftOp->getOpcode(), X,
6303 ConstantInt::get(Ty, ShiftDiff));
6304 InsertNewInstBefore(Shift, I);
6305
6306 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6307 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6308 }
6309
6310 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
6311 if (I.getOpcode() == Instruction::LShr) {
6312 assert(ShiftOp->getOpcode() == Instruction::Shl);
6313 Instruction *Shift =
6314 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6315 InsertNewInstBefore(Shift, I);
6316
6317 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6318 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6319 }
6320
6321 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6322 }
6323 }
6324 return 0;
6325}
6326
6327
6328/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6329/// expression. If so, decompose it, returning some value X, such that Val is
6330/// X*Scale+Offset.
6331///
6332static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6333 int &Offset) {
6334 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6335 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6336 Offset = CI->getZExtValue();
Chris Lattnerc59171a2007-10-12 05:30:59 +00006337 Scale = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006338 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattnerc59171a2007-10-12 05:30:59 +00006339 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6340 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6341 if (I->getOpcode() == Instruction::Shl) {
6342 // This is a value scaled by '1 << the shift amt'.
6343 Scale = 1U << RHS->getZExtValue();
6344 Offset = 0;
6345 return I->getOperand(0);
6346 } else if (I->getOpcode() == Instruction::Mul) {
6347 // This value is scaled by 'RHS'.
6348 Scale = RHS->getZExtValue();
6349 Offset = 0;
6350 return I->getOperand(0);
6351 } else if (I->getOpcode() == Instruction::Add) {
6352 // We have X+C. Check to see if we really have (X*C2)+C1,
6353 // where C1 is divisible by C2.
6354 unsigned SubScale;
6355 Value *SubVal =
6356 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6357 Offset += RHS->getZExtValue();
6358 Scale = SubScale;
6359 return SubVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006360 }
6361 }
6362 }
6363
6364 // Otherwise, we can't look past this.
6365 Scale = 1;
6366 Offset = 0;
6367 return Val;
6368}
6369
6370
6371/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6372/// try to eliminate the cast by moving the type information into the alloc.
6373Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6374 AllocationInst &AI) {
6375 const PointerType *PTy = cast<PointerType>(CI.getType());
6376
6377 // Remove any uses of AI that are dead.
6378 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6379
6380 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6381 Instruction *User = cast<Instruction>(*UI++);
6382 if (isInstructionTriviallyDead(User)) {
6383 while (UI != E && *UI == User)
6384 ++UI; // If this instruction uses AI more than once, don't break UI.
6385
6386 ++NumDeadInst;
6387 DOUT << "IC: DCE: " << *User;
6388 EraseInstFromFunction(*User);
6389 }
6390 }
6391
6392 // Get the type really allocated and the type casted to.
6393 const Type *AllocElTy = AI.getAllocatedType();
6394 const Type *CastElTy = PTy->getElementType();
6395 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6396
6397 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6398 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6399 if (CastElTyAlign < AllocElTyAlign) return 0;
6400
6401 // If the allocation has multiple uses, only promote it if we are strictly
6402 // increasing the alignment of the resultant allocation. If we keep it the
6403 // same, we open the door to infinite loops of various kinds.
6404 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6405
Duncan Sandsf99fdc62007-11-01 20:53:16 +00006406 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6407 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006408 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6409
6410 // See if we can satisfy the modulus by pulling a scale out of the array
6411 // size argument.
6412 unsigned ArraySizeScale;
6413 int ArrayOffset;
6414 Value *NumElements = // See if the array size is a decomposable linear expr.
6415 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6416
6417 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6418 // do the xform.
6419 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6420 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
6421
6422 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6423 Value *Amt = 0;
6424 if (Scale == 1) {
6425 Amt = NumElements;
6426 } else {
6427 // If the allocation size is constant, form a constant mul expression
6428 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6429 if (isa<ConstantInt>(NumElements))
6430 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6431 // otherwise multiply the amount and the number of elements
6432 else if (Scale != 1) {
6433 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6434 Amt = InsertNewInstBefore(Tmp, AI);
6435 }
6436 }
6437
6438 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6439 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
6440 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6441 Amt = InsertNewInstBefore(Tmp, AI);
6442 }
6443
6444 AllocationInst *New;
6445 if (isa<MallocInst>(AI))
6446 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6447 else
6448 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6449 InsertNewInstBefore(New, AI);
6450 New->takeName(&AI);
6451
6452 // If the allocation has multiple uses, insert a cast and change all things
6453 // that used it to use the new cast. This will also hack on CI, but it will
6454 // die soon.
6455 if (!AI.hasOneUse()) {
6456 AddUsesToWorkList(AI);
6457 // New is the allocation instruction, pointer typed. AI is the original
6458 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6459 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6460 InsertNewInstBefore(NewCast, AI);
6461 AI.replaceAllUsesWith(NewCast);
6462 }
6463 return ReplaceInstUsesWith(CI, New);
6464}
6465
6466/// CanEvaluateInDifferentType - Return true if we can take the specified value
6467/// and return it as type Ty without inserting any new casts and without
6468/// changing the computed value. This is used by code that tries to decide
6469/// whether promoting or shrinking integer operations to wider or smaller types
6470/// will allow us to eliminate a truncate or extend.
6471///
6472/// This is a truncation operation if Ty is smaller than V->getType(), or an
6473/// extension operation if Ty is larger.
6474static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattneref70bb82007-08-02 06:11:14 +00006475 unsigned CastOpc, int &NumCastsRemoved) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006476 // We can always evaluate constants in another type.
6477 if (isa<ConstantInt>(V))
6478 return true;
6479
6480 Instruction *I = dyn_cast<Instruction>(V);
6481 if (!I) return false;
6482
6483 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6484
Chris Lattneref70bb82007-08-02 06:11:14 +00006485 // If this is an extension or truncate, we can often eliminate it.
6486 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6487 // If this is a cast from the destination type, we can trivially eliminate
6488 // it, and this will remove a cast overall.
6489 if (I->getOperand(0)->getType() == Ty) {
6490 // If the first operand is itself a cast, and is eliminable, do not count
6491 // this as an eliminable cast. We would prefer to eliminate those two
6492 // casts first.
6493 if (!isa<CastInst>(I->getOperand(0)))
6494 ++NumCastsRemoved;
6495 return true;
6496 }
6497 }
6498
6499 // We can't extend or shrink something that has multiple uses: doing so would
6500 // require duplicating the instruction in general, which isn't profitable.
6501 if (!I->hasOneUse()) return false;
6502
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006503 switch (I->getOpcode()) {
6504 case Instruction::Add:
6505 case Instruction::Sub:
6506 case Instruction::And:
6507 case Instruction::Or:
6508 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006509 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00006510 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6511 NumCastsRemoved) &&
6512 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6513 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006514
Nick Lewyckyc52646a2008-01-22 05:08:48 +00006515 case Instruction::Mul:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00006516 // A multiply can be truncated by truncating its operands.
6517 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
6518 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6519 NumCastsRemoved) &&
6520 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6521 NumCastsRemoved);
6522
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006523 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006524 // If we are truncating the result of this SHL, and if it's a shift of a
6525 // constant amount, we can always perform a SHL in a smaller type.
6526 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6527 uint32_t BitWidth = Ty->getBitWidth();
6528 if (BitWidth < OrigTy->getBitWidth() &&
6529 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00006530 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6531 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006532 }
6533 break;
6534 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006535 // If this is a truncate of a logical shr, we can truncate it to a smaller
6536 // lshr iff we know that the bits we would otherwise be shifting in are
6537 // already zeros.
6538 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6539 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6540 uint32_t BitWidth = Ty->getBitWidth();
6541 if (BitWidth < OrigBitWidth &&
6542 MaskedValueIsZero(I->getOperand(0),
6543 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6544 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00006545 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6546 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006547 }
6548 }
6549 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006550 case Instruction::ZExt:
6551 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00006552 case Instruction::Trunc:
6553 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00006554 // can safely replace it. Note that replacing it does not reduce the number
6555 // of casts in the input.
6556 if (I->getOpcode() == CastOpc)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006557 return true;
Chris Lattner2799b2f2007-09-10 23:46:29 +00006558
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006559 break;
6560 default:
6561 // TODO: Can handle more cases here.
6562 break;
6563 }
6564
6565 return false;
6566}
6567
6568/// EvaluateInDifferentType - Given an expression that
6569/// CanEvaluateInDifferentType returns true for, actually insert the code to
6570/// evaluate the expression.
6571Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
6572 bool isSigned) {
6573 if (Constant *C = dyn_cast<Constant>(V))
6574 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
6575
6576 // Otherwise, it must be an instruction.
6577 Instruction *I = cast<Instruction>(V);
6578 Instruction *Res = 0;
6579 switch (I->getOpcode()) {
6580 case Instruction::Add:
6581 case Instruction::Sub:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00006582 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006583 case Instruction::And:
6584 case Instruction::Or:
6585 case Instruction::Xor:
6586 case Instruction::AShr:
6587 case Instruction::LShr:
6588 case Instruction::Shl: {
6589 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
6590 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6591 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6592 LHS, RHS, I->getName());
6593 break;
6594 }
6595 case Instruction::Trunc:
6596 case Instruction::ZExt:
6597 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006598 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00006599 // just return the source. There's no need to insert it because it is not
6600 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006601 if (I->getOperand(0)->getType() == Ty)
6602 return I->getOperand(0);
6603
Chris Lattneref70bb82007-08-02 06:11:14 +00006604 // Otherwise, must be the same type of case, so just reinsert a new one.
6605 Res = CastInst::create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
6606 Ty, I->getName());
6607 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006608 default:
6609 // TODO: Can handle more cases here.
6610 assert(0 && "Unreachable!");
6611 break;
6612 }
6613
6614 return InsertNewInstBefore(Res, *I);
6615}
6616
6617/// @brief Implement the transforms common to all CastInst visitors.
6618Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
6619 Value *Src = CI.getOperand(0);
6620
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006621 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
6622 // eliminate it now.
6623 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
6624 if (Instruction::CastOps opc =
6625 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6626 // The first cast (CSrc) is eliminable so we need to fix up or replace
6627 // the second cast (CI). CSrc will then have a good chance of being dead.
6628 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
6629 }
6630 }
6631
6632 // If we are casting a select then fold the cast into the select
6633 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6634 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6635 return NV;
6636
6637 // If we are casting a PHI then fold the cast into the PHI
6638 if (isa<PHINode>(Src))
6639 if (Instruction *NV = FoldOpIntoPhi(CI))
6640 return NV;
6641
6642 return 0;
6643}
6644
6645/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
6646Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
6647 Value *Src = CI.getOperand(0);
6648
6649 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
6650 // If casting the result of a getelementptr instruction with no offset, turn
6651 // this into a cast of the original pointer!
6652 if (GEP->hasAllZeroIndices()) {
6653 // Changing the cast operand is usually not a good idea but it is safe
6654 // here because the pointer operand is being replaced with another
6655 // pointer operand so the opcode doesn't need to change.
6656 AddToWorkList(GEP);
6657 CI.setOperand(0, GEP->getOperand(0));
6658 return &CI;
6659 }
6660
6661 // If the GEP has a single use, and the base pointer is a bitcast, and the
6662 // GEP computes a constant offset, see if we can convert these three
6663 // instructions into fewer. This typically happens with unions and other
6664 // non-type-safe code.
6665 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
6666 if (GEP->hasAllConstantIndices()) {
6667 // We are guaranteed to get a constant from EmitGEPOffset.
6668 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
6669 int64_t Offset = OffsetV->getSExtValue();
6670
6671 // Get the base pointer input of the bitcast, and the type it points to.
6672 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
6673 const Type *GEPIdxTy =
6674 cast<PointerType>(OrigBase->getType())->getElementType();
6675 if (GEPIdxTy->isSized()) {
6676 SmallVector<Value*, 8> NewIndices;
6677
6678 // Start with the index over the outer type. Note that the type size
6679 // might be zero (even if the offset isn't zero) if the indexed type
6680 // is something like [0 x {int, int}]
6681 const Type *IntPtrTy = TD->getIntPtrType();
6682 int64_t FirstIdx = 0;
Duncan Sandsf99fdc62007-11-01 20:53:16 +00006683 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006684 FirstIdx = Offset/TySize;
6685 Offset %= TySize;
6686
6687 // Handle silly modulus not returning values values [0..TySize).
6688 if (Offset < 0) {
6689 --FirstIdx;
6690 Offset += TySize;
6691 assert(Offset >= 0);
6692 }
6693 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
6694 }
6695
6696 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
6697
6698 // Index into the types. If we fail, set OrigBase to null.
6699 while (Offset) {
6700 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
6701 const StructLayout *SL = TD->getStructLayout(STy);
6702 if (Offset < (int64_t)SL->getSizeInBytes()) {
6703 unsigned Elt = SL->getElementContainingOffset(Offset);
6704 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
6705
6706 Offset -= SL->getElementOffset(Elt);
6707 GEPIdxTy = STy->getElementType(Elt);
6708 } else {
6709 // Otherwise, we can't index into this, bail out.
6710 Offset = 0;
6711 OrigBase = 0;
6712 }
6713 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
6714 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sandsf99fdc62007-11-01 20:53:16 +00006715 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006716 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
6717 Offset %= EltSize;
6718 } else {
6719 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
6720 }
6721 GEPIdxTy = STy->getElementType();
6722 } else {
6723 // Otherwise, we can't index into this, bail out.
6724 Offset = 0;
6725 OrigBase = 0;
6726 }
6727 }
6728 if (OrigBase) {
6729 // If we were able to index down into an element, create the GEP
6730 // and bitcast the result. This eliminates one bitcast, potentially
6731 // two.
David Greene393be882007-09-04 15:46:09 +00006732 Instruction *NGEP = new GetElementPtrInst(OrigBase,
6733 NewIndices.begin(),
6734 NewIndices.end(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006735 InsertNewInstBefore(NGEP, CI);
6736 NGEP->takeName(GEP);
6737
6738 if (isa<BitCastInst>(CI))
6739 return new BitCastInst(NGEP, CI.getType());
6740 assert(isa<PtrToIntInst>(CI));
6741 return new PtrToIntInst(NGEP, CI.getType());
6742 }
6743 }
6744 }
6745 }
6746 }
6747
6748 return commonCastTransforms(CI);
6749}
6750
6751
6752
6753/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6754/// integer types. This function implements the common transforms for all those
6755/// cases.
6756/// @brief Implement the transforms common to CastInst with integer operands
6757Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6758 if (Instruction *Result = commonCastTransforms(CI))
6759 return Result;
6760
6761 Value *Src = CI.getOperand(0);
6762 const Type *SrcTy = Src->getType();
6763 const Type *DestTy = CI.getType();
6764 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6765 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
6766
6767 // See if we can simplify any instructions used by the LHS whose sole
6768 // purpose is to compute bits we don't care about.
6769 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6770 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
6771 KnownZero, KnownOne))
6772 return &CI;
6773
6774 // If the source isn't an instruction or has more than one use then we
6775 // can't do anything more.
6776 Instruction *SrcI = dyn_cast<Instruction>(Src);
6777 if (!SrcI || !Src->hasOneUse())
6778 return 0;
6779
6780 // Attempt to propagate the cast into the instruction for int->int casts.
6781 int NumCastsRemoved = 0;
6782 if (!isa<BitCastInst>(CI) &&
6783 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattneref70bb82007-08-02 06:11:14 +00006784 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006785 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00006786 // eliminates the cast, so it is always a win. If this is a zero-extension,
6787 // we need to do an AND to maintain the clear top-part of the computation,
6788 // so we require that the input have eliminated at least one cast. If this
6789 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006790 // require that two casts have been eliminated.
6791 bool DoXForm;
6792 switch (CI.getOpcode()) {
6793 default:
6794 // All the others use floating point so we shouldn't actually
6795 // get here because of the check above.
6796 assert(0 && "Unknown cast type");
6797 case Instruction::Trunc:
6798 DoXForm = true;
6799 break;
6800 case Instruction::ZExt:
6801 DoXForm = NumCastsRemoved >= 1;
6802 break;
6803 case Instruction::SExt:
6804 DoXForm = NumCastsRemoved >= 2;
6805 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006806 }
6807
6808 if (DoXForm) {
6809 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6810 CI.getOpcode() == Instruction::SExt);
6811 assert(Res->getType() == DestTy);
6812 switch (CI.getOpcode()) {
6813 default: assert(0 && "Unknown cast type!");
6814 case Instruction::Trunc:
6815 case Instruction::BitCast:
6816 // Just replace this cast with the result.
6817 return ReplaceInstUsesWith(CI, Res);
6818 case Instruction::ZExt: {
6819 // We need to emit an AND to clear the high bits.
6820 assert(SrcBitSize < DestBitSize && "Not a zext?");
6821 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
6822 SrcBitSize));
6823 return BinaryOperator::createAnd(Res, C);
6824 }
6825 case Instruction::SExt:
6826 // We need to emit a cast to truncate, then a cast to sext.
6827 return CastInst::create(Instruction::SExt,
6828 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6829 CI), DestTy);
6830 }
6831 }
6832 }
6833
6834 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6835 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6836
6837 switch (SrcI->getOpcode()) {
6838 case Instruction::Add:
6839 case Instruction::Mul:
6840 case Instruction::And:
6841 case Instruction::Or:
6842 case Instruction::Xor:
6843 // If we are discarding information, rewrite.
6844 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6845 // Don't insert two casts if they cannot be eliminated. We allow
6846 // two casts to be inserted if the sizes are the same. This could
6847 // only be converting signedness, which is a noop.
6848 if (DestBitSize == SrcBitSize ||
6849 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6850 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6851 Instruction::CastOps opcode = CI.getOpcode();
6852 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6853 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6854 return BinaryOperator::create(
6855 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6856 }
6857 }
6858
6859 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6860 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6861 SrcI->getOpcode() == Instruction::Xor &&
6862 Op1 == ConstantInt::getTrue() &&
6863 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
6864 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
6865 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6866 }
6867 break;
6868 case Instruction::SDiv:
6869 case Instruction::UDiv:
6870 case Instruction::SRem:
6871 case Instruction::URem:
6872 // If we are just changing the sign, rewrite.
6873 if (DestBitSize == SrcBitSize) {
6874 // Don't insert two casts if they cannot be eliminated. We allow
6875 // two casts to be inserted if the sizes are the same. This could
6876 // only be converting signedness, which is a noop.
6877 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6878 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6879 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6880 Op0, DestTy, SrcI);
6881 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6882 Op1, DestTy, SrcI);
6883 return BinaryOperator::create(
6884 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6885 }
6886 }
6887 break;
6888
6889 case Instruction::Shl:
6890 // Allow changing the sign of the source operand. Do not allow
6891 // changing the size of the shift, UNLESS the shift amount is a
6892 // constant. We must not change variable sized shifts to a smaller
6893 // size, because it is undefined to shift more bits out than exist
6894 // in the value.
6895 if (DestBitSize == SrcBitSize ||
6896 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
6897 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6898 Instruction::BitCast : Instruction::Trunc);
6899 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6900 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6901 return BinaryOperator::createShl(Op0c, Op1c);
6902 }
6903 break;
6904 case Instruction::AShr:
6905 // If this is a signed shr, and if all bits shifted in are about to be
6906 // truncated off, turn it into an unsigned shr to allow greater
6907 // simplifications.
6908 if (DestBitSize < SrcBitSize &&
6909 isa<ConstantInt>(Op1)) {
6910 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
6911 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6912 // Insert the new logical shift right.
6913 return BinaryOperator::createLShr(Op0, Op1);
6914 }
6915 }
6916 break;
6917 }
6918 return 0;
6919}
6920
6921Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
6922 if (Instruction *Result = commonIntCastTransforms(CI))
6923 return Result;
6924
6925 Value *Src = CI.getOperand(0);
6926 const Type *Ty = CI.getType();
6927 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
6928 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
6929
6930 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6931 switch (SrcI->getOpcode()) {
6932 default: break;
6933 case Instruction::LShr:
6934 // We can shrink lshr to something smaller if we know the bits shifted in
6935 // are already zeros.
6936 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6937 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
6938
6939 // Get a mask for the bits shifting in.
6940 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
6941 Value* SrcIOp0 = SrcI->getOperand(0);
6942 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
6943 if (ShAmt >= DestBitWidth) // All zeros.
6944 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6945
6946 // Okay, we can shrink this. Truncate the input, then return a new
6947 // shift.
6948 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6949 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
6950 Ty, CI);
6951 return BinaryOperator::createLShr(V1, V2);
6952 }
6953 } else { // This is a variable shr.
6954
6955 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6956 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6957 // loop-invariant and CSE'd.
6958 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
6959 Value *One = ConstantInt::get(SrcI->getType(), 1);
6960
6961 Value *V = InsertNewInstBefore(
6962 BinaryOperator::createShl(One, SrcI->getOperand(1),
6963 "tmp"), CI);
6964 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6965 SrcI->getOperand(0),
6966 "tmp"), CI);
6967 Value *Zero = Constant::getNullValue(V->getType());
6968 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
6969 }
6970 }
6971 break;
6972 }
6973 }
6974
6975 return 0;
6976}
6977
6978Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
6979 // If one of the common conversion will work ..
6980 if (Instruction *Result = commonIntCastTransforms(CI))
6981 return Result;
6982
6983 Value *Src = CI.getOperand(0);
6984
6985 // If this is a cast of a cast
6986 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
6987 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6988 // types and if the sizes are just right we can convert this into a logical
6989 // 'and' which will be much cheaper than the pair of casts.
6990 if (isa<TruncInst>(CSrc)) {
6991 // Get the sizes of the types involved
6992 Value *A = CSrc->getOperand(0);
6993 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
6994 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6995 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
6996 // If we're actually extending zero bits and the trunc is a no-op
6997 if (MidSize < DstSize && SrcSize == DstSize) {
6998 // Replace both of the casts with an And of the type mask.
6999 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
7000 Constant *AndConst = ConstantInt::get(AndValue);
7001 Instruction *And =
7002 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
7003 // Unfortunately, if the type changed, we need to cast it back.
7004 if (And->getType() != CI.getType()) {
7005 And->setName(CSrc->getName()+".mask");
7006 InsertNewInstBefore(And, CI);
7007 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
7008 }
7009 return And;
7010 }
7011 }
7012 }
7013
7014 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7015 // If we are just checking for a icmp eq of a single bit and zext'ing it
7016 // to an integer, then shift the bit to the appropriate place and then
7017 // cast to integer to avoid the comparison.
7018 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7019 const APInt &Op1CV = Op1C->getValue();
7020
7021 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7022 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7023 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7024 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7025 Value *In = ICI->getOperand(0);
7026 Value *Sh = ConstantInt::get(In->getType(),
7027 In->getType()->getPrimitiveSizeInBits()-1);
7028 In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
7029 In->getName()+".lobit"),
7030 CI);
7031 if (In->getType() != CI.getType())
7032 In = CastInst::createIntegerCast(In, CI.getType(),
7033 false/*ZExt*/, "tmp", &CI);
7034
7035 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7036 Constant *One = ConstantInt::get(In->getType(), 1);
7037 In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
7038 In->getName()+".not"),
7039 CI);
7040 }
7041
7042 return ReplaceInstUsesWith(CI, In);
7043 }
7044
7045
7046
7047 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7048 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7049 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7050 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7051 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7052 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7053 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7054 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7055 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7056 // This only works for EQ and NE
7057 ICI->isEquality()) {
7058 // If Op1C some other power of two, convert:
7059 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7060 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7061 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7062 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7063
7064 APInt KnownZeroMask(~KnownZero);
7065 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7066 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7067 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7068 // (X&4) == 2 --> false
7069 // (X&4) != 2 --> true
7070 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7071 Res = ConstantExpr::getZExt(Res, CI.getType());
7072 return ReplaceInstUsesWith(CI, Res);
7073 }
7074
7075 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7076 Value *In = ICI->getOperand(0);
7077 if (ShiftAmt) {
7078 // Perform a logical shr by shiftamt.
7079 // Insert the shift to put the result in the low bit.
7080 In = InsertNewInstBefore(
7081 BinaryOperator::createLShr(In,
7082 ConstantInt::get(In->getType(), ShiftAmt),
7083 In->getName()+".lobit"), CI);
7084 }
7085
7086 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7087 Constant *One = ConstantInt::get(In->getType(), 1);
7088 In = BinaryOperator::createXor(In, One, "tmp");
7089 InsertNewInstBefore(cast<Instruction>(In), CI);
7090 }
7091
7092 if (CI.getType() == In->getType())
7093 return ReplaceInstUsesWith(CI, In);
7094 else
7095 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
7096 }
7097 }
7098 }
7099 }
7100 return 0;
7101}
7102
7103Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7104 if (Instruction *I = commonIntCastTransforms(CI))
7105 return I;
7106
7107 Value *Src = CI.getOperand(0);
7108
7109 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7110 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7111 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7112 // If we are just checking for a icmp eq of a single bit and zext'ing it
7113 // to an integer, then shift the bit to the appropriate place and then
7114 // cast to integer to avoid the comparison.
7115 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7116 const APInt &Op1CV = Op1C->getValue();
7117
7118 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7119 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7120 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7121 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7122 Value *In = ICI->getOperand(0);
7123 Value *Sh = ConstantInt::get(In->getType(),
7124 In->getType()->getPrimitiveSizeInBits()-1);
7125 In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
7126 In->getName()+".lobit"),
7127 CI);
7128 if (In->getType() != CI.getType())
7129 In = CastInst::createIntegerCast(In, CI.getType(),
7130 true/*SExt*/, "tmp", &CI);
7131
7132 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7133 In = InsertNewInstBefore(BinaryOperator::createNot(In,
7134 In->getName()+".not"), CI);
7135
7136 return ReplaceInstUsesWith(CI, In);
7137 }
7138 }
7139 }
7140
7141 return 0;
7142}
7143
7144Instruction *InstCombiner::visitFPTrunc(CastInst &CI) {
7145 return commonCastTransforms(CI);
7146}
7147
7148Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7149 return commonCastTransforms(CI);
7150}
7151
7152Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
7153 return commonCastTransforms(CI);
7154}
7155
7156Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
7157 return commonCastTransforms(CI);
7158}
7159
7160Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7161 return commonCastTransforms(CI);
7162}
7163
7164Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7165 return commonCastTransforms(CI);
7166}
7167
7168Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7169 return commonPointerCastTransforms(CI);
7170}
7171
Chris Lattner7c1626482008-01-08 07:23:51 +00007172Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7173 if (Instruction *I = commonCastTransforms(CI))
7174 return I;
7175
7176 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7177 if (!DestPointee->isSized()) return 0;
7178
7179 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7180 ConstantInt *Cst;
7181 Value *X;
7182 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7183 m_ConstantInt(Cst)))) {
7184 // If the source and destination operands have the same type, see if this
7185 // is a single-index GEP.
7186 if (X->getType() == CI.getType()) {
7187 // Get the size of the pointee type.
7188 uint64_t Size = TD->getABITypeSizeInBits(DestPointee);
7189
7190 // Convert the constant to intptr type.
7191 APInt Offset = Cst->getValue();
7192 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7193
7194 // If Offset is evenly divisible by Size, we can do this xform.
7195 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7196 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7197 return new GetElementPtrInst(X, ConstantInt::get(Offset));
7198 }
7199 }
7200 // TODO: Could handle other cases, e.g. where add is indexing into field of
7201 // struct etc.
7202 } else if (CI.getOperand(0)->hasOneUse() &&
7203 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7204 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7205 // "inttoptr+GEP" instead of "add+intptr".
7206
7207 // Get the size of the pointee type.
7208 uint64_t Size = TD->getABITypeSize(DestPointee);
7209
7210 // Convert the constant to intptr type.
7211 APInt Offset = Cst->getValue();
7212 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7213
7214 // If Offset is evenly divisible by Size, we can do this xform.
7215 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7216 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7217
7218 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7219 "tmp"), CI);
7220 return new GetElementPtrInst(P, ConstantInt::get(Offset), "tmp");
7221 }
7222 }
7223 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007224}
7225
7226Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
7227 // If the operands are integer typed then apply the integer transforms,
7228 // otherwise just apply the common ones.
7229 Value *Src = CI.getOperand(0);
7230 const Type *SrcTy = Src->getType();
7231 const Type *DestTy = CI.getType();
7232
7233 if (SrcTy->isInteger() && DestTy->isInteger()) {
7234 if (Instruction *Result = commonIntCastTransforms(CI))
7235 return Result;
7236 } else if (isa<PointerType>(SrcTy)) {
7237 if (Instruction *I = commonPointerCastTransforms(CI))
7238 return I;
7239 } else {
7240 if (Instruction *Result = commonCastTransforms(CI))
7241 return Result;
7242 }
7243
7244
7245 // Get rid of casts from one type to the same type. These are useless and can
7246 // be replaced by the operand.
7247 if (DestTy == Src->getType())
7248 return ReplaceInstUsesWith(CI, Src);
7249
7250 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7251 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7252 const Type *DstElTy = DstPTy->getElementType();
7253 const Type *SrcElTy = SrcPTy->getElementType();
7254
7255 // If we are casting a malloc or alloca to a pointer to a type of the same
7256 // size, rewrite the allocation instruction to allocate the "right" type.
7257 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7258 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7259 return V;
7260
7261 // If the source and destination are pointers, and this cast is equivalent
7262 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
7263 // This can enhance SROA and other transforms that want type-safe pointers.
7264 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7265 unsigned NumZeros = 0;
7266 while (SrcElTy != DstElTy &&
7267 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7268 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7269 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7270 ++NumZeros;
7271 }
7272
7273 // If we found a path from the src to dest, create the getelementptr now.
7274 if (SrcElTy == DstElTy) {
7275 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Chuck Rose III27d49792007-09-05 20:36:41 +00007276 return new GetElementPtrInst(Src, Idxs.begin(), Idxs.end(), "",
7277 ((Instruction*) NULL));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007278 }
7279 }
7280
7281 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7282 if (SVI->hasOneUse()) {
7283 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7284 // a bitconvert to a vector with the same # elts.
7285 if (isa<VectorType>(DestTy) &&
7286 cast<VectorType>(DestTy)->getNumElements() ==
7287 SVI->getType()->getNumElements()) {
7288 CastInst *Tmp;
7289 // If either of the operands is a cast from CI.getType(), then
7290 // evaluating the shuffle in the casted destination's type will allow
7291 // us to eliminate at least one cast.
7292 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7293 Tmp->getOperand(0)->getType() == DestTy) ||
7294 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7295 Tmp->getOperand(0)->getType() == DestTy)) {
7296 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7297 SVI->getOperand(0), DestTy, &CI);
7298 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7299 SVI->getOperand(1), DestTy, &CI);
7300 // Return a new shuffle vector. Use the same element ID's, as we
7301 // know the vector types match #elts.
7302 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
7303 }
7304 }
7305 }
7306 }
7307 return 0;
7308}
7309
7310/// GetSelectFoldableOperands - We want to turn code that looks like this:
7311/// %C = or %A, %B
7312/// %D = select %cond, %C, %A
7313/// into:
7314/// %C = select %cond, %B, 0
7315/// %D = or %A, %C
7316///
7317/// Assuming that the specified instruction is an operand to the select, return
7318/// a bitmask indicating which operands of this instruction are foldable if they
7319/// equal the other incoming value of the select.
7320///
7321static unsigned GetSelectFoldableOperands(Instruction *I) {
7322 switch (I->getOpcode()) {
7323 case Instruction::Add:
7324 case Instruction::Mul:
7325 case Instruction::And:
7326 case Instruction::Or:
7327 case Instruction::Xor:
7328 return 3; // Can fold through either operand.
7329 case Instruction::Sub: // Can only fold on the amount subtracted.
7330 case Instruction::Shl: // Can only fold on the shift amount.
7331 case Instruction::LShr:
7332 case Instruction::AShr:
7333 return 1;
7334 default:
7335 return 0; // Cannot fold
7336 }
7337}
7338
7339/// GetSelectFoldableConstant - For the same transformation as the previous
7340/// function, return the identity constant that goes into the select.
7341static Constant *GetSelectFoldableConstant(Instruction *I) {
7342 switch (I->getOpcode()) {
7343 default: assert(0 && "This cannot happen!"); abort();
7344 case Instruction::Add:
7345 case Instruction::Sub:
7346 case Instruction::Or:
7347 case Instruction::Xor:
7348 case Instruction::Shl:
7349 case Instruction::LShr:
7350 case Instruction::AShr:
7351 return Constant::getNullValue(I->getType());
7352 case Instruction::And:
7353 return Constant::getAllOnesValue(I->getType());
7354 case Instruction::Mul:
7355 return ConstantInt::get(I->getType(), 1);
7356 }
7357}
7358
7359/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7360/// have the same opcode and only one use each. Try to simplify this.
7361Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7362 Instruction *FI) {
7363 if (TI->getNumOperands() == 1) {
7364 // If this is a non-volatile load or a cast from the same type,
7365 // merge.
7366 if (TI->isCast()) {
7367 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7368 return 0;
7369 } else {
7370 return 0; // unknown unary op.
7371 }
7372
7373 // Fold this by inserting a select from the input values.
7374 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7375 FI->getOperand(0), SI.getName()+".v");
7376 InsertNewInstBefore(NewSI, SI);
7377 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
7378 TI->getType());
7379 }
7380
7381 // Only handle binary operators here.
7382 if (!isa<BinaryOperator>(TI))
7383 return 0;
7384
7385 // Figure out if the operations have any operands in common.
7386 Value *MatchOp, *OtherOpT, *OtherOpF;
7387 bool MatchIsOpZero;
7388 if (TI->getOperand(0) == FI->getOperand(0)) {
7389 MatchOp = TI->getOperand(0);
7390 OtherOpT = TI->getOperand(1);
7391 OtherOpF = FI->getOperand(1);
7392 MatchIsOpZero = true;
7393 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7394 MatchOp = TI->getOperand(1);
7395 OtherOpT = TI->getOperand(0);
7396 OtherOpF = FI->getOperand(0);
7397 MatchIsOpZero = false;
7398 } else if (!TI->isCommutative()) {
7399 return 0;
7400 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7401 MatchOp = TI->getOperand(0);
7402 OtherOpT = TI->getOperand(1);
7403 OtherOpF = FI->getOperand(0);
7404 MatchIsOpZero = true;
7405 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7406 MatchOp = TI->getOperand(1);
7407 OtherOpT = TI->getOperand(0);
7408 OtherOpF = FI->getOperand(1);
7409 MatchIsOpZero = true;
7410 } else {
7411 return 0;
7412 }
7413
7414 // If we reach here, they do have operations in common.
7415 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7416 OtherOpF, SI.getName()+".v");
7417 InsertNewInstBefore(NewSI, SI);
7418
7419 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7420 if (MatchIsOpZero)
7421 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7422 else
7423 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
7424 }
7425 assert(0 && "Shouldn't get here");
7426 return 0;
7427}
7428
7429Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
7430 Value *CondVal = SI.getCondition();
7431 Value *TrueVal = SI.getTrueValue();
7432 Value *FalseVal = SI.getFalseValue();
7433
7434 // select true, X, Y -> X
7435 // select false, X, Y -> Y
7436 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
7437 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
7438
7439 // select C, X, X -> X
7440 if (TrueVal == FalseVal)
7441 return ReplaceInstUsesWith(SI, TrueVal);
7442
7443 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7444 return ReplaceInstUsesWith(SI, FalseVal);
7445 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7446 return ReplaceInstUsesWith(SI, TrueVal);
7447 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7448 if (isa<Constant>(TrueVal))
7449 return ReplaceInstUsesWith(SI, TrueVal);
7450 else
7451 return ReplaceInstUsesWith(SI, FalseVal);
7452 }
7453
7454 if (SI.getType() == Type::Int1Ty) {
7455 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
7456 if (C->getZExtValue()) {
7457 // Change: A = select B, true, C --> A = or B, C
7458 return BinaryOperator::createOr(CondVal, FalseVal);
7459 } else {
7460 // Change: A = select B, false, C --> A = and !B, C
7461 Value *NotCond =
7462 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7463 "not."+CondVal->getName()), SI);
7464 return BinaryOperator::createAnd(NotCond, FalseVal);
7465 }
7466 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
7467 if (C->getZExtValue() == false) {
7468 // Change: A = select B, C, false --> A = and B, C
7469 return BinaryOperator::createAnd(CondVal, TrueVal);
7470 } else {
7471 // Change: A = select B, C, true --> A = or !B, C
7472 Value *NotCond =
7473 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7474 "not."+CondVal->getName()), SI);
7475 return BinaryOperator::createOr(NotCond, TrueVal);
7476 }
7477 }
Chris Lattner53f85a72007-11-25 21:27:53 +00007478
7479 // select a, b, a -> a&b
7480 // select a, a, b -> a|b
7481 if (CondVal == TrueVal)
7482 return BinaryOperator::createOr(CondVal, FalseVal);
7483 else if (CondVal == FalseVal)
7484 return BinaryOperator::createAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007485 }
7486
7487 // Selecting between two integer constants?
7488 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7489 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
7490 // select C, 1, 0 -> zext C to int
7491 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
7492 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
7493 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
7494 // select C, 0, 1 -> zext !C to int
7495 Value *NotCond =
7496 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7497 "not."+CondVal->getName()), SI);
7498 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
7499 }
7500
7501 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
7502
7503 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
7504
7505 // (x <s 0) ? -1 : 0 -> ashr x, 31
7506 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
7507 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
7508 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
7509 // The comparison constant and the result are not neccessarily the
7510 // same width. Make an all-ones value by inserting a AShr.
7511 Value *X = IC->getOperand(0);
7512 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
7513 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7514 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7515 ShAmt, "ones");
7516 InsertNewInstBefore(SRA, SI);
7517
7518 // Finally, convert to the type of the select RHS. We figure out
7519 // if this requires a SExt, Trunc or BitCast based on the sizes.
7520 Instruction::CastOps opc = Instruction::BitCast;
7521 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
7522 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
7523 if (SRASize < SISize)
7524 opc = Instruction::SExt;
7525 else if (SRASize > SISize)
7526 opc = Instruction::Trunc;
7527 return CastInst::create(opc, SRA, SI.getType());
7528 }
7529 }
7530
7531
7532 // If one of the constants is zero (we know they can't both be) and we
7533 // have an icmp instruction with zero, and we have an 'and' with the
7534 // non-constant value, eliminate this whole mess. This corresponds to
7535 // cases like this: ((X & 27) ? 27 : 0)
7536 if (TrueValC->isZero() || FalseValC->isZero())
7537 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
7538 cast<Constant>(IC->getOperand(1))->isNullValue())
7539 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7540 if (ICA->getOpcode() == Instruction::And &&
7541 isa<ConstantInt>(ICA->getOperand(1)) &&
7542 (ICA->getOperand(1) == TrueValC ||
7543 ICA->getOperand(1) == FalseValC) &&
7544 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7545 // Okay, now we know that everything is set up, we just don't
7546 // know whether we have a icmp_ne or icmp_eq and whether the
7547 // true or false val is the zero.
7548 bool ShouldNotVal = !TrueValC->isZero();
7549 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
7550 Value *V = ICA;
7551 if (ShouldNotVal)
7552 V = InsertNewInstBefore(BinaryOperator::create(
7553 Instruction::Xor, V, ICA->getOperand(1)), SI);
7554 return ReplaceInstUsesWith(SI, V);
7555 }
7556 }
7557 }
7558
7559 // See if we are selecting two values based on a comparison of the two values.
7560 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7561 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
7562 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen2e1b7692007-10-03 17:45:27 +00007563 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7564 // This is not safe in general for floating point:
7565 // consider X== -0, Y== +0.
7566 // It becomes safe if either operand is a nonzero constant.
7567 ConstantFP *CFPt, *CFPf;
7568 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7569 !CFPt->getValueAPF().isZero()) ||
7570 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7571 !CFPf->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007572 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen2e1b7692007-10-03 17:45:27 +00007573 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007574 // Transform (X != Y) ? X : Y -> X
7575 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7576 return ReplaceInstUsesWith(SI, TrueVal);
7577 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7578
7579 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
7580 // Transform (X == Y) ? Y : X -> X
Dale Johannesen2e1b7692007-10-03 17:45:27 +00007581 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7582 // This is not safe in general for floating point:
7583 // consider X== -0, Y== +0.
7584 // It becomes safe if either operand is a nonzero constant.
7585 ConstantFP *CFPt, *CFPf;
7586 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7587 !CFPt->getValueAPF().isZero()) ||
7588 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7589 !CFPf->getValueAPF().isZero()))
7590 return ReplaceInstUsesWith(SI, FalseVal);
7591 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007592 // Transform (X != Y) ? Y : X -> Y
7593 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7594 return ReplaceInstUsesWith(SI, TrueVal);
7595 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7596 }
7597 }
7598
7599 // See if we are selecting two values based on a comparison of the two values.
7600 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7601 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7602 // Transform (X == Y) ? X : Y -> Y
7603 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7604 return ReplaceInstUsesWith(SI, FalseVal);
7605 // Transform (X != Y) ? X : Y -> X
7606 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7607 return ReplaceInstUsesWith(SI, TrueVal);
7608 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7609
7610 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7611 // Transform (X == Y) ? Y : X -> X
7612 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7613 return ReplaceInstUsesWith(SI, FalseVal);
7614 // Transform (X != Y) ? Y : X -> Y
7615 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7616 return ReplaceInstUsesWith(SI, TrueVal);
7617 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7618 }
7619 }
7620
7621 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7622 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7623 if (TI->hasOneUse() && FI->hasOneUse()) {
7624 Instruction *AddOp = 0, *SubOp = 0;
7625
7626 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7627 if (TI->getOpcode() == FI->getOpcode())
7628 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7629 return IV;
7630
7631 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
7632 // even legal for FP.
7633 if (TI->getOpcode() == Instruction::Sub &&
7634 FI->getOpcode() == Instruction::Add) {
7635 AddOp = FI; SubOp = TI;
7636 } else if (FI->getOpcode() == Instruction::Sub &&
7637 TI->getOpcode() == Instruction::Add) {
7638 AddOp = TI; SubOp = FI;
7639 }
7640
7641 if (AddOp) {
7642 Value *OtherAddOp = 0;
7643 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7644 OtherAddOp = AddOp->getOperand(1);
7645 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7646 OtherAddOp = AddOp->getOperand(0);
7647 }
7648
7649 if (OtherAddOp) {
7650 // So at this point we know we have (Y -> OtherAddOp):
7651 // select C, (add X, Y), (sub X, Z)
7652 Value *NegVal; // Compute -Z
7653 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7654 NegVal = ConstantExpr::getNeg(C);
7655 } else {
7656 NegVal = InsertNewInstBefore(
7657 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
7658 }
7659
7660 Value *NewTrueOp = OtherAddOp;
7661 Value *NewFalseOp = NegVal;
7662 if (AddOp != TI)
7663 std::swap(NewTrueOp, NewFalseOp);
7664 Instruction *NewSel =
7665 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7666
7667 NewSel = InsertNewInstBefore(NewSel, SI);
7668 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
7669 }
7670 }
7671 }
7672
7673 // See if we can fold the select into one of our operands.
7674 if (SI.getType()->isInteger()) {
7675 // See the comment above GetSelectFoldableOperands for a description of the
7676 // transformation we are doing here.
7677 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7678 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7679 !isa<Constant>(FalseVal))
7680 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7681 unsigned OpToFold = 0;
7682 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7683 OpToFold = 1;
7684 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7685 OpToFold = 2;
7686 }
7687
7688 if (OpToFold) {
7689 Constant *C = GetSelectFoldableConstant(TVI);
7690 Instruction *NewSel =
7691 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
7692 InsertNewInstBefore(NewSel, SI);
7693 NewSel->takeName(TVI);
7694 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7695 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
7696 else {
7697 assert(0 && "Unknown instruction!!");
7698 }
7699 }
7700 }
7701
7702 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7703 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7704 !isa<Constant>(TrueVal))
7705 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7706 unsigned OpToFold = 0;
7707 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7708 OpToFold = 1;
7709 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7710 OpToFold = 2;
7711 }
7712
7713 if (OpToFold) {
7714 Constant *C = GetSelectFoldableConstant(FVI);
7715 Instruction *NewSel =
7716 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
7717 InsertNewInstBefore(NewSel, SI);
7718 NewSel->takeName(FVI);
7719 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7720 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
7721 else
7722 assert(0 && "Unknown instruction!!");
7723 }
7724 }
7725 }
7726
7727 if (BinaryOperator::isNot(CondVal)) {
7728 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7729 SI.setOperand(1, FalseVal);
7730 SI.setOperand(2, TrueVal);
7731 return &SI;
7732 }
7733
7734 return 0;
7735}
7736
Chris Lattner47cf3452007-08-09 19:05:49 +00007737/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
7738/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
7739/// and it is more than the alignment of the ultimate object, see if we can
7740/// increase the alignment of the ultimate object, making this check succeed.
7741static unsigned GetOrEnforceKnownAlignment(Value *V, TargetData *TD,
7742 unsigned PrefAlign = 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007743 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7744 unsigned Align = GV->getAlignment();
Andrew Lenharthdae02012007-11-08 18:45:15 +00007745 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007746 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattner47cf3452007-08-09 19:05:49 +00007747
7748 // If there is a large requested alignment and we can, bump up the alignment
7749 // of the global.
7750 if (PrefAlign > Align && GV->hasInitializer()) {
7751 GV->setAlignment(PrefAlign);
7752 Align = PrefAlign;
7753 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007754 return Align;
7755 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7756 unsigned Align = AI->getAlignment();
7757 if (Align == 0 && TD) {
7758 if (isa<AllocaInst>(AI))
7759 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
7760 else if (isa<MallocInst>(AI)) {
7761 // Malloc returns maximally aligned memory.
7762 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
7763 Align =
7764 std::max(Align,
7765 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
7766 Align =
7767 std::max(Align,
7768 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
7769 }
7770 }
Chris Lattner47cf3452007-08-09 19:05:49 +00007771
7772 // If there is a requested alignment and if this is an alloca, round up. We
7773 // don't do this for malloc, because some systems can't respect the request.
7774 if (PrefAlign > Align && isa<AllocaInst>(AI)) {
7775 AI->setAlignment(PrefAlign);
7776 Align = PrefAlign;
7777 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007778 return Align;
7779 } else if (isa<BitCastInst>(V) ||
7780 (isa<ConstantExpr>(V) &&
7781 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner47cf3452007-08-09 19:05:49 +00007782 return GetOrEnforceKnownAlignment(cast<User>(V)->getOperand(0),
7783 TD, PrefAlign);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007784 } else if (User *GEPI = dyn_castGetElementPtr(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007785 // If all indexes are zero, it is just the alignment of the base pointer.
7786 bool AllZeroOperands = true;
7787 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7788 if (!isa<Constant>(GEPI->getOperand(i)) ||
7789 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7790 AllZeroOperands = false;
7791 break;
7792 }
Chris Lattner47cf3452007-08-09 19:05:49 +00007793
7794 if (AllZeroOperands) {
7795 // Treat this like a bitcast.
7796 return GetOrEnforceKnownAlignment(GEPI->getOperand(0), TD, PrefAlign);
7797 }
7798
7799 unsigned BaseAlignment = GetOrEnforceKnownAlignment(GEPI->getOperand(0),TD);
7800 if (BaseAlignment == 0) return 0;
7801
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007802 // Otherwise, if the base alignment is >= the alignment we expect for the
7803 // base pointer type, then we know that the resultant pointer is aligned at
7804 // least as much as its type requires.
7805 if (!TD) return 0;
7806
7807 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
7808 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Lauro Ramos Venancio55da3352007-07-31 20:13:21 +00007809 unsigned Align = TD->getABITypeAlignment(PtrTy->getElementType());
7810 if (Align <= BaseAlignment) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007811 const Type *GEPTy = GEPI->getType();
7812 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Lauro Ramos Venancio55da3352007-07-31 20:13:21 +00007813 Align = std::min(Align, (unsigned)
7814 TD->getABITypeAlignment(GEPPtrTy->getElementType()));
7815 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007816 }
7817 return 0;
7818 }
7819 return 0;
7820}
7821
Chris Lattner00ae5132008-01-13 23:50:23 +00007822Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
7823 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1), TD);
7824 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2), TD);
7825 unsigned MinAlign = std::min(DstAlign, SrcAlign);
7826 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
7827
7828 if (CopyAlign < MinAlign) {
7829 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
7830 return MI;
7831 }
7832
7833 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
7834 // load/store.
7835 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
7836 if (MemOpLength == 0) return 0;
7837
Chris Lattnerc669fb62008-01-14 00:28:35 +00007838 // Source and destination pointer types are always "i8*" for intrinsic. See
7839 // if the size is something we can handle with a single primitive load/store.
7840 // A single load+store correctly handles overlapping memory in the memmove
7841 // case.
Chris Lattner00ae5132008-01-13 23:50:23 +00007842 unsigned Size = MemOpLength->getZExtValue();
7843 if (Size == 0 || Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +00007844 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +00007845
Chris Lattnerc669fb62008-01-14 00:28:35 +00007846 // Use an integer load+store unless we can find something better.
Chris Lattner00ae5132008-01-13 23:50:23 +00007847 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattnerc669fb62008-01-14 00:28:35 +00007848
7849 // Memcpy forces the use of i8* for the source and destination. That means
7850 // that if you're using memcpy to move one double around, you'll get a cast
7851 // from double* to i8*. We'd much rather use a double load+store rather than
7852 // an i64 load+store, here because this improves the odds that the source or
7853 // dest address will be promotable. See if we can find a better type than the
7854 // integer datatype.
7855 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
7856 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
7857 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
7858 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
7859 // down through these levels if so.
7860 while (!SrcETy->isFirstClassType()) {
7861 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
7862 if (STy->getNumElements() == 1)
7863 SrcETy = STy->getElementType(0);
7864 else
7865 break;
7866 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
7867 if (ATy->getNumElements() == 1)
7868 SrcETy = ATy->getElementType();
7869 else
7870 break;
7871 } else
7872 break;
7873 }
7874
7875 if (SrcETy->isFirstClassType())
7876 NewPtrTy = PointerType::getUnqual(SrcETy);
7877 }
7878 }
7879
7880
Chris Lattner00ae5132008-01-13 23:50:23 +00007881 // If the memcpy/memmove provides better alignment info than we can
7882 // infer, use it.
7883 SrcAlign = std::max(SrcAlign, CopyAlign);
7884 DstAlign = std::max(DstAlign, CopyAlign);
7885
7886 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
7887 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattnerc669fb62008-01-14 00:28:35 +00007888 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
7889 InsertNewInstBefore(L, *MI);
7890 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
7891
7892 // Set the size of the copy to 0, it will be deleted on the next iteration.
7893 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
7894 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +00007895}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007896
7897/// visitCallInst - CallInst simplification. This mostly only handles folding
7898/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
7899/// the heavy lifting.
7900///
7901Instruction *InstCombiner::visitCallInst(CallInst &CI) {
7902 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7903 if (!II) return visitCallSite(&CI);
7904
7905 // Intrinsics cannot occur in an invoke, so handle them here instead of in
7906 // visitCallSite.
7907 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
7908 bool Changed = false;
7909
7910 // memmove/cpy/set of zero bytes is a noop.
7911 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7912 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7913
7914 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
7915 if (CI->getZExtValue() == 1) {
7916 // Replace the instruction with just byte operations. We would
7917 // transform other cases to loads/stores, but we don't know if
7918 // alignment is sufficient.
7919 }
7920 }
7921
7922 // If we have a memmove and the source operation is a constant global,
7923 // then the source and dest pointers can't alias, so we can change this
7924 // into a call to memcpy.
Chris Lattner00ae5132008-01-13 23:50:23 +00007925 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007926 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
7927 if (GVSrc->isConstant()) {
7928 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner13c2d6e2008-01-13 22:23:22 +00007929 Intrinsic::ID MemCpyID;
7930 if (CI.getOperand(3)->getType() == Type::Int32Ty)
7931 MemCpyID = Intrinsic::memcpy_i32;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007932 else
Chris Lattner13c2d6e2008-01-13 22:23:22 +00007933 MemCpyID = Intrinsic::memcpy_i64;
7934 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007935 Changed = true;
7936 }
7937 }
7938
7939 // If we can determine a pointer alignment that is bigger than currently
7940 // set, update the alignment.
7941 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +00007942 if (Instruction *I = SimplifyMemTransfer(MI))
7943 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007944 } else if (isa<MemSetInst>(MI)) {
Chris Lattner47cf3452007-08-09 19:05:49 +00007945 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest(), TD);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007946 if (MI->getAlignment()->getZExtValue() < Alignment) {
7947 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
7948 Changed = true;
7949 }
7950 }
7951
7952 if (Changed) return II;
7953 } else {
7954 switch (II->getIntrinsicID()) {
7955 default: break;
7956 case Intrinsic::ppc_altivec_lvx:
7957 case Intrinsic::ppc_altivec_lvxl:
7958 case Intrinsic::x86_sse_loadu_ps:
7959 case Intrinsic::x86_sse2_loadu_pd:
7960 case Intrinsic::x86_sse2_loadu_dq:
7961 // Turn PPC lvx -> load if the pointer is known aligned.
7962 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattner47cf3452007-08-09 19:05:49 +00007963 if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
Chris Lattner13c2d6e2008-01-13 22:23:22 +00007964 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
7965 PointerType::getUnqual(II->getType()),
7966 CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007967 return new LoadInst(Ptr);
7968 }
7969 break;
7970 case Intrinsic::ppc_altivec_stvx:
7971 case Intrinsic::ppc_altivec_stvxl:
7972 // Turn stvx -> store if the pointer is known aligned.
Chris Lattner47cf3452007-08-09 19:05:49 +00007973 if (GetOrEnforceKnownAlignment(II->getOperand(2), TD, 16) >= 16) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00007974 const Type *OpPtrTy =
7975 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner13c2d6e2008-01-13 22:23:22 +00007976 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007977 return new StoreInst(II->getOperand(1), Ptr);
7978 }
7979 break;
7980 case Intrinsic::x86_sse_storeu_ps:
7981 case Intrinsic::x86_sse2_storeu_pd:
7982 case Intrinsic::x86_sse2_storeu_dq:
7983 case Intrinsic::x86_sse2_storel_dq:
7984 // Turn X86 storeu -> store if the pointer is known aligned.
Chris Lattner47cf3452007-08-09 19:05:49 +00007985 if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00007986 const Type *OpPtrTy =
7987 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner13c2d6e2008-01-13 22:23:22 +00007988 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007989 return new StoreInst(II->getOperand(2), Ptr);
7990 }
7991 break;
7992
7993 case Intrinsic::x86_sse_cvttss2si: {
7994 // These intrinsics only demands the 0th element of its input vector. If
7995 // we can simplify the input based on that, do so now.
7996 uint64_t UndefElts;
7997 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
7998 UndefElts)) {
7999 II->setOperand(1, V);
8000 return II;
8001 }
8002 break;
8003 }
8004
8005 case Intrinsic::ppc_altivec_vperm:
8006 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8007 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8008 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8009
8010 // Check that all of the elements are integer constants or undefs.
8011 bool AllEltsOk = true;
8012 for (unsigned i = 0; i != 16; ++i) {
8013 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8014 !isa<UndefValue>(Mask->getOperand(i))) {
8015 AllEltsOk = false;
8016 break;
8017 }
8018 }
8019
8020 if (AllEltsOk) {
8021 // Cast the input vectors to byte vectors.
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008022 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8023 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008024 Value *Result = UndefValue::get(Op0->getType());
8025
8026 // Only extract each element once.
8027 Value *ExtractedElts[32];
8028 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8029
8030 for (unsigned i = 0; i != 16; ++i) {
8031 if (isa<UndefValue>(Mask->getOperand(i)))
8032 continue;
8033 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8034 Idx &= 31; // Match the hardware behavior.
8035
8036 if (ExtractedElts[Idx] == 0) {
8037 Instruction *Elt =
8038 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8039 InsertNewInstBefore(Elt, CI);
8040 ExtractedElts[Idx] = Elt;
8041 }
8042
8043 // Insert this value into the result vector.
8044 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
8045 InsertNewInstBefore(cast<Instruction>(Result), CI);
8046 }
8047 return CastInst::create(Instruction::BitCast, Result, CI.getType());
8048 }
8049 }
8050 break;
8051
8052 case Intrinsic::stackrestore: {
8053 // If the save is right next to the restore, remove the restore. This can
8054 // happen when variable allocas are DCE'd.
8055 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8056 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8057 BasicBlock::iterator BI = SS;
8058 if (&*++BI == II)
8059 return EraseInstFromFunction(CI);
8060 }
8061 }
8062
8063 // If the stack restore is in a return/unwind block and if there are no
8064 // allocas or calls between the restore and the return, nuke the restore.
8065 TerminatorInst *TI = II->getParent()->getTerminator();
8066 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
8067 BasicBlock::iterator BI = II;
8068 bool CannotRemove = false;
8069 for (++BI; &*BI != TI; ++BI) {
8070 if (isa<AllocaInst>(BI) ||
8071 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
8072 CannotRemove = true;
8073 break;
8074 }
8075 }
8076 if (!CannotRemove)
8077 return EraseInstFromFunction(CI);
8078 }
8079 break;
8080 }
8081 }
8082 }
8083
8084 return visitCallSite(II);
8085}
8086
8087// InvokeInst simplification
8088//
8089Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8090 return visitCallSite(&II);
8091}
8092
8093// visitCallSite - Improvements for call and invoke instructions.
8094//
8095Instruction *InstCombiner::visitCallSite(CallSite CS) {
8096 bool Changed = false;
8097
8098 // If the callee is a constexpr cast of a function, attempt to move the cast
8099 // to the arguments of the call/invoke.
8100 if (transformConstExprCastCall(CS)) return 0;
8101
8102 Value *Callee = CS.getCalledValue();
8103
8104 if (Function *CalleeF = dyn_cast<Function>(Callee))
8105 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8106 Instruction *OldCall = CS.getInstruction();
8107 // If the call and callee calling conventions don't match, this call must
8108 // be unreachable, as the call is undefined.
8109 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00008110 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8111 OldCall);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008112 if (!OldCall->use_empty())
8113 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8114 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8115 return EraseInstFromFunction(*OldCall);
8116 return 0;
8117 }
8118
8119 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8120 // This instruction is not reachable, just remove it. We insert a store to
8121 // undef so that we know that this code is not reachable, despite the fact
8122 // that we can't modify the CFG here.
8123 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00008124 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008125 CS.getInstruction());
8126
8127 if (!CS.getInstruction()->use_empty())
8128 CS.getInstruction()->
8129 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8130
8131 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8132 // Don't break the CFG, insert a dummy cond branch.
8133 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
8134 ConstantInt::getTrue(), II);
8135 }
8136 return EraseInstFromFunction(*CS.getInstruction());
8137 }
8138
Duncan Sands74833f22007-09-17 10:26:40 +00008139 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8140 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8141 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8142 return transformCallThroughTrampoline(CS);
8143
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008144 const PointerType *PTy = cast<PointerType>(Callee->getType());
8145 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8146 if (FTy->isVarArg()) {
8147 // See if we can optimize any arguments passed through the varargs area of
8148 // the call.
8149 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8150 E = CS.arg_end(); I != E; ++I)
8151 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
8152 // If this cast does not effect the value passed through the varargs
8153 // area, we can eliminate the use of the cast.
8154 Value *Op = CI->getOperand(0);
8155 if (CI->isLosslessCast()) {
8156 *I = Op;
8157 Changed = true;
8158 }
8159 }
8160 }
8161
Duncan Sands2937e352007-12-19 21:13:37 +00008162 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +00008163 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +00008164 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +00008165 Changed = true;
8166 }
8167
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008168 return Changed ? CS.getInstruction() : 0;
8169}
8170
8171// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8172// attempt to move the cast to the arguments of the call/invoke.
8173//
8174bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8175 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8176 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
8177 if (CE->getOpcode() != Instruction::BitCast ||
8178 !isa<Function>(CE->getOperand(0)))
8179 return false;
8180 Function *Callee = cast<Function>(CE->getOperand(0));
8181 Instruction *Caller = CS.getInstruction();
Duncan Sandsc849e662008-01-06 18:27:01 +00008182 const ParamAttrsList* CallerPAL = CS.getParamAttrs();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008183
8184 // Okay, this is a cast from a function to a different type. Unless doing so
8185 // would cause a type conversion of one of our arguments, change this call to
8186 // be a direct call with arguments casted to the appropriate types.
8187 //
8188 const FunctionType *FT = Callee->getFunctionType();
8189 const Type *OldRetTy = Caller->getType();
8190
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008191 // Check to see if we are changing the return type...
8192 if (OldRetTy != FT->getReturnType()) {
8193 if (Callee->isDeclaration() && !Caller->use_empty() &&
8194 // Conversion is ok if changing from pointer to int of same size.
8195 !(isa<PointerType>(FT->getReturnType()) &&
8196 TD->getIntPtrType() == OldRetTy))
8197 return false; // Cannot transform this return value.
8198
Duncan Sands5c489582008-01-06 10:12:28 +00008199 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +00008200 // void -> non-void is handled specially
Duncan Sands4ced1f82008-01-13 08:02:44 +00008201 FT->getReturnType() != Type::VoidTy &&
8202 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +00008203 return false; // Cannot transform this return value.
8204
Duncan Sandsdbe97dc2008-01-07 17:16:06 +00008205 if (CallerPAL && !Caller->use_empty()) {
8206 uint16_t RAttrs = CallerPAL->getParamAttrs(0);
8207 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
8208 return false; // Attribute not compatible with transformed value.
8209 }
Duncan Sandsc849e662008-01-06 18:27:01 +00008210
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008211 // If the callsite is an invoke instruction, and the return value is used by
8212 // a PHI node in a successor, we cannot change the return type of the call
8213 // because there is no place to put the cast instruction (without breaking
8214 // the critical edge). Bail out in this case.
8215 if (!Caller->use_empty())
8216 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8217 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8218 UI != E; ++UI)
8219 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8220 if (PN->getParent() == II->getNormalDest() ||
8221 PN->getParent() == II->getUnwindDest())
8222 return false;
8223 }
8224
8225 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8226 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
8227
8228 CallSite::arg_iterator AI = CS.arg_begin();
8229 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8230 const Type *ParamTy = FT->getParamType(i);
8231 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +00008232
8233 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +00008234 return false; // Cannot transform this parameter value.
8235
Duncan Sandsdbe97dc2008-01-07 17:16:06 +00008236 if (CallerPAL) {
8237 uint16_t PAttrs = CallerPAL->getParamAttrs(i + 1);
8238 if (PAttrs & ParamAttr::typeIncompatible(ParamTy))
8239 return false; // Attribute not compatible with transformed value.
8240 }
Duncan Sands5c489582008-01-06 10:12:28 +00008241
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008242 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sands5c489582008-01-06 10:12:28 +00008243 // Some conversions are safe even if we do not have a body.
8244 // Either we can cast directly, or we can upconvert the argument
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008245 bool isConvertible = ActTy == ParamTy ||
8246 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
8247 (ParamTy->isInteger() && ActTy->isInteger() &&
8248 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8249 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
8250 && c->getValue().isStrictlyPositive());
8251 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008252 }
8253
8254 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
8255 Callee->isDeclaration())
8256 return false; // Do not delete arguments unless we have a function body...
8257
Duncan Sands4ced1f82008-01-13 08:02:44 +00008258 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() && CallerPAL)
Duncan Sandsc849e662008-01-06 18:27:01 +00008259 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +00008260 // won't be dropping them. Check that these extra arguments have attributes
8261 // that are compatible with being a vararg call argument.
8262 for (unsigned i = CallerPAL->size(); i; --i) {
8263 if (CallerPAL->getParamIndex(i - 1) <= FT->getNumParams())
8264 break;
8265 uint16_t PAttrs = CallerPAL->getParamAttrsAtIndex(i - 1);
8266 if (PAttrs & ParamAttr::VarArgsIncompatible)
8267 return false;
8268 }
Duncan Sandsc849e662008-01-06 18:27:01 +00008269
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008270 // Okay, we decided that this is a safe thing to do: go ahead and start
8271 // inserting cast instructions as necessary...
8272 std::vector<Value*> Args;
8273 Args.reserve(NumActualArgs);
Duncan Sandsc849e662008-01-06 18:27:01 +00008274 ParamAttrsVector attrVec;
8275 attrVec.reserve(NumCommonArgs);
8276
8277 // Get any return attributes.
8278 uint16_t RAttrs = CallerPAL ? CallerPAL->getParamAttrs(0) : 0;
8279
8280 // If the return value is not being used, the type may not be compatible
8281 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sandsdbe97dc2008-01-07 17:16:06 +00008282 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsc849e662008-01-06 18:27:01 +00008283
8284 // Add the new return attributes.
8285 if (RAttrs)
8286 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008287
8288 AI = CS.arg_begin();
8289 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8290 const Type *ParamTy = FT->getParamType(i);
8291 if ((*AI)->getType() == ParamTy) {
8292 Args.push_back(*AI);
8293 } else {
8294 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
8295 false, ParamTy, false);
8296 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
8297 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
8298 }
Duncan Sandsc849e662008-01-06 18:27:01 +00008299
8300 // Add any parameter attributes.
8301 uint16_t PAttrs = CallerPAL ? CallerPAL->getParamAttrs(i + 1) : 0;
8302 if (PAttrs)
8303 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008304 }
8305
8306 // If the function takes more arguments than the call was taking, add them
8307 // now...
8308 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8309 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8310
8311 // If we are removing arguments to the function, emit an obnoxious warning...
8312 if (FT->getNumParams() < NumActualArgs)
8313 if (!FT->isVarArg()) {
8314 cerr << "WARNING: While resolving call to function '"
8315 << Callee->getName() << "' arguments were dropped!\n";
8316 } else {
8317 // Add all of the arguments in their promoted form to the arg list...
8318 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8319 const Type *PTy = getPromotedType((*AI)->getType());
8320 if (PTy != (*AI)->getType()) {
8321 // Must promote to pass through va_arg area!
8322 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
8323 PTy, false);
8324 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
8325 InsertNewInstBefore(Cast, *Caller);
8326 Args.push_back(Cast);
8327 } else {
8328 Args.push_back(*AI);
8329 }
Duncan Sandsc849e662008-01-06 18:27:01 +00008330
Duncan Sands4ced1f82008-01-13 08:02:44 +00008331 // Add any parameter attributes.
8332 uint16_t PAttrs = CallerPAL ? CallerPAL->getParamAttrs(i + 1) : 0;
8333 if (PAttrs)
8334 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8335 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008336 }
8337
8338 if (FT->getReturnType() == Type::VoidTy)
8339 Caller->setName(""); // Void type should not have a name.
8340
Duncan Sandsc849e662008-01-06 18:27:01 +00008341 const ParamAttrsList* NewCallerPAL = ParamAttrsList::get(attrVec);
8342
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008343 Instruction *NC;
8344 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8345 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
David Greene8278ef52007-08-27 19:04:21 +00008346 Args.begin(), Args.end(), Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +00008347 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsc849e662008-01-06 18:27:01 +00008348 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008349 } else {
Chris Lattner03dc7d72007-08-02 16:53:43 +00008350 NC = new CallInst(Callee, Args.begin(), Args.end(),
8351 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008352 CallInst *CI = cast<CallInst>(Caller);
8353 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008354 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008355 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsc849e662008-01-06 18:27:01 +00008356 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008357 }
8358
8359 // Insert a cast of the return type as necessary.
8360 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +00008361 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008362 if (NV->getType() != Type::VoidTy) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008363 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +00008364 OldRetTy, false);
8365 NV = NC = CastInst::create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008366
8367 // If this is an invoke instruction, we should insert it after the first
8368 // non-phi, instruction in the normal successor block.
8369 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8370 BasicBlock::iterator I = II->getNormalDest()->begin();
8371 while (isa<PHINode>(I)) ++I;
8372 InsertNewInstBefore(NC, *I);
8373 } else {
8374 // Otherwise, it's a call, just insert cast right after the call instr
8375 InsertNewInstBefore(NC, *Caller);
8376 }
8377 AddUsersToWorkList(*Caller);
8378 } else {
8379 NV = UndefValue::get(Caller->getType());
8380 }
8381 }
8382
8383 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8384 Caller->replaceAllUsesWith(NV);
8385 Caller->eraseFromParent();
8386 RemoveFromWorkList(Caller);
8387 return true;
8388}
8389
Duncan Sands74833f22007-09-17 10:26:40 +00008390// transformCallThroughTrampoline - Turn a call to a function created by the
8391// init_trampoline intrinsic into a direct call to the underlying function.
8392//
8393Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
8394 Value *Callee = CS.getCalledValue();
8395 const PointerType *PTy = cast<PointerType>(Callee->getType());
8396 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Duncan Sands48b81112008-01-14 19:52:09 +00008397 const ParamAttrsList *Attrs = CS.getParamAttrs();
8398
8399 // If the call already has the 'nest' attribute somewhere then give up -
8400 // otherwise 'nest' would occur twice after splicing in the chain.
8401 if (Attrs && Attrs->hasAttrSomewhere(ParamAttr::Nest))
8402 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +00008403
8404 IntrinsicInst *Tramp =
8405 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
8406
8407 Function *NestF =
8408 cast<Function>(IntrinsicInst::StripPointerCasts(Tramp->getOperand(2)));
8409 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
8410 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
8411
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008412 if (const ParamAttrsList *NestAttrs = NestF->getParamAttrs()) {
Duncan Sands74833f22007-09-17 10:26:40 +00008413 unsigned NestIdx = 1;
8414 const Type *NestTy = 0;
8415 uint16_t NestAttr = 0;
8416
8417 // Look for a parameter marked with the 'nest' attribute.
8418 for (FunctionType::param_iterator I = NestFTy->param_begin(),
8419 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
8420 if (NestAttrs->paramHasAttr(NestIdx, ParamAttr::Nest)) {
8421 // Record the parameter type and any other attributes.
8422 NestTy = *I;
8423 NestAttr = NestAttrs->getParamAttrs(NestIdx);
8424 break;
8425 }
8426
8427 if (NestTy) {
8428 Instruction *Caller = CS.getInstruction();
8429 std::vector<Value*> NewArgs;
8430 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
8431
Duncan Sands48b81112008-01-14 19:52:09 +00008432 ParamAttrsVector NewAttrs;
8433 NewAttrs.reserve(Attrs ? Attrs->size() + 1 : 1);
8434
Duncan Sands74833f22007-09-17 10:26:40 +00008435 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +00008436 // mean appending it. Likewise for attributes.
8437
8438 // Add any function result attributes.
8439 uint16_t Attr = Attrs ? Attrs->getParamAttrs(0) : 0;
8440 if (Attr)
8441 NewAttrs.push_back (ParamAttrsWithIndex::get(0, Attr));
8442
Duncan Sands74833f22007-09-17 10:26:40 +00008443 {
8444 unsigned Idx = 1;
8445 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
8446 do {
8447 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +00008448 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00008449 Value *NestVal = Tramp->getOperand(3);
8450 if (NestVal->getType() != NestTy)
8451 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
8452 NewArgs.push_back(NestVal);
Duncan Sands48b81112008-01-14 19:52:09 +00008453 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +00008454 }
8455
8456 if (I == E)
8457 break;
8458
Duncan Sands48b81112008-01-14 19:52:09 +00008459 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00008460 NewArgs.push_back(*I);
Duncan Sands48b81112008-01-14 19:52:09 +00008461 Attr = Attrs ? Attrs->getParamAttrs(Idx) : 0;
8462 if (Attr)
8463 NewAttrs.push_back
8464 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +00008465
8466 ++Idx, ++I;
8467 } while (1);
8468 }
8469
8470 // The trampoline may have been bitcast to a bogus type (FTy).
8471 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +00008472 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +00008473
Duncan Sands74833f22007-09-17 10:26:40 +00008474 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +00008475 NewTypes.reserve(FTy->getNumParams()+1);
8476
Duncan Sands74833f22007-09-17 10:26:40 +00008477 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +00008478 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +00008479 {
8480 unsigned Idx = 1;
8481 FunctionType::param_iterator I = FTy->param_begin(),
8482 E = FTy->param_end();
8483
8484 do {
Duncan Sands48b81112008-01-14 19:52:09 +00008485 if (Idx == NestIdx)
8486 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +00008487 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +00008488
8489 if (I == E)
8490 break;
8491
Duncan Sands48b81112008-01-14 19:52:09 +00008492 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +00008493 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +00008494
8495 ++Idx, ++I;
8496 } while (1);
8497 }
8498
8499 // Replace the trampoline call with a direct call. Let the generic
8500 // code sort out any function type mismatches.
8501 FunctionType *NewFTy =
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008502 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lambbb2f2222007-12-17 01:12:55 +00008503 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
8504 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008505 const ParamAttrsList *NewPAL = ParamAttrsList::get(NewAttrs);
Duncan Sands74833f22007-09-17 10:26:40 +00008506
8507 Instruction *NewCaller;
8508 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8509 NewCaller = new InvokeInst(NewCallee,
8510 II->getNormalDest(), II->getUnwindDest(),
8511 NewArgs.begin(), NewArgs.end(),
8512 Caller->getName(), Caller);
8513 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008514 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00008515 } else {
8516 NewCaller = new CallInst(NewCallee, NewArgs.begin(), NewArgs.end(),
8517 Caller->getName(), Caller);
8518 if (cast<CallInst>(Caller)->isTailCall())
8519 cast<CallInst>(NewCaller)->setTailCall();
8520 cast<CallInst>(NewCaller)->
8521 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008522 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00008523 }
8524 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8525 Caller->replaceAllUsesWith(NewCaller);
8526 Caller->eraseFromParent();
8527 RemoveFromWorkList(Caller);
8528 return 0;
8529 }
8530 }
8531
8532 // Replace the trampoline call with a direct call. Since there is no 'nest'
8533 // parameter, there is no need to adjust the argument list. Let the generic
8534 // code sort out any function type mismatches.
8535 Constant *NewCallee =
8536 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
8537 CS.setCalledFunction(NewCallee);
8538 return CS.getInstruction();
8539}
8540
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008541/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
8542/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
8543/// and a single binop.
8544Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
8545 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8546 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
8547 isa<CmpInst>(FirstInst));
8548 unsigned Opc = FirstInst->getOpcode();
8549 Value *LHSVal = FirstInst->getOperand(0);
8550 Value *RHSVal = FirstInst->getOperand(1);
8551
8552 const Type *LHSType = LHSVal->getType();
8553 const Type *RHSType = RHSVal->getType();
8554
8555 // Scan to see if all operands are the same opcode, all have one use, and all
8556 // kill their operands (i.e. the operands have one use).
8557 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
8558 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
8559 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
8560 // Verify type of the LHS matches so we don't fold cmp's of different
8561 // types or GEP's with different index types.
8562 I->getOperand(0)->getType() != LHSType ||
8563 I->getOperand(1)->getType() != RHSType)
8564 return 0;
8565
8566 // If they are CmpInst instructions, check their predicates
8567 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
8568 if (cast<CmpInst>(I)->getPredicate() !=
8569 cast<CmpInst>(FirstInst)->getPredicate())
8570 return 0;
8571
8572 // Keep track of which operand needs a phi node.
8573 if (I->getOperand(0) != LHSVal) LHSVal = 0;
8574 if (I->getOperand(1) != RHSVal) RHSVal = 0;
8575 }
8576
8577 // Otherwise, this is safe to transform, determine if it is profitable.
8578
8579 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
8580 // Indexes are often folded into load/store instructions, so we don't want to
8581 // hide them behind a phi.
8582 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
8583 return 0;
8584
8585 Value *InLHS = FirstInst->getOperand(0);
8586 Value *InRHS = FirstInst->getOperand(1);
8587 PHINode *NewLHS = 0, *NewRHS = 0;
8588 if (LHSVal == 0) {
8589 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
8590 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
8591 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
8592 InsertNewInstBefore(NewLHS, PN);
8593 LHSVal = NewLHS;
8594 }
8595
8596 if (RHSVal == 0) {
8597 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
8598 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
8599 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
8600 InsertNewInstBefore(NewRHS, PN);
8601 RHSVal = NewRHS;
8602 }
8603
8604 // Add all operands to the new PHIs.
8605 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8606 if (NewLHS) {
8607 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8608 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
8609 }
8610 if (NewRHS) {
8611 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
8612 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
8613 }
8614 }
8615
8616 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
8617 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
8618 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8619 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
8620 RHSVal);
8621 else {
8622 assert(isa<GetElementPtrInst>(FirstInst));
8623 return new GetElementPtrInst(LHSVal, RHSVal);
8624 }
8625}
8626
8627/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
8628/// of the block that defines it. This means that it must be obvious the value
8629/// of the load is not changed from the point of the load to the end of the
8630/// block it is in.
8631///
8632/// Finally, it is safe, but not profitable, to sink a load targetting a
8633/// non-address-taken alloca. Doing so will cause us to not promote the alloca
8634/// to a register.
8635static bool isSafeToSinkLoad(LoadInst *L) {
8636 BasicBlock::iterator BBI = L, E = L->getParent()->end();
8637
8638 for (++BBI; BBI != E; ++BBI)
8639 if (BBI->mayWriteToMemory())
8640 return false;
8641
8642 // Check for non-address taken alloca. If not address-taken already, it isn't
8643 // profitable to do this xform.
8644 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
8645 bool isAddressTaken = false;
8646 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8647 UI != E; ++UI) {
8648 if (isa<LoadInst>(UI)) continue;
8649 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8650 // If storing TO the alloca, then the address isn't taken.
8651 if (SI->getOperand(1) == AI) continue;
8652 }
8653 isAddressTaken = true;
8654 break;
8655 }
8656
8657 if (!isAddressTaken)
8658 return false;
8659 }
8660
8661 return true;
8662}
8663
8664
8665// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
8666// operator and they all are only used by the PHI, PHI together their
8667// inputs, and do the operation once, to the result of the PHI.
8668Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
8669 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8670
8671 // Scan the instruction, looking for input operations that can be folded away.
8672 // If all input operands to the phi are the same instruction (e.g. a cast from
8673 // the same type or "+42") we can pull the operation through the PHI, reducing
8674 // code size and simplifying code.
8675 Constant *ConstantOp = 0;
8676 const Type *CastSrcTy = 0;
8677 bool isVolatile = false;
8678 if (isa<CastInst>(FirstInst)) {
8679 CastSrcTy = FirstInst->getOperand(0)->getType();
8680 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
8681 // Can fold binop, compare or shift here if the RHS is a constant,
8682 // otherwise call FoldPHIArgBinOpIntoPHI.
8683 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
8684 if (ConstantOp == 0)
8685 return FoldPHIArgBinOpIntoPHI(PN);
8686 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
8687 isVolatile = LI->isVolatile();
8688 // We can't sink the load if the loaded value could be modified between the
8689 // load and the PHI.
8690 if (LI->getParent() != PN.getIncomingBlock(0) ||
8691 !isSafeToSinkLoad(LI))
8692 return 0;
8693 } else if (isa<GetElementPtrInst>(FirstInst)) {
8694 if (FirstInst->getNumOperands() == 2)
8695 return FoldPHIArgBinOpIntoPHI(PN);
8696 // Can't handle general GEPs yet.
8697 return 0;
8698 } else {
8699 return 0; // Cannot fold this operation.
8700 }
8701
8702 // Check to see if all arguments are the same operation.
8703 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8704 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
8705 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
8706 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
8707 return 0;
8708 if (CastSrcTy) {
8709 if (I->getOperand(0)->getType() != CastSrcTy)
8710 return 0; // Cast operation must match.
8711 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8712 // We can't sink the load if the loaded value could be modified between
8713 // the load and the PHI.
8714 if (LI->isVolatile() != isVolatile ||
8715 LI->getParent() != PN.getIncomingBlock(i) ||
8716 !isSafeToSinkLoad(LI))
8717 return 0;
8718 } else if (I->getOperand(1) != ConstantOp) {
8719 return 0;
8720 }
8721 }
8722
8723 // Okay, they are all the same operation. Create a new PHI node of the
8724 // correct type, and PHI together all of the LHS's of the instructions.
8725 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
8726 PN.getName()+".in");
8727 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
8728
8729 Value *InVal = FirstInst->getOperand(0);
8730 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
8731
8732 // Add all operands to the new PHI.
8733 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8734 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8735 if (NewInVal != InVal)
8736 InVal = 0;
8737 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
8738 }
8739
8740 Value *PhiVal;
8741 if (InVal) {
8742 // The new PHI unions all of the same values together. This is really
8743 // common, so we handle it intelligently here for compile-time speed.
8744 PhiVal = InVal;
8745 delete NewPN;
8746 } else {
8747 InsertNewInstBefore(NewPN, PN);
8748 PhiVal = NewPN;
8749 }
8750
8751 // Insert and return the new operation.
8752 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
8753 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
8754 else if (isa<LoadInst>(FirstInst))
8755 return new LoadInst(PhiVal, "", isVolatile);
8756 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
8757 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
8758 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8759 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
8760 PhiVal, ConstantOp);
8761 else
8762 assert(0 && "Unknown operation");
8763 return 0;
8764}
8765
8766/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
8767/// that is dead.
8768static bool DeadPHICycle(PHINode *PN,
8769 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
8770 if (PN->use_empty()) return true;
8771 if (!PN->hasOneUse()) return false;
8772
8773 // Remember this node, and if we find the cycle, return.
8774 if (!PotentiallyDeadPHIs.insert(PN))
8775 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +00008776
8777 // Don't scan crazily complex things.
8778 if (PotentiallyDeadPHIs.size() == 16)
8779 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008780
8781 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
8782 return DeadPHICycle(PU, PotentiallyDeadPHIs);
8783
8784 return false;
8785}
8786
Chris Lattner27b695d2007-11-06 21:52:06 +00008787/// PHIsEqualValue - Return true if this phi node is always equal to
8788/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
8789/// z = some value; x = phi (y, z); y = phi (x, z)
8790static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
8791 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
8792 // See if we already saw this PHI node.
8793 if (!ValueEqualPHIs.insert(PN))
8794 return true;
8795
8796 // Don't scan crazily complex things.
8797 if (ValueEqualPHIs.size() == 16)
8798 return false;
8799
8800 // Scan the operands to see if they are either phi nodes or are equal to
8801 // the value.
8802 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
8803 Value *Op = PN->getIncomingValue(i);
8804 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
8805 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
8806 return false;
8807 } else if (Op != NonPhiInVal)
8808 return false;
8809 }
8810
8811 return true;
8812}
8813
8814
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008815// PHINode simplification
8816//
8817Instruction *InstCombiner::visitPHINode(PHINode &PN) {
8818 // If LCSSA is around, don't mess with Phi nodes
8819 if (MustPreserveLCSSA) return 0;
8820
8821 if (Value *V = PN.hasConstantValue())
8822 return ReplaceInstUsesWith(PN, V);
8823
8824 // If all PHI operands are the same operation, pull them through the PHI,
8825 // reducing code size.
8826 if (isa<Instruction>(PN.getIncomingValue(0)) &&
8827 PN.getIncomingValue(0)->hasOneUse())
8828 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
8829 return Result;
8830
8831 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
8832 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
8833 // PHI)... break the cycle.
8834 if (PN.hasOneUse()) {
8835 Instruction *PHIUser = cast<Instruction>(PN.use_back());
8836 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
8837 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
8838 PotentiallyDeadPHIs.insert(&PN);
8839 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
8840 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8841 }
8842
8843 // If this phi has a single use, and if that use just computes a value for
8844 // the next iteration of a loop, delete the phi. This occurs with unused
8845 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
8846 // common case here is good because the only other things that catch this
8847 // are induction variable analysis (sometimes) and ADCE, which is only run
8848 // late.
8849 if (PHIUser->hasOneUse() &&
8850 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
8851 PHIUser->use_back() == &PN) {
8852 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8853 }
8854 }
8855
Chris Lattner27b695d2007-11-06 21:52:06 +00008856 // We sometimes end up with phi cycles that non-obviously end up being the
8857 // same value, for example:
8858 // z = some value; x = phi (y, z); y = phi (x, z)
8859 // where the phi nodes don't necessarily need to be in the same block. Do a
8860 // quick check to see if the PHI node only contains a single non-phi value, if
8861 // so, scan to see if the phi cycle is actually equal to that value.
8862 {
8863 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
8864 // Scan for the first non-phi operand.
8865 while (InValNo != NumOperandVals &&
8866 isa<PHINode>(PN.getIncomingValue(InValNo)))
8867 ++InValNo;
8868
8869 if (InValNo != NumOperandVals) {
8870 Value *NonPhiInVal = PN.getOperand(InValNo);
8871
8872 // Scan the rest of the operands to see if there are any conflicts, if so
8873 // there is no need to recursively scan other phis.
8874 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
8875 Value *OpVal = PN.getIncomingValue(InValNo);
8876 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
8877 break;
8878 }
8879
8880 // If we scanned over all operands, then we have one unique value plus
8881 // phi values. Scan PHI nodes to see if they all merge in each other or
8882 // the value.
8883 if (InValNo == NumOperandVals) {
8884 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
8885 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
8886 return ReplaceInstUsesWith(PN, NonPhiInVal);
8887 }
8888 }
8889 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008890 return 0;
8891}
8892
8893static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
8894 Instruction *InsertPoint,
8895 InstCombiner *IC) {
8896 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
8897 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
8898 // We must cast correctly to the pointer type. Ensure that we
8899 // sign extend the integer value if it is smaller as this is
8900 // used for address computation.
8901 Instruction::CastOps opcode =
8902 (VTySize < PtrSize ? Instruction::SExt :
8903 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
8904 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
8905}
8906
8907
8908Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
8909 Value *PtrOp = GEP.getOperand(0);
8910 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
8911 // If so, eliminate the noop.
8912 if (GEP.getNumOperands() == 1)
8913 return ReplaceInstUsesWith(GEP, PtrOp);
8914
8915 if (isa<UndefValue>(GEP.getOperand(0)))
8916 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
8917
8918 bool HasZeroPointerIndex = false;
8919 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
8920 HasZeroPointerIndex = C->isNullValue();
8921
8922 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
8923 return ReplaceInstUsesWith(GEP, PtrOp);
8924
8925 // Eliminate unneeded casts for indices.
8926 bool MadeChange = false;
8927
8928 gep_type_iterator GTI = gep_type_begin(GEP);
8929 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
8930 if (isa<SequentialType>(*GTI)) {
8931 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
8932 if (CI->getOpcode() == Instruction::ZExt ||
8933 CI->getOpcode() == Instruction::SExt) {
8934 const Type *SrcTy = CI->getOperand(0)->getType();
8935 // We can eliminate a cast from i32 to i64 iff the target
8936 // is a 32-bit pointer target.
8937 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
8938 MadeChange = true;
8939 GEP.setOperand(i, CI->getOperand(0));
8940 }
8941 }
8942 }
8943 // If we are using a wider index than needed for this platform, shrink it
8944 // to what we need. If the incoming value needs a cast instruction,
8945 // insert it. This explicit cast can make subsequent optimizations more
8946 // obvious.
8947 Value *Op = GEP.getOperand(i);
Duncan Sandsf99fdc62007-11-01 20:53:16 +00008948 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008949 if (Constant *C = dyn_cast<Constant>(Op)) {
8950 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
8951 MadeChange = true;
8952 } else {
8953 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
8954 GEP);
8955 GEP.setOperand(i, Op);
8956 MadeChange = true;
8957 }
8958 }
8959 }
8960 if (MadeChange) return &GEP;
8961
8962 // If this GEP instruction doesn't move the pointer, and if the input operand
8963 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
8964 // real input to the dest type.
Chris Lattnerc59171a2007-10-12 05:30:59 +00008965 if (GEP.hasAllZeroIndices()) {
8966 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
8967 // If the bitcast is of an allocation, and the allocation will be
8968 // converted to match the type of the cast, don't touch this.
8969 if (isa<AllocationInst>(BCI->getOperand(0))) {
8970 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattner551a5872007-10-12 18:05:47 +00008971 if (Instruction *I = visitBitCast(*BCI)) {
8972 if (I != BCI) {
8973 I->takeName(BCI);
8974 BCI->getParent()->getInstList().insert(BCI, I);
8975 ReplaceInstUsesWith(*BCI, I);
8976 }
Chris Lattnerc59171a2007-10-12 05:30:59 +00008977 return &GEP;
Chris Lattner551a5872007-10-12 18:05:47 +00008978 }
Chris Lattnerc59171a2007-10-12 05:30:59 +00008979 }
8980 return new BitCastInst(BCI->getOperand(0), GEP.getType());
8981 }
8982 }
8983
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008984 // Combine Indices - If the source pointer to this getelementptr instruction
8985 // is a getelementptr instruction, combine the indices of the two
8986 // getelementptr instructions into a single instruction.
8987 //
8988 SmallVector<Value*, 8> SrcGEPOperands;
8989 if (User *Src = dyn_castGetElementPtr(PtrOp))
8990 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
8991
8992 if (!SrcGEPOperands.empty()) {
8993 // Note that if our source is a gep chain itself that we wait for that
8994 // chain to be resolved before we perform this transformation. This
8995 // avoids us creating a TON of code in some cases.
8996 //
8997 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
8998 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
8999 return 0; // Wait until our source is folded to completion.
9000
9001 SmallVector<Value*, 8> Indices;
9002
9003 // Find out whether the last index in the source GEP is a sequential idx.
9004 bool EndsWithSequential = false;
9005 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9006 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
9007 EndsWithSequential = !isa<StructType>(*I);
9008
9009 // Can we combine the two pointer arithmetics offsets?
9010 if (EndsWithSequential) {
9011 // Replace: gep (gep %P, long B), long A, ...
9012 // With: T = long A+B; gep %P, T, ...
9013 //
9014 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
9015 if (SO1 == Constant::getNullValue(SO1->getType())) {
9016 Sum = GO1;
9017 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9018 Sum = SO1;
9019 } else {
9020 // If they aren't the same type, convert both to an integer of the
9021 // target's pointer size.
9022 if (SO1->getType() != GO1->getType()) {
9023 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
9024 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
9025 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
9026 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
9027 } else {
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009028 unsigned PS = TD->getPointerSizeInBits();
9029 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009030 // Convert GO1 to SO1's type.
9031 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
9032
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009033 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009034 // Convert SO1 to GO1's type.
9035 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
9036 } else {
9037 const Type *PT = TD->getIntPtrType();
9038 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9039 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
9040 }
9041 }
9042 }
9043 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9044 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9045 else {
9046 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
9047 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
9048 }
9049 }
9050
9051 // Recycle the GEP we already have if possible.
9052 if (SrcGEPOperands.size() == 2) {
9053 GEP.setOperand(0, SrcGEPOperands[0]);
9054 GEP.setOperand(1, Sum);
9055 return &GEP;
9056 } else {
9057 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9058 SrcGEPOperands.end()-1);
9059 Indices.push_back(Sum);
9060 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9061 }
9062 } else if (isa<Constant>(*GEP.idx_begin()) &&
9063 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
9064 SrcGEPOperands.size() != 1) {
9065 // Otherwise we can do the fold if the first index of the GEP is a zero
9066 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9067 SrcGEPOperands.end());
9068 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9069 }
9070
9071 if (!Indices.empty())
David Greene393be882007-09-04 15:46:09 +00009072 return new GetElementPtrInst(SrcGEPOperands[0], Indices.begin(),
9073 Indices.end(), GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009074
9075 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
9076 // GEP of global variable. If all of the indices for this GEP are
9077 // constants, we can promote this to a constexpr instead of an instruction.
9078
9079 // Scan for nonconstants...
9080 SmallVector<Constant*, 8> Indices;
9081 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9082 for (; I != E && isa<Constant>(*I); ++I)
9083 Indices.push_back(cast<Constant>(*I));
9084
9085 if (I == E) { // If they are all constants...
9086 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9087 &Indices[0],Indices.size());
9088
9089 // Replace all uses of the GEP with the new constexpr...
9090 return ReplaceInstUsesWith(GEP, CE);
9091 }
9092 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
9093 if (!isa<PointerType>(X->getType())) {
9094 // Not interesting. Source pointer must be a cast from pointer.
9095 } else if (HasZeroPointerIndex) {
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009096 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9097 // into : GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009098 //
9099 // This occurs when the program declares an array extern like "int X[];"
9100 //
9101 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9102 const PointerType *XTy = cast<PointerType>(X->getType());
9103 if (const ArrayType *XATy =
9104 dyn_cast<ArrayType>(XTy->getElementType()))
9105 if (const ArrayType *CATy =
9106 dyn_cast<ArrayType>(CPTy->getElementType()))
9107 if (CATy->getElementType() == XATy->getElementType()) {
9108 // At this point, we know that the cast source type is a pointer
9109 // to an array of the same type as the destination pointer
9110 // array. Because the array type is never stepped over (there
9111 // is a leading zero) we can fold the cast into this GEP.
9112 GEP.setOperand(0, X);
9113 return &GEP;
9114 }
9115 } else if (GEP.getNumOperands() == 2) {
9116 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009117 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9118 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009119 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9120 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9121 if (isa<ArrayType>(SrcElTy) &&
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009122 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9123 TD->getABITypeSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +00009124 Value *Idx[2];
9125 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9126 Idx[1] = GEP.getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009127 Value *V = InsertNewInstBefore(
David Greene393be882007-09-04 15:46:09 +00009128 new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName()), GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009129 // V and GEP are both pointer types --> BitCast
9130 return new BitCastInst(V, GEP.getType());
9131 }
9132
9133 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009134 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009135 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009136 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009137
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009138 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009139 uint64_t ArrayEltSize =
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009140 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009141
9142 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9143 // allow either a mul, shift, or constant here.
9144 Value *NewIdx = 0;
9145 ConstantInt *Scale = 0;
9146 if (ArrayEltSize == 1) {
9147 NewIdx = GEP.getOperand(1);
9148 Scale = ConstantInt::get(NewIdx->getType(), 1);
9149 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
9150 NewIdx = ConstantInt::get(CI->getType(), 1);
9151 Scale = CI;
9152 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9153 if (Inst->getOpcode() == Instruction::Shl &&
9154 isa<ConstantInt>(Inst->getOperand(1))) {
9155 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9156 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9157 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
9158 NewIdx = Inst->getOperand(0);
9159 } else if (Inst->getOpcode() == Instruction::Mul &&
9160 isa<ConstantInt>(Inst->getOperand(1))) {
9161 Scale = cast<ConstantInt>(Inst->getOperand(1));
9162 NewIdx = Inst->getOperand(0);
9163 }
9164 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009165
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009166 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009167 // out, perform the transformation. Note, we don't know whether Scale is
9168 // signed or not. We'll use unsigned version of division/modulo
9169 // operation after making sure Scale doesn't have the sign bit set.
9170 if (Scale && Scale->getSExtValue() >= 0LL &&
9171 Scale->getZExtValue() % ArrayEltSize == 0) {
9172 Scale = ConstantInt::get(Scale->getType(),
9173 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009174 if (Scale->getZExtValue() != 1) {
9175 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009176 false /*ZExt*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009177 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
9178 NewIdx = InsertNewInstBefore(Sc, GEP);
9179 }
9180
9181 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +00009182 Value *Idx[2];
9183 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9184 Idx[1] = NewIdx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009185 Instruction *NewGEP =
David Greene393be882007-09-04 15:46:09 +00009186 new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009187 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9188 // The NewGEP must be pointer typed, so must the old one -> BitCast
9189 return new BitCastInst(NewGEP, GEP.getType());
9190 }
9191 }
9192 }
9193 }
9194
9195 return 0;
9196}
9197
9198Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9199 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
9200 if (AI.isArrayAllocation()) // Check C != 1
9201 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9202 const Type *NewTy =
9203 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
9204 AllocationInst *New = 0;
9205
9206 // Create and insert the replacement instruction...
9207 if (isa<MallocInst>(AI))
9208 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
9209 else {
9210 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
9211 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
9212 }
9213
9214 InsertNewInstBefore(New, AI);
9215
9216 // Scan to the end of the allocation instructions, to skip over a block of
9217 // allocas if possible...
9218 //
9219 BasicBlock::iterator It = New;
9220 while (isa<AllocationInst>(*It)) ++It;
9221
9222 // Now that I is pointing to the first non-allocation-inst in the block,
9223 // insert our getelementptr instruction...
9224 //
9225 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greene393be882007-09-04 15:46:09 +00009226 Value *Idx[2];
9227 Idx[0] = NullIdx;
9228 Idx[1] = NullIdx;
9229 Value *V = new GetElementPtrInst(New, Idx, Idx + 2,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009230 New->getName()+".sub", It);
9231
9232 // Now make everything use the getelementptr instead of the original
9233 // allocation.
9234 return ReplaceInstUsesWith(AI, V);
9235 } else if (isa<UndefValue>(AI.getArraySize())) {
9236 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9237 }
9238
9239 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9240 // Note that we only do this for alloca's, because malloc should allocate and
9241 // return a unique pointer, even for a zero byte allocation.
9242 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009243 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009244 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9245
9246 return 0;
9247}
9248
9249Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9250 Value *Op = FI.getOperand(0);
9251
9252 // free undef -> unreachable.
9253 if (isa<UndefValue>(Op)) {
9254 // Insert a new store to null because we cannot modify the CFG here.
9255 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00009256 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009257 return EraseInstFromFunction(FI);
9258 }
9259
9260 // If we have 'free null' delete the instruction. This can happen in stl code
9261 // when lots of inlining happens.
9262 if (isa<ConstantPointerNull>(Op))
9263 return EraseInstFromFunction(FI);
9264
9265 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9266 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9267 FI.setOperand(0, CI->getOperand(0));
9268 return &FI;
9269 }
9270
9271 // Change free (gep X, 0,0,0,0) into free(X)
9272 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9273 if (GEPI->hasAllZeroIndices()) {
9274 AddToWorkList(GEPI);
9275 FI.setOperand(0, GEPI->getOperand(0));
9276 return &FI;
9277 }
9278 }
9279
9280 // Change free(malloc) into nothing, if the malloc has a single use.
9281 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9282 if (MI->hasOneUse()) {
9283 EraseInstFromFunction(FI);
9284 return EraseInstFromFunction(*MI);
9285 }
9286
9287 return 0;
9288}
9289
9290
9291/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patela0f8ea82007-10-18 19:52:32 +00009292static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
9293 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009294 User *CI = cast<User>(LI.getOperand(0));
9295 Value *CastOp = CI->getOperand(0);
9296
Devang Patela0f8ea82007-10-18 19:52:32 +00009297 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9298 // Instead of loading constant c string, use corresponding integer value
9299 // directly if string length is small enough.
9300 const std::string &Str = CE->getOperand(0)->getStringValue();
9301 if (!Str.empty()) {
9302 unsigned len = Str.length();
9303 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9304 unsigned numBits = Ty->getPrimitiveSizeInBits();
9305 // Replace LI with immediate integer store.
9306 if ((numBits >> 3) == len + 1) {
9307 APInt StrVal(numBits, 0);
9308 APInt SingleChar(numBits, 0);
9309 if (TD->isLittleEndian()) {
9310 for (signed i = len-1; i >= 0; i--) {
9311 SingleChar = (uint64_t) Str[i];
9312 StrVal = (StrVal << 8) | SingleChar;
9313 }
9314 } else {
9315 for (unsigned i = 0; i < len; i++) {
9316 SingleChar = (uint64_t) Str[i];
9317 StrVal = (StrVal << 8) | SingleChar;
9318 }
9319 // Append NULL at the end.
9320 SingleChar = 0;
9321 StrVal = (StrVal << 8) | SingleChar;
9322 }
9323 Value *NL = ConstantInt::get(StrVal);
9324 return IC.ReplaceInstUsesWith(LI, NL);
9325 }
9326 }
9327 }
9328
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009329 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9330 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9331 const Type *SrcPTy = SrcTy->getElementType();
9332
9333 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
9334 isa<VectorType>(DestPTy)) {
9335 // If the source is an array, the code below will not succeed. Check to
9336 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9337 // constants.
9338 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9339 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9340 if (ASrcTy->getNumElements() != 0) {
9341 Value *Idxs[2];
9342 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9343 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
9344 SrcTy = cast<PointerType>(CastOp->getType());
9345 SrcPTy = SrcTy->getElementType();
9346 }
9347
9348 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
9349 isa<VectorType>(SrcPTy)) &&
9350 // Do not allow turning this into a load of an integer, which is then
9351 // casted to a pointer, this pessimizes pointer analysis a lot.
9352 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
9353 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9354 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
9355
9356 // Okay, we are casting from one integer or pointer type to another of
9357 // the same size. Instead of casting the pointer before the load, cast
9358 // the result of the loaded value.
9359 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
9360 CI->getName(),
9361 LI.isVolatile()),LI);
9362 // Now cast the result of the load.
9363 return new BitCastInst(NewLoad, LI.getType());
9364 }
9365 }
9366 }
9367 return 0;
9368}
9369
9370/// isSafeToLoadUnconditionally - Return true if we know that executing a load
9371/// from this value cannot trap. If it is not obviously safe to load from the
9372/// specified pointer, we do a quick local scan of the basic block containing
9373/// ScanFrom, to determine if the address is already accessed.
9374static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands9b27dbe2007-09-19 10:10:31 +00009375 // If it is an alloca it is always safe to load from.
9376 if (isa<AllocaInst>(V)) return true;
9377
Duncan Sandse40a94a2007-09-19 10:25:38 +00009378 // If it is a global variable it is mostly safe to load from.
Duncan Sands9b27dbe2007-09-19 10:10:31 +00009379 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sandse40a94a2007-09-19 10:25:38 +00009380 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands9b27dbe2007-09-19 10:10:31 +00009381 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009382
9383 // Otherwise, be a little bit agressive by scanning the local block where we
9384 // want to check to see if the pointer is already being loaded or stored
9385 // from/to. If so, the previous load or store would have already trapped,
9386 // so there is no harm doing an extra load (also, CSE will later eliminate
9387 // the load entirely).
9388 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
9389
9390 while (BBI != E) {
9391 --BBI;
9392
9393 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9394 if (LI->getOperand(0) == V) return true;
9395 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9396 if (SI->getOperand(1) == V) return true;
9397
9398 }
9399 return false;
9400}
9401
Chris Lattner0270a112007-08-11 18:48:48 +00009402/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
9403/// until we find the underlying object a pointer is referring to or something
9404/// we don't understand. Note that the returned pointer may be offset from the
9405/// input, because we ignore GEP indices.
9406static Value *GetUnderlyingObject(Value *Ptr) {
9407 while (1) {
9408 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
9409 if (CE->getOpcode() == Instruction::BitCast ||
9410 CE->getOpcode() == Instruction::GetElementPtr)
9411 Ptr = CE->getOperand(0);
9412 else
9413 return Ptr;
9414 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
9415 Ptr = BCI->getOperand(0);
9416 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
9417 Ptr = GEP->getOperand(0);
9418 } else {
9419 return Ptr;
9420 }
9421 }
9422}
9423
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009424Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
9425 Value *Op = LI.getOperand(0);
9426
Dan Gohman5c4d0e12007-07-20 16:34:21 +00009427 // Attempt to improve the alignment.
Chris Lattner47cf3452007-08-09 19:05:49 +00009428 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op, TD);
Dan Gohman5c4d0e12007-07-20 16:34:21 +00009429 if (KnownAlign > LI.getAlignment())
9430 LI.setAlignment(KnownAlign);
9431
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009432 // load (cast X) --> cast (load X) iff safe
9433 if (isa<CastInst>(Op))
Devang Patela0f8ea82007-10-18 19:52:32 +00009434 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009435 return Res;
9436
9437 // None of the following transforms are legal for volatile loads.
9438 if (LI.isVolatile()) return 0;
9439
9440 if (&LI.getParent()->front() != &LI) {
9441 BasicBlock::iterator BBI = &LI; --BBI;
9442 // If the instruction immediately before this is a store to the same
9443 // address, do a simple form of store->load forwarding.
9444 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9445 if (SI->getOperand(1) == LI.getOperand(0))
9446 return ReplaceInstUsesWith(LI, SI->getOperand(0));
9447 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
9448 if (LIB->getOperand(0) == LI.getOperand(0))
9449 return ReplaceInstUsesWith(LI, LIB);
9450 }
9451
Christopher Lamb2c175392007-12-29 07:56:53 +00009452 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9453 const Value *GEPI0 = GEPI->getOperand(0);
9454 // TODO: Consider a target hook for valid address spaces for this xform.
9455 if (isa<ConstantPointerNull>(GEPI0) &&
9456 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009457 // Insert a new store to null instruction before the load to indicate
9458 // that this code is not reachable. We do this instead of inserting
9459 // an unreachable instruction directly because we cannot modify the
9460 // CFG.
9461 new StoreInst(UndefValue::get(LI.getType()),
9462 Constant::getNullValue(Op->getType()), &LI);
9463 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9464 }
Christopher Lamb2c175392007-12-29 07:56:53 +00009465 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009466
9467 if (Constant *C = dyn_cast<Constant>(Op)) {
9468 // load null/undef -> undef
Christopher Lamb2c175392007-12-29 07:56:53 +00009469 // TODO: Consider a target hook for valid address spaces for this xform.
9470 if (isa<UndefValue>(C) || (C->isNullValue() &&
9471 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009472 // Insert a new store to null instruction before the load to indicate that
9473 // this code is not reachable. We do this instead of inserting an
9474 // unreachable instruction directly because we cannot modify the CFG.
9475 new StoreInst(UndefValue::get(LI.getType()),
9476 Constant::getNullValue(Op->getType()), &LI);
9477 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9478 }
9479
9480 // Instcombine load (constant global) into the value loaded.
9481 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
9482 if (GV->isConstant() && !GV->isDeclaration())
9483 return ReplaceInstUsesWith(LI, GV->getInitializer());
9484
9485 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
9486 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
9487 if (CE->getOpcode() == Instruction::GetElementPtr) {
9488 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
9489 if (GV->isConstant() && !GV->isDeclaration())
9490 if (Constant *V =
9491 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
9492 return ReplaceInstUsesWith(LI, V);
9493 if (CE->getOperand(0)->isNullValue()) {
9494 // Insert a new store to null instruction before the load to indicate
9495 // that this code is not reachable. We do this instead of inserting
9496 // an unreachable instruction directly because we cannot modify the
9497 // CFG.
9498 new StoreInst(UndefValue::get(LI.getType()),
9499 Constant::getNullValue(Op->getType()), &LI);
9500 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9501 }
9502
9503 } else if (CE->isCast()) {
Devang Patela0f8ea82007-10-18 19:52:32 +00009504 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009505 return Res;
9506 }
9507 }
Chris Lattner0270a112007-08-11 18:48:48 +00009508
9509 // If this load comes from anywhere in a constant global, and if the global
9510 // is all undef or zero, we know what it loads.
9511 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
9512 if (GV->isConstant() && GV->hasInitializer()) {
9513 if (GV->getInitializer()->isNullValue())
9514 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
9515 else if (isa<UndefValue>(GV->getInitializer()))
9516 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9517 }
9518 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009519
9520 if (Op->hasOneUse()) {
9521 // Change select and PHI nodes to select values instead of addresses: this
9522 // helps alias analysis out a lot, allows many others simplifications, and
9523 // exposes redundancy in the code.
9524 //
9525 // Note that we cannot do the transformation unless we know that the
9526 // introduced loads cannot trap! Something like this is valid as long as
9527 // the condition is always false: load (select bool %C, int* null, int* %G),
9528 // but it would not be valid if we transformed it to load from null
9529 // unconditionally.
9530 //
9531 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
9532 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
9533 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
9534 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
9535 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
9536 SI->getOperand(1)->getName()+".val"), LI);
9537 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
9538 SI->getOperand(2)->getName()+".val"), LI);
9539 return new SelectInst(SI->getCondition(), V1, V2);
9540 }
9541
9542 // load (select (cond, null, P)) -> load P
9543 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
9544 if (C->isNullValue()) {
9545 LI.setOperand(0, SI->getOperand(2));
9546 return &LI;
9547 }
9548
9549 // load (select (cond, P, null)) -> load P
9550 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
9551 if (C->isNullValue()) {
9552 LI.setOperand(0, SI->getOperand(1));
9553 return &LI;
9554 }
9555 }
9556 }
9557 return 0;
9558}
9559
9560/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
9561/// when possible.
9562static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
9563 User *CI = cast<User>(SI.getOperand(1));
9564 Value *CastOp = CI->getOperand(0);
9565
9566 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9567 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9568 const Type *SrcPTy = SrcTy->getElementType();
9569
9570 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
9571 // If the source is an array, the code below will not succeed. Check to
9572 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9573 // constants.
9574 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9575 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9576 if (ASrcTy->getNumElements() != 0) {
9577 Value* Idxs[2];
9578 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9579 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
9580 SrcTy = cast<PointerType>(CastOp->getType());
9581 SrcPTy = SrcTy->getElementType();
9582 }
9583
9584 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
9585 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9586 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
9587
9588 // Okay, we are casting from one integer or pointer type to another of
9589 // the same size. Instead of casting the pointer before
9590 // the store, cast the value to be stored.
9591 Value *NewCast;
9592 Value *SIOp0 = SI.getOperand(0);
9593 Instruction::CastOps opcode = Instruction::BitCast;
9594 const Type* CastSrcTy = SIOp0->getType();
9595 const Type* CastDstTy = SrcPTy;
9596 if (isa<PointerType>(CastDstTy)) {
9597 if (CastSrcTy->isInteger())
9598 opcode = Instruction::IntToPtr;
9599 } else if (isa<IntegerType>(CastDstTy)) {
9600 if (isa<PointerType>(SIOp0->getType()))
9601 opcode = Instruction::PtrToInt;
9602 }
9603 if (Constant *C = dyn_cast<Constant>(SIOp0))
9604 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
9605 else
9606 NewCast = IC.InsertNewInstBefore(
9607 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
9608 SI);
9609 return new StoreInst(NewCast, CastOp);
9610 }
9611 }
9612 }
9613 return 0;
9614}
9615
9616Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
9617 Value *Val = SI.getOperand(0);
9618 Value *Ptr = SI.getOperand(1);
9619
9620 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
9621 EraseInstFromFunction(SI);
9622 ++NumCombined;
9623 return 0;
9624 }
9625
9626 // If the RHS is an alloca with a single use, zapify the store, making the
9627 // alloca dead.
9628 if (Ptr->hasOneUse()) {
9629 if (isa<AllocaInst>(Ptr)) {
9630 EraseInstFromFunction(SI);
9631 ++NumCombined;
9632 return 0;
9633 }
9634
9635 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
9636 if (isa<AllocaInst>(GEP->getOperand(0)) &&
9637 GEP->getOperand(0)->hasOneUse()) {
9638 EraseInstFromFunction(SI);
9639 ++NumCombined;
9640 return 0;
9641 }
9642 }
9643
Dan Gohman5c4d0e12007-07-20 16:34:21 +00009644 // Attempt to improve the alignment.
Chris Lattner47cf3452007-08-09 19:05:49 +00009645 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr, TD);
Dan Gohman5c4d0e12007-07-20 16:34:21 +00009646 if (KnownAlign > SI.getAlignment())
9647 SI.setAlignment(KnownAlign);
9648
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009649 // Do really simple DSE, to catch cases where there are several consequtive
9650 // stores to the same location, separated by a few arithmetic operations. This
9651 // situation often occurs with bitfield accesses.
9652 BasicBlock::iterator BBI = &SI;
9653 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
9654 --ScanInsts) {
9655 --BBI;
9656
9657 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
9658 // Prev store isn't volatile, and stores to the same location?
9659 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
9660 ++NumDeadStore;
9661 ++BBI;
9662 EraseInstFromFunction(*PrevSI);
9663 continue;
9664 }
9665 break;
9666 }
9667
9668 // If this is a load, we have to stop. However, if the loaded value is from
9669 // the pointer we're loading and is producing the pointer we're storing,
9670 // then *this* store is dead (X = load P; store X -> P).
9671 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattner24905f72007-09-07 05:33:03 +00009672 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009673 EraseInstFromFunction(SI);
9674 ++NumCombined;
9675 return 0;
9676 }
9677 // Otherwise, this is a load from some other location. Stores before it
9678 // may not be dead.
9679 break;
9680 }
9681
9682 // Don't skip over loads or things that can modify memory.
9683 if (BBI->mayWriteToMemory())
9684 break;
9685 }
9686
9687
9688 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
9689
9690 // store X, null -> turns into 'unreachable' in SimplifyCFG
9691 if (isa<ConstantPointerNull>(Ptr)) {
9692 if (!isa<UndefValue>(Val)) {
9693 SI.setOperand(0, UndefValue::get(Val->getType()));
9694 if (Instruction *U = dyn_cast<Instruction>(Val))
9695 AddToWorkList(U); // Dropped a use.
9696 ++NumCombined;
9697 }
9698 return 0; // Do not modify these!
9699 }
9700
9701 // store undef, Ptr -> noop
9702 if (isa<UndefValue>(Val)) {
9703 EraseInstFromFunction(SI);
9704 ++NumCombined;
9705 return 0;
9706 }
9707
9708 // If the pointer destination is a cast, see if we can fold the cast into the
9709 // source instead.
9710 if (isa<CastInst>(Ptr))
9711 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9712 return Res;
9713 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
9714 if (CE->isCast())
9715 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9716 return Res;
9717
9718
9719 // If this store is the last instruction in the basic block, and if the block
9720 // ends with an unconditional branch, try to move it to the successor block.
9721 BBI = &SI; ++BBI;
9722 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
9723 if (BI->isUnconditional())
9724 if (SimplifyStoreAtEndOfBlock(SI))
9725 return 0; // xform done!
9726
9727 return 0;
9728}
9729
9730/// SimplifyStoreAtEndOfBlock - Turn things like:
9731/// if () { *P = v1; } else { *P = v2 }
9732/// into a phi node with a store in the successor.
9733///
9734/// Simplify things like:
9735/// *P = v1; if () { *P = v2; }
9736/// into a phi node with a store in the successor.
9737///
9738bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
9739 BasicBlock *StoreBB = SI.getParent();
9740
9741 // Check to see if the successor block has exactly two incoming edges. If
9742 // so, see if the other predecessor contains a store to the same location.
9743 // if so, insert a PHI node (if needed) and move the stores down.
9744 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
9745
9746 // Determine whether Dest has exactly two predecessors and, if so, compute
9747 // the other predecessor.
9748 pred_iterator PI = pred_begin(DestBB);
9749 BasicBlock *OtherBB = 0;
9750 if (*PI != StoreBB)
9751 OtherBB = *PI;
9752 ++PI;
9753 if (PI == pred_end(DestBB))
9754 return false;
9755
9756 if (*PI != StoreBB) {
9757 if (OtherBB)
9758 return false;
9759 OtherBB = *PI;
9760 }
9761 if (++PI != pred_end(DestBB))
9762 return false;
9763
9764
9765 // Verify that the other block ends in a branch and is not otherwise empty.
9766 BasicBlock::iterator BBI = OtherBB->getTerminator();
9767 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
9768 if (!OtherBr || BBI == OtherBB->begin())
9769 return false;
9770
9771 // If the other block ends in an unconditional branch, check for the 'if then
9772 // else' case. there is an instruction before the branch.
9773 StoreInst *OtherStore = 0;
9774 if (OtherBr->isUnconditional()) {
9775 // If this isn't a store, or isn't a store to the same location, bail out.
9776 --BBI;
9777 OtherStore = dyn_cast<StoreInst>(BBI);
9778 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
9779 return false;
9780 } else {
9781 // Otherwise, the other block ended with a conditional branch. If one of the
9782 // destinations is StoreBB, then we have the if/then case.
9783 if (OtherBr->getSuccessor(0) != StoreBB &&
9784 OtherBr->getSuccessor(1) != StoreBB)
9785 return false;
9786
9787 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
9788 // if/then triangle. See if there is a store to the same ptr as SI that
9789 // lives in OtherBB.
9790 for (;; --BBI) {
9791 // Check to see if we find the matching store.
9792 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
9793 if (OtherStore->getOperand(1) != SI.getOperand(1))
9794 return false;
9795 break;
9796 }
9797 // If we find something that may be using the stored value, or if we run
9798 // out of instructions, we can't do the xform.
9799 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
9800 BBI == OtherBB->begin())
9801 return false;
9802 }
9803
9804 // In order to eliminate the store in OtherBr, we have to
9805 // make sure nothing reads the stored value in StoreBB.
9806 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
9807 // FIXME: This should really be AA driven.
9808 if (isa<LoadInst>(I) || I->mayWriteToMemory())
9809 return false;
9810 }
9811 }
9812
9813 // Insert a PHI node now if we need it.
9814 Value *MergedVal = OtherStore->getOperand(0);
9815 if (MergedVal != SI.getOperand(0)) {
9816 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
9817 PN->reserveOperandSpace(2);
9818 PN->addIncoming(SI.getOperand(0), SI.getParent());
9819 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
9820 MergedVal = InsertNewInstBefore(PN, DestBB->front());
9821 }
9822
9823 // Advance to a place where it is safe to insert the new store and
9824 // insert it.
9825 BBI = DestBB->begin();
9826 while (isa<PHINode>(BBI)) ++BBI;
9827 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
9828 OtherStore->isVolatile()), *BBI);
9829
9830 // Nuke the old stores.
9831 EraseInstFromFunction(SI);
9832 EraseInstFromFunction(*OtherStore);
9833 ++NumCombined;
9834 return true;
9835}
9836
9837
9838Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
9839 // Change br (not X), label True, label False to: br X, label False, True
9840 Value *X = 0;
9841 BasicBlock *TrueDest;
9842 BasicBlock *FalseDest;
9843 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
9844 !isa<Constant>(X)) {
9845 // Swap Destinations and condition...
9846 BI.setCondition(X);
9847 BI.setSuccessor(0, FalseDest);
9848 BI.setSuccessor(1, TrueDest);
9849 return &BI;
9850 }
9851
9852 // Cannonicalize fcmp_one -> fcmp_oeq
9853 FCmpInst::Predicate FPred; Value *Y;
9854 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
9855 TrueDest, FalseDest)))
9856 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
9857 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
9858 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
9859 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
9860 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
9861 NewSCC->takeName(I);
9862 // Swap Destinations and condition...
9863 BI.setCondition(NewSCC);
9864 BI.setSuccessor(0, FalseDest);
9865 BI.setSuccessor(1, TrueDest);
9866 RemoveFromWorkList(I);
9867 I->eraseFromParent();
9868 AddToWorkList(NewSCC);
9869 return &BI;
9870 }
9871
9872 // Cannonicalize icmp_ne -> icmp_eq
9873 ICmpInst::Predicate IPred;
9874 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
9875 TrueDest, FalseDest)))
9876 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
9877 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
9878 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
9879 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
9880 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
9881 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
9882 NewSCC->takeName(I);
9883 // Swap Destinations and condition...
9884 BI.setCondition(NewSCC);
9885 BI.setSuccessor(0, FalseDest);
9886 BI.setSuccessor(1, TrueDest);
9887 RemoveFromWorkList(I);
9888 I->eraseFromParent();;
9889 AddToWorkList(NewSCC);
9890 return &BI;
9891 }
9892
9893 return 0;
9894}
9895
9896Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
9897 Value *Cond = SI.getCondition();
9898 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
9899 if (I->getOpcode() == Instruction::Add)
9900 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
9901 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
9902 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
9903 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
9904 AddRHS));
9905 SI.setOperand(0, I->getOperand(0));
9906 AddToWorkList(I);
9907 return &SI;
9908 }
9909 }
9910 return 0;
9911}
9912
9913/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
9914/// is to leave as a vector operation.
9915static bool CheapToScalarize(Value *V, bool isConstant) {
9916 if (isa<ConstantAggregateZero>(V))
9917 return true;
9918 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
9919 if (isConstant) return true;
9920 // If all elts are the same, we can extract.
9921 Constant *Op0 = C->getOperand(0);
9922 for (unsigned i = 1; i < C->getNumOperands(); ++i)
9923 if (C->getOperand(i) != Op0)
9924 return false;
9925 return true;
9926 }
9927 Instruction *I = dyn_cast<Instruction>(V);
9928 if (!I) return false;
9929
9930 // Insert element gets simplified to the inserted element or is deleted if
9931 // this is constant idx extract element and its a constant idx insertelt.
9932 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
9933 isa<ConstantInt>(I->getOperand(2)))
9934 return true;
9935 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
9936 return true;
9937 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
9938 if (BO->hasOneUse() &&
9939 (CheapToScalarize(BO->getOperand(0), isConstant) ||
9940 CheapToScalarize(BO->getOperand(1), isConstant)))
9941 return true;
9942 if (CmpInst *CI = dyn_cast<CmpInst>(I))
9943 if (CI->hasOneUse() &&
9944 (CheapToScalarize(CI->getOperand(0), isConstant) ||
9945 CheapToScalarize(CI->getOperand(1), isConstant)))
9946 return true;
9947
9948 return false;
9949}
9950
9951/// Read and decode a shufflevector mask.
9952///
9953/// It turns undef elements into values that are larger than the number of
9954/// elements in the input.
9955static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
9956 unsigned NElts = SVI->getType()->getNumElements();
9957 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
9958 return std::vector<unsigned>(NElts, 0);
9959 if (isa<UndefValue>(SVI->getOperand(2)))
9960 return std::vector<unsigned>(NElts, 2*NElts);
9961
9962 std::vector<unsigned> Result;
9963 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
9964 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
9965 if (isa<UndefValue>(CP->getOperand(i)))
9966 Result.push_back(NElts*2); // undef -> 8
9967 else
9968 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
9969 return Result;
9970}
9971
9972/// FindScalarElement - Given a vector and an element number, see if the scalar
9973/// value is already around as a register, for example if it were inserted then
9974/// extracted from the vector.
9975static Value *FindScalarElement(Value *V, unsigned EltNo) {
9976 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
9977 const VectorType *PTy = cast<VectorType>(V->getType());
9978 unsigned Width = PTy->getNumElements();
9979 if (EltNo >= Width) // Out of range access.
9980 return UndefValue::get(PTy->getElementType());
9981
9982 if (isa<UndefValue>(V))
9983 return UndefValue::get(PTy->getElementType());
9984 else if (isa<ConstantAggregateZero>(V))
9985 return Constant::getNullValue(PTy->getElementType());
9986 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
9987 return CP->getOperand(EltNo);
9988 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
9989 // If this is an insert to a variable element, we don't know what it is.
9990 if (!isa<ConstantInt>(III->getOperand(2)))
9991 return 0;
9992 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
9993
9994 // If this is an insert to the element we are looking for, return the
9995 // inserted value.
9996 if (EltNo == IIElt)
9997 return III->getOperand(1);
9998
9999 // Otherwise, the insertelement doesn't modify the value, recurse on its
10000 // vector input.
10001 return FindScalarElement(III->getOperand(0), EltNo);
10002 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
10003 unsigned InEl = getShuffleMask(SVI)[EltNo];
10004 if (InEl < Width)
10005 return FindScalarElement(SVI->getOperand(0), InEl);
10006 else if (InEl < Width*2)
10007 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10008 else
10009 return UndefValue::get(PTy->getElementType());
10010 }
10011
10012 // Otherwise, we don't know.
10013 return 0;
10014}
10015
10016Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
10017
10018 // If vector val is undef, replace extract with scalar undef.
10019 if (isa<UndefValue>(EI.getOperand(0)))
10020 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10021
10022 // If vector val is constant 0, replace extract with scalar 0.
10023 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10024 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10025
10026 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
10027 // If vector val is constant with uniform operands, replace EI
10028 // with that operand
10029 Constant *op0 = C->getOperand(0);
10030 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10031 if (C->getOperand(i) != op0) {
10032 op0 = 0;
10033 break;
10034 }
10035 if (op0)
10036 return ReplaceInstUsesWith(EI, op0);
10037 }
10038
10039 // If extracting a specified index from the vector, see if we can recursively
10040 // find a previously computed scalar that was inserted into the vector.
10041 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10042 unsigned IndexVal = IdxC->getZExtValue();
10043 unsigned VectorWidth =
10044 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10045
10046 // If this is extracting an invalid index, turn this into undef, to avoid
10047 // crashing the code below.
10048 if (IndexVal >= VectorWidth)
10049 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10050
10051 // This instruction only demands the single element from the input vector.
10052 // If the input vector has a single use, simplify it based on this use
10053 // property.
10054 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
10055 uint64_t UndefElts;
10056 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
10057 1 << IndexVal,
10058 UndefElts)) {
10059 EI.setOperand(0, V);
10060 return &EI;
10061 }
10062 }
10063
10064 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
10065 return ReplaceInstUsesWith(EI, Elt);
10066
10067 // If the this extractelement is directly using a bitcast from a vector of
10068 // the same number of elements, see if we can find the source element from
10069 // it. In this case, we will end up needing to bitcast the scalars.
10070 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10071 if (const VectorType *VT =
10072 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10073 if (VT->getNumElements() == VectorWidth)
10074 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10075 return new BitCastInst(Elt, EI.getType());
10076 }
10077 }
10078
10079 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
10080 if (I->hasOneUse()) {
10081 // Push extractelement into predecessor operation if legal and
10082 // profitable to do so
10083 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
10084 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10085 if (CheapToScalarize(BO, isConstantElt)) {
10086 ExtractElementInst *newEI0 =
10087 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10088 EI.getName()+".lhs");
10089 ExtractElementInst *newEI1 =
10090 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10091 EI.getName()+".rhs");
10092 InsertNewInstBefore(newEI0, EI);
10093 InsertNewInstBefore(newEI1, EI);
10094 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
10095 }
10096 } else if (isa<LoadInst>(I)) {
Christopher Lambbb2f2222007-12-17 01:12:55 +000010097 unsigned AS =
10098 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +000010099 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10100 PointerType::get(EI.getType(), AS),EI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010101 GetElementPtrInst *GEP =
10102 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
10103 InsertNewInstBefore(GEP, EI);
10104 return new LoadInst(GEP);
10105 }
10106 }
10107 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10108 // Extracting the inserted element?
10109 if (IE->getOperand(2) == EI.getOperand(1))
10110 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10111 // If the inserted and extracted elements are constants, they must not
10112 // be the same value, extract from the pre-inserted value instead.
10113 if (isa<Constant>(IE->getOperand(2)) &&
10114 isa<Constant>(EI.getOperand(1))) {
10115 AddUsesToWorkList(EI);
10116 EI.setOperand(0, IE->getOperand(0));
10117 return &EI;
10118 }
10119 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10120 // If this is extracting an element from a shufflevector, figure out where
10121 // it came from and extract from the appropriate input element instead.
10122 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10123 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
10124 Value *Src;
10125 if (SrcIdx < SVI->getType()->getNumElements())
10126 Src = SVI->getOperand(0);
10127 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10128 SrcIdx -= SVI->getType()->getNumElements();
10129 Src = SVI->getOperand(1);
10130 } else {
10131 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10132 }
10133 return new ExtractElementInst(Src, SrcIdx);
10134 }
10135 }
10136 }
10137 return 0;
10138}
10139
10140/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10141/// elements from either LHS or RHS, return the shuffle mask and true.
10142/// Otherwise, return false.
10143static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10144 std::vector<Constant*> &Mask) {
10145 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10146 "Invalid CollectSingleShuffleElements");
10147 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10148
10149 if (isa<UndefValue>(V)) {
10150 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10151 return true;
10152 } else if (V == LHS) {
10153 for (unsigned i = 0; i != NumElts; ++i)
10154 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10155 return true;
10156 } else if (V == RHS) {
10157 for (unsigned i = 0; i != NumElts; ++i)
10158 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
10159 return true;
10160 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10161 // If this is an insert of an extract from some other vector, include it.
10162 Value *VecOp = IEI->getOperand(0);
10163 Value *ScalarOp = IEI->getOperand(1);
10164 Value *IdxOp = IEI->getOperand(2);
10165
10166 if (!isa<ConstantInt>(IdxOp))
10167 return false;
10168 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10169
10170 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10171 // Okay, we can handle this if the vector we are insertinting into is
10172 // transitively ok.
10173 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10174 // If so, update the mask to reflect the inserted undef.
10175 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
10176 return true;
10177 }
10178 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10179 if (isa<ConstantInt>(EI->getOperand(1)) &&
10180 EI->getOperand(0)->getType() == V->getType()) {
10181 unsigned ExtractedIdx =
10182 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10183
10184 // This must be extracting from either LHS or RHS.
10185 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10186 // Okay, we can handle this if the vector we are insertinting into is
10187 // transitively ok.
10188 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10189 // If so, update the mask to reflect the inserted value.
10190 if (EI->getOperand(0) == LHS) {
10191 Mask[InsertedIdx & (NumElts-1)] =
10192 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10193 } else {
10194 assert(EI->getOperand(0) == RHS);
10195 Mask[InsertedIdx & (NumElts-1)] =
10196 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
10197
10198 }
10199 return true;
10200 }
10201 }
10202 }
10203 }
10204 }
10205 // TODO: Handle shufflevector here!
10206
10207 return false;
10208}
10209
10210/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10211/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10212/// that computes V and the LHS value of the shuffle.
10213static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
10214 Value *&RHS) {
10215 assert(isa<VectorType>(V->getType()) &&
10216 (RHS == 0 || V->getType() == RHS->getType()) &&
10217 "Invalid shuffle!");
10218 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10219
10220 if (isa<UndefValue>(V)) {
10221 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10222 return V;
10223 } else if (isa<ConstantAggregateZero>(V)) {
10224 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
10225 return V;
10226 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10227 // If this is an insert of an extract from some other vector, include it.
10228 Value *VecOp = IEI->getOperand(0);
10229 Value *ScalarOp = IEI->getOperand(1);
10230 Value *IdxOp = IEI->getOperand(2);
10231
10232 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10233 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10234 EI->getOperand(0)->getType() == V->getType()) {
10235 unsigned ExtractedIdx =
10236 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10237 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10238
10239 // Either the extracted from or inserted into vector must be RHSVec,
10240 // otherwise we'd end up with a shuffle of three inputs.
10241 if (EI->getOperand(0) == RHS || RHS == 0) {
10242 RHS = EI->getOperand(0);
10243 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
10244 Mask[InsertedIdx & (NumElts-1)] =
10245 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
10246 return V;
10247 }
10248
10249 if (VecOp == RHS) {
10250 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
10251 // Everything but the extracted element is replaced with the RHS.
10252 for (unsigned i = 0; i != NumElts; ++i) {
10253 if (i != InsertedIdx)
10254 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
10255 }
10256 return V;
10257 }
10258
10259 // If this insertelement is a chain that comes from exactly these two
10260 // vectors, return the vector and the effective shuffle.
10261 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10262 return EI->getOperand(0);
10263
10264 }
10265 }
10266 }
10267 // TODO: Handle shufflevector here!
10268
10269 // Otherwise, can't do anything fancy. Return an identity vector.
10270 for (unsigned i = 0; i != NumElts; ++i)
10271 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10272 return V;
10273}
10274
10275Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
10276 Value *VecOp = IE.getOperand(0);
10277 Value *ScalarOp = IE.getOperand(1);
10278 Value *IdxOp = IE.getOperand(2);
10279
10280 // Inserting an undef or into an undefined place, remove this.
10281 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
10282 ReplaceInstUsesWith(IE, VecOp);
10283
10284 // If the inserted element was extracted from some other vector, and if the
10285 // indexes are constant, try to turn this into a shufflevector operation.
10286 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10287 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10288 EI->getOperand(0)->getType() == IE.getType()) {
10289 unsigned NumVectorElts = IE.getType()->getNumElements();
10290 unsigned ExtractedIdx =
10291 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10292 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10293
10294 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
10295 return ReplaceInstUsesWith(IE, VecOp);
10296
10297 if (InsertedIdx >= NumVectorElts) // Out of range insert.
10298 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
10299
10300 // If we are extracting a value from a vector, then inserting it right
10301 // back into the same place, just use the input vector.
10302 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
10303 return ReplaceInstUsesWith(IE, VecOp);
10304
10305 // We could theoretically do this for ANY input. However, doing so could
10306 // turn chains of insertelement instructions into a chain of shufflevector
10307 // instructions, and right now we do not merge shufflevectors. As such,
10308 // only do this in a situation where it is clear that there is benefit.
10309 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
10310 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
10311 // the values of VecOp, except then one read from EIOp0.
10312 // Build a new shuffle mask.
10313 std::vector<Constant*> Mask;
10314 if (isa<UndefValue>(VecOp))
10315 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
10316 else {
10317 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
10318 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
10319 NumVectorElts));
10320 }
10321 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10322 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
10323 ConstantVector::get(Mask));
10324 }
10325
10326 // If this insertelement isn't used by some other insertelement, turn it
10327 // (and any insertelements it points to), into one big shuffle.
10328 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
10329 std::vector<Constant*> Mask;
10330 Value *RHS = 0;
10331 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
10332 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
10333 // We now have a shuffle of LHS, RHS, Mask.
10334 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
10335 }
10336 }
10337 }
10338
10339 return 0;
10340}
10341
10342
10343Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
10344 Value *LHS = SVI.getOperand(0);
10345 Value *RHS = SVI.getOperand(1);
10346 std::vector<unsigned> Mask = getShuffleMask(&SVI);
10347
10348 bool MadeChange = false;
10349
10350 // Undefined shuffle mask -> undefined value.
10351 if (isa<UndefValue>(SVI.getOperand(2)))
10352 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
10353
10354 // If we have shuffle(x, undef, mask) and any elements of mask refer to
10355 // the undef, change them to undefs.
10356 if (isa<UndefValue>(SVI.getOperand(1))) {
10357 // Scan to see if there are any references to the RHS. If so, replace them
10358 // with undef element refs and set MadeChange to true.
10359 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10360 if (Mask[i] >= e && Mask[i] != 2*e) {
10361 Mask[i] = 2*e;
10362 MadeChange = true;
10363 }
10364 }
10365
10366 if (MadeChange) {
10367 // Remap any references to RHS to use LHS.
10368 std::vector<Constant*> Elts;
10369 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10370 if (Mask[i] == 2*e)
10371 Elts.push_back(UndefValue::get(Type::Int32Ty));
10372 else
10373 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10374 }
10375 SVI.setOperand(2, ConstantVector::get(Elts));
10376 }
10377 }
10378
10379 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
10380 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
10381 if (LHS == RHS || isa<UndefValue>(LHS)) {
10382 if (isa<UndefValue>(LHS) && LHS == RHS) {
10383 // shuffle(undef,undef,mask) -> undef.
10384 return ReplaceInstUsesWith(SVI, LHS);
10385 }
10386
10387 // Remap any references to RHS to use LHS.
10388 std::vector<Constant*> Elts;
10389 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10390 if (Mask[i] >= 2*e)
10391 Elts.push_back(UndefValue::get(Type::Int32Ty));
10392 else {
10393 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
10394 (Mask[i] < e && isa<UndefValue>(LHS)))
10395 Mask[i] = 2*e; // Turn into undef.
10396 else
10397 Mask[i] &= (e-1); // Force to LHS.
10398 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10399 }
10400 }
10401 SVI.setOperand(0, SVI.getOperand(1));
10402 SVI.setOperand(1, UndefValue::get(RHS->getType()));
10403 SVI.setOperand(2, ConstantVector::get(Elts));
10404 LHS = SVI.getOperand(0);
10405 RHS = SVI.getOperand(1);
10406 MadeChange = true;
10407 }
10408
10409 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
10410 bool isLHSID = true, isRHSID = true;
10411
10412 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10413 if (Mask[i] >= e*2) continue; // Ignore undef values.
10414 // Is this an identity shuffle of the LHS value?
10415 isLHSID &= (Mask[i] == i);
10416
10417 // Is this an identity shuffle of the RHS value?
10418 isRHSID &= (Mask[i]-e == i);
10419 }
10420
10421 // Eliminate identity shuffles.
10422 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
10423 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
10424
10425 // If the LHS is a shufflevector itself, see if we can combine it with this
10426 // one without producing an unusual shuffle. Here we are really conservative:
10427 // we are absolutely afraid of producing a shuffle mask not in the input
10428 // program, because the code gen may not be smart enough to turn a merged
10429 // shuffle into two specific shuffles: it may produce worse code. As such,
10430 // we only merge two shuffles if the result is one of the two input shuffle
10431 // masks. In this case, merging the shuffles just removes one instruction,
10432 // which we know is safe. This is good for things like turning:
10433 // (splat(splat)) -> splat.
10434 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
10435 if (isa<UndefValue>(RHS)) {
10436 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
10437
10438 std::vector<unsigned> NewMask;
10439 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
10440 if (Mask[i] >= 2*e)
10441 NewMask.push_back(2*e);
10442 else
10443 NewMask.push_back(LHSMask[Mask[i]]);
10444
10445 // If the result mask is equal to the src shuffle or this shuffle mask, do
10446 // the replacement.
10447 if (NewMask == LHSMask || NewMask == Mask) {
10448 std::vector<Constant*> Elts;
10449 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
10450 if (NewMask[i] >= e*2) {
10451 Elts.push_back(UndefValue::get(Type::Int32Ty));
10452 } else {
10453 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
10454 }
10455 }
10456 return new ShuffleVectorInst(LHSSVI->getOperand(0),
10457 LHSSVI->getOperand(1),
10458 ConstantVector::get(Elts));
10459 }
10460 }
10461 }
10462
10463 return MadeChange ? &SVI : 0;
10464}
10465
10466
10467
10468
10469/// TryToSinkInstruction - Try to move the specified instruction from its
10470/// current block into the beginning of DestBlock, which can only happen if it's
10471/// safe to move the instruction past all of the instructions between it and the
10472/// end of its block.
10473static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
10474 assert(I->hasOneUse() && "Invariants didn't hold!");
10475
10476 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
10477 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
10478
10479 // Do not sink alloca instructions out of the entry block.
10480 if (isa<AllocaInst>(I) && I->getParent() ==
10481 &DestBlock->getParent()->getEntryBlock())
10482 return false;
10483
10484 // We can only sink load instructions if there is nothing between the load and
10485 // the end of block that could change the value.
10486 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10487 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
10488 Scan != E; ++Scan)
10489 if (Scan->mayWriteToMemory())
10490 return false;
10491 }
10492
10493 BasicBlock::iterator InsertPos = DestBlock->begin();
10494 while (isa<PHINode>(InsertPos)) ++InsertPos;
10495
10496 I->moveBefore(InsertPos);
10497 ++NumSunkInst;
10498 return true;
10499}
10500
10501
10502/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
10503/// all reachable code to the worklist.
10504///
10505/// This has a couple of tricks to make the code faster and more powerful. In
10506/// particular, we constant fold and DCE instructions as we go, to avoid adding
10507/// them to the worklist (this significantly speeds up instcombine on code where
10508/// many instructions are dead or constant). Additionally, if we find a branch
10509/// whose condition is a known constant, we only visit the reachable successors.
10510///
10511static void AddReachableCodeToWorklist(BasicBlock *BB,
10512 SmallPtrSet<BasicBlock*, 64> &Visited,
10513 InstCombiner &IC,
10514 const TargetData *TD) {
10515 std::vector<BasicBlock*> Worklist;
10516 Worklist.push_back(BB);
10517
10518 while (!Worklist.empty()) {
10519 BB = Worklist.back();
10520 Worklist.pop_back();
10521
10522 // We have now visited this block! If we've already been here, ignore it.
10523 if (!Visited.insert(BB)) continue;
10524
10525 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
10526 Instruction *Inst = BBI++;
10527
10528 // DCE instruction if trivially dead.
10529 if (isInstructionTriviallyDead(Inst)) {
10530 ++NumDeadInst;
10531 DOUT << "IC: DCE: " << *Inst;
10532 Inst->eraseFromParent();
10533 continue;
10534 }
10535
10536 // ConstantProp instruction if trivially constant.
10537 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
10538 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
10539 Inst->replaceAllUsesWith(C);
10540 ++NumConstProp;
10541 Inst->eraseFromParent();
10542 continue;
10543 }
Chris Lattnere0f462d2007-07-20 22:06:41 +000010544
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010545 IC.AddToWorkList(Inst);
10546 }
10547
10548 // Recursively visit successors. If this is a branch or switch on a
10549 // constant, only visit the reachable successor.
10550 TerminatorInst *TI = BB->getTerminator();
10551 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
10552 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
10553 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
10554 Worklist.push_back(BI->getSuccessor(!CondVal));
10555 continue;
10556 }
10557 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
10558 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
10559 // See if this is an explicit destination.
10560 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
10561 if (SI->getCaseValue(i) == Cond) {
10562 Worklist.push_back(SI->getSuccessor(i));
10563 continue;
10564 }
10565
10566 // Otherwise it is the default destination.
10567 Worklist.push_back(SI->getSuccessor(0));
10568 continue;
10569 }
10570 }
10571
10572 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
10573 Worklist.push_back(TI->getSuccessor(i));
10574 }
10575}
10576
10577bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
10578 bool Changed = false;
10579 TD = &getAnalysis<TargetData>();
10580
10581 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
10582 << F.getNameStr() << "\n");
10583
10584 {
10585 // Do a depth-first traversal of the function, populate the worklist with
10586 // the reachable instructions. Ignore blocks that are not reachable. Keep
10587 // track of which blocks we visit.
10588 SmallPtrSet<BasicBlock*, 64> Visited;
10589 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
10590
10591 // Do a quick scan over the function. If we find any blocks that are
10592 // unreachable, remove any instructions inside of them. This prevents
10593 // the instcombine code from having to deal with some bad special cases.
10594 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
10595 if (!Visited.count(BB)) {
10596 Instruction *Term = BB->getTerminator();
10597 while (Term != BB->begin()) { // Remove instrs bottom-up
10598 BasicBlock::iterator I = Term; --I;
10599
10600 DOUT << "IC: DCE: " << *I;
10601 ++NumDeadInst;
10602
10603 if (!I->use_empty())
10604 I->replaceAllUsesWith(UndefValue::get(I->getType()));
10605 I->eraseFromParent();
10606 }
10607 }
10608 }
10609
10610 while (!Worklist.empty()) {
10611 Instruction *I = RemoveOneFromWorkList();
10612 if (I == 0) continue; // skip null values.
10613
10614 // Check to see if we can DCE the instruction.
10615 if (isInstructionTriviallyDead(I)) {
10616 // Add operands to the worklist.
10617 if (I->getNumOperands() < 4)
10618 AddUsesToWorkList(*I);
10619 ++NumDeadInst;
10620
10621 DOUT << "IC: DCE: " << *I;
10622
10623 I->eraseFromParent();
10624 RemoveFromWorkList(I);
10625 continue;
10626 }
10627
10628 // Instruction isn't dead, see if we can constant propagate it.
10629 if (Constant *C = ConstantFoldInstruction(I, TD)) {
10630 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
10631
10632 // Add operands to the worklist.
10633 AddUsesToWorkList(*I);
10634 ReplaceInstUsesWith(*I, C);
10635
10636 ++NumConstProp;
10637 I->eraseFromParent();
10638 RemoveFromWorkList(I);
10639 continue;
10640 }
10641
10642 // See if we can trivially sink this instruction to a successor basic block.
10643 if (I->hasOneUse()) {
10644 BasicBlock *BB = I->getParent();
10645 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
10646 if (UserParent != BB) {
10647 bool UserIsSuccessor = false;
10648 // See if the user is one of our successors.
10649 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
10650 if (*SI == UserParent) {
10651 UserIsSuccessor = true;
10652 break;
10653 }
10654
10655 // If the user is one of our immediate successors, and if that successor
10656 // only has us as a predecessors (we'd have to split the critical edge
10657 // otherwise), we can keep going.
10658 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
10659 next(pred_begin(UserParent)) == pred_end(UserParent))
10660 // Okay, the CFG is simple enough, try to sink this instruction.
10661 Changed |= TryToSinkInstruction(I, UserParent);
10662 }
10663 }
10664
10665 // Now that we have an instruction, try combining it to simplify it...
10666#ifndef NDEBUG
10667 std::string OrigI;
10668#endif
10669 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
10670 if (Instruction *Result = visit(*I)) {
10671 ++NumCombined;
10672 // Should we replace the old instruction with a new one?
10673 if (Result != I) {
10674 DOUT << "IC: Old = " << *I
10675 << " New = " << *Result;
10676
10677 // Everything uses the new instruction now.
10678 I->replaceAllUsesWith(Result);
10679
10680 // Push the new instruction and any users onto the worklist.
10681 AddToWorkList(Result);
10682 AddUsersToWorkList(*Result);
10683
10684 // Move the name to the new instruction first.
10685 Result->takeName(I);
10686
10687 // Insert the new instruction into the basic block...
10688 BasicBlock *InstParent = I->getParent();
10689 BasicBlock::iterator InsertPos = I;
10690
10691 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
10692 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
10693 ++InsertPos;
10694
10695 InstParent->getInstList().insert(InsertPos, Result);
10696
10697 // Make sure that we reprocess all operands now that we reduced their
10698 // use counts.
10699 AddUsesToWorkList(*I);
10700
10701 // Instructions can end up on the worklist more than once. Make sure
10702 // we do not process an instruction that has been deleted.
10703 RemoveFromWorkList(I);
10704
10705 // Erase the old instruction.
10706 InstParent->getInstList().erase(I);
10707 } else {
10708#ifndef NDEBUG
10709 DOUT << "IC: Mod = " << OrigI
10710 << " New = " << *I;
10711#endif
10712
10713 // If the instruction was modified, it's possible that it is now dead.
10714 // if so, remove it.
10715 if (isInstructionTriviallyDead(I)) {
10716 // Make sure we process all operands now that we are reducing their
10717 // use counts.
10718 AddUsesToWorkList(*I);
10719
10720 // Instructions may end up in the worklist more than once. Erase all
10721 // occurrences of this instruction.
10722 RemoveFromWorkList(I);
10723 I->eraseFromParent();
10724 } else {
10725 AddToWorkList(I);
10726 AddUsersToWorkList(*I);
10727 }
10728 }
10729 Changed = true;
10730 }
10731 }
10732
10733 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnerb933ea62007-08-05 08:47:58 +000010734
10735 // Do an explicit clear, this shrinks the map if needed.
10736 WorklistMap.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010737 return Changed;
10738}
10739
10740
10741bool InstCombiner::runOnFunction(Function &F) {
10742 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
10743
10744 bool EverMadeChange = false;
10745
10746 // Iterate while there is work to do.
10747 unsigned Iteration = 0;
10748 while (DoOneIteration(F, Iteration++))
10749 EverMadeChange = true;
10750 return EverMadeChange;
10751}
10752
10753FunctionPass *llvm::createInstructionCombiningPass() {
10754 return new InstCombiner();
10755}
10756