blob: 5ba48572a5d1c4d607f5a465969475bf0212b241 [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);
Chris Lattnerdf7e8402008-01-27 05:29:54 +0000206 Instruction *visitFPTrunc(FPTruncInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000207 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
Chris Lattner5be238b2008-01-28 00:58:18 +00002497 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2498 // This does not apply for fdiv.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002499 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner5be238b2008-01-28 00:58:18 +00002500 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2501 // the same basic block, then we replace the select with Y, and the
2502 // condition of the select with false (if the cond value is in the same BB).
2503 // If the select has uses other than the div, this allows them to be
2504 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2505 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002506 if (ST->isNullValue()) {
2507 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2508 if (CondI && CondI->getParent() == I.getParent())
2509 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2510 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2511 I.setOperand(1, SI->getOperand(2));
2512 else
2513 UpdateValueUsesWith(SI, SI->getOperand(2));
2514 return &I;
2515 }
2516
Chris Lattner5be238b2008-01-28 00:58:18 +00002517 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2518 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002519 if (ST->isNullValue()) {
2520 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2521 if (CondI && CondI->getParent() == I.getParent())
2522 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2523 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2524 I.setOperand(1, SI->getOperand(1));
2525 else
2526 UpdateValueUsesWith(SI, SI->getOperand(1));
2527 return &I;
2528 }
2529 }
2530
2531 return 0;
2532}
2533
2534/// This function implements the transforms common to both integer division
2535/// instructions (udiv and sdiv). It is called by the visitors to those integer
2536/// division instructions.
2537/// @brief Common integer divide transforms
2538Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2539 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2540
2541 if (Instruction *Common = commonDivTransforms(I))
2542 return Common;
2543
2544 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2545 // div X, 1 == X
2546 if (RHS->equalsInt(1))
2547 return ReplaceInstUsesWith(I, Op0);
2548
2549 // (X / C1) / C2 -> X / (C1*C2)
2550 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2551 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2552 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
2553 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2554 Multiply(RHS, LHSRHS));
2555 }
2556
2557 if (!RHS->isZero()) { // avoid X udiv 0
2558 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2559 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2560 return R;
2561 if (isa<PHINode>(Op0))
2562 if (Instruction *NV = FoldOpIntoPhi(I))
2563 return NV;
2564 }
2565 }
2566
2567 // 0 / X == 0, we don't need to preserve faults!
2568 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2569 if (LHS->equalsInt(0))
2570 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2571
2572 return 0;
2573}
2574
2575Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2576 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2577
2578 // Handle the integer div common cases
2579 if (Instruction *Common = commonIDivTransforms(I))
2580 return Common;
2581
2582 // X udiv C^2 -> X >> C
2583 // Check to see if this is an unsigned division with an exact power of 2,
2584 // if so, convert to a right shift.
2585 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2586 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
2587 return BinaryOperator::createLShr(Op0,
2588 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2589 }
2590
2591 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2592 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2593 if (RHSI->getOpcode() == Instruction::Shl &&
2594 isa<ConstantInt>(RHSI->getOperand(0))) {
2595 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2596 if (C1.isPowerOf2()) {
2597 Value *N = RHSI->getOperand(1);
2598 const Type *NTy = N->getType();
2599 if (uint32_t C2 = C1.logBase2()) {
2600 Constant *C2V = ConstantInt::get(NTy, C2);
2601 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
2602 }
2603 return BinaryOperator::createLShr(Op0, N);
2604 }
2605 }
2606 }
2607
2608 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2609 // where C1&C2 are powers of two.
2610 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2611 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2612 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2613 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2614 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2615 // Compute the shift amounts
2616 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2617 // Construct the "on true" case of the select
2618 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2619 Instruction *TSI = BinaryOperator::createLShr(
2620 Op0, TC, SI->getName()+".t");
2621 TSI = InsertNewInstBefore(TSI, I);
2622
2623 // Construct the "on false" case of the select
2624 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2625 Instruction *FSI = BinaryOperator::createLShr(
2626 Op0, FC, SI->getName()+".f");
2627 FSI = InsertNewInstBefore(FSI, I);
2628
2629 // construct the select instruction and return it.
2630 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2631 }
2632 }
2633 return 0;
2634}
2635
2636Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2637 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2638
2639 // Handle the integer div common cases
2640 if (Instruction *Common = commonIDivTransforms(I))
2641 return Common;
2642
2643 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2644 // sdiv X, -1 == -X
2645 if (RHS->isAllOnesValue())
2646 return BinaryOperator::createNeg(Op0);
2647
2648 // -X/C -> X/-C
2649 if (Value *LHSNeg = dyn_castNegVal(Op0))
2650 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2651 }
2652
2653 // If the sign bits of both operands are zero (i.e. we can prove they are
2654 // unsigned inputs), turn this into a udiv.
2655 if (I.getType()->isInteger()) {
2656 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2657 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmandb3dd962007-11-05 23:16:33 +00002658 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002659 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2660 }
2661 }
2662
2663 return 0;
2664}
2665
2666Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2667 return commonDivTransforms(I);
2668}
2669
2670/// GetFactor - If we can prove that the specified value is at least a multiple
2671/// of some factor, return that factor.
2672static Constant *GetFactor(Value *V) {
2673 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2674 return CI;
2675
2676 // Unless we can be tricky, we know this is a multiple of 1.
2677 Constant *Result = ConstantInt::get(V->getType(), 1);
2678
2679 Instruction *I = dyn_cast<Instruction>(V);
2680 if (!I) return Result;
2681
2682 if (I->getOpcode() == Instruction::Mul) {
2683 // Handle multiplies by a constant, etc.
2684 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2685 GetFactor(I->getOperand(1)));
2686 } else if (I->getOpcode() == Instruction::Shl) {
2687 // (X<<C) -> X * (1 << C)
2688 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2689 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2690 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2691 }
2692 } else if (I->getOpcode() == Instruction::And) {
2693 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2694 // X & 0xFFF0 is known to be a multiple of 16.
2695 uint32_t Zeros = RHS->getValue().countTrailingZeros();
Chris Lattnera03930e2007-11-23 22:35:18 +00002696 if (Zeros != V->getType()->getPrimitiveSizeInBits())// don't shift by "32"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002697 return ConstantExpr::getShl(Result,
2698 ConstantInt::get(Result->getType(), Zeros));
2699 }
2700 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2701 // Only handle int->int casts.
2702 if (!CI->isIntegerCast())
2703 return Result;
2704 Value *Op = CI->getOperand(0);
2705 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
2706 }
2707 return Result;
2708}
2709
2710/// This function implements the transforms on rem instructions that work
2711/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2712/// is used by the visitors to those instructions.
2713/// @brief Transforms common to all three rem instructions
2714Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2715 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2716
2717 // 0 % X == 0, we don't need to preserve faults!
2718 if (Constant *LHS = dyn_cast<Constant>(Op0))
2719 if (LHS->isNullValue())
2720 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2721
2722 if (isa<UndefValue>(Op0)) // undef % X -> 0
2723 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2724 if (isa<UndefValue>(Op1))
2725 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2726
2727 // Handle cases involving: rem X, (select Cond, Y, Z)
2728 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2729 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2730 // the same basic block, then we replace the select with Y, and the
2731 // condition of the select with false (if the cond value is in the same
2732 // BB). If the select has uses other than the div, this allows them to be
2733 // simplified also.
2734 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2735 if (ST->isNullValue()) {
2736 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2737 if (CondI && CondI->getParent() == I.getParent())
2738 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2739 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2740 I.setOperand(1, SI->getOperand(2));
2741 else
2742 UpdateValueUsesWith(SI, SI->getOperand(2));
2743 return &I;
2744 }
2745 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2746 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2747 if (ST->isNullValue()) {
2748 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2749 if (CondI && CondI->getParent() == I.getParent())
2750 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2751 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2752 I.setOperand(1, SI->getOperand(1));
2753 else
2754 UpdateValueUsesWith(SI, SI->getOperand(1));
2755 return &I;
2756 }
2757 }
2758
2759 return 0;
2760}
2761
2762/// This function implements the transforms common to both integer remainder
2763/// instructions (urem and srem). It is called by the visitors to those integer
2764/// remainder instructions.
2765/// @brief Common integer remainder transforms
2766Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2767 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2768
2769 if (Instruction *common = commonRemTransforms(I))
2770 return common;
2771
2772 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2773 // X % 0 == undef, we don't need to preserve faults!
2774 if (RHS->equalsInt(0))
2775 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2776
2777 if (RHS->equalsInt(1)) // X % 1 == 0
2778 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2779
2780 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2781 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2782 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2783 return R;
2784 } else if (isa<PHINode>(Op0I)) {
2785 if (Instruction *NV = FoldOpIntoPhi(I))
2786 return NV;
2787 }
2788 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2789 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
2790 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2791 }
2792 }
2793
2794 return 0;
2795}
2796
2797Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2798 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2799
2800 if (Instruction *common = commonIRemTransforms(I))
2801 return common;
2802
2803 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2804 // X urem C^2 -> X and C
2805 // Check to see if this is an unsigned remainder with an exact power of 2,
2806 // if so, convert to a bitwise and.
2807 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2808 if (C->getValue().isPowerOf2())
2809 return BinaryOperator::createAnd(Op0, SubOne(C));
2810 }
2811
2812 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2813 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2814 if (RHSI->getOpcode() == Instruction::Shl &&
2815 isa<ConstantInt>(RHSI->getOperand(0))) {
2816 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
2817 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2818 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2819 "tmp"), I);
2820 return BinaryOperator::createAnd(Op0, Add);
2821 }
2822 }
2823 }
2824
2825 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2826 // where C1&C2 are powers of two.
2827 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2828 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2829 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2830 // STO == 0 and SFO == 0 handled above.
2831 if ((STO->getValue().isPowerOf2()) &&
2832 (SFO->getValue().isPowerOf2())) {
2833 Value *TrueAnd = InsertNewInstBefore(
2834 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2835 Value *FalseAnd = InsertNewInstBefore(
2836 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2837 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2838 }
2839 }
2840 }
2841
2842 return 0;
2843}
2844
2845Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2846 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2847
Dan Gohmandb3dd962007-11-05 23:16:33 +00002848 // Handle the integer rem common cases
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002849 if (Instruction *common = commonIRemTransforms(I))
2850 return common;
2851
2852 if (Value *RHSNeg = dyn_castNegVal(Op1))
2853 if (!isa<ConstantInt>(RHSNeg) ||
2854 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
2855 // X % -Y -> X % Y
2856 AddUsesToWorkList(I);
2857 I.setOperand(1, RHSNeg);
2858 return &I;
2859 }
2860
Dan Gohmandb3dd962007-11-05 23:16:33 +00002861 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002862 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00002863 if (I.getType()->isInteger()) {
2864 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2865 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2866 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2867 return BinaryOperator::createURem(Op0, Op1, I.getName());
2868 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002869 }
2870
2871 return 0;
2872}
2873
2874Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2875 return commonRemTransforms(I);
2876}
2877
2878// isMaxValueMinusOne - return true if this is Max-1
2879static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2880 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2881 if (!isSigned)
2882 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
2883 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
2884}
2885
2886// isMinValuePlusOne - return true if this is Min+1
2887static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2888 if (!isSigned)
2889 return C->getValue() == 1; // unsigned
2890
2891 // Calculate 1111111111000000000000
2892 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2893 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
2894}
2895
2896// isOneBitSet - Return true if there is exactly one bit set in the specified
2897// constant.
2898static bool isOneBitSet(const ConstantInt *CI) {
2899 return CI->getValue().isPowerOf2();
2900}
2901
2902// isHighOnes - Return true if the constant is of the form 1+0+.
2903// This is the same as lowones(~X).
2904static bool isHighOnes(const ConstantInt *CI) {
2905 return (~CI->getValue() + 1).isPowerOf2();
2906}
2907
2908/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
2909/// are carefully arranged to allow folding of expressions such as:
2910///
2911/// (A < B) | (A > B) --> (A != B)
2912///
2913/// Note that this is only valid if the first and second predicates have the
2914/// same sign. Is illegal to do: (A u< B) | (A s> B)
2915///
2916/// Three bits are used to represent the condition, as follows:
2917/// 0 A > B
2918/// 1 A == B
2919/// 2 A < B
2920///
2921/// <=> Value Definition
2922/// 000 0 Always false
2923/// 001 1 A > B
2924/// 010 2 A == B
2925/// 011 3 A >= B
2926/// 100 4 A < B
2927/// 101 5 A != B
2928/// 110 6 A <= B
2929/// 111 7 Always true
2930///
2931static unsigned getICmpCode(const ICmpInst *ICI) {
2932 switch (ICI->getPredicate()) {
2933 // False -> 0
2934 case ICmpInst::ICMP_UGT: return 1; // 001
2935 case ICmpInst::ICMP_SGT: return 1; // 001
2936 case ICmpInst::ICMP_EQ: return 2; // 010
2937 case ICmpInst::ICMP_UGE: return 3; // 011
2938 case ICmpInst::ICMP_SGE: return 3; // 011
2939 case ICmpInst::ICMP_ULT: return 4; // 100
2940 case ICmpInst::ICMP_SLT: return 4; // 100
2941 case ICmpInst::ICMP_NE: return 5; // 101
2942 case ICmpInst::ICMP_ULE: return 6; // 110
2943 case ICmpInst::ICMP_SLE: return 6; // 110
2944 // True -> 7
2945 default:
2946 assert(0 && "Invalid ICmp predicate!");
2947 return 0;
2948 }
2949}
2950
2951/// getICmpValue - This is the complement of getICmpCode, which turns an
2952/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00002953/// new ICmp instruction. The sign is passed in to determine which kind
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002954/// of predicate to use in new icmp instructions.
2955static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
2956 switch (code) {
2957 default: assert(0 && "Illegal ICmp code!");
2958 case 0: return ConstantInt::getFalse();
2959 case 1:
2960 if (sign)
2961 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
2962 else
2963 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
2964 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
2965 case 3:
2966 if (sign)
2967 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
2968 else
2969 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
2970 case 4:
2971 if (sign)
2972 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
2973 else
2974 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
2975 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
2976 case 6:
2977 if (sign)
2978 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
2979 else
2980 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
2981 case 7: return ConstantInt::getTrue();
2982 }
2983}
2984
2985static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
2986 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
2987 (ICmpInst::isSignedPredicate(p1) &&
2988 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
2989 (ICmpInst::isSignedPredicate(p2) &&
2990 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
2991}
2992
2993namespace {
2994// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
2995struct FoldICmpLogical {
2996 InstCombiner &IC;
2997 Value *LHS, *RHS;
2998 ICmpInst::Predicate pred;
2999 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3000 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3001 pred(ICI->getPredicate()) {}
3002 bool shouldApply(Value *V) const {
3003 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3004 if (PredicatesFoldable(pred, ICI->getPredicate()))
3005 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
3006 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
3007 return false;
3008 }
3009 Instruction *apply(Instruction &Log) const {
3010 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3011 if (ICI->getOperand(0) != LHS) {
3012 assert(ICI->getOperand(1) == LHS);
3013 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3014 }
3015
3016 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3017 unsigned LHSCode = getICmpCode(ICI);
3018 unsigned RHSCode = getICmpCode(RHSICI);
3019 unsigned Code;
3020 switch (Log.getOpcode()) {
3021 case Instruction::And: Code = LHSCode & RHSCode; break;
3022 case Instruction::Or: Code = LHSCode | RHSCode; break;
3023 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3024 default: assert(0 && "Illegal logical opcode!"); return 0;
3025 }
3026
3027 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3028 ICmpInst::isSignedPredicate(ICI->getPredicate());
3029
3030 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3031 if (Instruction *I = dyn_cast<Instruction>(RV))
3032 return I;
3033 // Otherwise, it's a constant boolean value...
3034 return IC.ReplaceInstUsesWith(Log, RV);
3035 }
3036};
3037} // end anonymous namespace
3038
3039// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3040// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3041// guaranteed to be a binary operator.
3042Instruction *InstCombiner::OptAndOp(Instruction *Op,
3043 ConstantInt *OpRHS,
3044 ConstantInt *AndRHS,
3045 BinaryOperator &TheAnd) {
3046 Value *X = Op->getOperand(0);
3047 Constant *Together = 0;
3048 if (!Op->isShift())
3049 Together = And(AndRHS, OpRHS);
3050
3051 switch (Op->getOpcode()) {
3052 case Instruction::Xor:
3053 if (Op->hasOneUse()) {
3054 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3055 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
3056 InsertNewInstBefore(And, TheAnd);
3057 And->takeName(Op);
3058 return BinaryOperator::createXor(And, Together);
3059 }
3060 break;
3061 case Instruction::Or:
3062 if (Together == AndRHS) // (X | C) & C --> C
3063 return ReplaceInstUsesWith(TheAnd, AndRHS);
3064
3065 if (Op->hasOneUse() && Together != OpRHS) {
3066 // (X | C1) & C2 --> (X | (C1&C2)) & C2
3067 Instruction *Or = BinaryOperator::createOr(X, Together);
3068 InsertNewInstBefore(Or, TheAnd);
3069 Or->takeName(Op);
3070 return BinaryOperator::createAnd(Or, AndRHS);
3071 }
3072 break;
3073 case Instruction::Add:
3074 if (Op->hasOneUse()) {
3075 // Adding a one to a single bit bit-field should be turned into an XOR
3076 // of the bit. First thing to check is to see if this AND is with a
3077 // single bit constant.
3078 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3079
3080 // If there is only one bit set...
3081 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3082 // Ok, at this point, we know that we are masking the result of the
3083 // ADD down to exactly one bit. If the constant we are adding has
3084 // no bits set below this bit, then we can eliminate the ADD.
3085 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3086
3087 // Check to see if any bits below the one bit set in AndRHSV are set.
3088 if ((AddRHS & (AndRHSV-1)) == 0) {
3089 // If not, the only thing that can effect the output of the AND is
3090 // the bit specified by AndRHSV. If that bit is set, the effect of
3091 // the XOR is to toggle the bit. If it is clear, then the ADD has
3092 // no effect.
3093 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3094 TheAnd.setOperand(0, X);
3095 return &TheAnd;
3096 } else {
3097 // Pull the XOR out of the AND.
3098 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
3099 InsertNewInstBefore(NewAnd, TheAnd);
3100 NewAnd->takeName(Op);
3101 return BinaryOperator::createXor(NewAnd, AndRHS);
3102 }
3103 }
3104 }
3105 }
3106 break;
3107
3108 case Instruction::Shl: {
3109 // We know that the AND will not produce any of the bits shifted in, so if
3110 // the anded constant includes them, clear them now!
3111 //
3112 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3113 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3114 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3115 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3116
3117 if (CI->getValue() == ShlMask) {
3118 // Masking out bits that the shift already masks
3119 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3120 } else if (CI != AndRHS) { // Reducing bits set in and.
3121 TheAnd.setOperand(1, CI);
3122 return &TheAnd;
3123 }
3124 break;
3125 }
3126 case Instruction::LShr:
3127 {
3128 // We know that the AND will not produce any of the bits shifted in, so if
3129 // the anded constant includes them, clear them now! This only applies to
3130 // unsigned shifts, because a signed shr may bring in set bits!
3131 //
3132 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3133 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3134 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3135 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3136
3137 if (CI->getValue() == ShrMask) {
3138 // Masking out bits that the shift already masks.
3139 return ReplaceInstUsesWith(TheAnd, Op);
3140 } else if (CI != AndRHS) {
3141 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3142 return &TheAnd;
3143 }
3144 break;
3145 }
3146 case Instruction::AShr:
3147 // Signed shr.
3148 // See if this is shifting in some sign extension, then masking it out
3149 // with an and.
3150 if (Op->hasOneUse()) {
3151 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3152 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3153 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3154 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3155 if (C == AndRHS) { // Masking out bits shifted in.
3156 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3157 // Make the argument unsigned.
3158 Value *ShVal = Op->getOperand(0);
3159 ShVal = InsertNewInstBefore(
3160 BinaryOperator::createLShr(ShVal, OpRHS,
3161 Op->getName()), TheAnd);
3162 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
3163 }
3164 }
3165 break;
3166 }
3167 return 0;
3168}
3169
3170
3171/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3172/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3173/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3174/// whether to treat the V, Lo and HI as signed or not. IB is the location to
3175/// insert new instructions.
3176Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3177 bool isSigned, bool Inside,
3178 Instruction &IB) {
3179 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3180 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3181 "Lo is not <= Hi in range emission code!");
3182
3183 if (Inside) {
3184 if (Lo == Hi) // Trivially false.
3185 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3186
3187 // V >= Min && V < Hi --> V < Hi
3188 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3189 ICmpInst::Predicate pred = (isSigned ?
3190 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3191 return new ICmpInst(pred, V, Hi);
3192 }
3193
3194 // Emit V-Lo <u Hi-Lo
3195 Constant *NegLo = ConstantExpr::getNeg(Lo);
3196 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3197 InsertNewInstBefore(Add, IB);
3198 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3199 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3200 }
3201
3202 if (Lo == Hi) // Trivially true.
3203 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3204
3205 // V < Min || V >= Hi -> V > Hi-1
3206 Hi = SubOne(cast<ConstantInt>(Hi));
3207 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3208 ICmpInst::Predicate pred = (isSigned ?
3209 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3210 return new ICmpInst(pred, V, Hi);
3211 }
3212
3213 // Emit V-Lo >u Hi-1-Lo
3214 // Note that Hi has already had one subtracted from it, above.
3215 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3216 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3217 InsertNewInstBefore(Add, IB);
3218 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3219 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3220}
3221
3222// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3223// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3224// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3225// not, since all 1s are not contiguous.
3226static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3227 const APInt& V = Val->getValue();
3228 uint32_t BitWidth = Val->getType()->getBitWidth();
3229 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3230
3231 // look for the first zero bit after the run of ones
3232 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3233 // look for the first non-zero bit
3234 ME = V.getActiveBits();
3235 return true;
3236}
3237
3238/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3239/// where isSub determines whether the operator is a sub. If we can fold one of
3240/// the following xforms:
3241///
3242/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3243/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3244/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3245///
3246/// return (A +/- B).
3247///
3248Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3249 ConstantInt *Mask, bool isSub,
3250 Instruction &I) {
3251 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3252 if (!LHSI || LHSI->getNumOperands() != 2 ||
3253 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3254
3255 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3256
3257 switch (LHSI->getOpcode()) {
3258 default: return 0;
3259 case Instruction::And:
3260 if (And(N, Mask) == Mask) {
3261 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3262 if ((Mask->getValue().countLeadingZeros() +
3263 Mask->getValue().countPopulation()) ==
3264 Mask->getValue().getBitWidth())
3265 break;
3266
3267 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3268 // part, we don't need any explicit masks to take them out of A. If that
3269 // is all N is, ignore it.
3270 uint32_t MB = 0, ME = 0;
3271 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3272 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3273 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3274 if (MaskedValueIsZero(RHS, Mask))
3275 break;
3276 }
3277 }
3278 return 0;
3279 case Instruction::Or:
3280 case Instruction::Xor:
3281 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3282 if ((Mask->getValue().countLeadingZeros() +
3283 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3284 && And(N, Mask)->isZero())
3285 break;
3286 return 0;
3287 }
3288
3289 Instruction *New;
3290 if (isSub)
3291 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3292 else
3293 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3294 return InsertNewInstBefore(New, I);
3295}
3296
3297Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3298 bool Changed = SimplifyCommutative(I);
3299 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3300
3301 if (isa<UndefValue>(Op1)) // X & undef -> 0
3302 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3303
3304 // and X, X = X
3305 if (Op0 == Op1)
3306 return ReplaceInstUsesWith(I, Op1);
3307
3308 // See if we can simplify any instructions used by the instruction whose sole
3309 // purpose is to compute bits we don't care about.
3310 if (!isa<VectorType>(I.getType())) {
3311 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3312 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3313 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3314 KnownZero, KnownOne))
3315 return &I;
3316 } else {
3317 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3318 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
3319 return ReplaceInstUsesWith(I, I.getOperand(0));
3320 } else if (isa<ConstantAggregateZero>(Op1)) {
3321 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
3322 }
3323 }
3324
3325 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3326 const APInt& AndRHSMask = AndRHS->getValue();
3327 APInt NotAndRHS(~AndRHSMask);
3328
3329 // Optimize a variety of ((val OP C1) & C2) combinations...
3330 if (isa<BinaryOperator>(Op0)) {
3331 Instruction *Op0I = cast<Instruction>(Op0);
3332 Value *Op0LHS = Op0I->getOperand(0);
3333 Value *Op0RHS = Op0I->getOperand(1);
3334 switch (Op0I->getOpcode()) {
3335 case Instruction::Xor:
3336 case Instruction::Or:
3337 // If the mask is only needed on one incoming arm, push it up.
3338 if (Op0I->hasOneUse()) {
3339 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3340 // Not masking anything out for the LHS, move to RHS.
3341 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3342 Op0RHS->getName()+".masked");
3343 InsertNewInstBefore(NewRHS, I);
3344 return BinaryOperator::create(
3345 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3346 }
3347 if (!isa<Constant>(Op0RHS) &&
3348 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3349 // Not masking anything out for the RHS, move to LHS.
3350 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3351 Op0LHS->getName()+".masked");
3352 InsertNewInstBefore(NewLHS, I);
3353 return BinaryOperator::create(
3354 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3355 }
3356 }
3357
3358 break;
3359 case Instruction::Add:
3360 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3361 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3362 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3363 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3364 return BinaryOperator::createAnd(V, AndRHS);
3365 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3366 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
3367 break;
3368
3369 case Instruction::Sub:
3370 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3371 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3372 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3373 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3374 return BinaryOperator::createAnd(V, AndRHS);
3375 break;
3376 }
3377
3378 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3379 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3380 return Res;
3381 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3382 // If this is an integer truncation or change from signed-to-unsigned, and
3383 // if the source is an and/or with immediate, transform it. This
3384 // frequently occurs for bitfield accesses.
3385 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3386 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3387 CastOp->getNumOperands() == 2)
3388 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
3389 if (CastOp->getOpcode() == Instruction::And) {
3390 // Change: and (cast (and X, C1) to T), C2
3391 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3392 // This will fold the two constants together, which may allow
3393 // other simplifications.
3394 Instruction *NewCast = CastInst::createTruncOrBitCast(
3395 CastOp->getOperand(0), I.getType(),
3396 CastOp->getName()+".shrunk");
3397 NewCast = InsertNewInstBefore(NewCast, I);
3398 // trunc_or_bitcast(C1)&C2
3399 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3400 C3 = ConstantExpr::getAnd(C3, AndRHS);
3401 return BinaryOperator::createAnd(NewCast, C3);
3402 } else if (CastOp->getOpcode() == Instruction::Or) {
3403 // Change: and (cast (or X, C1) to T), C2
3404 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3405 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3406 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3407 return ReplaceInstUsesWith(I, AndRHS);
3408 }
3409 }
3410 }
3411
3412 // Try to fold constant and into select arguments.
3413 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3414 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3415 return R;
3416 if (isa<PHINode>(Op0))
3417 if (Instruction *NV = FoldOpIntoPhi(I))
3418 return NV;
3419 }
3420
3421 Value *Op0NotVal = dyn_castNotVal(Op0);
3422 Value *Op1NotVal = dyn_castNotVal(Op1);
3423
3424 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3425 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3426
3427 // (~A & ~B) == (~(A | B)) - De Morgan's Law
3428 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3429 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3430 I.getName()+".demorgan");
3431 InsertNewInstBefore(Or, I);
3432 return BinaryOperator::createNot(Or);
3433 }
3434
3435 {
3436 Value *A = 0, *B = 0, *C = 0, *D = 0;
3437 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3438 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3439 return ReplaceInstUsesWith(I, Op1);
3440
3441 // (A|B) & ~(A&B) -> A^B
3442 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3443 if ((A == C && B == D) || (A == D && B == C))
3444 return BinaryOperator::createXor(A, B);
3445 }
3446 }
3447
3448 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3449 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3450 return ReplaceInstUsesWith(I, Op0);
3451
3452 // ~(A&B) & (A|B) -> A^B
3453 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3454 if ((A == C && B == D) || (A == D && B == C))
3455 return BinaryOperator::createXor(A, B);
3456 }
3457 }
3458
3459 if (Op0->hasOneUse() &&
3460 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3461 if (A == Op1) { // (A^B)&A -> A&(A^B)
3462 I.swapOperands(); // Simplify below
3463 std::swap(Op0, Op1);
3464 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3465 cast<BinaryOperator>(Op0)->swapOperands();
3466 I.swapOperands(); // Simplify below
3467 std::swap(Op0, Op1);
3468 }
3469 }
3470 if (Op1->hasOneUse() &&
3471 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3472 if (B == Op0) { // B&(A^B) -> B&(B^A)
3473 cast<BinaryOperator>(Op1)->swapOperands();
3474 std::swap(A, B);
3475 }
3476 if (A == Op0) { // A&(A^B) -> A & ~B
3477 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3478 InsertNewInstBefore(NotB, I);
3479 return BinaryOperator::createAnd(A, NotB);
3480 }
3481 }
3482 }
3483
3484 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3485 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3486 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3487 return R;
3488
3489 Value *LHSVal, *RHSVal;
3490 ConstantInt *LHSCst, *RHSCst;
3491 ICmpInst::Predicate LHSCC, RHSCC;
3492 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3493 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3494 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3495 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3496 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3497 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3498 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner205ad1d2007-11-22 23:47:13 +00003499 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3500
3501 // Don't try to fold ICMP_SLT + ICMP_ULT.
3502 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3503 ICmpInst::isSignedPredicate(LHSCC) ==
3504 ICmpInst::isSignedPredicate(RHSCC))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003505 // Ensure that the larger constant is on the RHS.
Chris Lattnerda628ca2008-01-13 20:59:02 +00003506 ICmpInst::Predicate GT;
3507 if (ICmpInst::isSignedPredicate(LHSCC) ||
3508 (ICmpInst::isEquality(LHSCC) &&
3509 ICmpInst::isSignedPredicate(RHSCC)))
3510 GT = ICmpInst::ICMP_SGT;
3511 else
3512 GT = ICmpInst::ICMP_UGT;
3513
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003514 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3515 ICmpInst *LHS = cast<ICmpInst>(Op0);
3516 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3517 std::swap(LHS, RHS);
3518 std::swap(LHSCst, RHSCst);
3519 std::swap(LHSCC, RHSCC);
3520 }
3521
3522 // At this point, we know we have have two icmp instructions
3523 // comparing a value against two constants and and'ing the result
3524 // together. Because of the above check, we know that we only have
3525 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3526 // (from the FoldICmpLogical check above), that the two constants
3527 // are not equal and that the larger constant is on the RHS
3528 assert(LHSCst != RHSCst && "Compares not folded above?");
3529
3530 switch (LHSCC) {
3531 default: assert(0 && "Unknown integer condition code!");
3532 case ICmpInst::ICMP_EQ:
3533 switch (RHSCC) {
3534 default: assert(0 && "Unknown integer condition code!");
3535 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3536 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3537 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3538 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3539 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3540 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3541 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3542 return ReplaceInstUsesWith(I, LHS);
3543 }
3544 case ICmpInst::ICMP_NE:
3545 switch (RHSCC) {
3546 default: assert(0 && "Unknown integer condition code!");
3547 case ICmpInst::ICMP_ULT:
3548 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3549 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3550 break; // (X != 13 & X u< 15) -> no change
3551 case ICmpInst::ICMP_SLT:
3552 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3553 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3554 break; // (X != 13 & X s< 15) -> no change
3555 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3556 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3557 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3558 return ReplaceInstUsesWith(I, RHS);
3559 case ICmpInst::ICMP_NE:
3560 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3561 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3562 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3563 LHSVal->getName()+".off");
3564 InsertNewInstBefore(Add, I);
3565 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3566 ConstantInt::get(Add->getType(), 1));
3567 }
3568 break; // (X != 13 & X != 15) -> no change
3569 }
3570 break;
3571 case ICmpInst::ICMP_ULT:
3572 switch (RHSCC) {
3573 default: assert(0 && "Unknown integer condition code!");
3574 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3575 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3576 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3577 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3578 break;
3579 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3580 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3581 return ReplaceInstUsesWith(I, LHS);
3582 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3583 break;
3584 }
3585 break;
3586 case ICmpInst::ICMP_SLT:
3587 switch (RHSCC) {
3588 default: assert(0 && "Unknown integer condition code!");
3589 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3590 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3591 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3592 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3593 break;
3594 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3595 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3596 return ReplaceInstUsesWith(I, LHS);
3597 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3598 break;
3599 }
3600 break;
3601 case ICmpInst::ICMP_UGT:
3602 switch (RHSCC) {
3603 default: assert(0 && "Unknown integer condition code!");
3604 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3605 return ReplaceInstUsesWith(I, LHS);
3606 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3607 return ReplaceInstUsesWith(I, RHS);
3608 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3609 break;
3610 case ICmpInst::ICMP_NE:
3611 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3612 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3613 break; // (X u> 13 & X != 15) -> no change
3614 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3615 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3616 true, I);
3617 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3618 break;
3619 }
3620 break;
3621 case ICmpInst::ICMP_SGT:
3622 switch (RHSCC) {
3623 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerab0fc252007-11-16 06:04:17 +00003624 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003625 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3626 return ReplaceInstUsesWith(I, RHS);
3627 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3628 break;
3629 case ICmpInst::ICMP_NE:
3630 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3631 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3632 break; // (X s> 13 & X != 15) -> no change
3633 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3634 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3635 true, I);
3636 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3637 break;
3638 }
3639 break;
3640 }
3641 }
3642 }
3643
3644 // fold (and (cast A), (cast B)) -> (cast (and A, B))
3645 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3646 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3647 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3648 const Type *SrcTy = Op0C->getOperand(0)->getType();
3649 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3650 // Only do this if the casts both really cause code to be generated.
3651 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3652 I.getType(), TD) &&
3653 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3654 I.getType(), TD)) {
3655 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3656 Op1C->getOperand(0),
3657 I.getName());
3658 InsertNewInstBefore(NewOp, I);
3659 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3660 }
3661 }
3662
3663 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
3664 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3665 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3666 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
3667 SI0->getOperand(1) == SI1->getOperand(1) &&
3668 (SI0->hasOneUse() || SI1->hasOneUse())) {
3669 Instruction *NewOp =
3670 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3671 SI1->getOperand(0),
3672 SI0->getName()), I);
3673 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3674 SI1->getOperand(1));
3675 }
3676 }
3677
Chris Lattner91882432007-10-24 05:38:08 +00003678 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3679 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3680 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3681 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3682 RHS->getPredicate() == FCmpInst::FCMP_ORD)
3683 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3684 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3685 // If either of the constants are nans, then the whole thing returns
3686 // false.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00003687 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00003688 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3689 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3690 RHS->getOperand(0));
3691 }
3692 }
3693 }
3694
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003695 return Changed ? &I : 0;
3696}
3697
3698/// CollectBSwapParts - Look to see if the specified value defines a single byte
3699/// in the result. If it does, and if the specified byte hasn't been filled in
3700/// yet, fill it in and return false.
3701static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3702 Instruction *I = dyn_cast<Instruction>(V);
3703 if (I == 0) return true;
3704
3705 // If this is an or instruction, it is an inner node of the bswap.
3706 if (I->getOpcode() == Instruction::Or)
3707 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3708 CollectBSwapParts(I->getOperand(1), ByteValues);
3709
3710 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
3711 // If this is a shift by a constant int, and it is "24", then its operand
3712 // defines a byte. We only handle unsigned types here.
3713 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3714 // Not shifting the entire input by N-1 bytes?
3715 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
3716 8*(ByteValues.size()-1))
3717 return true;
3718
3719 unsigned DestNo;
3720 if (I->getOpcode() == Instruction::Shl) {
3721 // X << 24 defines the top byte with the lowest of the input bytes.
3722 DestNo = ByteValues.size()-1;
3723 } else {
3724 // X >>u 24 defines the low byte with the highest of the input bytes.
3725 DestNo = 0;
3726 }
3727
3728 // If the destination byte value is already defined, the values are or'd
3729 // together, which isn't a bswap (unless it's an or of the same bits).
3730 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3731 return true;
3732 ByteValues[DestNo] = I->getOperand(0);
3733 return false;
3734 }
3735
3736 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3737 // don't have this.
3738 Value *Shift = 0, *ShiftLHS = 0;
3739 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3740 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3741 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3742 return true;
3743 Instruction *SI = cast<Instruction>(Shift);
3744
3745 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3746 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3747 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
3748 return true;
3749
3750 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3751 unsigned DestByte;
3752 if (AndAmt->getValue().getActiveBits() > 64)
3753 return true;
3754 uint64_t AndAmtVal = AndAmt->getZExtValue();
3755 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3756 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
3757 break;
3758 // Unknown mask for bswap.
3759 if (DestByte == ByteValues.size()) return true;
3760
3761 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3762 unsigned SrcByte;
3763 if (SI->getOpcode() == Instruction::Shl)
3764 SrcByte = DestByte - ShiftBytes;
3765 else
3766 SrcByte = DestByte + ShiftBytes;
3767
3768 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3769 if (SrcByte != ByteValues.size()-DestByte-1)
3770 return true;
3771
3772 // If the destination byte value is already defined, the values are or'd
3773 // together, which isn't a bswap (unless it's an or of the same bits).
3774 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3775 return true;
3776 ByteValues[DestByte] = SI->getOperand(0);
3777 return false;
3778}
3779
3780/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3781/// If so, insert the new bswap intrinsic and return it.
3782Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3783 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3784 if (!ITy || ITy->getBitWidth() % 16)
3785 return 0; // Can only bswap pairs of bytes. Can't do vectors.
3786
3787 /// ByteValues - For each byte of the result, we keep track of which value
3788 /// defines each byte.
3789 SmallVector<Value*, 8> ByteValues;
3790 ByteValues.resize(ITy->getBitWidth()/8);
3791
3792 // Try to find all the pieces corresponding to the bswap.
3793 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3794 CollectBSwapParts(I.getOperand(1), ByteValues))
3795 return 0;
3796
3797 // Check to see if all of the bytes come from the same value.
3798 Value *V = ByteValues[0];
3799 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3800
3801 // Check to make sure that all of the bytes come from the same value.
3802 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3803 if (ByteValues[i] != V)
3804 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00003805 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003806 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00003807 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003808 return new CallInst(F, V);
3809}
3810
3811
3812Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3813 bool Changed = SimplifyCommutative(I);
3814 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3815
3816 if (isa<UndefValue>(Op1)) // X | undef -> -1
3817 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3818
3819 // or X, X = X
3820 if (Op0 == Op1)
3821 return ReplaceInstUsesWith(I, Op0);
3822
3823 // See if we can simplify any instructions used by the instruction whose sole
3824 // purpose is to compute bits we don't care about.
3825 if (!isa<VectorType>(I.getType())) {
3826 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3827 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3828 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3829 KnownZero, KnownOne))
3830 return &I;
3831 } else if (isa<ConstantAggregateZero>(Op1)) {
3832 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
3833 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3834 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
3835 return ReplaceInstUsesWith(I, I.getOperand(1));
3836 }
3837
3838
3839
3840 // or X, -1 == -1
3841 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3842 ConstantInt *C1 = 0; Value *X = 0;
3843 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3844 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3845 Instruction *Or = BinaryOperator::createOr(X, RHS);
3846 InsertNewInstBefore(Or, I);
3847 Or->takeName(Op0);
3848 return BinaryOperator::createAnd(Or,
3849 ConstantInt::get(RHS->getValue() | C1->getValue()));
3850 }
3851
3852 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3853 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3854 Instruction *Or = BinaryOperator::createOr(X, RHS);
3855 InsertNewInstBefore(Or, I);
3856 Or->takeName(Op0);
3857 return BinaryOperator::createXor(Or,
3858 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
3859 }
3860
3861 // Try to fold constant and into select arguments.
3862 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3863 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3864 return R;
3865 if (isa<PHINode>(Op0))
3866 if (Instruction *NV = FoldOpIntoPhi(I))
3867 return NV;
3868 }
3869
3870 Value *A = 0, *B = 0;
3871 ConstantInt *C1 = 0, *C2 = 0;
3872
3873 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3874 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3875 return ReplaceInstUsesWith(I, Op1);
3876 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3877 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3878 return ReplaceInstUsesWith(I, Op0);
3879
3880 // (A | B) | C and A | (B | C) -> bswap if possible.
3881 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
3882 if (match(Op0, m_Or(m_Value(), m_Value())) ||
3883 match(Op1, m_Or(m_Value(), m_Value())) ||
3884 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3885 match(Op1, m_Shift(m_Value(), m_Value())))) {
3886 if (Instruction *BSwap = MatchBSwap(I))
3887 return BSwap;
3888 }
3889
3890 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3891 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3892 MaskedValueIsZero(Op1, C1->getValue())) {
3893 Instruction *NOr = BinaryOperator::createOr(A, Op1);
3894 InsertNewInstBefore(NOr, I);
3895 NOr->takeName(Op0);
3896 return BinaryOperator::createXor(NOr, C1);
3897 }
3898
3899 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
3900 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3901 MaskedValueIsZero(Op0, C1->getValue())) {
3902 Instruction *NOr = BinaryOperator::createOr(A, Op0);
3903 InsertNewInstBefore(NOr, I);
3904 NOr->takeName(Op0);
3905 return BinaryOperator::createXor(NOr, C1);
3906 }
3907
3908 // (A & C)|(B & D)
3909 Value *C = 0, *D = 0;
3910 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
3911 match(Op1, m_And(m_Value(B), m_Value(D)))) {
3912 Value *V1 = 0, *V2 = 0, *V3 = 0;
3913 C1 = dyn_cast<ConstantInt>(C);
3914 C2 = dyn_cast<ConstantInt>(D);
3915 if (C1 && C2) { // (A & C1)|(B & C2)
3916 // If we have: ((V + N) & C1) | (V & C2)
3917 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
3918 // replace with V+N.
3919 if (C1->getValue() == ~C2->getValue()) {
3920 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
3921 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
3922 // Add commutes, try both ways.
3923 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
3924 return ReplaceInstUsesWith(I, A);
3925 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
3926 return ReplaceInstUsesWith(I, A);
3927 }
3928 // Or commutes, try both ways.
3929 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
3930 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
3931 // Add commutes, try both ways.
3932 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
3933 return ReplaceInstUsesWith(I, B);
3934 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
3935 return ReplaceInstUsesWith(I, B);
3936 }
3937 }
3938 V1 = 0; V2 = 0; V3 = 0;
3939 }
3940
3941 // Check to see if we have any common things being and'ed. If so, find the
3942 // terms for V1 & (V2|V3).
3943 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
3944 if (A == B) // (A & C)|(A & D) == A & (C|D)
3945 V1 = A, V2 = C, V3 = D;
3946 else if (A == D) // (A & C)|(B & A) == A & (B|C)
3947 V1 = A, V2 = B, V3 = C;
3948 else if (C == B) // (A & C)|(C & D) == C & (A|D)
3949 V1 = C, V2 = A, V3 = D;
3950 else if (C == D) // (A & C)|(B & C) == C & (A|B)
3951 V1 = C, V2 = A, V3 = B;
3952
3953 if (V1) {
3954 Value *Or =
3955 InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
3956 return BinaryOperator::createAnd(V1, Or);
3957 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003958 }
3959 }
3960
3961 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
3962 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3963 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3964 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
3965 SI0->getOperand(1) == SI1->getOperand(1) &&
3966 (SI0->hasOneUse() || SI1->hasOneUse())) {
3967 Instruction *NewOp =
3968 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
3969 SI1->getOperand(0),
3970 SI0->getName()), I);
3971 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3972 SI1->getOperand(1));
3973 }
3974 }
3975
3976 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
3977 if (A == Op1) // ~A | A == -1
3978 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3979 } else {
3980 A = 0;
3981 }
3982 // Note, A is still live here!
3983 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
3984 if (Op0 == B)
3985 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3986
3987 // (~A | ~B) == (~(A & B)) - De Morgan's Law
3988 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3989 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
3990 I.getName()+".demorgan"), I);
3991 return BinaryOperator::createNot(And);
3992 }
3993 }
3994
3995 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
3996 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
3997 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3998 return R;
3999
4000 Value *LHSVal, *RHSVal;
4001 ConstantInt *LHSCst, *RHSCst;
4002 ICmpInst::Predicate LHSCC, RHSCC;
4003 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4004 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4005 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4006 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4007 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4008 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4009 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4010 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4011 // We can't fold (ugt x, C) | (sgt x, C2).
4012 PredicatesFoldable(LHSCC, RHSCC)) {
4013 // Ensure that the larger constant is on the RHS.
4014 ICmpInst *LHS = cast<ICmpInst>(Op0);
4015 bool NeedsSwap;
4016 if (ICmpInst::isSignedPredicate(LHSCC))
4017 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4018 else
4019 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4020
4021 if (NeedsSwap) {
4022 std::swap(LHS, RHS);
4023 std::swap(LHSCst, RHSCst);
4024 std::swap(LHSCC, RHSCC);
4025 }
4026
4027 // At this point, we know we have have two icmp instructions
4028 // comparing a value against two constants and or'ing the result
4029 // together. Because of the above check, we know that we only have
4030 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4031 // FoldICmpLogical check above), that the two constants are not
4032 // equal.
4033 assert(LHSCst != RHSCst && "Compares not folded above?");
4034
4035 switch (LHSCC) {
4036 default: assert(0 && "Unknown integer condition code!");
4037 case ICmpInst::ICMP_EQ:
4038 switch (RHSCC) {
4039 default: assert(0 && "Unknown integer condition code!");
4040 case ICmpInst::ICMP_EQ:
4041 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4042 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4043 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4044 LHSVal->getName()+".off");
4045 InsertNewInstBefore(Add, I);
4046 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4047 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4048 }
4049 break; // (X == 13 | X == 15) -> no change
4050 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4051 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4052 break;
4053 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4054 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4055 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4056 return ReplaceInstUsesWith(I, RHS);
4057 }
4058 break;
4059 case ICmpInst::ICMP_NE:
4060 switch (RHSCC) {
4061 default: assert(0 && "Unknown integer condition code!");
4062 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4063 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4064 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4065 return ReplaceInstUsesWith(I, LHS);
4066 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4067 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4068 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4069 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4070 }
4071 break;
4072 case ICmpInst::ICMP_ULT:
4073 switch (RHSCC) {
4074 default: assert(0 && "Unknown integer condition code!");
4075 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4076 break;
4077 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner26376862007-11-01 02:18:41 +00004078 // If RHSCst is [us]MAXINT, it is always false. Not handling
4079 // this can cause overflow.
4080 if (RHSCst->isMaxValue(false))
4081 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004082 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4083 false, I);
4084 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4085 break;
4086 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4087 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4088 return ReplaceInstUsesWith(I, RHS);
4089 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4090 break;
4091 }
4092 break;
4093 case ICmpInst::ICMP_SLT:
4094 switch (RHSCC) {
4095 default: assert(0 && "Unknown integer condition code!");
4096 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4097 break;
4098 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner26376862007-11-01 02:18:41 +00004099 // If RHSCst is [us]MAXINT, it is always false. Not handling
4100 // this can cause overflow.
4101 if (RHSCst->isMaxValue(true))
4102 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004103 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4104 false, I);
4105 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4106 break;
4107 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4108 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4109 return ReplaceInstUsesWith(I, RHS);
4110 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4111 break;
4112 }
4113 break;
4114 case ICmpInst::ICMP_UGT:
4115 switch (RHSCC) {
4116 default: assert(0 && "Unknown integer condition code!");
4117 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4118 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4119 return ReplaceInstUsesWith(I, LHS);
4120 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4121 break;
4122 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4123 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4124 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4125 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4126 break;
4127 }
4128 break;
4129 case ICmpInst::ICMP_SGT:
4130 switch (RHSCC) {
4131 default: assert(0 && "Unknown integer condition code!");
4132 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4133 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4134 return ReplaceInstUsesWith(I, LHS);
4135 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4136 break;
4137 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4138 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4139 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4140 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4141 break;
4142 }
4143 break;
4144 }
4145 }
4146 }
4147
4148 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004149 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004150 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4151 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4152 const Type *SrcTy = Op0C->getOperand(0)->getType();
4153 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4154 // Only do this if the casts both really cause code to be generated.
4155 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4156 I.getType(), TD) &&
4157 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4158 I.getType(), TD)) {
4159 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4160 Op1C->getOperand(0),
4161 I.getName());
4162 InsertNewInstBefore(NewOp, I);
4163 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4164 }
4165 }
Chris Lattner91882432007-10-24 05:38:08 +00004166 }
4167
4168
4169 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4170 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4171 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4172 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4173 RHS->getPredicate() == FCmpInst::FCMP_UNO)
4174 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4175 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4176 // If either of the constants are nans, then the whole thing returns
4177 // true.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00004178 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00004179 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4180
4181 // Otherwise, no need to compare the two constants, compare the
4182 // rest.
4183 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4184 RHS->getOperand(0));
4185 }
4186 }
4187 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004188
4189 return Changed ? &I : 0;
4190}
4191
4192// XorSelf - Implements: X ^ X --> 0
4193struct XorSelf {
4194 Value *RHS;
4195 XorSelf(Value *rhs) : RHS(rhs) {}
4196 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4197 Instruction *apply(BinaryOperator &Xor) const {
4198 return &Xor;
4199 }
4200};
4201
4202
4203Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4204 bool Changed = SimplifyCommutative(I);
4205 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4206
4207 if (isa<UndefValue>(Op1))
4208 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4209
4210 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4211 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00004212 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004213 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4214 }
4215
4216 // See if we can simplify any instructions used by the instruction whose sole
4217 // purpose is to compute bits we don't care about.
4218 if (!isa<VectorType>(I.getType())) {
4219 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4220 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4221 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4222 KnownZero, KnownOne))
4223 return &I;
4224 } else if (isa<ConstantAggregateZero>(Op1)) {
4225 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
4226 }
4227
4228 // Is this a ~ operation?
4229 if (Value *NotOp = dyn_castNotVal(&I)) {
4230 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4231 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4232 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4233 if (Op0I->getOpcode() == Instruction::And ||
4234 Op0I->getOpcode() == Instruction::Or) {
4235 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4236 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4237 Instruction *NotY =
4238 BinaryOperator::createNot(Op0I->getOperand(1),
4239 Op0I->getOperand(1)->getName()+".not");
4240 InsertNewInstBefore(NotY, I);
4241 if (Op0I->getOpcode() == Instruction::And)
4242 return BinaryOperator::createOr(Op0NotVal, NotY);
4243 else
4244 return BinaryOperator::createAnd(Op0NotVal, NotY);
4245 }
4246 }
4247 }
4248 }
4249
4250
4251 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky1405e922007-08-06 20:04:16 +00004252 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4253 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4254 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004255 return new ICmpInst(ICI->getInversePredicate(),
4256 ICI->getOperand(0), ICI->getOperand(1));
4257
Nick Lewycky1405e922007-08-06 20:04:16 +00004258 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4259 return new FCmpInst(FCI->getInversePredicate(),
4260 FCI->getOperand(0), FCI->getOperand(1));
4261 }
4262
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004263 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4264 // ~(c-X) == X-c-1 == X+(-c-1)
4265 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4266 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4267 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4268 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4269 ConstantInt::get(I.getType(), 1));
4270 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
4271 }
4272
4273 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4274 if (Op0I->getOpcode() == Instruction::Add) {
4275 // ~(X-c) --> (-c-1)-X
4276 if (RHS->isAllOnesValue()) {
4277 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4278 return BinaryOperator::createSub(
4279 ConstantExpr::getSub(NegOp0CI,
4280 ConstantInt::get(I.getType(), 1)),
4281 Op0I->getOperand(0));
4282 } else if (RHS->getValue().isSignBit()) {
4283 // (X + C) ^ signbit -> (X + C + signbit)
4284 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4285 return BinaryOperator::createAdd(Op0I->getOperand(0), C);
4286
4287 }
4288 } else if (Op0I->getOpcode() == Instruction::Or) {
4289 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4290 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4291 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4292 // Anything in both C1 and C2 is known to be zero, remove it from
4293 // NewRHS.
4294 Constant *CommonBits = And(Op0CI, RHS);
4295 NewRHS = ConstantExpr::getAnd(NewRHS,
4296 ConstantExpr::getNot(CommonBits));
4297 AddToWorkList(Op0I);
4298 I.setOperand(0, Op0I->getOperand(0));
4299 I.setOperand(1, NewRHS);
4300 return &I;
4301 }
4302 }
4303 }
4304
4305 // Try to fold constant and into select arguments.
4306 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4307 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4308 return R;
4309 if (isa<PHINode>(Op0))
4310 if (Instruction *NV = FoldOpIntoPhi(I))
4311 return NV;
4312 }
4313
4314 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
4315 if (X == Op1)
4316 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4317
4318 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
4319 if (X == Op0)
4320 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4321
4322
4323 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4324 if (Op1I) {
4325 Value *A, *B;
4326 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4327 if (A == Op0) { // B^(B|A) == (A|B)^B
4328 Op1I->swapOperands();
4329 I.swapOperands();
4330 std::swap(Op0, Op1);
4331 } else if (B == Op0) { // B^(A|B) == (A|B)^B
4332 I.swapOperands(); // Simplified below.
4333 std::swap(Op0, Op1);
4334 }
4335 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4336 if (Op0 == A) // A^(A^B) == B
4337 return ReplaceInstUsesWith(I, B);
4338 else if (Op0 == B) // A^(B^A) == B
4339 return ReplaceInstUsesWith(I, A);
4340 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4341 if (A == Op0) { // A^(A&B) -> A^(B&A)
4342 Op1I->swapOperands();
4343 std::swap(A, B);
4344 }
4345 if (B == Op0) { // A^(B&A) -> (B&A)^A
4346 I.swapOperands(); // Simplified below.
4347 std::swap(Op0, Op1);
4348 }
4349 }
4350 }
4351
4352 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4353 if (Op0I) {
4354 Value *A, *B;
4355 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4356 if (A == Op1) // (B|A)^B == (A|B)^B
4357 std::swap(A, B);
4358 if (B == Op1) { // (A|B)^B == A & ~B
4359 Instruction *NotB =
4360 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4361 return BinaryOperator::createAnd(A, NotB);
4362 }
4363 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4364 if (Op1 == A) // (A^B)^A == B
4365 return ReplaceInstUsesWith(I, B);
4366 else if (Op1 == B) // (B^A)^A == B
4367 return ReplaceInstUsesWith(I, A);
4368 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4369 if (A == Op1) // (A&B)^A -> (B&A)^A
4370 std::swap(A, B);
4371 if (B == Op1 && // (B&A)^A == ~B & A
4372 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
4373 Instruction *N =
4374 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
4375 return BinaryOperator::createAnd(N, Op1);
4376 }
4377 }
4378 }
4379
4380 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4381 if (Op0I && Op1I && Op0I->isShift() &&
4382 Op0I->getOpcode() == Op1I->getOpcode() &&
4383 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4384 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4385 Instruction *NewOp =
4386 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4387 Op1I->getOperand(0),
4388 Op0I->getName()), I);
4389 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4390 Op1I->getOperand(1));
4391 }
4392
4393 if (Op0I && Op1I) {
4394 Value *A, *B, *C, *D;
4395 // (A & B)^(A | B) -> A ^ B
4396 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4397 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4398 if ((A == C && B == D) || (A == D && B == C))
4399 return BinaryOperator::createXor(A, B);
4400 }
4401 // (A | B)^(A & B) -> A ^ B
4402 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4403 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4404 if ((A == C && B == D) || (A == D && B == C))
4405 return BinaryOperator::createXor(A, B);
4406 }
4407
4408 // (A & B)^(C & D)
4409 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4410 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4411 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4412 // (X & Y)^(X & Y) -> (Y^Z) & X
4413 Value *X = 0, *Y = 0, *Z = 0;
4414 if (A == C)
4415 X = A, Y = B, Z = D;
4416 else if (A == D)
4417 X = A, Y = B, Z = C;
4418 else if (B == C)
4419 X = B, Y = A, Z = D;
4420 else if (B == D)
4421 X = B, Y = A, Z = C;
4422
4423 if (X) {
4424 Instruction *NewOp =
4425 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4426 return BinaryOperator::createAnd(NewOp, X);
4427 }
4428 }
4429 }
4430
4431 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4432 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4433 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4434 return R;
4435
4436 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004437 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004438 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4439 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4440 const Type *SrcTy = Op0C->getOperand(0)->getType();
4441 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4442 // Only do this if the casts both really cause code to be generated.
4443 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4444 I.getType(), TD) &&
4445 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4446 I.getType(), TD)) {
4447 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4448 Op1C->getOperand(0),
4449 I.getName());
4450 InsertNewInstBefore(NewOp, I);
4451 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4452 }
4453 }
Chris Lattner91882432007-10-24 05:38:08 +00004454 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004455 return Changed ? &I : 0;
4456}
4457
4458/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4459/// overflowed for this type.
4460static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4461 ConstantInt *In2, bool IsSigned = false) {
4462 Result = cast<ConstantInt>(Add(In1, In2));
4463
4464 if (IsSigned)
4465 if (In2->getValue().isNegative())
4466 return Result->getValue().sgt(In1->getValue());
4467 else
4468 return Result->getValue().slt(In1->getValue());
4469 else
4470 return Result->getValue().ult(In1->getValue());
4471}
4472
4473/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4474/// code necessary to compute the offset from the base pointer (without adding
4475/// in the base pointer). Return the result as a signed integer of intptr size.
4476static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4477 TargetData &TD = IC.getTargetData();
4478 gep_type_iterator GTI = gep_type_begin(GEP);
4479 const Type *IntPtrTy = TD.getIntPtrType();
4480 Value *Result = Constant::getNullValue(IntPtrTy);
4481
4482 // Build a mask for high order bits.
4483 unsigned IntPtrWidth = TD.getPointerSize()*8;
4484 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4485
4486 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4487 Value *Op = GEP->getOperand(i);
Duncan Sandsf99fdc62007-11-01 20:53:16 +00004488 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004489 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4490 if (OpC->isZero()) continue;
4491
4492 // Handle a struct index, which adds its field offset to the pointer.
4493 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4494 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4495
4496 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4497 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4498 else
4499 Result = IC.InsertNewInstBefore(
4500 BinaryOperator::createAdd(Result,
4501 ConstantInt::get(IntPtrTy, Size),
4502 GEP->getName()+".offs"), I);
4503 continue;
4504 }
4505
4506 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4507 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4508 Scale = ConstantExpr::getMul(OC, Scale);
4509 if (Constant *RC = dyn_cast<Constant>(Result))
4510 Result = ConstantExpr::getAdd(RC, Scale);
4511 else {
4512 // Emit an add instruction.
4513 Result = IC.InsertNewInstBefore(
4514 BinaryOperator::createAdd(Result, Scale,
4515 GEP->getName()+".offs"), I);
4516 }
4517 continue;
4518 }
4519 // Convert to correct type.
4520 if (Op->getType() != IntPtrTy) {
4521 if (Constant *OpC = dyn_cast<Constant>(Op))
4522 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4523 else
4524 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4525 Op->getName()+".c"), I);
4526 }
4527 if (Size != 1) {
4528 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4529 if (Constant *OpC = dyn_cast<Constant>(Op))
4530 Op = ConstantExpr::getMul(OpC, Scale);
4531 else // We'll let instcombine(mul) convert this to a shl if possible.
4532 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4533 GEP->getName()+".idx"), I);
4534 }
4535
4536 // Emit an add instruction.
4537 if (isa<Constant>(Op) && isa<Constant>(Result))
4538 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4539 cast<Constant>(Result));
4540 else
4541 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4542 GEP->getName()+".offs"), I);
4543 }
4544 return Result;
4545}
4546
4547/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4548/// else. At this point we know that the GEP is on the LHS of the comparison.
4549Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4550 ICmpInst::Predicate Cond,
4551 Instruction &I) {
4552 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4553
4554 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4555 if (isa<PointerType>(CI->getOperand(0)->getType()))
4556 RHS = CI->getOperand(0);
4557
4558 Value *PtrBase = GEPLHS->getOperand(0);
4559 if (PtrBase == RHS) {
4560 // As an optimization, we don't actually have to compute the actual value of
4561 // OFFSET if this is a icmp_eq or icmp_ne comparison, just return whether
4562 // each index is zero or not.
4563 if (Cond == ICmpInst::ICMP_EQ || Cond == ICmpInst::ICMP_NE) {
4564 Instruction *InVal = 0;
4565 gep_type_iterator GTI = gep_type_begin(GEPLHS);
4566 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i, ++GTI) {
4567 bool EmitIt = true;
4568 if (Constant *C = dyn_cast<Constant>(GEPLHS->getOperand(i))) {
4569 if (isa<UndefValue>(C)) // undef index -> undef.
4570 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
4571 if (C->isNullValue())
4572 EmitIt = false;
Duncan Sandsf99fdc62007-11-01 20:53:16 +00004573 else if (TD->getABITypeSize(GTI.getIndexedType()) == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004574 EmitIt = false; // This is indexing into a zero sized array?
4575 } else if (isa<ConstantInt>(C))
4576 return ReplaceInstUsesWith(I, // No comparison is needed here.
4577 ConstantInt::get(Type::Int1Ty,
4578 Cond == ICmpInst::ICMP_NE));
4579 }
4580
4581 if (EmitIt) {
4582 Instruction *Comp =
4583 new ICmpInst(Cond, GEPLHS->getOperand(i),
4584 Constant::getNullValue(GEPLHS->getOperand(i)->getType()));
4585 if (InVal == 0)
4586 InVal = Comp;
4587 else {
4588 InVal = InsertNewInstBefore(InVal, I);
4589 InsertNewInstBefore(Comp, I);
4590 if (Cond == ICmpInst::ICMP_NE) // True if any are unequal
4591 InVal = BinaryOperator::createOr(InVal, Comp);
4592 else // True if all are equal
4593 InVal = BinaryOperator::createAnd(InVal, Comp);
4594 }
4595 }
4596 }
4597
4598 if (InVal)
4599 return InVal;
4600 else
4601 // No comparison is needed here, all indexes = 0
4602 ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4603 Cond == ICmpInst::ICMP_EQ));
4604 }
4605
4606 // Only lower this if the icmp is the only user of the GEP or if we expect
4607 // the result to fold to a constant!
4608 if (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) {
4609 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4610 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4611 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4612 Constant::getNullValue(Offset->getType()));
4613 }
4614 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4615 // If the base pointers are different, but the indices are the same, just
4616 // compare the base pointer.
4617 if (PtrBase != GEPRHS->getOperand(0)) {
4618 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4619 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4620 GEPRHS->getOperand(0)->getType();
4621 if (IndicesTheSame)
4622 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4623 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4624 IndicesTheSame = false;
4625 break;
4626 }
4627
4628 // If all indices are the same, just compare the base pointers.
4629 if (IndicesTheSame)
4630 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4631 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4632
4633 // Otherwise, the base pointers are different and the indices are
4634 // different, bail out.
4635 return 0;
4636 }
4637
4638 // If one of the GEPs has all zero indices, recurse.
4639 bool AllZeros = true;
4640 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4641 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4642 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4643 AllZeros = false;
4644 break;
4645 }
4646 if (AllZeros)
4647 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4648 ICmpInst::getSwappedPredicate(Cond), I);
4649
4650 // If the other GEP has all zero indices, recurse.
4651 AllZeros = true;
4652 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4653 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4654 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4655 AllZeros = false;
4656 break;
4657 }
4658 if (AllZeros)
4659 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4660
4661 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4662 // If the GEPs only differ by one index, compare it.
4663 unsigned NumDifferences = 0; // Keep track of # differences.
4664 unsigned DiffOperand = 0; // The operand that differs.
4665 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4666 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4667 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4668 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4669 // Irreconcilable differences.
4670 NumDifferences = 2;
4671 break;
4672 } else {
4673 if (NumDifferences++) break;
4674 DiffOperand = i;
4675 }
4676 }
4677
4678 if (NumDifferences == 0) // SAME GEP?
4679 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky2de09a92007-09-06 02:40:25 +00004680 ConstantInt::get(Type::Int1Ty,
4681 isTrueWhenEqual(Cond)));
4682
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004683 else if (NumDifferences == 1) {
4684 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4685 Value *RHSV = GEPRHS->getOperand(DiffOperand);
4686 // Make sure we do a signed comparison here.
4687 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4688 }
4689 }
4690
4691 // Only lower this if the icmp is the only user of the GEP or if we expect
4692 // the result to fold to a constant!
4693 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4694 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4695 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4696 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4697 Value *R = EmitGEPOffset(GEPRHS, I, *this);
4698 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4699 }
4700 }
4701 return 0;
4702}
4703
4704Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4705 bool Changed = SimplifyCompare(I);
4706 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4707
4708 // Fold trivial predicates.
4709 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4710 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4711 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4712 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4713
4714 // Simplify 'fcmp pred X, X'
4715 if (Op0 == Op1) {
4716 switch (I.getPredicate()) {
4717 default: assert(0 && "Unknown predicate!");
4718 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4719 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4720 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4721 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4722 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4723 case FCmpInst::FCMP_OLT: // True if ordered and less than
4724 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4725 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4726
4727 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4728 case FCmpInst::FCMP_ULT: // True if unordered or less than
4729 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4730 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4731 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4732 I.setPredicate(FCmpInst::FCMP_UNO);
4733 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4734 return &I;
4735
4736 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4737 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4738 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4739 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4740 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4741 I.setPredicate(FCmpInst::FCMP_ORD);
4742 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4743 return &I;
4744 }
4745 }
4746
4747 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
4748 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4749
4750 // Handle fcmp with constant RHS
4751 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4752 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4753 switch (LHSI->getOpcode()) {
4754 case Instruction::PHI:
4755 if (Instruction *NV = FoldOpIntoPhi(I))
4756 return NV;
4757 break;
4758 case Instruction::Select:
4759 // If either operand of the select is a constant, we can fold the
4760 // comparison into the select arms, which will cause one to be
4761 // constant folded and the select turned into a bitwise or.
4762 Value *Op1 = 0, *Op2 = 0;
4763 if (LHSI->hasOneUse()) {
4764 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4765 // Fold the known value into the constant operand.
4766 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4767 // Insert a new FCmp of the other select operand.
4768 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4769 LHSI->getOperand(2), RHSC,
4770 I.getName()), I);
4771 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4772 // Fold the known value into the constant operand.
4773 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4774 // Insert a new FCmp of the other select operand.
4775 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4776 LHSI->getOperand(1), RHSC,
4777 I.getName()), I);
4778 }
4779 }
4780
4781 if (Op1)
4782 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4783 break;
4784 }
4785 }
4786
4787 return Changed ? &I : 0;
4788}
4789
4790Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4791 bool Changed = SimplifyCompare(I);
4792 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4793 const Type *Ty = Op0->getType();
4794
4795 // icmp X, X
4796 if (Op0 == Op1)
4797 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4798 isTrueWhenEqual(I)));
4799
4800 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
4801 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lambf78cd322007-12-18 21:32:20 +00004802
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004803 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4804 // addresses never equal each other! We already know that Op0 != Op1.
4805 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4806 isa<ConstantPointerNull>(Op0)) &&
4807 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4808 isa<ConstantPointerNull>(Op1)))
4809 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4810 !isTrueWhenEqual(I)));
4811
4812 // icmp's with boolean values can always be turned into bitwise operations
4813 if (Ty == Type::Int1Ty) {
4814 switch (I.getPredicate()) {
4815 default: assert(0 && "Invalid icmp instruction!");
4816 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
4817 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4818 InsertNewInstBefore(Xor, I);
4819 return BinaryOperator::createNot(Xor);
4820 }
4821 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
4822 return BinaryOperator::createXor(Op0, Op1);
4823
4824 case ICmpInst::ICMP_UGT:
4825 case ICmpInst::ICMP_SGT:
4826 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
4827 // FALL THROUGH
4828 case ICmpInst::ICMP_ULT:
4829 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
4830 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4831 InsertNewInstBefore(Not, I);
4832 return BinaryOperator::createAnd(Not, Op1);
4833 }
4834 case ICmpInst::ICMP_UGE:
4835 case ICmpInst::ICMP_SGE:
4836 std::swap(Op0, Op1); // Change icmp ge -> icmp le
4837 // FALL THROUGH
4838 case ICmpInst::ICMP_ULE:
4839 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
4840 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4841 InsertNewInstBefore(Not, I);
4842 return BinaryOperator::createOr(Not, Op1);
4843 }
4844 }
4845 }
4846
4847 // See if we are doing a comparison between a constant and an instruction that
4848 // can be folded into the comparison.
4849 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lambfa6b3102007-12-20 07:21:11 +00004850 Value *A, *B;
4851
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00004852 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
4853 if (I.isEquality() && CI->isNullValue() &&
4854 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
4855 // (icmp cond A B) if cond is equality
4856 return new ICmpInst(I.getPredicate(), A, B);
Owen Anderson42f61ed2007-12-28 07:42:12 +00004857 }
Christopher Lambfa6b3102007-12-20 07:21:11 +00004858
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004859 switch (I.getPredicate()) {
4860 default: break;
4861 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4862 if (CI->isMinValue(false))
4863 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4864 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4865 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4866 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4867 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4868 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
4869 if (CI->isMinValue(true))
4870 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
4871 ConstantInt::getAllOnesValue(Op0->getType()));
4872
4873 break;
4874
4875 case ICmpInst::ICMP_SLT:
4876 if (CI->isMinValue(true)) // A <s MIN -> FALSE
4877 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4878 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4879 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4880 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4881 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4882 break;
4883
4884 case ICmpInst::ICMP_UGT:
4885 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
4886 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4887 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4888 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4889 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4890 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4891
4892 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
4893 if (CI->isMaxValue(true))
4894 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
4895 ConstantInt::getNullValue(Op0->getType()));
4896 break;
4897
4898 case ICmpInst::ICMP_SGT:
4899 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
4900 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4901 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4902 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4903 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4904 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4905 break;
4906
4907 case ICmpInst::ICMP_ULE:
4908 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
4909 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4910 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4911 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4912 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4913 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4914 break;
4915
4916 case ICmpInst::ICMP_SLE:
4917 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
4918 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4919 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4920 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4921 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4922 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4923 break;
4924
4925 case ICmpInst::ICMP_UGE:
4926 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
4927 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4928 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4929 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4930 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4931 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4932 break;
4933
4934 case ICmpInst::ICMP_SGE:
4935 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
4936 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4937 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4938 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4939 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4940 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4941 break;
4942 }
4943
4944 // If we still have a icmp le or icmp ge instruction, turn it into the
4945 // appropriate icmp lt or icmp gt instruction. Since the border cases have
4946 // already been handled above, this requires little checking.
4947 //
4948 switch (I.getPredicate()) {
4949 default: break;
4950 case ICmpInst::ICMP_ULE:
4951 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
4952 case ICmpInst::ICMP_SLE:
4953 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
4954 case ICmpInst::ICMP_UGE:
4955 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
4956 case ICmpInst::ICMP_SGE:
4957 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
4958 }
4959
4960 // See if we can fold the comparison based on bits known to be zero or one
4961 // in the input. If this comparison is a normal comparison, it demands all
4962 // bits, if it is a sign bit comparison, it only demands the sign bit.
4963
4964 bool UnusedBit;
4965 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
4966
4967 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
4968 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4969 if (SimplifyDemandedBits(Op0,
4970 isSignBit ? APInt::getSignBit(BitWidth)
4971 : APInt::getAllOnesValue(BitWidth),
4972 KnownZero, KnownOne, 0))
4973 return &I;
4974
4975 // Given the known and unknown bits, compute a range that the LHS could be
4976 // in.
4977 if ((KnownOne | KnownZero) != 0) {
4978 // Compute the Min, Max and RHS values based on the known bits. For the
4979 // EQ and NE we use unsigned values.
4980 APInt Min(BitWidth, 0), Max(BitWidth, 0);
4981 const APInt& RHSVal = CI->getValue();
4982 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
4983 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4984 Max);
4985 } else {
4986 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
4987 Max);
4988 }
4989 switch (I.getPredicate()) { // LE/GE have been folded already.
4990 default: assert(0 && "Unknown icmp opcode!");
4991 case ICmpInst::ICMP_EQ:
4992 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
4993 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4994 break;
4995 case ICmpInst::ICMP_NE:
4996 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
4997 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4998 break;
4999 case ICmpInst::ICMP_ULT:
5000 if (Max.ult(RHSVal))
5001 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5002 if (Min.uge(RHSVal))
5003 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5004 break;
5005 case ICmpInst::ICMP_UGT:
5006 if (Min.ugt(RHSVal))
5007 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5008 if (Max.ule(RHSVal))
5009 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5010 break;
5011 case ICmpInst::ICMP_SLT:
5012 if (Max.slt(RHSVal))
5013 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5014 if (Min.sgt(RHSVal))
5015 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5016 break;
5017 case ICmpInst::ICMP_SGT:
5018 if (Min.sgt(RHSVal))
5019 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5020 if (Max.sle(RHSVal))
5021 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5022 break;
5023 }
5024 }
5025
5026 // Since the RHS is a ConstantInt (CI), if the left hand side is an
5027 // instruction, see if that instruction also has constants so that the
5028 // instruction can be folded into the icmp
5029 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5030 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5031 return Res;
5032 }
5033
5034 // Handle icmp with constant (but not simple integer constant) RHS
5035 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5036 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5037 switch (LHSI->getOpcode()) {
5038 case Instruction::GetElementPtr:
5039 if (RHSC->isNullValue()) {
5040 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5041 bool isAllZeros = true;
5042 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5043 if (!isa<Constant>(LHSI->getOperand(i)) ||
5044 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5045 isAllZeros = false;
5046 break;
5047 }
5048 if (isAllZeros)
5049 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5050 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5051 }
5052 break;
5053
5054 case Instruction::PHI:
5055 if (Instruction *NV = FoldOpIntoPhi(I))
5056 return NV;
5057 break;
5058 case Instruction::Select: {
5059 // If either operand of the select is a constant, we can fold the
5060 // comparison into the select arms, which will cause one to be
5061 // constant folded and the select turned into a bitwise or.
5062 Value *Op1 = 0, *Op2 = 0;
5063 if (LHSI->hasOneUse()) {
5064 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5065 // Fold the known value into the constant operand.
5066 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5067 // Insert a new ICmp of the other select operand.
5068 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5069 LHSI->getOperand(2), RHSC,
5070 I.getName()), I);
5071 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5072 // Fold the known value into the constant operand.
5073 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5074 // Insert a new ICmp of the other select operand.
5075 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5076 LHSI->getOperand(1), RHSC,
5077 I.getName()), I);
5078 }
5079 }
5080
5081 if (Op1)
5082 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5083 break;
5084 }
5085 case Instruction::Malloc:
5086 // If we have (malloc != null), and if the malloc has a single use, we
5087 // can assume it is successful and remove the malloc.
5088 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5089 AddToWorkList(LHSI);
5090 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5091 !isTrueWhenEqual(I)));
5092 }
5093 break;
5094 }
5095 }
5096
5097 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5098 if (User *GEP = dyn_castGetElementPtr(Op0))
5099 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5100 return NI;
5101 if (User *GEP = dyn_castGetElementPtr(Op1))
5102 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5103 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5104 return NI;
5105
5106 // Test to see if the operands of the icmp are casted versions of other
5107 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5108 // now.
5109 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5110 if (isa<PointerType>(Op0->getType()) &&
5111 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
5112 // We keep moving the cast from the left operand over to the right
5113 // operand, where it can often be eliminated completely.
5114 Op0 = CI->getOperand(0);
5115
5116 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5117 // so eliminate it as well.
5118 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5119 Op1 = CI2->getOperand(0);
5120
5121 // If Op1 is a constant, we can fold the cast into the constant.
5122 if (Op0->getType() != Op1->getType())
5123 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5124 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5125 } else {
5126 // Otherwise, cast the RHS right before the icmp
Chris Lattner13c2d6e2008-01-13 22:23:22 +00005127 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005128 }
5129 return new ICmpInst(I.getPredicate(), Op0, Op1);
5130 }
5131 }
5132
5133 if (isa<CastInst>(Op0)) {
5134 // Handle the special case of: icmp (cast bool to X), <cst>
5135 // This comes up when you have code like
5136 // int X = A < B;
5137 // if (X) ...
5138 // For generality, we handle any zero-extension of any operand comparison
5139 // with a constant or another cast from the same type.
5140 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5141 if (Instruction *R = visitICmpInstWithCastAndCast(I))
5142 return R;
5143 }
5144
5145 if (I.isEquality()) {
5146 Value *A, *B, *C, *D;
5147 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5148 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5149 Value *OtherVal = A == Op1 ? B : A;
5150 return new ICmpInst(I.getPredicate(), OtherVal,
5151 Constant::getNullValue(A->getType()));
5152 }
5153
5154 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5155 // A^c1 == C^c2 --> A == C^(c1^c2)
5156 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5157 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5158 if (Op1->hasOneUse()) {
5159 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
5160 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5161 return new ICmpInst(I.getPredicate(), A,
5162 InsertNewInstBefore(Xor, I));
5163 }
5164
5165 // A^B == A^D -> B == D
5166 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5167 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5168 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5169 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5170 }
5171 }
5172
5173 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5174 (A == Op0 || B == Op0)) {
5175 // A == (A^B) -> B == 0
5176 Value *OtherVal = A == Op0 ? B : A;
5177 return new ICmpInst(I.getPredicate(), OtherVal,
5178 Constant::getNullValue(A->getType()));
5179 }
5180 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5181 // (A-B) == A -> B == 0
5182 return new ICmpInst(I.getPredicate(), B,
5183 Constant::getNullValue(B->getType()));
5184 }
5185 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5186 // A == (A-B) -> B == 0
5187 return new ICmpInst(I.getPredicate(), B,
5188 Constant::getNullValue(B->getType()));
5189 }
5190
5191 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5192 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5193 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5194 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5195 Value *X = 0, *Y = 0, *Z = 0;
5196
5197 if (A == C) {
5198 X = B; Y = D; Z = A;
5199 } else if (A == D) {
5200 X = B; Y = C; Z = A;
5201 } else if (B == C) {
5202 X = A; Y = D; Z = B;
5203 } else if (B == D) {
5204 X = A; Y = C; Z = B;
5205 }
5206
5207 if (X) { // Build (X^Y) & Z
5208 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5209 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5210 I.setOperand(0, Op1);
5211 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5212 return &I;
5213 }
5214 }
5215 }
5216 return Changed ? &I : 0;
5217}
5218
5219
5220/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5221/// and CmpRHS are both known to be integer constants.
5222Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5223 ConstantInt *DivRHS) {
5224 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5225 const APInt &CmpRHSV = CmpRHS->getValue();
5226
5227 // FIXME: If the operand types don't match the type of the divide
5228 // then don't attempt this transform. The code below doesn't have the
5229 // logic to deal with a signed divide and an unsigned compare (and
5230 // vice versa). This is because (x /s C1) <s C2 produces different
5231 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5232 // (x /u C1) <u C2. Simply casting the operands and result won't
5233 // work. :( The if statement below tests that condition and bails
5234 // if it finds it.
5235 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5236 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5237 return 0;
5238 if (DivRHS->isZero())
5239 return 0; // The ProdOV computation fails on divide by zero.
5240
5241 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5242 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5243 // C2 (CI). By solving for X we can turn this into a range check
5244 // instead of computing a divide.
5245 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5246
5247 // Determine if the product overflows by seeing if the product is
5248 // not equal to the divide. Make sure we do the same kind of divide
5249 // as in the LHS instruction that we're folding.
5250 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5251 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5252
5253 // Get the ICmp opcode
5254 ICmpInst::Predicate Pred = ICI.getPredicate();
5255
5256 // Figure out the interval that is being checked. For example, a comparison
5257 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5258 // Compute this interval based on the constants involved and the signedness of
5259 // the compare/divide. This computes a half-open interval, keeping track of
5260 // whether either value in the interval overflows. After analysis each
5261 // overflow variable is set to 0 if it's corresponding bound variable is valid
5262 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5263 int LoOverflow = 0, HiOverflow = 0;
5264 ConstantInt *LoBound = 0, *HiBound = 0;
5265
5266
5267 if (!DivIsSigned) { // udiv
5268 // e.g. X/5 op 3 --> [15, 20)
5269 LoBound = Prod;
5270 HiOverflow = LoOverflow = ProdOV;
5271 if (!HiOverflow)
5272 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
5273 } else if (DivRHS->getValue().isPositive()) { // Divisor is > 0.
5274 if (CmpRHSV == 0) { // (X / pos) op 0
5275 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
5276 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5277 HiBound = DivRHS;
5278 } else if (CmpRHSV.isPositive()) { // (X / pos) op pos
5279 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5280 HiOverflow = LoOverflow = ProdOV;
5281 if (!HiOverflow)
5282 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5283 } else { // (X / pos) op neg
5284 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
5285 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5286 LoOverflow = AddWithOverflow(LoBound, Prod,
5287 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5288 HiBound = AddOne(Prod);
5289 HiOverflow = ProdOV ? -1 : 0;
5290 }
5291 } else { // Divisor is < 0.
5292 if (CmpRHSV == 0) { // (X / neg) op 0
5293 // e.g. X/-5 op 0 --> [-4, 5)
5294 LoBound = AddOne(DivRHS);
5295 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5296 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5297 HiOverflow = 1; // [INTMIN+1, overflow)
5298 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5299 }
5300 } else if (CmpRHSV.isPositive()) { // (X / neg) op pos
5301 // e.g. X/-5 op 3 --> [-19, -14)
5302 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5303 if (!LoOverflow)
5304 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5305 HiBound = AddOne(Prod);
5306 } else { // (X / neg) op neg
5307 // e.g. X/-5 op -3 --> [15, 20)
5308 LoBound = Prod;
5309 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
5310 HiBound = Subtract(Prod, DivRHS);
5311 }
5312
5313 // Dividing by a negative swaps the condition. LT <-> GT
5314 Pred = ICmpInst::getSwappedPredicate(Pred);
5315 }
5316
5317 Value *X = DivI->getOperand(0);
5318 switch (Pred) {
5319 default: assert(0 && "Unhandled icmp opcode!");
5320 case ICmpInst::ICMP_EQ:
5321 if (LoOverflow && HiOverflow)
5322 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5323 else if (HiOverflow)
5324 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5325 ICmpInst::ICMP_UGE, X, LoBound);
5326 else if (LoOverflow)
5327 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5328 ICmpInst::ICMP_ULT, X, HiBound);
5329 else
5330 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
5331 case ICmpInst::ICMP_NE:
5332 if (LoOverflow && HiOverflow)
5333 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5334 else if (HiOverflow)
5335 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5336 ICmpInst::ICMP_ULT, X, LoBound);
5337 else if (LoOverflow)
5338 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5339 ICmpInst::ICMP_UGE, X, HiBound);
5340 else
5341 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
5342 case ICmpInst::ICMP_ULT:
5343 case ICmpInst::ICMP_SLT:
5344 if (LoOverflow == +1) // Low bound is greater than input range.
5345 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5346 if (LoOverflow == -1) // Low bound is less than input range.
5347 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5348 return new ICmpInst(Pred, X, LoBound);
5349 case ICmpInst::ICMP_UGT:
5350 case ICmpInst::ICMP_SGT:
5351 if (HiOverflow == +1) // High bound greater than input range.
5352 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5353 else if (HiOverflow == -1) // High bound less than input range.
5354 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5355 if (Pred == ICmpInst::ICMP_UGT)
5356 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5357 else
5358 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5359 }
5360}
5361
5362
5363/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5364///
5365Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5366 Instruction *LHSI,
5367 ConstantInt *RHS) {
5368 const APInt &RHSV = RHS->getValue();
5369
5370 switch (LHSI->getOpcode()) {
5371 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
5372 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5373 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5374 // fold the xor.
5375 if (ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0 ||
5376 ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue()) {
5377 Value *CompareVal = LHSI->getOperand(0);
5378
5379 // If the sign bit of the XorCST is not set, there is no change to
5380 // the operation, just stop using the Xor.
5381 if (!XorCST->getValue().isNegative()) {
5382 ICI.setOperand(0, CompareVal);
5383 AddToWorkList(LHSI);
5384 return &ICI;
5385 }
5386
5387 // Was the old condition true if the operand is positive?
5388 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5389
5390 // If so, the new one isn't.
5391 isTrueIfPositive ^= true;
5392
5393 if (isTrueIfPositive)
5394 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5395 else
5396 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5397 }
5398 }
5399 break;
5400 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5401 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5402 LHSI->getOperand(0)->hasOneUse()) {
5403 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5404
5405 // If the LHS is an AND of a truncating cast, we can widen the
5406 // and/compare to be the input width without changing the value
5407 // produced, eliminating a cast.
5408 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5409 // We can do this transformation if either the AND constant does not
5410 // have its sign bit set or if it is an equality comparison.
5411 // Extending a relational comparison when we're checking the sign
5412 // bit would not work.
5413 if (Cast->hasOneUse() &&
5414 (ICI.isEquality() || AndCST->getValue().isPositive() &&
5415 RHSV.isPositive())) {
5416 uint32_t BitWidth =
5417 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5418 APInt NewCST = AndCST->getValue();
5419 NewCST.zext(BitWidth);
5420 APInt NewCI = RHSV;
5421 NewCI.zext(BitWidth);
5422 Instruction *NewAnd =
5423 BinaryOperator::createAnd(Cast->getOperand(0),
5424 ConstantInt::get(NewCST),LHSI->getName());
5425 InsertNewInstBefore(NewAnd, ICI);
5426 return new ICmpInst(ICI.getPredicate(), NewAnd,
5427 ConstantInt::get(NewCI));
5428 }
5429 }
5430
5431 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5432 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5433 // happens a LOT in code produced by the C front-end, for bitfield
5434 // access.
5435 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5436 if (Shift && !Shift->isShift())
5437 Shift = 0;
5438
5439 ConstantInt *ShAmt;
5440 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5441 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5442 const Type *AndTy = AndCST->getType(); // Type of the and.
5443
5444 // We can fold this as long as we can't shift unknown bits
5445 // into the mask. This can only happen with signed shift
5446 // rights, as they sign-extend.
5447 if (ShAmt) {
5448 bool CanFold = Shift->isLogicalShift();
5449 if (!CanFold) {
5450 // To test for the bad case of the signed shr, see if any
5451 // of the bits shifted in could be tested after the mask.
5452 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5453 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5454
5455 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5456 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5457 AndCST->getValue()) == 0)
5458 CanFold = true;
5459 }
5460
5461 if (CanFold) {
5462 Constant *NewCst;
5463 if (Shift->getOpcode() == Instruction::Shl)
5464 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5465 else
5466 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5467
5468 // Check to see if we are shifting out any of the bits being
5469 // compared.
5470 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5471 // If we shifted bits out, the fold is not going to work out.
5472 // As a special case, check to see if this means that the
5473 // result is always true or false now.
5474 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5475 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5476 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5477 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5478 } else {
5479 ICI.setOperand(1, NewCst);
5480 Constant *NewAndCST;
5481 if (Shift->getOpcode() == Instruction::Shl)
5482 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5483 else
5484 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5485 LHSI->setOperand(1, NewAndCST);
5486 LHSI->setOperand(0, Shift->getOperand(0));
5487 AddToWorkList(Shift); // Shift is dead.
5488 AddUsesToWorkList(ICI);
5489 return &ICI;
5490 }
5491 }
5492 }
5493
5494 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5495 // preferable because it allows the C<<Y expression to be hoisted out
5496 // of a loop if Y is invariant and X is not.
5497 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5498 ICI.isEquality() && !Shift->isArithmeticShift() &&
5499 isa<Instruction>(Shift->getOperand(0))) {
5500 // Compute C << Y.
5501 Value *NS;
5502 if (Shift->getOpcode() == Instruction::LShr) {
5503 NS = BinaryOperator::createShl(AndCST,
5504 Shift->getOperand(1), "tmp");
5505 } else {
5506 // Insert a logical shift.
5507 NS = BinaryOperator::createLShr(AndCST,
5508 Shift->getOperand(1), "tmp");
5509 }
5510 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5511
5512 // Compute X & (C << Y).
5513 Instruction *NewAnd =
5514 BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5515 InsertNewInstBefore(NewAnd, ICI);
5516
5517 ICI.setOperand(0, NewAnd);
5518 return &ICI;
5519 }
5520 }
5521 break;
5522
5523 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
5524 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5525 if (!ShAmt) break;
5526
5527 uint32_t TypeBits = RHSV.getBitWidth();
5528
5529 // Check that the shift amount is in range. If not, don't perform
5530 // undefined shifts. When the shift is visited it will be
5531 // simplified.
5532 if (ShAmt->uge(TypeBits))
5533 break;
5534
5535 if (ICI.isEquality()) {
5536 // If we are comparing against bits always shifted out, the
5537 // comparison cannot succeed.
5538 Constant *Comp =
5539 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5540 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5541 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5542 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5543 return ReplaceInstUsesWith(ICI, Cst);
5544 }
5545
5546 if (LHSI->hasOneUse()) {
5547 // Otherwise strength reduce the shift into an and.
5548 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5549 Constant *Mask =
5550 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5551
5552 Instruction *AndI =
5553 BinaryOperator::createAnd(LHSI->getOperand(0),
5554 Mask, LHSI->getName()+".mask");
5555 Value *And = InsertNewInstBefore(AndI, ICI);
5556 return new ICmpInst(ICI.getPredicate(), And,
5557 ConstantInt::get(RHSV.lshr(ShAmtVal)));
5558 }
5559 }
5560
5561 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5562 bool TrueIfSigned = false;
5563 if (LHSI->hasOneUse() &&
5564 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5565 // (X << 31) <s 0 --> (X&1) != 0
5566 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5567 (TypeBits-ShAmt->getZExtValue()-1));
5568 Instruction *AndI =
5569 BinaryOperator::createAnd(LHSI->getOperand(0),
5570 Mask, LHSI->getName()+".mask");
5571 Value *And = InsertNewInstBefore(AndI, ICI);
5572
5573 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5574 And, Constant::getNullValue(And->getType()));
5575 }
5576 break;
5577 }
5578
5579 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
5580 case Instruction::AShr: {
5581 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5582 if (!ShAmt) break;
5583
5584 if (ICI.isEquality()) {
5585 // Check that the shift amount is in range. If not, don't perform
5586 // undefined shifts. When the shift is visited it will be
5587 // simplified.
5588 uint32_t TypeBits = RHSV.getBitWidth();
5589 if (ShAmt->uge(TypeBits))
5590 break;
5591 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5592
5593 // If we are comparing against bits always shifted out, the
5594 // comparison cannot succeed.
5595 APInt Comp = RHSV << ShAmtVal;
5596 if (LHSI->getOpcode() == Instruction::LShr)
5597 Comp = Comp.lshr(ShAmtVal);
5598 else
5599 Comp = Comp.ashr(ShAmtVal);
5600
5601 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5602 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5603 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5604 return ReplaceInstUsesWith(ICI, Cst);
5605 }
5606
5607 if (LHSI->hasOneUse() || RHSV == 0) {
5608 // Otherwise strength reduce the shift into an and.
5609 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5610 Constant *Mask = ConstantInt::get(Val);
5611
5612 Instruction *AndI =
5613 BinaryOperator::createAnd(LHSI->getOperand(0),
5614 Mask, LHSI->getName()+".mask");
5615 Value *And = InsertNewInstBefore(AndI, ICI);
5616 return new ICmpInst(ICI.getPredicate(), And,
5617 ConstantExpr::getShl(RHS, ShAmt));
5618 }
5619 }
5620 break;
5621 }
5622
5623 case Instruction::SDiv:
5624 case Instruction::UDiv:
5625 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5626 // Fold this div into the comparison, producing a range check.
5627 // Determine, based on the divide type, what the range is being
5628 // checked. If there is an overflow on the low or high side, remember
5629 // it, otherwise compute the range [low, hi) bounding the new value.
5630 // See: InsertRangeTest above for the kinds of replacements possible.
5631 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
5632 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
5633 DivRHS))
5634 return R;
5635 break;
5636 }
5637
5638 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5639 if (ICI.isEquality()) {
5640 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5641
5642 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5643 // the second operand is a constant, simplify a bit.
5644 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
5645 switch (BO->getOpcode()) {
5646 case Instruction::SRem:
5647 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5648 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
5649 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
5650 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
5651 Instruction *NewRem =
5652 BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
5653 BO->getName());
5654 InsertNewInstBefore(NewRem, ICI);
5655 return new ICmpInst(ICI.getPredicate(), NewRem,
5656 Constant::getNullValue(BO->getType()));
5657 }
5658 }
5659 break;
5660 case Instruction::Add:
5661 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5662 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5663 if (BO->hasOneUse())
5664 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5665 Subtract(RHS, BOp1C));
5666 } else if (RHSV == 0) {
5667 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5668 // efficiently invertible, or if the add has just this one use.
5669 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5670
5671 if (Value *NegVal = dyn_castNegVal(BOp1))
5672 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
5673 else if (Value *NegVal = dyn_castNegVal(BOp0))
5674 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
5675 else if (BO->hasOneUse()) {
5676 Instruction *Neg = BinaryOperator::createNeg(BOp1);
5677 InsertNewInstBefore(Neg, ICI);
5678 Neg->takeName(BO);
5679 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
5680 }
5681 }
5682 break;
5683 case Instruction::Xor:
5684 // For the xor case, we can xor two constants together, eliminating
5685 // the explicit xor.
5686 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5687 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5688 ConstantExpr::getXor(RHS, BOC));
5689
5690 // FALLTHROUGH
5691 case Instruction::Sub:
5692 // Replace (([sub|xor] A, B) != 0) with (A != B)
5693 if (RHSV == 0)
5694 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5695 BO->getOperand(1));
5696 break;
5697
5698 case Instruction::Or:
5699 // If bits are being or'd in that are not present in the constant we
5700 // are comparing against, then the comparison could never succeed!
5701 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5702 Constant *NotCI = ConstantExpr::getNot(RHS);
5703 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5704 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5705 isICMP_NE));
5706 }
5707 break;
5708
5709 case Instruction::And:
5710 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5711 // If bits are being compared against that are and'd out, then the
5712 // comparison can never succeed!
5713 if ((RHSV & ~BOC->getValue()) != 0)
5714 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5715 isICMP_NE));
5716
5717 // If we have ((X & C) == C), turn it into ((X & C) != 0).
5718 if (RHS == BOC && RHSV.isPowerOf2())
5719 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5720 ICmpInst::ICMP_NE, LHSI,
5721 Constant::getNullValue(RHS->getType()));
5722
5723 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5724 if (isSignBit(BOC)) {
5725 Value *X = BO->getOperand(0);
5726 Constant *Zero = Constant::getNullValue(X->getType());
5727 ICmpInst::Predicate pred = isICMP_NE ?
5728 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5729 return new ICmpInst(pred, X, Zero);
5730 }
5731
5732 // ((X & ~7) == 0) --> X < 8
5733 if (RHSV == 0 && isHighOnes(BOC)) {
5734 Value *X = BO->getOperand(0);
5735 Constant *NegX = ConstantExpr::getNeg(BOC);
5736 ICmpInst::Predicate pred = isICMP_NE ?
5737 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5738 return new ICmpInst(pred, X, NegX);
5739 }
5740 }
5741 default: break;
5742 }
5743 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
5744 // Handle icmp {eq|ne} <intrinsic>, intcst.
5745 if (II->getIntrinsicID() == Intrinsic::bswap) {
5746 AddToWorkList(II);
5747 ICI.setOperand(0, II->getOperand(1));
5748 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
5749 return &ICI;
5750 }
5751 }
5752 } else { // Not a ICMP_EQ/ICMP_NE
5753 // If the LHS is a cast from an integral value of the same size,
5754 // then since we know the RHS is a constant, try to simlify.
5755 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
5756 Value *CastOp = Cast->getOperand(0);
5757 const Type *SrcTy = CastOp->getType();
5758 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
5759 if (SrcTy->isInteger() &&
5760 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5761 // If this is an unsigned comparison, try to make the comparison use
5762 // smaller constant values.
5763 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
5764 // X u< 128 => X s> -1
5765 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5766 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
5767 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
5768 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
5769 // X u> 127 => X s< 0
5770 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5771 Constant::getNullValue(SrcTy));
5772 }
5773 }
5774 }
5775 }
5776 return 0;
5777}
5778
5779/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5780/// We only handle extending casts so far.
5781///
5782Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5783 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
5784 Value *LHSCIOp = LHSCI->getOperand(0);
5785 const Type *SrcTy = LHSCIOp->getType();
5786 const Type *DestTy = LHSCI->getType();
5787 Value *RHSCIOp;
5788
5789 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
5790 // integer type is the same size as the pointer type.
5791 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
5792 getTargetData().getPointerSizeInBits() ==
5793 cast<IntegerType>(DestTy)->getBitWidth()) {
5794 Value *RHSOp = 0;
5795 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
5796 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
5797 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
5798 RHSOp = RHSC->getOperand(0);
5799 // If the pointer types don't match, insert a bitcast.
5800 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner13c2d6e2008-01-13 22:23:22 +00005801 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005802 }
5803
5804 if (RHSOp)
5805 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
5806 }
5807
5808 // The code below only handles extension cast instructions, so far.
5809 // Enforce this.
5810 if (LHSCI->getOpcode() != Instruction::ZExt &&
5811 LHSCI->getOpcode() != Instruction::SExt)
5812 return 0;
5813
5814 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5815 bool isSignedCmp = ICI.isSignedPredicate();
5816
5817 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
5818 // Not an extension from the same type?
5819 RHSCIOp = CI->getOperand(0);
5820 if (RHSCIOp->getType() != LHSCIOp->getType())
5821 return 0;
5822
5823 // If the signedness of the two compares doesn't agree (i.e. one is a sext
5824 // and the other is a zext), then we can't handle this.
5825 if (CI->getOpcode() != LHSCI->getOpcode())
5826 return 0;
5827
5828 // Likewise, if the signedness of the [sz]exts and the compare don't match,
5829 // then we can't handle this.
5830 if (isSignedExt != isSignedCmp && !ICI.isEquality())
5831 return 0;
5832
5833 // Okay, just insert a compare of the reduced operands now!
5834 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5835 }
5836
5837 // If we aren't dealing with a constant on the RHS, exit early
5838 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5839 if (!CI)
5840 return 0;
5841
5842 // Compute the constant that would happen if we truncated to SrcTy then
5843 // reextended to DestTy.
5844 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5845 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5846
5847 // If the re-extended constant didn't change...
5848 if (Res2 == CI) {
5849 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5850 // For example, we might have:
5851 // %A = sext short %X to uint
5852 // %B = icmp ugt uint %A, 1330
5853 // It is incorrect to transform this into
5854 // %B = icmp ugt short %X, 1330
5855 // because %A may have negative value.
5856 //
5857 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5858 // OR operation is EQ/NE.
5859 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
5860 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5861 else
5862 return 0;
5863 }
5864
5865 // The re-extended constant changed so the constant cannot be represented
5866 // in the shorter type. Consequently, we cannot emit a simple comparison.
5867
5868 // First, handle some easy cases. We know the result cannot be equal at this
5869 // point so handle the ICI.isEquality() cases
5870 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5871 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5872 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5873 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5874
5875 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5876 // should have been folded away previously and not enter in here.
5877 Value *Result;
5878 if (isSignedCmp) {
5879 // We're performing a signed comparison.
5880 if (cast<ConstantInt>(CI)->getValue().isNegative())
5881 Result = ConstantInt::getFalse(); // X < (small) --> false
5882 else
5883 Result = ConstantInt::getTrue(); // X < (large) --> true
5884 } else {
5885 // We're performing an unsigned comparison.
5886 if (isSignedExt) {
5887 // We're performing an unsigned comp with a sign extended value.
5888 // This is true if the input is >= 0. [aka >s -1]
5889 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
5890 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5891 NegOne, ICI.getName()), ICI);
5892 } else {
5893 // Unsigned extend & unsigned compare -> always true.
5894 Result = ConstantInt::getTrue();
5895 }
5896 }
5897
5898 // Finally, return the value computed.
5899 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5900 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5901 return ReplaceInstUsesWith(ICI, Result);
5902 } else {
5903 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5904 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5905 "ICmp should be folded!");
5906 if (Constant *CI = dyn_cast<Constant>(Result))
5907 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
5908 else
5909 return BinaryOperator::createNot(Result);
5910 }
5911}
5912
5913Instruction *InstCombiner::visitShl(BinaryOperator &I) {
5914 return commonShiftTransforms(I);
5915}
5916
5917Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
5918 return commonShiftTransforms(I);
5919}
5920
5921Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00005922 if (Instruction *R = commonShiftTransforms(I))
5923 return R;
5924
5925 Value *Op0 = I.getOperand(0);
5926
5927 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
5928 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
5929 if (CSI->isAllOnesValue())
5930 return ReplaceInstUsesWith(I, CSI);
5931
5932 // See if we can turn a signed shr into an unsigned shr.
5933 if (MaskedValueIsZero(Op0,
5934 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
5935 return BinaryOperator::createLShr(Op0, I.getOperand(1));
5936
5937 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005938}
5939
5940Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
5941 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
5942 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5943
5944 // shl X, 0 == X and shr X, 0 == X
5945 // shl 0, X == 0 and shr 0, X == 0
5946 if (Op1 == Constant::getNullValue(Op1->getType()) ||
5947 Op0 == Constant::getNullValue(Op0->getType()))
5948 return ReplaceInstUsesWith(I, Op0);
5949
5950 if (isa<UndefValue>(Op0)) {
5951 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
5952 return ReplaceInstUsesWith(I, Op0);
5953 else // undef << X -> 0, undef >>u X -> 0
5954 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5955 }
5956 if (isa<UndefValue>(Op1)) {
5957 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
5958 return ReplaceInstUsesWith(I, Op0);
5959 else // X << undef, X >>u undef -> 0
5960 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
5961 }
5962
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005963 // Try to fold constant and into select arguments.
5964 if (isa<Constant>(Op0))
5965 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
5966 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5967 return R;
5968
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005969 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
5970 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
5971 return Res;
5972 return 0;
5973}
5974
5975Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
5976 BinaryOperator &I) {
5977 bool isLeftShift = I.getOpcode() == Instruction::Shl;
5978
5979 // See if we can simplify any instructions used by the instruction whose sole
5980 // purpose is to compute bits we don't care about.
5981 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
5982 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
5983 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
5984 KnownZero, KnownOne))
5985 return &I;
5986
5987 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
5988 // of a signed value.
5989 //
5990 if (Op1->uge(TypeBits)) {
5991 if (I.getOpcode() != Instruction::AShr)
5992 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
5993 else {
5994 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
5995 return &I;
5996 }
5997 }
5998
5999 // ((X*C1) << C2) == (X * (C1 << C2))
6000 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6001 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6002 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6003 return BinaryOperator::createMul(BO->getOperand(0),
6004 ConstantExpr::getShl(BOOp, Op1));
6005
6006 // Try to fold constant and into select arguments.
6007 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6008 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6009 return R;
6010 if (isa<PHINode>(Op0))
6011 if (Instruction *NV = FoldOpIntoPhi(I))
6012 return NV;
6013
Chris Lattnerc6d1f642007-12-22 09:07:47 +00006014 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6015 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6016 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6017 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6018 // place. Don't try to do this transformation in this case. Also, we
6019 // require that the input operand is a shift-by-constant so that we have
6020 // confidence that the shifts will get folded together. We could do this
6021 // xform in more cases, but it is unlikely to be profitable.
6022 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6023 isa<ConstantInt>(TrOp->getOperand(1))) {
6024 // Okay, we'll do this xform. Make the shift of shift.
6025 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6026 Instruction *NSh = BinaryOperator::create(I.getOpcode(), TrOp, ShAmt,
6027 I.getName());
6028 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6029
6030 // For logical shifts, the truncation has the effect of making the high
6031 // part of the register be zeros. Emulate this by inserting an AND to
6032 // clear the top bits as needed. This 'and' will usually be zapped by
6033 // other xforms later if dead.
6034 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6035 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6036 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6037
6038 // The mask we constructed says what the trunc would do if occurring
6039 // between the shifts. We want to know the effect *after* the second
6040 // shift. We know that it is a logical shift by a constant, so adjust the
6041 // mask as appropriate.
6042 if (I.getOpcode() == Instruction::Shl)
6043 MaskV <<= Op1->getZExtValue();
6044 else {
6045 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6046 MaskV = MaskV.lshr(Op1->getZExtValue());
6047 }
6048
6049 Instruction *And = BinaryOperator::createAnd(NSh, ConstantInt::get(MaskV),
6050 TI->getName());
6051 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6052
6053 // Return the value truncated to the interesting size.
6054 return new TruncInst(And, I.getType());
6055 }
6056 }
6057
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006058 if (Op0->hasOneUse()) {
6059 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6060 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6061 Value *V1, *V2;
6062 ConstantInt *CC;
6063 switch (Op0BO->getOpcode()) {
6064 default: break;
6065 case Instruction::Add:
6066 case Instruction::And:
6067 case Instruction::Or:
6068 case Instruction::Xor: {
6069 // These operators commute.
6070 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
6071 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6072 match(Op0BO->getOperand(1),
6073 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6074 Instruction *YS = BinaryOperator::createShl(
6075 Op0BO->getOperand(0), Op1,
6076 Op0BO->getName());
6077 InsertNewInstBefore(YS, I); // (Y << C)
6078 Instruction *X =
6079 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
6080 Op0BO->getOperand(1)->getName());
6081 InsertNewInstBefore(X, I); // (X + (Y << C))
6082 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6083 return BinaryOperator::createAnd(X, ConstantInt::get(
6084 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6085 }
6086
6087 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
6088 Value *Op0BOOp1 = Op0BO->getOperand(1);
6089 if (isLeftShift && Op0BOOp1->hasOneUse() &&
6090 match(Op0BOOp1,
6091 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6092 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6093 V2 == Op1) {
6094 Instruction *YS = BinaryOperator::createShl(
6095 Op0BO->getOperand(0), Op1,
6096 Op0BO->getName());
6097 InsertNewInstBefore(YS, I); // (Y << C)
6098 Instruction *XM =
6099 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
6100 V1->getName()+".mask");
6101 InsertNewInstBefore(XM, I); // X & (CC << C)
6102
6103 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6104 }
6105 }
6106
6107 // FALL THROUGH.
6108 case Instruction::Sub: {
6109 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6110 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6111 match(Op0BO->getOperand(0),
6112 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6113 Instruction *YS = BinaryOperator::createShl(
6114 Op0BO->getOperand(1), Op1,
6115 Op0BO->getName());
6116 InsertNewInstBefore(YS, I); // (Y << C)
6117 Instruction *X =
6118 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
6119 Op0BO->getOperand(0)->getName());
6120 InsertNewInstBefore(X, I); // (X + (Y << C))
6121 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6122 return BinaryOperator::createAnd(X, ConstantInt::get(
6123 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6124 }
6125
6126 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
6127 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6128 match(Op0BO->getOperand(0),
6129 m_And(m_Shr(m_Value(V1), m_Value(V2)),
6130 m_ConstantInt(CC))) && V2 == Op1 &&
6131 cast<BinaryOperator>(Op0BO->getOperand(0))
6132 ->getOperand(0)->hasOneUse()) {
6133 Instruction *YS = BinaryOperator::createShl(
6134 Op0BO->getOperand(1), Op1,
6135 Op0BO->getName());
6136 InsertNewInstBefore(YS, I); // (Y << C)
6137 Instruction *XM =
6138 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
6139 V1->getName()+".mask");
6140 InsertNewInstBefore(XM, I); // X & (CC << C)
6141
6142 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
6143 }
6144
6145 break;
6146 }
6147 }
6148
6149
6150 // If the operand is an bitwise operator with a constant RHS, and the
6151 // shift is the only use, we can pull it out of the shift.
6152 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6153 bool isValid = true; // Valid only for And, Or, Xor
6154 bool highBitSet = false; // Transform if high bit of constant set?
6155
6156 switch (Op0BO->getOpcode()) {
6157 default: isValid = false; break; // Do not perform transform!
6158 case Instruction::Add:
6159 isValid = isLeftShift;
6160 break;
6161 case Instruction::Or:
6162 case Instruction::Xor:
6163 highBitSet = false;
6164 break;
6165 case Instruction::And:
6166 highBitSet = true;
6167 break;
6168 }
6169
6170 // If this is a signed shift right, and the high bit is modified
6171 // by the logical operation, do not perform the transformation.
6172 // The highBitSet boolean indicates the value of the high bit of
6173 // the constant which would cause it to be modified for this
6174 // operation.
6175 //
Chris Lattner15b76e32007-12-06 06:25:04 +00006176 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006177 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006178
6179 if (isValid) {
6180 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6181
6182 Instruction *NewShift =
6183 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
6184 InsertNewInstBefore(NewShift, I);
6185 NewShift->takeName(Op0BO);
6186
6187 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6188 NewRHS);
6189 }
6190 }
6191 }
6192 }
6193
6194 // Find out if this is a shift of a shift by a constant.
6195 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6196 if (ShiftOp && !ShiftOp->isShift())
6197 ShiftOp = 0;
6198
6199 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6200 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6201 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6202 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6203 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6204 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6205 Value *X = ShiftOp->getOperand(0);
6206
6207 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
6208 if (AmtSum > TypeBits)
6209 AmtSum = TypeBits;
6210
6211 const IntegerType *Ty = cast<IntegerType>(I.getType());
6212
6213 // Check for (X << c1) << c2 and (X >> c1) >> c2
6214 if (I.getOpcode() == ShiftOp->getOpcode()) {
6215 return BinaryOperator::create(I.getOpcode(), X,
6216 ConstantInt::get(Ty, AmtSum));
6217 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6218 I.getOpcode() == Instruction::AShr) {
6219 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
6220 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6221 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6222 I.getOpcode() == Instruction::LShr) {
6223 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6224 Instruction *Shift =
6225 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6226 InsertNewInstBefore(Shift, I);
6227
6228 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6229 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6230 }
6231
6232 // Okay, if we get here, one shift must be left, and the other shift must be
6233 // right. See if the amounts are equal.
6234 if (ShiftAmt1 == ShiftAmt2) {
6235 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6236 if (I.getOpcode() == Instruction::Shl) {
6237 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
6238 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
6239 }
6240 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6241 if (I.getOpcode() == Instruction::LShr) {
6242 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
6243 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
6244 }
6245 // We can simplify ((X << C) >>s C) into a trunc + sext.
6246 // NOTE: we could do this for any C, but that would make 'unusual' integer
6247 // types. For now, just stick to ones well-supported by the code
6248 // generators.
6249 const Type *SExtType = 0;
6250 switch (Ty->getBitWidth() - ShiftAmt1) {
6251 case 1 :
6252 case 8 :
6253 case 16 :
6254 case 32 :
6255 case 64 :
6256 case 128:
6257 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6258 break;
6259 default: break;
6260 }
6261 if (SExtType) {
6262 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6263 InsertNewInstBefore(NewTrunc, I);
6264 return new SExtInst(NewTrunc, Ty);
6265 }
6266 // Otherwise, we can't handle it yet.
6267 } else if (ShiftAmt1 < ShiftAmt2) {
6268 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
6269
6270 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6271 if (I.getOpcode() == Instruction::Shl) {
6272 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6273 ShiftOp->getOpcode() == Instruction::AShr);
6274 Instruction *Shift =
6275 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6276 InsertNewInstBefore(Shift, I);
6277
6278 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6279 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6280 }
6281
6282 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
6283 if (I.getOpcode() == Instruction::LShr) {
6284 assert(ShiftOp->getOpcode() == Instruction::Shl);
6285 Instruction *Shift =
6286 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6287 InsertNewInstBefore(Shift, I);
6288
6289 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6290 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6291 }
6292
6293 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6294 } else {
6295 assert(ShiftAmt2 < ShiftAmt1);
6296 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6297
6298 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6299 if (I.getOpcode() == Instruction::Shl) {
6300 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6301 ShiftOp->getOpcode() == Instruction::AShr);
6302 Instruction *Shift =
6303 BinaryOperator::create(ShiftOp->getOpcode(), X,
6304 ConstantInt::get(Ty, ShiftDiff));
6305 InsertNewInstBefore(Shift, I);
6306
6307 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6308 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6309 }
6310
6311 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
6312 if (I.getOpcode() == Instruction::LShr) {
6313 assert(ShiftOp->getOpcode() == Instruction::Shl);
6314 Instruction *Shift =
6315 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6316 InsertNewInstBefore(Shift, I);
6317
6318 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6319 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6320 }
6321
6322 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6323 }
6324 }
6325 return 0;
6326}
6327
6328
6329/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6330/// expression. If so, decompose it, returning some value X, such that Val is
6331/// X*Scale+Offset.
6332///
6333static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6334 int &Offset) {
6335 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6336 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6337 Offset = CI->getZExtValue();
Chris Lattnerc59171a2007-10-12 05:30:59 +00006338 Scale = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006339 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattnerc59171a2007-10-12 05:30:59 +00006340 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6341 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6342 if (I->getOpcode() == Instruction::Shl) {
6343 // This is a value scaled by '1 << the shift amt'.
6344 Scale = 1U << RHS->getZExtValue();
6345 Offset = 0;
6346 return I->getOperand(0);
6347 } else if (I->getOpcode() == Instruction::Mul) {
6348 // This value is scaled by 'RHS'.
6349 Scale = RHS->getZExtValue();
6350 Offset = 0;
6351 return I->getOperand(0);
6352 } else if (I->getOpcode() == Instruction::Add) {
6353 // We have X+C. Check to see if we really have (X*C2)+C1,
6354 // where C1 is divisible by C2.
6355 unsigned SubScale;
6356 Value *SubVal =
6357 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6358 Offset += RHS->getZExtValue();
6359 Scale = SubScale;
6360 return SubVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006361 }
6362 }
6363 }
6364
6365 // Otherwise, we can't look past this.
6366 Scale = 1;
6367 Offset = 0;
6368 return Val;
6369}
6370
6371
6372/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6373/// try to eliminate the cast by moving the type information into the alloc.
6374Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6375 AllocationInst &AI) {
6376 const PointerType *PTy = cast<PointerType>(CI.getType());
6377
6378 // Remove any uses of AI that are dead.
6379 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6380
6381 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6382 Instruction *User = cast<Instruction>(*UI++);
6383 if (isInstructionTriviallyDead(User)) {
6384 while (UI != E && *UI == User)
6385 ++UI; // If this instruction uses AI more than once, don't break UI.
6386
6387 ++NumDeadInst;
6388 DOUT << "IC: DCE: " << *User;
6389 EraseInstFromFunction(*User);
6390 }
6391 }
6392
6393 // Get the type really allocated and the type casted to.
6394 const Type *AllocElTy = AI.getAllocatedType();
6395 const Type *CastElTy = PTy->getElementType();
6396 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6397
6398 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6399 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6400 if (CastElTyAlign < AllocElTyAlign) return 0;
6401
6402 // If the allocation has multiple uses, only promote it if we are strictly
6403 // increasing the alignment of the resultant allocation. If we keep it the
6404 // same, we open the door to infinite loops of various kinds.
6405 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6406
Duncan Sandsf99fdc62007-11-01 20:53:16 +00006407 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6408 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006409 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6410
6411 // See if we can satisfy the modulus by pulling a scale out of the array
6412 // size argument.
6413 unsigned ArraySizeScale;
6414 int ArrayOffset;
6415 Value *NumElements = // See if the array size is a decomposable linear expr.
6416 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6417
6418 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6419 // do the xform.
6420 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6421 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
6422
6423 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6424 Value *Amt = 0;
6425 if (Scale == 1) {
6426 Amt = NumElements;
6427 } else {
6428 // If the allocation size is constant, form a constant mul expression
6429 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6430 if (isa<ConstantInt>(NumElements))
6431 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6432 // otherwise multiply the amount and the number of elements
6433 else if (Scale != 1) {
6434 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6435 Amt = InsertNewInstBefore(Tmp, AI);
6436 }
6437 }
6438
6439 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6440 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
6441 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6442 Amt = InsertNewInstBefore(Tmp, AI);
6443 }
6444
6445 AllocationInst *New;
6446 if (isa<MallocInst>(AI))
6447 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6448 else
6449 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6450 InsertNewInstBefore(New, AI);
6451 New->takeName(&AI);
6452
6453 // If the allocation has multiple uses, insert a cast and change all things
6454 // that used it to use the new cast. This will also hack on CI, but it will
6455 // die soon.
6456 if (!AI.hasOneUse()) {
6457 AddUsesToWorkList(AI);
6458 // New is the allocation instruction, pointer typed. AI is the original
6459 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6460 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6461 InsertNewInstBefore(NewCast, AI);
6462 AI.replaceAllUsesWith(NewCast);
6463 }
6464 return ReplaceInstUsesWith(CI, New);
6465}
6466
6467/// CanEvaluateInDifferentType - Return true if we can take the specified value
6468/// and return it as type Ty without inserting any new casts and without
6469/// changing the computed value. This is used by code that tries to decide
6470/// whether promoting or shrinking integer operations to wider or smaller types
6471/// will allow us to eliminate a truncate or extend.
6472///
6473/// This is a truncation operation if Ty is smaller than V->getType(), or an
6474/// extension operation if Ty is larger.
6475static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattneref70bb82007-08-02 06:11:14 +00006476 unsigned CastOpc, int &NumCastsRemoved) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006477 // We can always evaluate constants in another type.
6478 if (isa<ConstantInt>(V))
6479 return true;
6480
6481 Instruction *I = dyn_cast<Instruction>(V);
6482 if (!I) return false;
6483
6484 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6485
Chris Lattneref70bb82007-08-02 06:11:14 +00006486 // If this is an extension or truncate, we can often eliminate it.
6487 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6488 // If this is a cast from the destination type, we can trivially eliminate
6489 // it, and this will remove a cast overall.
6490 if (I->getOperand(0)->getType() == Ty) {
6491 // If the first operand is itself a cast, and is eliminable, do not count
6492 // this as an eliminable cast. We would prefer to eliminate those two
6493 // casts first.
6494 if (!isa<CastInst>(I->getOperand(0)))
6495 ++NumCastsRemoved;
6496 return true;
6497 }
6498 }
6499
6500 // We can't extend or shrink something that has multiple uses: doing so would
6501 // require duplicating the instruction in general, which isn't profitable.
6502 if (!I->hasOneUse()) return false;
6503
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006504 switch (I->getOpcode()) {
6505 case Instruction::Add:
6506 case Instruction::Sub:
6507 case Instruction::And:
6508 case Instruction::Or:
6509 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006510 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00006511 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6512 NumCastsRemoved) &&
6513 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6514 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006515
Nick Lewyckyc52646a2008-01-22 05:08:48 +00006516 case Instruction::Mul:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00006517 // A multiply can be truncated by truncating its operands.
6518 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
6519 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6520 NumCastsRemoved) &&
6521 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6522 NumCastsRemoved);
6523
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006524 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006525 // If we are truncating the result of this SHL, and if it's a shift of a
6526 // constant amount, we can always perform a SHL in a smaller type.
6527 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6528 uint32_t BitWidth = Ty->getBitWidth();
6529 if (BitWidth < OrigTy->getBitWidth() &&
6530 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00006531 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6532 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006533 }
6534 break;
6535 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006536 // If this is a truncate of a logical shr, we can truncate it to a smaller
6537 // lshr iff we know that the bits we would otherwise be shifting in are
6538 // already zeros.
6539 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6540 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6541 uint32_t BitWidth = Ty->getBitWidth();
6542 if (BitWidth < OrigBitWidth &&
6543 MaskedValueIsZero(I->getOperand(0),
6544 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6545 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00006546 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6547 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006548 }
6549 }
6550 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006551 case Instruction::ZExt:
6552 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00006553 case Instruction::Trunc:
6554 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00006555 // can safely replace it. Note that replacing it does not reduce the number
6556 // of casts in the input.
6557 if (I->getOpcode() == CastOpc)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006558 return true;
Chris Lattner2799b2f2007-09-10 23:46:29 +00006559
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006560 break;
6561 default:
6562 // TODO: Can handle more cases here.
6563 break;
6564 }
6565
6566 return false;
6567}
6568
6569/// EvaluateInDifferentType - Given an expression that
6570/// CanEvaluateInDifferentType returns true for, actually insert the code to
6571/// evaluate the expression.
6572Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
6573 bool isSigned) {
6574 if (Constant *C = dyn_cast<Constant>(V))
6575 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
6576
6577 // Otherwise, it must be an instruction.
6578 Instruction *I = cast<Instruction>(V);
6579 Instruction *Res = 0;
6580 switch (I->getOpcode()) {
6581 case Instruction::Add:
6582 case Instruction::Sub:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00006583 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006584 case Instruction::And:
6585 case Instruction::Or:
6586 case Instruction::Xor:
6587 case Instruction::AShr:
6588 case Instruction::LShr:
6589 case Instruction::Shl: {
6590 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
6591 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6592 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6593 LHS, RHS, I->getName());
6594 break;
6595 }
6596 case Instruction::Trunc:
6597 case Instruction::ZExt:
6598 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006599 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00006600 // just return the source. There's no need to insert it because it is not
6601 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006602 if (I->getOperand(0)->getType() == Ty)
6603 return I->getOperand(0);
6604
Chris Lattneref70bb82007-08-02 06:11:14 +00006605 // Otherwise, must be the same type of case, so just reinsert a new one.
6606 Res = CastInst::create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
6607 Ty, I->getName());
6608 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006609 default:
6610 // TODO: Can handle more cases here.
6611 assert(0 && "Unreachable!");
6612 break;
6613 }
6614
6615 return InsertNewInstBefore(Res, *I);
6616}
6617
6618/// @brief Implement the transforms common to all CastInst visitors.
6619Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
6620 Value *Src = CI.getOperand(0);
6621
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006622 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
6623 // eliminate it now.
6624 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
6625 if (Instruction::CastOps opc =
6626 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6627 // The first cast (CSrc) is eliminable so we need to fix up or replace
6628 // the second cast (CI). CSrc will then have a good chance of being dead.
6629 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
6630 }
6631 }
6632
6633 // If we are casting a select then fold the cast into the select
6634 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6635 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6636 return NV;
6637
6638 // If we are casting a PHI then fold the cast into the PHI
6639 if (isa<PHINode>(Src))
6640 if (Instruction *NV = FoldOpIntoPhi(CI))
6641 return NV;
6642
6643 return 0;
6644}
6645
6646/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
6647Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
6648 Value *Src = CI.getOperand(0);
6649
6650 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
6651 // If casting the result of a getelementptr instruction with no offset, turn
6652 // this into a cast of the original pointer!
6653 if (GEP->hasAllZeroIndices()) {
6654 // Changing the cast operand is usually not a good idea but it is safe
6655 // here because the pointer operand is being replaced with another
6656 // pointer operand so the opcode doesn't need to change.
6657 AddToWorkList(GEP);
6658 CI.setOperand(0, GEP->getOperand(0));
6659 return &CI;
6660 }
6661
6662 // If the GEP has a single use, and the base pointer is a bitcast, and the
6663 // GEP computes a constant offset, see if we can convert these three
6664 // instructions into fewer. This typically happens with unions and other
6665 // non-type-safe code.
6666 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
6667 if (GEP->hasAllConstantIndices()) {
6668 // We are guaranteed to get a constant from EmitGEPOffset.
6669 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
6670 int64_t Offset = OffsetV->getSExtValue();
6671
6672 // Get the base pointer input of the bitcast, and the type it points to.
6673 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
6674 const Type *GEPIdxTy =
6675 cast<PointerType>(OrigBase->getType())->getElementType();
6676 if (GEPIdxTy->isSized()) {
6677 SmallVector<Value*, 8> NewIndices;
6678
6679 // Start with the index over the outer type. Note that the type size
6680 // might be zero (even if the offset isn't zero) if the indexed type
6681 // is something like [0 x {int, int}]
6682 const Type *IntPtrTy = TD->getIntPtrType();
6683 int64_t FirstIdx = 0;
Duncan Sandsf99fdc62007-11-01 20:53:16 +00006684 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006685 FirstIdx = Offset/TySize;
6686 Offset %= TySize;
6687
6688 // Handle silly modulus not returning values values [0..TySize).
6689 if (Offset < 0) {
6690 --FirstIdx;
6691 Offset += TySize;
6692 assert(Offset >= 0);
6693 }
6694 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
6695 }
6696
6697 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
6698
6699 // Index into the types. If we fail, set OrigBase to null.
6700 while (Offset) {
6701 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
6702 const StructLayout *SL = TD->getStructLayout(STy);
6703 if (Offset < (int64_t)SL->getSizeInBytes()) {
6704 unsigned Elt = SL->getElementContainingOffset(Offset);
6705 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
6706
6707 Offset -= SL->getElementOffset(Elt);
6708 GEPIdxTy = STy->getElementType(Elt);
6709 } else {
6710 // Otherwise, we can't index into this, bail out.
6711 Offset = 0;
6712 OrigBase = 0;
6713 }
6714 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
6715 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sandsf99fdc62007-11-01 20:53:16 +00006716 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006717 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
6718 Offset %= EltSize;
6719 } else {
6720 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
6721 }
6722 GEPIdxTy = STy->getElementType();
6723 } else {
6724 // Otherwise, we can't index into this, bail out.
6725 Offset = 0;
6726 OrigBase = 0;
6727 }
6728 }
6729 if (OrigBase) {
6730 // If we were able to index down into an element, create the GEP
6731 // and bitcast the result. This eliminates one bitcast, potentially
6732 // two.
David Greene393be882007-09-04 15:46:09 +00006733 Instruction *NGEP = new GetElementPtrInst(OrigBase,
6734 NewIndices.begin(),
6735 NewIndices.end(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006736 InsertNewInstBefore(NGEP, CI);
6737 NGEP->takeName(GEP);
6738
6739 if (isa<BitCastInst>(CI))
6740 return new BitCastInst(NGEP, CI.getType());
6741 assert(isa<PtrToIntInst>(CI));
6742 return new PtrToIntInst(NGEP, CI.getType());
6743 }
6744 }
6745 }
6746 }
6747 }
6748
6749 return commonCastTransforms(CI);
6750}
6751
6752
6753
6754/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6755/// integer types. This function implements the common transforms for all those
6756/// cases.
6757/// @brief Implement the transforms common to CastInst with integer operands
6758Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6759 if (Instruction *Result = commonCastTransforms(CI))
6760 return Result;
6761
6762 Value *Src = CI.getOperand(0);
6763 const Type *SrcTy = Src->getType();
6764 const Type *DestTy = CI.getType();
6765 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6766 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
6767
6768 // See if we can simplify any instructions used by the LHS whose sole
6769 // purpose is to compute bits we don't care about.
6770 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6771 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
6772 KnownZero, KnownOne))
6773 return &CI;
6774
6775 // If the source isn't an instruction or has more than one use then we
6776 // can't do anything more.
6777 Instruction *SrcI = dyn_cast<Instruction>(Src);
6778 if (!SrcI || !Src->hasOneUse())
6779 return 0;
6780
6781 // Attempt to propagate the cast into the instruction for int->int casts.
6782 int NumCastsRemoved = 0;
6783 if (!isa<BitCastInst>(CI) &&
6784 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattneref70bb82007-08-02 06:11:14 +00006785 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006786 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00006787 // eliminates the cast, so it is always a win. If this is a zero-extension,
6788 // we need to do an AND to maintain the clear top-part of the computation,
6789 // so we require that the input have eliminated at least one cast. If this
6790 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006791 // require that two casts have been eliminated.
6792 bool DoXForm;
6793 switch (CI.getOpcode()) {
6794 default:
6795 // All the others use floating point so we shouldn't actually
6796 // get here because of the check above.
6797 assert(0 && "Unknown cast type");
6798 case Instruction::Trunc:
6799 DoXForm = true;
6800 break;
6801 case Instruction::ZExt:
6802 DoXForm = NumCastsRemoved >= 1;
6803 break;
6804 case Instruction::SExt:
6805 DoXForm = NumCastsRemoved >= 2;
6806 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006807 }
6808
6809 if (DoXForm) {
6810 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6811 CI.getOpcode() == Instruction::SExt);
6812 assert(Res->getType() == DestTy);
6813 switch (CI.getOpcode()) {
6814 default: assert(0 && "Unknown cast type!");
6815 case Instruction::Trunc:
6816 case Instruction::BitCast:
6817 // Just replace this cast with the result.
6818 return ReplaceInstUsesWith(CI, Res);
6819 case Instruction::ZExt: {
6820 // We need to emit an AND to clear the high bits.
6821 assert(SrcBitSize < DestBitSize && "Not a zext?");
6822 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
6823 SrcBitSize));
6824 return BinaryOperator::createAnd(Res, C);
6825 }
6826 case Instruction::SExt:
6827 // We need to emit a cast to truncate, then a cast to sext.
6828 return CastInst::create(Instruction::SExt,
6829 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6830 CI), DestTy);
6831 }
6832 }
6833 }
6834
6835 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6836 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6837
6838 switch (SrcI->getOpcode()) {
6839 case Instruction::Add:
6840 case Instruction::Mul:
6841 case Instruction::And:
6842 case Instruction::Or:
6843 case Instruction::Xor:
6844 // If we are discarding information, rewrite.
6845 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6846 // Don't insert two casts if they cannot be eliminated. We allow
6847 // two casts to be inserted if the sizes are the same. This could
6848 // only be converting signedness, which is a noop.
6849 if (DestBitSize == SrcBitSize ||
6850 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6851 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6852 Instruction::CastOps opcode = CI.getOpcode();
6853 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6854 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6855 return BinaryOperator::create(
6856 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6857 }
6858 }
6859
6860 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6861 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6862 SrcI->getOpcode() == Instruction::Xor &&
6863 Op1 == ConstantInt::getTrue() &&
6864 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
6865 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
6866 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6867 }
6868 break;
6869 case Instruction::SDiv:
6870 case Instruction::UDiv:
6871 case Instruction::SRem:
6872 case Instruction::URem:
6873 // If we are just changing the sign, rewrite.
6874 if (DestBitSize == SrcBitSize) {
6875 // Don't insert two casts if they cannot be eliminated. We allow
6876 // two casts to be inserted if the sizes are the same. This could
6877 // only be converting signedness, which is a noop.
6878 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6879 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6880 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6881 Op0, DestTy, SrcI);
6882 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6883 Op1, DestTy, SrcI);
6884 return BinaryOperator::create(
6885 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6886 }
6887 }
6888 break;
6889
6890 case Instruction::Shl:
6891 // Allow changing the sign of the source operand. Do not allow
6892 // changing the size of the shift, UNLESS the shift amount is a
6893 // constant. We must not change variable sized shifts to a smaller
6894 // size, because it is undefined to shift more bits out than exist
6895 // in the value.
6896 if (DestBitSize == SrcBitSize ||
6897 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
6898 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6899 Instruction::BitCast : Instruction::Trunc);
6900 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6901 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6902 return BinaryOperator::createShl(Op0c, Op1c);
6903 }
6904 break;
6905 case Instruction::AShr:
6906 // If this is a signed shr, and if all bits shifted in are about to be
6907 // truncated off, turn it into an unsigned shr to allow greater
6908 // simplifications.
6909 if (DestBitSize < SrcBitSize &&
6910 isa<ConstantInt>(Op1)) {
6911 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
6912 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
6913 // Insert the new logical shift right.
6914 return BinaryOperator::createLShr(Op0, Op1);
6915 }
6916 }
6917 break;
6918 }
6919 return 0;
6920}
6921
6922Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
6923 if (Instruction *Result = commonIntCastTransforms(CI))
6924 return Result;
6925
6926 Value *Src = CI.getOperand(0);
6927 const Type *Ty = CI.getType();
6928 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
6929 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
6930
6931 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
6932 switch (SrcI->getOpcode()) {
6933 default: break;
6934 case Instruction::LShr:
6935 // We can shrink lshr to something smaller if we know the bits shifted in
6936 // are already zeros.
6937 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
6938 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
6939
6940 // Get a mask for the bits shifting in.
6941 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
6942 Value* SrcIOp0 = SrcI->getOperand(0);
6943 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
6944 if (ShAmt >= DestBitWidth) // All zeros.
6945 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
6946
6947 // Okay, we can shrink this. Truncate the input, then return a new
6948 // shift.
6949 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
6950 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
6951 Ty, CI);
6952 return BinaryOperator::createLShr(V1, V2);
6953 }
6954 } else { // This is a variable shr.
6955
6956 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
6957 // more LLVM instructions, but allows '1 << Y' to be hoisted if
6958 // loop-invariant and CSE'd.
6959 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
6960 Value *One = ConstantInt::get(SrcI->getType(), 1);
6961
6962 Value *V = InsertNewInstBefore(
6963 BinaryOperator::createShl(One, SrcI->getOperand(1),
6964 "tmp"), CI);
6965 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
6966 SrcI->getOperand(0),
6967 "tmp"), CI);
6968 Value *Zero = Constant::getNullValue(V->getType());
6969 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
6970 }
6971 }
6972 break;
6973 }
6974 }
6975
6976 return 0;
6977}
6978
6979Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
6980 // If one of the common conversion will work ..
6981 if (Instruction *Result = commonIntCastTransforms(CI))
6982 return Result;
6983
6984 Value *Src = CI.getOperand(0);
6985
6986 // If this is a cast of a cast
6987 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
6988 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
6989 // types and if the sizes are just right we can convert this into a logical
6990 // 'and' which will be much cheaper than the pair of casts.
6991 if (isa<TruncInst>(CSrc)) {
6992 // Get the sizes of the types involved
6993 Value *A = CSrc->getOperand(0);
6994 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
6995 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
6996 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
6997 // If we're actually extending zero bits and the trunc is a no-op
6998 if (MidSize < DstSize && SrcSize == DstSize) {
6999 // Replace both of the casts with an And of the type mask.
7000 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
7001 Constant *AndConst = ConstantInt::get(AndValue);
7002 Instruction *And =
7003 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
7004 // Unfortunately, if the type changed, we need to cast it back.
7005 if (And->getType() != CI.getType()) {
7006 And->setName(CSrc->getName()+".mask");
7007 InsertNewInstBefore(And, CI);
7008 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
7009 }
7010 return And;
7011 }
7012 }
7013 }
7014
7015 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7016 // If we are just checking for a icmp eq of a single bit and zext'ing it
7017 // to an integer, then shift the bit to the appropriate place and then
7018 // cast to integer to avoid the comparison.
7019 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7020 const APInt &Op1CV = Op1C->getValue();
7021
7022 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7023 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7024 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7025 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7026 Value *In = ICI->getOperand(0);
7027 Value *Sh = ConstantInt::get(In->getType(),
7028 In->getType()->getPrimitiveSizeInBits()-1);
7029 In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
7030 In->getName()+".lobit"),
7031 CI);
7032 if (In->getType() != CI.getType())
7033 In = CastInst::createIntegerCast(In, CI.getType(),
7034 false/*ZExt*/, "tmp", &CI);
7035
7036 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7037 Constant *One = ConstantInt::get(In->getType(), 1);
7038 In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
7039 In->getName()+".not"),
7040 CI);
7041 }
7042
7043 return ReplaceInstUsesWith(CI, In);
7044 }
7045
7046
7047
7048 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7049 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7050 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7051 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7052 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7053 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7054 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7055 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7056 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7057 // This only works for EQ and NE
7058 ICI->isEquality()) {
7059 // If Op1C some other power of two, convert:
7060 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7061 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7062 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7063 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7064
7065 APInt KnownZeroMask(~KnownZero);
7066 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7067 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7068 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7069 // (X&4) == 2 --> false
7070 // (X&4) != 2 --> true
7071 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7072 Res = ConstantExpr::getZExt(Res, CI.getType());
7073 return ReplaceInstUsesWith(CI, Res);
7074 }
7075
7076 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7077 Value *In = ICI->getOperand(0);
7078 if (ShiftAmt) {
7079 // Perform a logical shr by shiftamt.
7080 // Insert the shift to put the result in the low bit.
7081 In = InsertNewInstBefore(
7082 BinaryOperator::createLShr(In,
7083 ConstantInt::get(In->getType(), ShiftAmt),
7084 In->getName()+".lobit"), CI);
7085 }
7086
7087 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7088 Constant *One = ConstantInt::get(In->getType(), 1);
7089 In = BinaryOperator::createXor(In, One, "tmp");
7090 InsertNewInstBefore(cast<Instruction>(In), CI);
7091 }
7092
7093 if (CI.getType() == In->getType())
7094 return ReplaceInstUsesWith(CI, In);
7095 else
7096 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
7097 }
7098 }
7099 }
7100 }
7101 return 0;
7102}
7103
7104Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7105 if (Instruction *I = commonIntCastTransforms(CI))
7106 return I;
7107
7108 Value *Src = CI.getOperand(0);
7109
7110 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7111 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7112 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7113 // If we are just checking for a icmp eq of a single bit and zext'ing it
7114 // to an integer, then shift the bit to the appropriate place and then
7115 // cast to integer to avoid the comparison.
7116 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7117 const APInt &Op1CV = Op1C->getValue();
7118
7119 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7120 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7121 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7122 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7123 Value *In = ICI->getOperand(0);
7124 Value *Sh = ConstantInt::get(In->getType(),
7125 In->getType()->getPrimitiveSizeInBits()-1);
7126 In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
7127 In->getName()+".lobit"),
7128 CI);
7129 if (In->getType() != CI.getType())
7130 In = CastInst::createIntegerCast(In, CI.getType(),
7131 true/*SExt*/, "tmp", &CI);
7132
7133 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7134 In = InsertNewInstBefore(BinaryOperator::createNot(In,
7135 In->getName()+".not"), CI);
7136
7137 return ReplaceInstUsesWith(CI, In);
7138 }
7139 }
7140 }
7141
7142 return 0;
7143}
7144
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007145/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7146/// in the specified FP type without changing its value.
7147static Constant *FitsInFPType(ConstantFP *CFP, const Type *FPTy,
7148 const fltSemantics &Sem) {
7149 APFloat F = CFP->getValueAPF();
7150 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
7151 return ConstantFP::get(FPTy, F);
7152 return 0;
7153}
7154
7155/// LookThroughFPExtensions - If this is an fp extension instruction, look
7156/// through it until we get the source value.
7157static Value *LookThroughFPExtensions(Value *V) {
7158 if (Instruction *I = dyn_cast<Instruction>(V))
7159 if (I->getOpcode() == Instruction::FPExt)
7160 return LookThroughFPExtensions(I->getOperand(0));
7161
7162 // If this value is a constant, return the constant in the smallest FP type
7163 // that can accurately represent it. This allows us to turn
7164 // (float)((double)X+2.0) into x+2.0f.
7165 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7166 if (CFP->getType() == Type::PPC_FP128Ty)
7167 return V; // No constant folding of this.
7168 // See if the value can be truncated to float and then reextended.
7169 if (Value *V = FitsInFPType(CFP, Type::FloatTy, APFloat::IEEEsingle))
7170 return V;
7171 if (CFP->getType() == Type::DoubleTy)
7172 return V; // Won't shrink.
7173 if (Value *V = FitsInFPType(CFP, Type::DoubleTy, APFloat::IEEEdouble))
7174 return V;
7175 // Don't try to shrink to various long double types.
7176 }
7177
7178 return V;
7179}
7180
7181Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7182 if (Instruction *I = commonCastTransforms(CI))
7183 return I;
7184
7185 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7186 // smaller than the destination type, we can eliminate the truncate by doing
7187 // the add as the smaller type. This applies to add/sub/mul/div as well as
7188 // many builtins (sqrt, etc).
7189 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7190 if (OpI && OpI->hasOneUse()) {
7191 switch (OpI->getOpcode()) {
7192 default: break;
7193 case Instruction::Add:
7194 case Instruction::Sub:
7195 case Instruction::Mul:
7196 case Instruction::FDiv:
7197 case Instruction::FRem:
7198 const Type *SrcTy = OpI->getType();
7199 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7200 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7201 if (LHSTrunc->getType() != SrcTy &&
7202 RHSTrunc->getType() != SrcTy) {
7203 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7204 // If the source types were both smaller than the destination type of
7205 // the cast, do this xform.
7206 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7207 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7208 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7209 CI.getType(), CI);
7210 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7211 CI.getType(), CI);
7212 return BinaryOperator::create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7213 }
7214 }
7215 break;
7216 }
7217 }
7218 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007219}
7220
7221Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7222 return commonCastTransforms(CI);
7223}
7224
7225Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
7226 return commonCastTransforms(CI);
7227}
7228
7229Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
7230 return commonCastTransforms(CI);
7231}
7232
7233Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7234 return commonCastTransforms(CI);
7235}
7236
7237Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7238 return commonCastTransforms(CI);
7239}
7240
7241Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7242 return commonPointerCastTransforms(CI);
7243}
7244
Chris Lattner7c1626482008-01-08 07:23:51 +00007245Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7246 if (Instruction *I = commonCastTransforms(CI))
7247 return I;
7248
7249 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7250 if (!DestPointee->isSized()) return 0;
7251
7252 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7253 ConstantInt *Cst;
7254 Value *X;
7255 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7256 m_ConstantInt(Cst)))) {
7257 // If the source and destination operands have the same type, see if this
7258 // is a single-index GEP.
7259 if (X->getType() == CI.getType()) {
7260 // Get the size of the pointee type.
7261 uint64_t Size = TD->getABITypeSizeInBits(DestPointee);
7262
7263 // Convert the constant to intptr type.
7264 APInt Offset = Cst->getValue();
7265 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7266
7267 // If Offset is evenly divisible by Size, we can do this xform.
7268 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7269 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7270 return new GetElementPtrInst(X, ConstantInt::get(Offset));
7271 }
7272 }
7273 // TODO: Could handle other cases, e.g. where add is indexing into field of
7274 // struct etc.
7275 } else if (CI.getOperand(0)->hasOneUse() &&
7276 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7277 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7278 // "inttoptr+GEP" instead of "add+intptr".
7279
7280 // Get the size of the pointee type.
7281 uint64_t Size = TD->getABITypeSize(DestPointee);
7282
7283 // Convert the constant to intptr type.
7284 APInt Offset = Cst->getValue();
7285 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7286
7287 // If Offset is evenly divisible by Size, we can do this xform.
7288 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7289 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7290
7291 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7292 "tmp"), CI);
7293 return new GetElementPtrInst(P, ConstantInt::get(Offset), "tmp");
7294 }
7295 }
7296 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007297}
7298
7299Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
7300 // If the operands are integer typed then apply the integer transforms,
7301 // otherwise just apply the common ones.
7302 Value *Src = CI.getOperand(0);
7303 const Type *SrcTy = Src->getType();
7304 const Type *DestTy = CI.getType();
7305
7306 if (SrcTy->isInteger() && DestTy->isInteger()) {
7307 if (Instruction *Result = commonIntCastTransforms(CI))
7308 return Result;
7309 } else if (isa<PointerType>(SrcTy)) {
7310 if (Instruction *I = commonPointerCastTransforms(CI))
7311 return I;
7312 } else {
7313 if (Instruction *Result = commonCastTransforms(CI))
7314 return Result;
7315 }
7316
7317
7318 // Get rid of casts from one type to the same type. These are useless and can
7319 // be replaced by the operand.
7320 if (DestTy == Src->getType())
7321 return ReplaceInstUsesWith(CI, Src);
7322
7323 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7324 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7325 const Type *DstElTy = DstPTy->getElementType();
7326 const Type *SrcElTy = SrcPTy->getElementType();
7327
7328 // If we are casting a malloc or alloca to a pointer to a type of the same
7329 // size, rewrite the allocation instruction to allocate the "right" type.
7330 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7331 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7332 return V;
7333
7334 // If the source and destination are pointers, and this cast is equivalent
7335 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
7336 // This can enhance SROA and other transforms that want type-safe pointers.
7337 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7338 unsigned NumZeros = 0;
7339 while (SrcElTy != DstElTy &&
7340 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7341 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7342 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7343 ++NumZeros;
7344 }
7345
7346 // If we found a path from the src to dest, create the getelementptr now.
7347 if (SrcElTy == DstElTy) {
7348 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Chuck Rose III27d49792007-09-05 20:36:41 +00007349 return new GetElementPtrInst(Src, Idxs.begin(), Idxs.end(), "",
7350 ((Instruction*) NULL));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007351 }
7352 }
7353
7354 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7355 if (SVI->hasOneUse()) {
7356 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7357 // a bitconvert to a vector with the same # elts.
7358 if (isa<VectorType>(DestTy) &&
7359 cast<VectorType>(DestTy)->getNumElements() ==
7360 SVI->getType()->getNumElements()) {
7361 CastInst *Tmp;
7362 // If either of the operands is a cast from CI.getType(), then
7363 // evaluating the shuffle in the casted destination's type will allow
7364 // us to eliminate at least one cast.
7365 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7366 Tmp->getOperand(0)->getType() == DestTy) ||
7367 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7368 Tmp->getOperand(0)->getType() == DestTy)) {
7369 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7370 SVI->getOperand(0), DestTy, &CI);
7371 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7372 SVI->getOperand(1), DestTy, &CI);
7373 // Return a new shuffle vector. Use the same element ID's, as we
7374 // know the vector types match #elts.
7375 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
7376 }
7377 }
7378 }
7379 }
7380 return 0;
7381}
7382
7383/// GetSelectFoldableOperands - We want to turn code that looks like this:
7384/// %C = or %A, %B
7385/// %D = select %cond, %C, %A
7386/// into:
7387/// %C = select %cond, %B, 0
7388/// %D = or %A, %C
7389///
7390/// Assuming that the specified instruction is an operand to the select, return
7391/// a bitmask indicating which operands of this instruction are foldable if they
7392/// equal the other incoming value of the select.
7393///
7394static unsigned GetSelectFoldableOperands(Instruction *I) {
7395 switch (I->getOpcode()) {
7396 case Instruction::Add:
7397 case Instruction::Mul:
7398 case Instruction::And:
7399 case Instruction::Or:
7400 case Instruction::Xor:
7401 return 3; // Can fold through either operand.
7402 case Instruction::Sub: // Can only fold on the amount subtracted.
7403 case Instruction::Shl: // Can only fold on the shift amount.
7404 case Instruction::LShr:
7405 case Instruction::AShr:
7406 return 1;
7407 default:
7408 return 0; // Cannot fold
7409 }
7410}
7411
7412/// GetSelectFoldableConstant - For the same transformation as the previous
7413/// function, return the identity constant that goes into the select.
7414static Constant *GetSelectFoldableConstant(Instruction *I) {
7415 switch (I->getOpcode()) {
7416 default: assert(0 && "This cannot happen!"); abort();
7417 case Instruction::Add:
7418 case Instruction::Sub:
7419 case Instruction::Or:
7420 case Instruction::Xor:
7421 case Instruction::Shl:
7422 case Instruction::LShr:
7423 case Instruction::AShr:
7424 return Constant::getNullValue(I->getType());
7425 case Instruction::And:
7426 return Constant::getAllOnesValue(I->getType());
7427 case Instruction::Mul:
7428 return ConstantInt::get(I->getType(), 1);
7429 }
7430}
7431
7432/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7433/// have the same opcode and only one use each. Try to simplify this.
7434Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7435 Instruction *FI) {
7436 if (TI->getNumOperands() == 1) {
7437 // If this is a non-volatile load or a cast from the same type,
7438 // merge.
7439 if (TI->isCast()) {
7440 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7441 return 0;
7442 } else {
7443 return 0; // unknown unary op.
7444 }
7445
7446 // Fold this by inserting a select from the input values.
7447 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7448 FI->getOperand(0), SI.getName()+".v");
7449 InsertNewInstBefore(NewSI, SI);
7450 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
7451 TI->getType());
7452 }
7453
7454 // Only handle binary operators here.
7455 if (!isa<BinaryOperator>(TI))
7456 return 0;
7457
7458 // Figure out if the operations have any operands in common.
7459 Value *MatchOp, *OtherOpT, *OtherOpF;
7460 bool MatchIsOpZero;
7461 if (TI->getOperand(0) == FI->getOperand(0)) {
7462 MatchOp = TI->getOperand(0);
7463 OtherOpT = TI->getOperand(1);
7464 OtherOpF = FI->getOperand(1);
7465 MatchIsOpZero = true;
7466 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7467 MatchOp = TI->getOperand(1);
7468 OtherOpT = TI->getOperand(0);
7469 OtherOpF = FI->getOperand(0);
7470 MatchIsOpZero = false;
7471 } else if (!TI->isCommutative()) {
7472 return 0;
7473 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7474 MatchOp = TI->getOperand(0);
7475 OtherOpT = TI->getOperand(1);
7476 OtherOpF = FI->getOperand(0);
7477 MatchIsOpZero = true;
7478 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7479 MatchOp = TI->getOperand(1);
7480 OtherOpT = TI->getOperand(0);
7481 OtherOpF = FI->getOperand(1);
7482 MatchIsOpZero = true;
7483 } else {
7484 return 0;
7485 }
7486
7487 // If we reach here, they do have operations in common.
7488 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7489 OtherOpF, SI.getName()+".v");
7490 InsertNewInstBefore(NewSI, SI);
7491
7492 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7493 if (MatchIsOpZero)
7494 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7495 else
7496 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
7497 }
7498 assert(0 && "Shouldn't get here");
7499 return 0;
7500}
7501
7502Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
7503 Value *CondVal = SI.getCondition();
7504 Value *TrueVal = SI.getTrueValue();
7505 Value *FalseVal = SI.getFalseValue();
7506
7507 // select true, X, Y -> X
7508 // select false, X, Y -> Y
7509 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
7510 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
7511
7512 // select C, X, X -> X
7513 if (TrueVal == FalseVal)
7514 return ReplaceInstUsesWith(SI, TrueVal);
7515
7516 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7517 return ReplaceInstUsesWith(SI, FalseVal);
7518 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7519 return ReplaceInstUsesWith(SI, TrueVal);
7520 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7521 if (isa<Constant>(TrueVal))
7522 return ReplaceInstUsesWith(SI, TrueVal);
7523 else
7524 return ReplaceInstUsesWith(SI, FalseVal);
7525 }
7526
7527 if (SI.getType() == Type::Int1Ty) {
7528 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
7529 if (C->getZExtValue()) {
7530 // Change: A = select B, true, C --> A = or B, C
7531 return BinaryOperator::createOr(CondVal, FalseVal);
7532 } else {
7533 // Change: A = select B, false, C --> A = and !B, C
7534 Value *NotCond =
7535 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7536 "not."+CondVal->getName()), SI);
7537 return BinaryOperator::createAnd(NotCond, FalseVal);
7538 }
7539 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
7540 if (C->getZExtValue() == false) {
7541 // Change: A = select B, C, false --> A = and B, C
7542 return BinaryOperator::createAnd(CondVal, TrueVal);
7543 } else {
7544 // Change: A = select B, C, true --> A = or !B, C
7545 Value *NotCond =
7546 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7547 "not."+CondVal->getName()), SI);
7548 return BinaryOperator::createOr(NotCond, TrueVal);
7549 }
7550 }
Chris Lattner53f85a72007-11-25 21:27:53 +00007551
7552 // select a, b, a -> a&b
7553 // select a, a, b -> a|b
7554 if (CondVal == TrueVal)
7555 return BinaryOperator::createOr(CondVal, FalseVal);
7556 else if (CondVal == FalseVal)
7557 return BinaryOperator::createAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007558 }
7559
7560 // Selecting between two integer constants?
7561 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7562 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
7563 // select C, 1, 0 -> zext C to int
7564 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
7565 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
7566 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
7567 // select C, 0, 1 -> zext !C to int
7568 Value *NotCond =
7569 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7570 "not."+CondVal->getName()), SI);
7571 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
7572 }
7573
7574 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
7575
7576 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
7577
7578 // (x <s 0) ? -1 : 0 -> ashr x, 31
7579 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
7580 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
7581 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
7582 // The comparison constant and the result are not neccessarily the
7583 // same width. Make an all-ones value by inserting a AShr.
7584 Value *X = IC->getOperand(0);
7585 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
7586 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7587 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7588 ShAmt, "ones");
7589 InsertNewInstBefore(SRA, SI);
7590
7591 // Finally, convert to the type of the select RHS. We figure out
7592 // if this requires a SExt, Trunc or BitCast based on the sizes.
7593 Instruction::CastOps opc = Instruction::BitCast;
7594 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
7595 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
7596 if (SRASize < SISize)
7597 opc = Instruction::SExt;
7598 else if (SRASize > SISize)
7599 opc = Instruction::Trunc;
7600 return CastInst::create(opc, SRA, SI.getType());
7601 }
7602 }
7603
7604
7605 // If one of the constants is zero (we know they can't both be) and we
7606 // have an icmp instruction with zero, and we have an 'and' with the
7607 // non-constant value, eliminate this whole mess. This corresponds to
7608 // cases like this: ((X & 27) ? 27 : 0)
7609 if (TrueValC->isZero() || FalseValC->isZero())
7610 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
7611 cast<Constant>(IC->getOperand(1))->isNullValue())
7612 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7613 if (ICA->getOpcode() == Instruction::And &&
7614 isa<ConstantInt>(ICA->getOperand(1)) &&
7615 (ICA->getOperand(1) == TrueValC ||
7616 ICA->getOperand(1) == FalseValC) &&
7617 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7618 // Okay, now we know that everything is set up, we just don't
7619 // know whether we have a icmp_ne or icmp_eq and whether the
7620 // true or false val is the zero.
7621 bool ShouldNotVal = !TrueValC->isZero();
7622 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
7623 Value *V = ICA;
7624 if (ShouldNotVal)
7625 V = InsertNewInstBefore(BinaryOperator::create(
7626 Instruction::Xor, V, ICA->getOperand(1)), SI);
7627 return ReplaceInstUsesWith(SI, V);
7628 }
7629 }
7630 }
7631
7632 // See if we are selecting two values based on a comparison of the two values.
7633 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7634 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
7635 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen2e1b7692007-10-03 17:45:27 +00007636 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7637 // This is not safe in general for floating point:
7638 // consider X== -0, Y== +0.
7639 // It becomes safe if either operand is a nonzero constant.
7640 ConstantFP *CFPt, *CFPf;
7641 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7642 !CFPt->getValueAPF().isZero()) ||
7643 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7644 !CFPf->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007645 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen2e1b7692007-10-03 17:45:27 +00007646 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007647 // Transform (X != Y) ? X : Y -> X
7648 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7649 return ReplaceInstUsesWith(SI, TrueVal);
7650 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7651
7652 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
7653 // Transform (X == Y) ? Y : X -> X
Dale Johannesen2e1b7692007-10-03 17:45:27 +00007654 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7655 // This is not safe in general for floating point:
7656 // consider X== -0, Y== +0.
7657 // It becomes safe if either operand is a nonzero constant.
7658 ConstantFP *CFPt, *CFPf;
7659 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7660 !CFPt->getValueAPF().isZero()) ||
7661 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7662 !CFPf->getValueAPF().isZero()))
7663 return ReplaceInstUsesWith(SI, FalseVal);
7664 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007665 // Transform (X != Y) ? Y : X -> Y
7666 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7667 return ReplaceInstUsesWith(SI, TrueVal);
7668 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7669 }
7670 }
7671
7672 // See if we are selecting two values based on a comparison of the two values.
7673 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7674 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7675 // Transform (X == Y) ? X : Y -> Y
7676 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7677 return ReplaceInstUsesWith(SI, FalseVal);
7678 // Transform (X != Y) ? X : Y -> X
7679 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7680 return ReplaceInstUsesWith(SI, TrueVal);
7681 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7682
7683 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7684 // Transform (X == Y) ? Y : X -> X
7685 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7686 return ReplaceInstUsesWith(SI, FalseVal);
7687 // Transform (X != Y) ? Y : X -> Y
7688 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7689 return ReplaceInstUsesWith(SI, TrueVal);
7690 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7691 }
7692 }
7693
7694 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7695 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7696 if (TI->hasOneUse() && FI->hasOneUse()) {
7697 Instruction *AddOp = 0, *SubOp = 0;
7698
7699 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7700 if (TI->getOpcode() == FI->getOpcode())
7701 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7702 return IV;
7703
7704 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
7705 // even legal for FP.
7706 if (TI->getOpcode() == Instruction::Sub &&
7707 FI->getOpcode() == Instruction::Add) {
7708 AddOp = FI; SubOp = TI;
7709 } else if (FI->getOpcode() == Instruction::Sub &&
7710 TI->getOpcode() == Instruction::Add) {
7711 AddOp = TI; SubOp = FI;
7712 }
7713
7714 if (AddOp) {
7715 Value *OtherAddOp = 0;
7716 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7717 OtherAddOp = AddOp->getOperand(1);
7718 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7719 OtherAddOp = AddOp->getOperand(0);
7720 }
7721
7722 if (OtherAddOp) {
7723 // So at this point we know we have (Y -> OtherAddOp):
7724 // select C, (add X, Y), (sub X, Z)
7725 Value *NegVal; // Compute -Z
7726 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7727 NegVal = ConstantExpr::getNeg(C);
7728 } else {
7729 NegVal = InsertNewInstBefore(
7730 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
7731 }
7732
7733 Value *NewTrueOp = OtherAddOp;
7734 Value *NewFalseOp = NegVal;
7735 if (AddOp != TI)
7736 std::swap(NewTrueOp, NewFalseOp);
7737 Instruction *NewSel =
7738 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7739
7740 NewSel = InsertNewInstBefore(NewSel, SI);
7741 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
7742 }
7743 }
7744 }
7745
7746 // See if we can fold the select into one of our operands.
7747 if (SI.getType()->isInteger()) {
7748 // See the comment above GetSelectFoldableOperands for a description of the
7749 // transformation we are doing here.
7750 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7751 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7752 !isa<Constant>(FalseVal))
7753 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7754 unsigned OpToFold = 0;
7755 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7756 OpToFold = 1;
7757 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7758 OpToFold = 2;
7759 }
7760
7761 if (OpToFold) {
7762 Constant *C = GetSelectFoldableConstant(TVI);
7763 Instruction *NewSel =
7764 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
7765 InsertNewInstBefore(NewSel, SI);
7766 NewSel->takeName(TVI);
7767 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7768 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
7769 else {
7770 assert(0 && "Unknown instruction!!");
7771 }
7772 }
7773 }
7774
7775 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7776 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7777 !isa<Constant>(TrueVal))
7778 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7779 unsigned OpToFold = 0;
7780 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7781 OpToFold = 1;
7782 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7783 OpToFold = 2;
7784 }
7785
7786 if (OpToFold) {
7787 Constant *C = GetSelectFoldableConstant(FVI);
7788 Instruction *NewSel =
7789 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
7790 InsertNewInstBefore(NewSel, SI);
7791 NewSel->takeName(FVI);
7792 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7793 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
7794 else
7795 assert(0 && "Unknown instruction!!");
7796 }
7797 }
7798 }
7799
7800 if (BinaryOperator::isNot(CondVal)) {
7801 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7802 SI.setOperand(1, FalseVal);
7803 SI.setOperand(2, TrueVal);
7804 return &SI;
7805 }
7806
7807 return 0;
7808}
7809
Chris Lattner47cf3452007-08-09 19:05:49 +00007810/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
7811/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
7812/// and it is more than the alignment of the ultimate object, see if we can
7813/// increase the alignment of the ultimate object, making this check succeed.
7814static unsigned GetOrEnforceKnownAlignment(Value *V, TargetData *TD,
7815 unsigned PrefAlign = 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007816 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7817 unsigned Align = GV->getAlignment();
Andrew Lenharthdae02012007-11-08 18:45:15 +00007818 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007819 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattner47cf3452007-08-09 19:05:49 +00007820
7821 // If there is a large requested alignment and we can, bump up the alignment
7822 // of the global.
7823 if (PrefAlign > Align && GV->hasInitializer()) {
7824 GV->setAlignment(PrefAlign);
7825 Align = PrefAlign;
7826 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007827 return Align;
7828 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7829 unsigned Align = AI->getAlignment();
7830 if (Align == 0 && TD) {
7831 if (isa<AllocaInst>(AI))
7832 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
7833 else if (isa<MallocInst>(AI)) {
7834 // Malloc returns maximally aligned memory.
7835 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
7836 Align =
7837 std::max(Align,
7838 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
7839 Align =
7840 std::max(Align,
7841 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
7842 }
7843 }
Chris Lattner47cf3452007-08-09 19:05:49 +00007844
7845 // If there is a requested alignment and if this is an alloca, round up. We
7846 // don't do this for malloc, because some systems can't respect the request.
7847 if (PrefAlign > Align && isa<AllocaInst>(AI)) {
7848 AI->setAlignment(PrefAlign);
7849 Align = PrefAlign;
7850 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007851 return Align;
7852 } else if (isa<BitCastInst>(V) ||
7853 (isa<ConstantExpr>(V) &&
7854 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner47cf3452007-08-09 19:05:49 +00007855 return GetOrEnforceKnownAlignment(cast<User>(V)->getOperand(0),
7856 TD, PrefAlign);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007857 } else if (User *GEPI = dyn_castGetElementPtr(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007858 // If all indexes are zero, it is just the alignment of the base pointer.
7859 bool AllZeroOperands = true;
7860 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7861 if (!isa<Constant>(GEPI->getOperand(i)) ||
7862 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7863 AllZeroOperands = false;
7864 break;
7865 }
Chris Lattner47cf3452007-08-09 19:05:49 +00007866
7867 if (AllZeroOperands) {
7868 // Treat this like a bitcast.
7869 return GetOrEnforceKnownAlignment(GEPI->getOperand(0), TD, PrefAlign);
7870 }
7871
7872 unsigned BaseAlignment = GetOrEnforceKnownAlignment(GEPI->getOperand(0),TD);
7873 if (BaseAlignment == 0) return 0;
7874
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007875 // Otherwise, if the base alignment is >= the alignment we expect for the
7876 // base pointer type, then we know that the resultant pointer is aligned at
7877 // least as much as its type requires.
7878 if (!TD) return 0;
7879
7880 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
7881 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Lauro Ramos Venancio55da3352007-07-31 20:13:21 +00007882 unsigned Align = TD->getABITypeAlignment(PtrTy->getElementType());
7883 if (Align <= BaseAlignment) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007884 const Type *GEPTy = GEPI->getType();
7885 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Lauro Ramos Venancio55da3352007-07-31 20:13:21 +00007886 Align = std::min(Align, (unsigned)
7887 TD->getABITypeAlignment(GEPPtrTy->getElementType()));
7888 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007889 }
7890 return 0;
7891 }
7892 return 0;
7893}
7894
Chris Lattner00ae5132008-01-13 23:50:23 +00007895Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
7896 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1), TD);
7897 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2), TD);
7898 unsigned MinAlign = std::min(DstAlign, SrcAlign);
7899 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
7900
7901 if (CopyAlign < MinAlign) {
7902 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
7903 return MI;
7904 }
7905
7906 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
7907 // load/store.
7908 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
7909 if (MemOpLength == 0) return 0;
7910
Chris Lattnerc669fb62008-01-14 00:28:35 +00007911 // Source and destination pointer types are always "i8*" for intrinsic. See
7912 // if the size is something we can handle with a single primitive load/store.
7913 // A single load+store correctly handles overlapping memory in the memmove
7914 // case.
Chris Lattner00ae5132008-01-13 23:50:23 +00007915 unsigned Size = MemOpLength->getZExtValue();
7916 if (Size == 0 || Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +00007917 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +00007918
Chris Lattnerc669fb62008-01-14 00:28:35 +00007919 // Use an integer load+store unless we can find something better.
Chris Lattner00ae5132008-01-13 23:50:23 +00007920 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattnerc669fb62008-01-14 00:28:35 +00007921
7922 // Memcpy forces the use of i8* for the source and destination. That means
7923 // that if you're using memcpy to move one double around, you'll get a cast
7924 // from double* to i8*. We'd much rather use a double load+store rather than
7925 // an i64 load+store, here because this improves the odds that the source or
7926 // dest address will be promotable. See if we can find a better type than the
7927 // integer datatype.
7928 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
7929 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
7930 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
7931 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
7932 // down through these levels if so.
7933 while (!SrcETy->isFirstClassType()) {
7934 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
7935 if (STy->getNumElements() == 1)
7936 SrcETy = STy->getElementType(0);
7937 else
7938 break;
7939 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
7940 if (ATy->getNumElements() == 1)
7941 SrcETy = ATy->getElementType();
7942 else
7943 break;
7944 } else
7945 break;
7946 }
7947
7948 if (SrcETy->isFirstClassType())
7949 NewPtrTy = PointerType::getUnqual(SrcETy);
7950 }
7951 }
7952
7953
Chris Lattner00ae5132008-01-13 23:50:23 +00007954 // If the memcpy/memmove provides better alignment info than we can
7955 // infer, use it.
7956 SrcAlign = std::max(SrcAlign, CopyAlign);
7957 DstAlign = std::max(DstAlign, CopyAlign);
7958
7959 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
7960 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattnerc669fb62008-01-14 00:28:35 +00007961 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
7962 InsertNewInstBefore(L, *MI);
7963 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
7964
7965 // Set the size of the copy to 0, it will be deleted on the next iteration.
7966 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
7967 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +00007968}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007969
7970/// visitCallInst - CallInst simplification. This mostly only handles folding
7971/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
7972/// the heavy lifting.
7973///
7974Instruction *InstCombiner::visitCallInst(CallInst &CI) {
7975 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
7976 if (!II) return visitCallSite(&CI);
7977
7978 // Intrinsics cannot occur in an invoke, so handle them here instead of in
7979 // visitCallSite.
7980 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
7981 bool Changed = false;
7982
7983 // memmove/cpy/set of zero bytes is a noop.
7984 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
7985 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
7986
7987 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
7988 if (CI->getZExtValue() == 1) {
7989 // Replace the instruction with just byte operations. We would
7990 // transform other cases to loads/stores, but we don't know if
7991 // alignment is sufficient.
7992 }
7993 }
7994
7995 // If we have a memmove and the source operation is a constant global,
7996 // then the source and dest pointers can't alias, so we can change this
7997 // into a call to memcpy.
Chris Lattner00ae5132008-01-13 23:50:23 +00007998 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007999 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8000 if (GVSrc->isConstant()) {
8001 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008002 Intrinsic::ID MemCpyID;
8003 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8004 MemCpyID = Intrinsic::memcpy_i32;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008005 else
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008006 MemCpyID = Intrinsic::memcpy_i64;
8007 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008008 Changed = true;
8009 }
8010 }
8011
8012 // If we can determine a pointer alignment that is bigger than currently
8013 // set, update the alignment.
8014 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +00008015 if (Instruction *I = SimplifyMemTransfer(MI))
8016 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008017 } else if (isa<MemSetInst>(MI)) {
Chris Lattner47cf3452007-08-09 19:05:49 +00008018 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest(), TD);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008019 if (MI->getAlignment()->getZExtValue() < Alignment) {
8020 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8021 Changed = true;
8022 }
8023 }
8024
8025 if (Changed) return II;
8026 } else {
8027 switch (II->getIntrinsicID()) {
8028 default: break;
8029 case Intrinsic::ppc_altivec_lvx:
8030 case Intrinsic::ppc_altivec_lvxl:
8031 case Intrinsic::x86_sse_loadu_ps:
8032 case Intrinsic::x86_sse2_loadu_pd:
8033 case Intrinsic::x86_sse2_loadu_dq:
8034 // Turn PPC lvx -> load if the pointer is known aligned.
8035 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattner47cf3452007-08-09 19:05:49 +00008036 if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008037 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8038 PointerType::getUnqual(II->getType()),
8039 CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008040 return new LoadInst(Ptr);
8041 }
8042 break;
8043 case Intrinsic::ppc_altivec_stvx:
8044 case Intrinsic::ppc_altivec_stvxl:
8045 // Turn stvx -> store if the pointer is known aligned.
Chris Lattner47cf3452007-08-09 19:05:49 +00008046 if (GetOrEnforceKnownAlignment(II->getOperand(2), TD, 16) >= 16) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00008047 const Type *OpPtrTy =
8048 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008049 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008050 return new StoreInst(II->getOperand(1), Ptr);
8051 }
8052 break;
8053 case Intrinsic::x86_sse_storeu_ps:
8054 case Intrinsic::x86_sse2_storeu_pd:
8055 case Intrinsic::x86_sse2_storeu_dq:
8056 case Intrinsic::x86_sse2_storel_dq:
8057 // Turn X86 storeu -> store if the pointer is known aligned.
Chris Lattner47cf3452007-08-09 19:05:49 +00008058 if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00008059 const Type *OpPtrTy =
8060 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008061 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008062 return new StoreInst(II->getOperand(2), Ptr);
8063 }
8064 break;
8065
8066 case Intrinsic::x86_sse_cvttss2si: {
8067 // These intrinsics only demands the 0th element of its input vector. If
8068 // we can simplify the input based on that, do so now.
8069 uint64_t UndefElts;
8070 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8071 UndefElts)) {
8072 II->setOperand(1, V);
8073 return II;
8074 }
8075 break;
8076 }
8077
8078 case Intrinsic::ppc_altivec_vperm:
8079 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8080 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8081 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8082
8083 // Check that all of the elements are integer constants or undefs.
8084 bool AllEltsOk = true;
8085 for (unsigned i = 0; i != 16; ++i) {
8086 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8087 !isa<UndefValue>(Mask->getOperand(i))) {
8088 AllEltsOk = false;
8089 break;
8090 }
8091 }
8092
8093 if (AllEltsOk) {
8094 // Cast the input vectors to byte vectors.
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008095 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8096 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008097 Value *Result = UndefValue::get(Op0->getType());
8098
8099 // Only extract each element once.
8100 Value *ExtractedElts[32];
8101 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8102
8103 for (unsigned i = 0; i != 16; ++i) {
8104 if (isa<UndefValue>(Mask->getOperand(i)))
8105 continue;
8106 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8107 Idx &= 31; // Match the hardware behavior.
8108
8109 if (ExtractedElts[Idx] == 0) {
8110 Instruction *Elt =
8111 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8112 InsertNewInstBefore(Elt, CI);
8113 ExtractedElts[Idx] = Elt;
8114 }
8115
8116 // Insert this value into the result vector.
8117 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
8118 InsertNewInstBefore(cast<Instruction>(Result), CI);
8119 }
8120 return CastInst::create(Instruction::BitCast, Result, CI.getType());
8121 }
8122 }
8123 break;
8124
8125 case Intrinsic::stackrestore: {
8126 // If the save is right next to the restore, remove the restore. This can
8127 // happen when variable allocas are DCE'd.
8128 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8129 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8130 BasicBlock::iterator BI = SS;
8131 if (&*++BI == II)
8132 return EraseInstFromFunction(CI);
8133 }
8134 }
8135
8136 // If the stack restore is in a return/unwind block and if there are no
8137 // allocas or calls between the restore and the return, nuke the restore.
8138 TerminatorInst *TI = II->getParent()->getTerminator();
8139 if (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)) {
8140 BasicBlock::iterator BI = II;
8141 bool CannotRemove = false;
8142 for (++BI; &*BI != TI; ++BI) {
8143 if (isa<AllocaInst>(BI) ||
8144 (isa<CallInst>(BI) && !isa<IntrinsicInst>(BI))) {
8145 CannotRemove = true;
8146 break;
8147 }
8148 }
8149 if (!CannotRemove)
8150 return EraseInstFromFunction(CI);
8151 }
8152 break;
8153 }
8154 }
8155 }
8156
8157 return visitCallSite(II);
8158}
8159
8160// InvokeInst simplification
8161//
8162Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8163 return visitCallSite(&II);
8164}
8165
8166// visitCallSite - Improvements for call and invoke instructions.
8167//
8168Instruction *InstCombiner::visitCallSite(CallSite CS) {
8169 bool Changed = false;
8170
8171 // If the callee is a constexpr cast of a function, attempt to move the cast
8172 // to the arguments of the call/invoke.
8173 if (transformConstExprCastCall(CS)) return 0;
8174
8175 Value *Callee = CS.getCalledValue();
8176
8177 if (Function *CalleeF = dyn_cast<Function>(Callee))
8178 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8179 Instruction *OldCall = CS.getInstruction();
8180 // If the call and callee calling conventions don't match, this call must
8181 // be unreachable, as the call is undefined.
8182 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00008183 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8184 OldCall);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008185 if (!OldCall->use_empty())
8186 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8187 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8188 return EraseInstFromFunction(*OldCall);
8189 return 0;
8190 }
8191
8192 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8193 // This instruction is not reachable, just remove it. We insert a store to
8194 // undef so that we know that this code is not reachable, despite the fact
8195 // that we can't modify the CFG here.
8196 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00008197 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008198 CS.getInstruction());
8199
8200 if (!CS.getInstruction()->use_empty())
8201 CS.getInstruction()->
8202 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8203
8204 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8205 // Don't break the CFG, insert a dummy cond branch.
8206 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
8207 ConstantInt::getTrue(), II);
8208 }
8209 return EraseInstFromFunction(*CS.getInstruction());
8210 }
8211
Duncan Sands74833f22007-09-17 10:26:40 +00008212 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8213 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8214 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8215 return transformCallThroughTrampoline(CS);
8216
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008217 const PointerType *PTy = cast<PointerType>(Callee->getType());
8218 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8219 if (FTy->isVarArg()) {
8220 // See if we can optimize any arguments passed through the varargs area of
8221 // the call.
8222 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8223 E = CS.arg_end(); I != E; ++I)
8224 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
8225 // If this cast does not effect the value passed through the varargs
8226 // area, we can eliminate the use of the cast.
8227 Value *Op = CI->getOperand(0);
8228 if (CI->isLosslessCast()) {
8229 *I = Op;
8230 Changed = true;
8231 }
8232 }
8233 }
8234
Duncan Sands2937e352007-12-19 21:13:37 +00008235 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +00008236 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +00008237 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +00008238 Changed = true;
8239 }
8240
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008241 return Changed ? CS.getInstruction() : 0;
8242}
8243
8244// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8245// attempt to move the cast to the arguments of the call/invoke.
8246//
8247bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8248 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8249 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
8250 if (CE->getOpcode() != Instruction::BitCast ||
8251 !isa<Function>(CE->getOperand(0)))
8252 return false;
8253 Function *Callee = cast<Function>(CE->getOperand(0));
8254 Instruction *Caller = CS.getInstruction();
Duncan Sandsc849e662008-01-06 18:27:01 +00008255 const ParamAttrsList* CallerPAL = CS.getParamAttrs();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008256
8257 // Okay, this is a cast from a function to a different type. Unless doing so
8258 // would cause a type conversion of one of our arguments, change this call to
8259 // be a direct call with arguments casted to the appropriate types.
8260 //
8261 const FunctionType *FT = Callee->getFunctionType();
8262 const Type *OldRetTy = Caller->getType();
8263
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008264 // Check to see if we are changing the return type...
8265 if (OldRetTy != FT->getReturnType()) {
8266 if (Callee->isDeclaration() && !Caller->use_empty() &&
8267 // Conversion is ok if changing from pointer to int of same size.
8268 !(isa<PointerType>(FT->getReturnType()) &&
8269 TD->getIntPtrType() == OldRetTy))
8270 return false; // Cannot transform this return value.
8271
Duncan Sands5c489582008-01-06 10:12:28 +00008272 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +00008273 // void -> non-void is handled specially
Duncan Sands4ced1f82008-01-13 08:02:44 +00008274 FT->getReturnType() != Type::VoidTy &&
8275 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +00008276 return false; // Cannot transform this return value.
8277
Duncan Sandsdbe97dc2008-01-07 17:16:06 +00008278 if (CallerPAL && !Caller->use_empty()) {
8279 uint16_t RAttrs = CallerPAL->getParamAttrs(0);
8280 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
8281 return false; // Attribute not compatible with transformed value.
8282 }
Duncan Sandsc849e662008-01-06 18:27:01 +00008283
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008284 // If the callsite is an invoke instruction, and the return value is used by
8285 // a PHI node in a successor, we cannot change the return type of the call
8286 // because there is no place to put the cast instruction (without breaking
8287 // the critical edge). Bail out in this case.
8288 if (!Caller->use_empty())
8289 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8290 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8291 UI != E; ++UI)
8292 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8293 if (PN->getParent() == II->getNormalDest() ||
8294 PN->getParent() == II->getUnwindDest())
8295 return false;
8296 }
8297
8298 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8299 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
8300
8301 CallSite::arg_iterator AI = CS.arg_begin();
8302 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8303 const Type *ParamTy = FT->getParamType(i);
8304 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +00008305
8306 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +00008307 return false; // Cannot transform this parameter value.
8308
Duncan Sandsdbe97dc2008-01-07 17:16:06 +00008309 if (CallerPAL) {
8310 uint16_t PAttrs = CallerPAL->getParamAttrs(i + 1);
8311 if (PAttrs & ParamAttr::typeIncompatible(ParamTy))
8312 return false; // Attribute not compatible with transformed value.
8313 }
Duncan Sands5c489582008-01-06 10:12:28 +00008314
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008315 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sands5c489582008-01-06 10:12:28 +00008316 // Some conversions are safe even if we do not have a body.
8317 // Either we can cast directly, or we can upconvert the argument
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008318 bool isConvertible = ActTy == ParamTy ||
8319 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
8320 (ParamTy->isInteger() && ActTy->isInteger() &&
8321 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8322 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
8323 && c->getValue().isStrictlyPositive());
8324 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008325 }
8326
8327 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
8328 Callee->isDeclaration())
8329 return false; // Do not delete arguments unless we have a function body...
8330
Duncan Sands4ced1f82008-01-13 08:02:44 +00008331 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() && CallerPAL)
Duncan Sandsc849e662008-01-06 18:27:01 +00008332 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +00008333 // won't be dropping them. Check that these extra arguments have attributes
8334 // that are compatible with being a vararg call argument.
8335 for (unsigned i = CallerPAL->size(); i; --i) {
8336 if (CallerPAL->getParamIndex(i - 1) <= FT->getNumParams())
8337 break;
8338 uint16_t PAttrs = CallerPAL->getParamAttrsAtIndex(i - 1);
8339 if (PAttrs & ParamAttr::VarArgsIncompatible)
8340 return false;
8341 }
Duncan Sandsc849e662008-01-06 18:27:01 +00008342
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008343 // Okay, we decided that this is a safe thing to do: go ahead and start
8344 // inserting cast instructions as necessary...
8345 std::vector<Value*> Args;
8346 Args.reserve(NumActualArgs);
Duncan Sandsc849e662008-01-06 18:27:01 +00008347 ParamAttrsVector attrVec;
8348 attrVec.reserve(NumCommonArgs);
8349
8350 // Get any return attributes.
8351 uint16_t RAttrs = CallerPAL ? CallerPAL->getParamAttrs(0) : 0;
8352
8353 // If the return value is not being used, the type may not be compatible
8354 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sandsdbe97dc2008-01-07 17:16:06 +00008355 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsc849e662008-01-06 18:27:01 +00008356
8357 // Add the new return attributes.
8358 if (RAttrs)
8359 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008360
8361 AI = CS.arg_begin();
8362 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8363 const Type *ParamTy = FT->getParamType(i);
8364 if ((*AI)->getType() == ParamTy) {
8365 Args.push_back(*AI);
8366 } else {
8367 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
8368 false, ParamTy, false);
8369 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
8370 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
8371 }
Duncan Sandsc849e662008-01-06 18:27:01 +00008372
8373 // Add any parameter attributes.
8374 uint16_t PAttrs = CallerPAL ? CallerPAL->getParamAttrs(i + 1) : 0;
8375 if (PAttrs)
8376 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008377 }
8378
8379 // If the function takes more arguments than the call was taking, add them
8380 // now...
8381 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8382 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8383
8384 // If we are removing arguments to the function, emit an obnoxious warning...
8385 if (FT->getNumParams() < NumActualArgs)
8386 if (!FT->isVarArg()) {
8387 cerr << "WARNING: While resolving call to function '"
8388 << Callee->getName() << "' arguments were dropped!\n";
8389 } else {
8390 // Add all of the arguments in their promoted form to the arg list...
8391 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8392 const Type *PTy = getPromotedType((*AI)->getType());
8393 if (PTy != (*AI)->getType()) {
8394 // Must promote to pass through va_arg area!
8395 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
8396 PTy, false);
8397 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
8398 InsertNewInstBefore(Cast, *Caller);
8399 Args.push_back(Cast);
8400 } else {
8401 Args.push_back(*AI);
8402 }
Duncan Sandsc849e662008-01-06 18:27:01 +00008403
Duncan Sands4ced1f82008-01-13 08:02:44 +00008404 // Add any parameter attributes.
8405 uint16_t PAttrs = CallerPAL ? CallerPAL->getParamAttrs(i + 1) : 0;
8406 if (PAttrs)
8407 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8408 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008409 }
8410
8411 if (FT->getReturnType() == Type::VoidTy)
8412 Caller->setName(""); // Void type should not have a name.
8413
Duncan Sandsc849e662008-01-06 18:27:01 +00008414 const ParamAttrsList* NewCallerPAL = ParamAttrsList::get(attrVec);
8415
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008416 Instruction *NC;
8417 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8418 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
David Greene8278ef52007-08-27 19:04:21 +00008419 Args.begin(), Args.end(), Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +00008420 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsc849e662008-01-06 18:27:01 +00008421 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008422 } else {
Chris Lattner03dc7d72007-08-02 16:53:43 +00008423 NC = new CallInst(Callee, Args.begin(), Args.end(),
8424 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008425 CallInst *CI = cast<CallInst>(Caller);
8426 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008427 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008428 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsc849e662008-01-06 18:27:01 +00008429 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008430 }
8431
8432 // Insert a cast of the return type as necessary.
8433 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +00008434 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008435 if (NV->getType() != Type::VoidTy) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008436 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +00008437 OldRetTy, false);
8438 NV = NC = CastInst::create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008439
8440 // If this is an invoke instruction, we should insert it after the first
8441 // non-phi, instruction in the normal successor block.
8442 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8443 BasicBlock::iterator I = II->getNormalDest()->begin();
8444 while (isa<PHINode>(I)) ++I;
8445 InsertNewInstBefore(NC, *I);
8446 } else {
8447 // Otherwise, it's a call, just insert cast right after the call instr
8448 InsertNewInstBefore(NC, *Caller);
8449 }
8450 AddUsersToWorkList(*Caller);
8451 } else {
8452 NV = UndefValue::get(Caller->getType());
8453 }
8454 }
8455
8456 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8457 Caller->replaceAllUsesWith(NV);
8458 Caller->eraseFromParent();
8459 RemoveFromWorkList(Caller);
8460 return true;
8461}
8462
Duncan Sands74833f22007-09-17 10:26:40 +00008463// transformCallThroughTrampoline - Turn a call to a function created by the
8464// init_trampoline intrinsic into a direct call to the underlying function.
8465//
8466Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
8467 Value *Callee = CS.getCalledValue();
8468 const PointerType *PTy = cast<PointerType>(Callee->getType());
8469 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Duncan Sands48b81112008-01-14 19:52:09 +00008470 const ParamAttrsList *Attrs = CS.getParamAttrs();
8471
8472 // If the call already has the 'nest' attribute somewhere then give up -
8473 // otherwise 'nest' would occur twice after splicing in the chain.
8474 if (Attrs && Attrs->hasAttrSomewhere(ParamAttr::Nest))
8475 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +00008476
8477 IntrinsicInst *Tramp =
8478 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
8479
8480 Function *NestF =
8481 cast<Function>(IntrinsicInst::StripPointerCasts(Tramp->getOperand(2)));
8482 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
8483 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
8484
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008485 if (const ParamAttrsList *NestAttrs = NestF->getParamAttrs()) {
Duncan Sands74833f22007-09-17 10:26:40 +00008486 unsigned NestIdx = 1;
8487 const Type *NestTy = 0;
8488 uint16_t NestAttr = 0;
8489
8490 // Look for a parameter marked with the 'nest' attribute.
8491 for (FunctionType::param_iterator I = NestFTy->param_begin(),
8492 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
8493 if (NestAttrs->paramHasAttr(NestIdx, ParamAttr::Nest)) {
8494 // Record the parameter type and any other attributes.
8495 NestTy = *I;
8496 NestAttr = NestAttrs->getParamAttrs(NestIdx);
8497 break;
8498 }
8499
8500 if (NestTy) {
8501 Instruction *Caller = CS.getInstruction();
8502 std::vector<Value*> NewArgs;
8503 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
8504
Duncan Sands48b81112008-01-14 19:52:09 +00008505 ParamAttrsVector NewAttrs;
8506 NewAttrs.reserve(Attrs ? Attrs->size() + 1 : 1);
8507
Duncan Sands74833f22007-09-17 10:26:40 +00008508 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +00008509 // mean appending it. Likewise for attributes.
8510
8511 // Add any function result attributes.
8512 uint16_t Attr = Attrs ? Attrs->getParamAttrs(0) : 0;
8513 if (Attr)
8514 NewAttrs.push_back (ParamAttrsWithIndex::get(0, Attr));
8515
Duncan Sands74833f22007-09-17 10:26:40 +00008516 {
8517 unsigned Idx = 1;
8518 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
8519 do {
8520 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +00008521 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00008522 Value *NestVal = Tramp->getOperand(3);
8523 if (NestVal->getType() != NestTy)
8524 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
8525 NewArgs.push_back(NestVal);
Duncan Sands48b81112008-01-14 19:52:09 +00008526 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +00008527 }
8528
8529 if (I == E)
8530 break;
8531
Duncan Sands48b81112008-01-14 19:52:09 +00008532 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00008533 NewArgs.push_back(*I);
Duncan Sands48b81112008-01-14 19:52:09 +00008534 Attr = Attrs ? Attrs->getParamAttrs(Idx) : 0;
8535 if (Attr)
8536 NewAttrs.push_back
8537 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +00008538
8539 ++Idx, ++I;
8540 } while (1);
8541 }
8542
8543 // The trampoline may have been bitcast to a bogus type (FTy).
8544 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +00008545 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +00008546
Duncan Sands74833f22007-09-17 10:26:40 +00008547 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +00008548 NewTypes.reserve(FTy->getNumParams()+1);
8549
Duncan Sands74833f22007-09-17 10:26:40 +00008550 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +00008551 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +00008552 {
8553 unsigned Idx = 1;
8554 FunctionType::param_iterator I = FTy->param_begin(),
8555 E = FTy->param_end();
8556
8557 do {
Duncan Sands48b81112008-01-14 19:52:09 +00008558 if (Idx == NestIdx)
8559 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +00008560 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +00008561
8562 if (I == E)
8563 break;
8564
Duncan Sands48b81112008-01-14 19:52:09 +00008565 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +00008566 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +00008567
8568 ++Idx, ++I;
8569 } while (1);
8570 }
8571
8572 // Replace the trampoline call with a direct call. Let the generic
8573 // code sort out any function type mismatches.
8574 FunctionType *NewFTy =
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008575 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lambbb2f2222007-12-17 01:12:55 +00008576 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
8577 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008578 const ParamAttrsList *NewPAL = ParamAttrsList::get(NewAttrs);
Duncan Sands74833f22007-09-17 10:26:40 +00008579
8580 Instruction *NewCaller;
8581 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8582 NewCaller = new InvokeInst(NewCallee,
8583 II->getNormalDest(), II->getUnwindDest(),
8584 NewArgs.begin(), NewArgs.end(),
8585 Caller->getName(), Caller);
8586 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008587 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00008588 } else {
8589 NewCaller = new CallInst(NewCallee, NewArgs.begin(), NewArgs.end(),
8590 Caller->getName(), Caller);
8591 if (cast<CallInst>(Caller)->isTailCall())
8592 cast<CallInst>(NewCaller)->setTailCall();
8593 cast<CallInst>(NewCaller)->
8594 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008595 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00008596 }
8597 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8598 Caller->replaceAllUsesWith(NewCaller);
8599 Caller->eraseFromParent();
8600 RemoveFromWorkList(Caller);
8601 return 0;
8602 }
8603 }
8604
8605 // Replace the trampoline call with a direct call. Since there is no 'nest'
8606 // parameter, there is no need to adjust the argument list. Let the generic
8607 // code sort out any function type mismatches.
8608 Constant *NewCallee =
8609 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
8610 CS.setCalledFunction(NewCallee);
8611 return CS.getInstruction();
8612}
8613
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008614/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
8615/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
8616/// and a single binop.
8617Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
8618 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8619 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
8620 isa<CmpInst>(FirstInst));
8621 unsigned Opc = FirstInst->getOpcode();
8622 Value *LHSVal = FirstInst->getOperand(0);
8623 Value *RHSVal = FirstInst->getOperand(1);
8624
8625 const Type *LHSType = LHSVal->getType();
8626 const Type *RHSType = RHSVal->getType();
8627
8628 // Scan to see if all operands are the same opcode, all have one use, and all
8629 // kill their operands (i.e. the operands have one use).
8630 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
8631 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
8632 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
8633 // Verify type of the LHS matches so we don't fold cmp's of different
8634 // types or GEP's with different index types.
8635 I->getOperand(0)->getType() != LHSType ||
8636 I->getOperand(1)->getType() != RHSType)
8637 return 0;
8638
8639 // If they are CmpInst instructions, check their predicates
8640 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
8641 if (cast<CmpInst>(I)->getPredicate() !=
8642 cast<CmpInst>(FirstInst)->getPredicate())
8643 return 0;
8644
8645 // Keep track of which operand needs a phi node.
8646 if (I->getOperand(0) != LHSVal) LHSVal = 0;
8647 if (I->getOperand(1) != RHSVal) RHSVal = 0;
8648 }
8649
8650 // Otherwise, this is safe to transform, determine if it is profitable.
8651
8652 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
8653 // Indexes are often folded into load/store instructions, so we don't want to
8654 // hide them behind a phi.
8655 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
8656 return 0;
8657
8658 Value *InLHS = FirstInst->getOperand(0);
8659 Value *InRHS = FirstInst->getOperand(1);
8660 PHINode *NewLHS = 0, *NewRHS = 0;
8661 if (LHSVal == 0) {
8662 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
8663 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
8664 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
8665 InsertNewInstBefore(NewLHS, PN);
8666 LHSVal = NewLHS;
8667 }
8668
8669 if (RHSVal == 0) {
8670 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
8671 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
8672 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
8673 InsertNewInstBefore(NewRHS, PN);
8674 RHSVal = NewRHS;
8675 }
8676
8677 // Add all operands to the new PHIs.
8678 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8679 if (NewLHS) {
8680 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8681 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
8682 }
8683 if (NewRHS) {
8684 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
8685 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
8686 }
8687 }
8688
8689 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
8690 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
8691 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8692 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
8693 RHSVal);
8694 else {
8695 assert(isa<GetElementPtrInst>(FirstInst));
8696 return new GetElementPtrInst(LHSVal, RHSVal);
8697 }
8698}
8699
8700/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
8701/// of the block that defines it. This means that it must be obvious the value
8702/// of the load is not changed from the point of the load to the end of the
8703/// block it is in.
8704///
8705/// Finally, it is safe, but not profitable, to sink a load targetting a
8706/// non-address-taken alloca. Doing so will cause us to not promote the alloca
8707/// to a register.
8708static bool isSafeToSinkLoad(LoadInst *L) {
8709 BasicBlock::iterator BBI = L, E = L->getParent()->end();
8710
8711 for (++BBI; BBI != E; ++BBI)
8712 if (BBI->mayWriteToMemory())
8713 return false;
8714
8715 // Check for non-address taken alloca. If not address-taken already, it isn't
8716 // profitable to do this xform.
8717 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
8718 bool isAddressTaken = false;
8719 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8720 UI != E; ++UI) {
8721 if (isa<LoadInst>(UI)) continue;
8722 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8723 // If storing TO the alloca, then the address isn't taken.
8724 if (SI->getOperand(1) == AI) continue;
8725 }
8726 isAddressTaken = true;
8727 break;
8728 }
8729
8730 if (!isAddressTaken)
8731 return false;
8732 }
8733
8734 return true;
8735}
8736
8737
8738// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
8739// operator and they all are only used by the PHI, PHI together their
8740// inputs, and do the operation once, to the result of the PHI.
8741Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
8742 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8743
8744 // Scan the instruction, looking for input operations that can be folded away.
8745 // If all input operands to the phi are the same instruction (e.g. a cast from
8746 // the same type or "+42") we can pull the operation through the PHI, reducing
8747 // code size and simplifying code.
8748 Constant *ConstantOp = 0;
8749 const Type *CastSrcTy = 0;
8750 bool isVolatile = false;
8751 if (isa<CastInst>(FirstInst)) {
8752 CastSrcTy = FirstInst->getOperand(0)->getType();
8753 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
8754 // Can fold binop, compare or shift here if the RHS is a constant,
8755 // otherwise call FoldPHIArgBinOpIntoPHI.
8756 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
8757 if (ConstantOp == 0)
8758 return FoldPHIArgBinOpIntoPHI(PN);
8759 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
8760 isVolatile = LI->isVolatile();
8761 // We can't sink the load if the loaded value could be modified between the
8762 // load and the PHI.
8763 if (LI->getParent() != PN.getIncomingBlock(0) ||
8764 !isSafeToSinkLoad(LI))
8765 return 0;
8766 } else if (isa<GetElementPtrInst>(FirstInst)) {
8767 if (FirstInst->getNumOperands() == 2)
8768 return FoldPHIArgBinOpIntoPHI(PN);
8769 // Can't handle general GEPs yet.
8770 return 0;
8771 } else {
8772 return 0; // Cannot fold this operation.
8773 }
8774
8775 // Check to see if all arguments are the same operation.
8776 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8777 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
8778 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
8779 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
8780 return 0;
8781 if (CastSrcTy) {
8782 if (I->getOperand(0)->getType() != CastSrcTy)
8783 return 0; // Cast operation must match.
8784 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8785 // We can't sink the load if the loaded value could be modified between
8786 // the load and the PHI.
8787 if (LI->isVolatile() != isVolatile ||
8788 LI->getParent() != PN.getIncomingBlock(i) ||
8789 !isSafeToSinkLoad(LI))
8790 return 0;
8791 } else if (I->getOperand(1) != ConstantOp) {
8792 return 0;
8793 }
8794 }
8795
8796 // Okay, they are all the same operation. Create a new PHI node of the
8797 // correct type, and PHI together all of the LHS's of the instructions.
8798 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
8799 PN.getName()+".in");
8800 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
8801
8802 Value *InVal = FirstInst->getOperand(0);
8803 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
8804
8805 // Add all operands to the new PHI.
8806 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8807 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8808 if (NewInVal != InVal)
8809 InVal = 0;
8810 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
8811 }
8812
8813 Value *PhiVal;
8814 if (InVal) {
8815 // The new PHI unions all of the same values together. This is really
8816 // common, so we handle it intelligently here for compile-time speed.
8817 PhiVal = InVal;
8818 delete NewPN;
8819 } else {
8820 InsertNewInstBefore(NewPN, PN);
8821 PhiVal = NewPN;
8822 }
8823
8824 // Insert and return the new operation.
8825 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
8826 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
8827 else if (isa<LoadInst>(FirstInst))
8828 return new LoadInst(PhiVal, "", isVolatile);
8829 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
8830 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
8831 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8832 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
8833 PhiVal, ConstantOp);
8834 else
8835 assert(0 && "Unknown operation");
8836 return 0;
8837}
8838
8839/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
8840/// that is dead.
8841static bool DeadPHICycle(PHINode *PN,
8842 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
8843 if (PN->use_empty()) return true;
8844 if (!PN->hasOneUse()) return false;
8845
8846 // Remember this node, and if we find the cycle, return.
8847 if (!PotentiallyDeadPHIs.insert(PN))
8848 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +00008849
8850 // Don't scan crazily complex things.
8851 if (PotentiallyDeadPHIs.size() == 16)
8852 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008853
8854 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
8855 return DeadPHICycle(PU, PotentiallyDeadPHIs);
8856
8857 return false;
8858}
8859
Chris Lattner27b695d2007-11-06 21:52:06 +00008860/// PHIsEqualValue - Return true if this phi node is always equal to
8861/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
8862/// z = some value; x = phi (y, z); y = phi (x, z)
8863static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
8864 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
8865 // See if we already saw this PHI node.
8866 if (!ValueEqualPHIs.insert(PN))
8867 return true;
8868
8869 // Don't scan crazily complex things.
8870 if (ValueEqualPHIs.size() == 16)
8871 return false;
8872
8873 // Scan the operands to see if they are either phi nodes or are equal to
8874 // the value.
8875 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
8876 Value *Op = PN->getIncomingValue(i);
8877 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
8878 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
8879 return false;
8880 } else if (Op != NonPhiInVal)
8881 return false;
8882 }
8883
8884 return true;
8885}
8886
8887
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008888// PHINode simplification
8889//
8890Instruction *InstCombiner::visitPHINode(PHINode &PN) {
8891 // If LCSSA is around, don't mess with Phi nodes
8892 if (MustPreserveLCSSA) return 0;
8893
8894 if (Value *V = PN.hasConstantValue())
8895 return ReplaceInstUsesWith(PN, V);
8896
8897 // If all PHI operands are the same operation, pull them through the PHI,
8898 // reducing code size.
8899 if (isa<Instruction>(PN.getIncomingValue(0)) &&
8900 PN.getIncomingValue(0)->hasOneUse())
8901 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
8902 return Result;
8903
8904 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
8905 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
8906 // PHI)... break the cycle.
8907 if (PN.hasOneUse()) {
8908 Instruction *PHIUser = cast<Instruction>(PN.use_back());
8909 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
8910 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
8911 PotentiallyDeadPHIs.insert(&PN);
8912 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
8913 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8914 }
8915
8916 // If this phi has a single use, and if that use just computes a value for
8917 // the next iteration of a loop, delete the phi. This occurs with unused
8918 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
8919 // common case here is good because the only other things that catch this
8920 // are induction variable analysis (sometimes) and ADCE, which is only run
8921 // late.
8922 if (PHIUser->hasOneUse() &&
8923 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
8924 PHIUser->use_back() == &PN) {
8925 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
8926 }
8927 }
8928
Chris Lattner27b695d2007-11-06 21:52:06 +00008929 // We sometimes end up with phi cycles that non-obviously end up being the
8930 // same value, for example:
8931 // z = some value; x = phi (y, z); y = phi (x, z)
8932 // where the phi nodes don't necessarily need to be in the same block. Do a
8933 // quick check to see if the PHI node only contains a single non-phi value, if
8934 // so, scan to see if the phi cycle is actually equal to that value.
8935 {
8936 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
8937 // Scan for the first non-phi operand.
8938 while (InValNo != NumOperandVals &&
8939 isa<PHINode>(PN.getIncomingValue(InValNo)))
8940 ++InValNo;
8941
8942 if (InValNo != NumOperandVals) {
8943 Value *NonPhiInVal = PN.getOperand(InValNo);
8944
8945 // Scan the rest of the operands to see if there are any conflicts, if so
8946 // there is no need to recursively scan other phis.
8947 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
8948 Value *OpVal = PN.getIncomingValue(InValNo);
8949 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
8950 break;
8951 }
8952
8953 // If we scanned over all operands, then we have one unique value plus
8954 // phi values. Scan PHI nodes to see if they all merge in each other or
8955 // the value.
8956 if (InValNo == NumOperandVals) {
8957 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
8958 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
8959 return ReplaceInstUsesWith(PN, NonPhiInVal);
8960 }
8961 }
8962 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008963 return 0;
8964}
8965
8966static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
8967 Instruction *InsertPoint,
8968 InstCombiner *IC) {
8969 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
8970 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
8971 // We must cast correctly to the pointer type. Ensure that we
8972 // sign extend the integer value if it is smaller as this is
8973 // used for address computation.
8974 Instruction::CastOps opcode =
8975 (VTySize < PtrSize ? Instruction::SExt :
8976 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
8977 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
8978}
8979
8980
8981Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
8982 Value *PtrOp = GEP.getOperand(0);
8983 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
8984 // If so, eliminate the noop.
8985 if (GEP.getNumOperands() == 1)
8986 return ReplaceInstUsesWith(GEP, PtrOp);
8987
8988 if (isa<UndefValue>(GEP.getOperand(0)))
8989 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
8990
8991 bool HasZeroPointerIndex = false;
8992 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
8993 HasZeroPointerIndex = C->isNullValue();
8994
8995 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
8996 return ReplaceInstUsesWith(GEP, PtrOp);
8997
8998 // Eliminate unneeded casts for indices.
8999 bool MadeChange = false;
9000
9001 gep_type_iterator GTI = gep_type_begin(GEP);
9002 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
9003 if (isa<SequentialType>(*GTI)) {
9004 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
9005 if (CI->getOpcode() == Instruction::ZExt ||
9006 CI->getOpcode() == Instruction::SExt) {
9007 const Type *SrcTy = CI->getOperand(0)->getType();
9008 // We can eliminate a cast from i32 to i64 iff the target
9009 // is a 32-bit pointer target.
9010 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9011 MadeChange = true;
9012 GEP.setOperand(i, CI->getOperand(0));
9013 }
9014 }
9015 }
9016 // If we are using a wider index than needed for this platform, shrink it
9017 // to what we need. If the incoming value needs a cast instruction,
9018 // insert it. This explicit cast can make subsequent optimizations more
9019 // obvious.
9020 Value *Op = GEP.getOperand(i);
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009021 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009022 if (Constant *C = dyn_cast<Constant>(Op)) {
9023 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
9024 MadeChange = true;
9025 } else {
9026 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9027 GEP);
9028 GEP.setOperand(i, Op);
9029 MadeChange = true;
9030 }
9031 }
9032 }
9033 if (MadeChange) return &GEP;
9034
9035 // If this GEP instruction doesn't move the pointer, and if the input operand
9036 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9037 // real input to the dest type.
Chris Lattnerc59171a2007-10-12 05:30:59 +00009038 if (GEP.hasAllZeroIndices()) {
9039 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9040 // If the bitcast is of an allocation, and the allocation will be
9041 // converted to match the type of the cast, don't touch this.
9042 if (isa<AllocationInst>(BCI->getOperand(0))) {
9043 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattner551a5872007-10-12 18:05:47 +00009044 if (Instruction *I = visitBitCast(*BCI)) {
9045 if (I != BCI) {
9046 I->takeName(BCI);
9047 BCI->getParent()->getInstList().insert(BCI, I);
9048 ReplaceInstUsesWith(*BCI, I);
9049 }
Chris Lattnerc59171a2007-10-12 05:30:59 +00009050 return &GEP;
Chris Lattner551a5872007-10-12 18:05:47 +00009051 }
Chris Lattnerc59171a2007-10-12 05:30:59 +00009052 }
9053 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9054 }
9055 }
9056
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009057 // Combine Indices - If the source pointer to this getelementptr instruction
9058 // is a getelementptr instruction, combine the indices of the two
9059 // getelementptr instructions into a single instruction.
9060 //
9061 SmallVector<Value*, 8> SrcGEPOperands;
9062 if (User *Src = dyn_castGetElementPtr(PtrOp))
9063 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
9064
9065 if (!SrcGEPOperands.empty()) {
9066 // Note that if our source is a gep chain itself that we wait for that
9067 // chain to be resolved before we perform this transformation. This
9068 // avoids us creating a TON of code in some cases.
9069 //
9070 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9071 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9072 return 0; // Wait until our source is folded to completion.
9073
9074 SmallVector<Value*, 8> Indices;
9075
9076 // Find out whether the last index in the source GEP is a sequential idx.
9077 bool EndsWithSequential = false;
9078 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9079 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
9080 EndsWithSequential = !isa<StructType>(*I);
9081
9082 // Can we combine the two pointer arithmetics offsets?
9083 if (EndsWithSequential) {
9084 // Replace: gep (gep %P, long B), long A, ...
9085 // With: T = long A+B; gep %P, T, ...
9086 //
9087 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
9088 if (SO1 == Constant::getNullValue(SO1->getType())) {
9089 Sum = GO1;
9090 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9091 Sum = SO1;
9092 } else {
9093 // If they aren't the same type, convert both to an integer of the
9094 // target's pointer size.
9095 if (SO1->getType() != GO1->getType()) {
9096 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
9097 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
9098 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
9099 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
9100 } else {
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009101 unsigned PS = TD->getPointerSizeInBits();
9102 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009103 // Convert GO1 to SO1's type.
9104 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
9105
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009106 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009107 // Convert SO1 to GO1's type.
9108 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
9109 } else {
9110 const Type *PT = TD->getIntPtrType();
9111 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9112 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
9113 }
9114 }
9115 }
9116 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9117 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9118 else {
9119 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
9120 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
9121 }
9122 }
9123
9124 // Recycle the GEP we already have if possible.
9125 if (SrcGEPOperands.size() == 2) {
9126 GEP.setOperand(0, SrcGEPOperands[0]);
9127 GEP.setOperand(1, Sum);
9128 return &GEP;
9129 } else {
9130 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9131 SrcGEPOperands.end()-1);
9132 Indices.push_back(Sum);
9133 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9134 }
9135 } else if (isa<Constant>(*GEP.idx_begin()) &&
9136 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
9137 SrcGEPOperands.size() != 1) {
9138 // Otherwise we can do the fold if the first index of the GEP is a zero
9139 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9140 SrcGEPOperands.end());
9141 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9142 }
9143
9144 if (!Indices.empty())
David Greene393be882007-09-04 15:46:09 +00009145 return new GetElementPtrInst(SrcGEPOperands[0], Indices.begin(),
9146 Indices.end(), GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009147
9148 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
9149 // GEP of global variable. If all of the indices for this GEP are
9150 // constants, we can promote this to a constexpr instead of an instruction.
9151
9152 // Scan for nonconstants...
9153 SmallVector<Constant*, 8> Indices;
9154 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9155 for (; I != E && isa<Constant>(*I); ++I)
9156 Indices.push_back(cast<Constant>(*I));
9157
9158 if (I == E) { // If they are all constants...
9159 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9160 &Indices[0],Indices.size());
9161
9162 // Replace all uses of the GEP with the new constexpr...
9163 return ReplaceInstUsesWith(GEP, CE);
9164 }
9165 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
9166 if (!isa<PointerType>(X->getType())) {
9167 // Not interesting. Source pointer must be a cast from pointer.
9168 } else if (HasZeroPointerIndex) {
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009169 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9170 // into : GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009171 //
9172 // This occurs when the program declares an array extern like "int X[];"
9173 //
9174 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9175 const PointerType *XTy = cast<PointerType>(X->getType());
9176 if (const ArrayType *XATy =
9177 dyn_cast<ArrayType>(XTy->getElementType()))
9178 if (const ArrayType *CATy =
9179 dyn_cast<ArrayType>(CPTy->getElementType()))
9180 if (CATy->getElementType() == XATy->getElementType()) {
9181 // At this point, we know that the cast source type is a pointer
9182 // to an array of the same type as the destination pointer
9183 // array. Because the array type is never stepped over (there
9184 // is a leading zero) we can fold the cast into this GEP.
9185 GEP.setOperand(0, X);
9186 return &GEP;
9187 }
9188 } else if (GEP.getNumOperands() == 2) {
9189 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009190 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9191 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009192 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9193 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9194 if (isa<ArrayType>(SrcElTy) &&
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009195 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9196 TD->getABITypeSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +00009197 Value *Idx[2];
9198 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9199 Idx[1] = GEP.getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009200 Value *V = InsertNewInstBefore(
David Greene393be882007-09-04 15:46:09 +00009201 new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName()), GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009202 // V and GEP are both pointer types --> BitCast
9203 return new BitCastInst(V, GEP.getType());
9204 }
9205
9206 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009207 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009208 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009209 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009210
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009211 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009212 uint64_t ArrayEltSize =
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009213 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009214
9215 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9216 // allow either a mul, shift, or constant here.
9217 Value *NewIdx = 0;
9218 ConstantInt *Scale = 0;
9219 if (ArrayEltSize == 1) {
9220 NewIdx = GEP.getOperand(1);
9221 Scale = ConstantInt::get(NewIdx->getType(), 1);
9222 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
9223 NewIdx = ConstantInt::get(CI->getType(), 1);
9224 Scale = CI;
9225 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9226 if (Inst->getOpcode() == Instruction::Shl &&
9227 isa<ConstantInt>(Inst->getOperand(1))) {
9228 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9229 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9230 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
9231 NewIdx = Inst->getOperand(0);
9232 } else if (Inst->getOpcode() == Instruction::Mul &&
9233 isa<ConstantInt>(Inst->getOperand(1))) {
9234 Scale = cast<ConstantInt>(Inst->getOperand(1));
9235 NewIdx = Inst->getOperand(0);
9236 }
9237 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009238
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009239 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009240 // out, perform the transformation. Note, we don't know whether Scale is
9241 // signed or not. We'll use unsigned version of division/modulo
9242 // operation after making sure Scale doesn't have the sign bit set.
9243 if (Scale && Scale->getSExtValue() >= 0LL &&
9244 Scale->getZExtValue() % ArrayEltSize == 0) {
9245 Scale = ConstantInt::get(Scale->getType(),
9246 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009247 if (Scale->getZExtValue() != 1) {
9248 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009249 false /*ZExt*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009250 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
9251 NewIdx = InsertNewInstBefore(Sc, GEP);
9252 }
9253
9254 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +00009255 Value *Idx[2];
9256 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9257 Idx[1] = NewIdx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009258 Instruction *NewGEP =
David Greene393be882007-09-04 15:46:09 +00009259 new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009260 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9261 // The NewGEP must be pointer typed, so must the old one -> BitCast
9262 return new BitCastInst(NewGEP, GEP.getType());
9263 }
9264 }
9265 }
9266 }
9267
9268 return 0;
9269}
9270
9271Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9272 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
9273 if (AI.isArrayAllocation()) // Check C != 1
9274 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9275 const Type *NewTy =
9276 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
9277 AllocationInst *New = 0;
9278
9279 // Create and insert the replacement instruction...
9280 if (isa<MallocInst>(AI))
9281 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
9282 else {
9283 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
9284 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
9285 }
9286
9287 InsertNewInstBefore(New, AI);
9288
9289 // Scan to the end of the allocation instructions, to skip over a block of
9290 // allocas if possible...
9291 //
9292 BasicBlock::iterator It = New;
9293 while (isa<AllocationInst>(*It)) ++It;
9294
9295 // Now that I is pointing to the first non-allocation-inst in the block,
9296 // insert our getelementptr instruction...
9297 //
9298 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greene393be882007-09-04 15:46:09 +00009299 Value *Idx[2];
9300 Idx[0] = NullIdx;
9301 Idx[1] = NullIdx;
9302 Value *V = new GetElementPtrInst(New, Idx, Idx + 2,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009303 New->getName()+".sub", It);
9304
9305 // Now make everything use the getelementptr instead of the original
9306 // allocation.
9307 return ReplaceInstUsesWith(AI, V);
9308 } else if (isa<UndefValue>(AI.getArraySize())) {
9309 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9310 }
9311
9312 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9313 // Note that we only do this for alloca's, because malloc should allocate and
9314 // return a unique pointer, even for a zero byte allocation.
9315 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009316 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009317 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9318
9319 return 0;
9320}
9321
9322Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9323 Value *Op = FI.getOperand(0);
9324
9325 // free undef -> unreachable.
9326 if (isa<UndefValue>(Op)) {
9327 // Insert a new store to null because we cannot modify the CFG here.
9328 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00009329 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009330 return EraseInstFromFunction(FI);
9331 }
9332
9333 // If we have 'free null' delete the instruction. This can happen in stl code
9334 // when lots of inlining happens.
9335 if (isa<ConstantPointerNull>(Op))
9336 return EraseInstFromFunction(FI);
9337
9338 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9339 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9340 FI.setOperand(0, CI->getOperand(0));
9341 return &FI;
9342 }
9343
9344 // Change free (gep X, 0,0,0,0) into free(X)
9345 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9346 if (GEPI->hasAllZeroIndices()) {
9347 AddToWorkList(GEPI);
9348 FI.setOperand(0, GEPI->getOperand(0));
9349 return &FI;
9350 }
9351 }
9352
9353 // Change free(malloc) into nothing, if the malloc has a single use.
9354 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9355 if (MI->hasOneUse()) {
9356 EraseInstFromFunction(FI);
9357 return EraseInstFromFunction(*MI);
9358 }
9359
9360 return 0;
9361}
9362
9363
9364/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patela0f8ea82007-10-18 19:52:32 +00009365static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
9366 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009367 User *CI = cast<User>(LI.getOperand(0));
9368 Value *CastOp = CI->getOperand(0);
9369
Devang Patela0f8ea82007-10-18 19:52:32 +00009370 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9371 // Instead of loading constant c string, use corresponding integer value
9372 // directly if string length is small enough.
9373 const std::string &Str = CE->getOperand(0)->getStringValue();
9374 if (!Str.empty()) {
9375 unsigned len = Str.length();
9376 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9377 unsigned numBits = Ty->getPrimitiveSizeInBits();
9378 // Replace LI with immediate integer store.
9379 if ((numBits >> 3) == len + 1) {
9380 APInt StrVal(numBits, 0);
9381 APInt SingleChar(numBits, 0);
9382 if (TD->isLittleEndian()) {
9383 for (signed i = len-1; i >= 0; i--) {
9384 SingleChar = (uint64_t) Str[i];
9385 StrVal = (StrVal << 8) | SingleChar;
9386 }
9387 } else {
9388 for (unsigned i = 0; i < len; i++) {
9389 SingleChar = (uint64_t) Str[i];
9390 StrVal = (StrVal << 8) | SingleChar;
9391 }
9392 // Append NULL at the end.
9393 SingleChar = 0;
9394 StrVal = (StrVal << 8) | SingleChar;
9395 }
9396 Value *NL = ConstantInt::get(StrVal);
9397 return IC.ReplaceInstUsesWith(LI, NL);
9398 }
9399 }
9400 }
9401
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009402 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9403 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9404 const Type *SrcPTy = SrcTy->getElementType();
9405
9406 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
9407 isa<VectorType>(DestPTy)) {
9408 // If the source is an array, the code below will not succeed. Check to
9409 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9410 // constants.
9411 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9412 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9413 if (ASrcTy->getNumElements() != 0) {
9414 Value *Idxs[2];
9415 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9416 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
9417 SrcTy = cast<PointerType>(CastOp->getType());
9418 SrcPTy = SrcTy->getElementType();
9419 }
9420
9421 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
9422 isa<VectorType>(SrcPTy)) &&
9423 // Do not allow turning this into a load of an integer, which is then
9424 // casted to a pointer, this pessimizes pointer analysis a lot.
9425 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
9426 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9427 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
9428
9429 // Okay, we are casting from one integer or pointer type to another of
9430 // the same size. Instead of casting the pointer before the load, cast
9431 // the result of the loaded value.
9432 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
9433 CI->getName(),
9434 LI.isVolatile()),LI);
9435 // Now cast the result of the load.
9436 return new BitCastInst(NewLoad, LI.getType());
9437 }
9438 }
9439 }
9440 return 0;
9441}
9442
9443/// isSafeToLoadUnconditionally - Return true if we know that executing a load
9444/// from this value cannot trap. If it is not obviously safe to load from the
9445/// specified pointer, we do a quick local scan of the basic block containing
9446/// ScanFrom, to determine if the address is already accessed.
9447static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands9b27dbe2007-09-19 10:10:31 +00009448 // If it is an alloca it is always safe to load from.
9449 if (isa<AllocaInst>(V)) return true;
9450
Duncan Sandse40a94a2007-09-19 10:25:38 +00009451 // If it is a global variable it is mostly safe to load from.
Duncan Sands9b27dbe2007-09-19 10:10:31 +00009452 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sandse40a94a2007-09-19 10:25:38 +00009453 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands9b27dbe2007-09-19 10:10:31 +00009454 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009455
9456 // Otherwise, be a little bit agressive by scanning the local block where we
9457 // want to check to see if the pointer is already being loaded or stored
9458 // from/to. If so, the previous load or store would have already trapped,
9459 // so there is no harm doing an extra load (also, CSE will later eliminate
9460 // the load entirely).
9461 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
9462
9463 while (BBI != E) {
9464 --BBI;
9465
9466 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9467 if (LI->getOperand(0) == V) return true;
9468 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9469 if (SI->getOperand(1) == V) return true;
9470
9471 }
9472 return false;
9473}
9474
Chris Lattner0270a112007-08-11 18:48:48 +00009475/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
9476/// until we find the underlying object a pointer is referring to or something
9477/// we don't understand. Note that the returned pointer may be offset from the
9478/// input, because we ignore GEP indices.
9479static Value *GetUnderlyingObject(Value *Ptr) {
9480 while (1) {
9481 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
9482 if (CE->getOpcode() == Instruction::BitCast ||
9483 CE->getOpcode() == Instruction::GetElementPtr)
9484 Ptr = CE->getOperand(0);
9485 else
9486 return Ptr;
9487 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
9488 Ptr = BCI->getOperand(0);
9489 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
9490 Ptr = GEP->getOperand(0);
9491 } else {
9492 return Ptr;
9493 }
9494 }
9495}
9496
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009497Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
9498 Value *Op = LI.getOperand(0);
9499
Dan Gohman5c4d0e12007-07-20 16:34:21 +00009500 // Attempt to improve the alignment.
Chris Lattner47cf3452007-08-09 19:05:49 +00009501 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op, TD);
Dan Gohman5c4d0e12007-07-20 16:34:21 +00009502 if (KnownAlign > LI.getAlignment())
9503 LI.setAlignment(KnownAlign);
9504
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009505 // load (cast X) --> cast (load X) iff safe
9506 if (isa<CastInst>(Op))
Devang Patela0f8ea82007-10-18 19:52:32 +00009507 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009508 return Res;
9509
9510 // None of the following transforms are legal for volatile loads.
9511 if (LI.isVolatile()) return 0;
9512
9513 if (&LI.getParent()->front() != &LI) {
9514 BasicBlock::iterator BBI = &LI; --BBI;
9515 // If the instruction immediately before this is a store to the same
9516 // address, do a simple form of store->load forwarding.
9517 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9518 if (SI->getOperand(1) == LI.getOperand(0))
9519 return ReplaceInstUsesWith(LI, SI->getOperand(0));
9520 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
9521 if (LIB->getOperand(0) == LI.getOperand(0))
9522 return ReplaceInstUsesWith(LI, LIB);
9523 }
9524
Christopher Lamb2c175392007-12-29 07:56:53 +00009525 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9526 const Value *GEPI0 = GEPI->getOperand(0);
9527 // TODO: Consider a target hook for valid address spaces for this xform.
9528 if (isa<ConstantPointerNull>(GEPI0) &&
9529 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009530 // Insert a new store to null instruction before the load to indicate
9531 // that this code is not reachable. We do this instead of inserting
9532 // an unreachable instruction directly because we cannot modify the
9533 // CFG.
9534 new StoreInst(UndefValue::get(LI.getType()),
9535 Constant::getNullValue(Op->getType()), &LI);
9536 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9537 }
Christopher Lamb2c175392007-12-29 07:56:53 +00009538 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009539
9540 if (Constant *C = dyn_cast<Constant>(Op)) {
9541 // load null/undef -> undef
Christopher Lamb2c175392007-12-29 07:56:53 +00009542 // TODO: Consider a target hook for valid address spaces for this xform.
9543 if (isa<UndefValue>(C) || (C->isNullValue() &&
9544 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009545 // Insert a new store to null instruction before the load to indicate that
9546 // this code is not reachable. We do this instead of inserting an
9547 // unreachable instruction directly because we cannot modify the CFG.
9548 new StoreInst(UndefValue::get(LI.getType()),
9549 Constant::getNullValue(Op->getType()), &LI);
9550 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9551 }
9552
9553 // Instcombine load (constant global) into the value loaded.
9554 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
9555 if (GV->isConstant() && !GV->isDeclaration())
9556 return ReplaceInstUsesWith(LI, GV->getInitializer());
9557
9558 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
9559 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
9560 if (CE->getOpcode() == Instruction::GetElementPtr) {
9561 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
9562 if (GV->isConstant() && !GV->isDeclaration())
9563 if (Constant *V =
9564 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
9565 return ReplaceInstUsesWith(LI, V);
9566 if (CE->getOperand(0)->isNullValue()) {
9567 // Insert a new store to null instruction before the load to indicate
9568 // that this code is not reachable. We do this instead of inserting
9569 // an unreachable instruction directly because we cannot modify the
9570 // CFG.
9571 new StoreInst(UndefValue::get(LI.getType()),
9572 Constant::getNullValue(Op->getType()), &LI);
9573 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9574 }
9575
9576 } else if (CE->isCast()) {
Devang Patela0f8ea82007-10-18 19:52:32 +00009577 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009578 return Res;
9579 }
9580 }
Chris Lattner0270a112007-08-11 18:48:48 +00009581
9582 // If this load comes from anywhere in a constant global, and if the global
9583 // is all undef or zero, we know what it loads.
9584 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
9585 if (GV->isConstant() && GV->hasInitializer()) {
9586 if (GV->getInitializer()->isNullValue())
9587 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
9588 else if (isa<UndefValue>(GV->getInitializer()))
9589 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9590 }
9591 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009592
9593 if (Op->hasOneUse()) {
9594 // Change select and PHI nodes to select values instead of addresses: this
9595 // helps alias analysis out a lot, allows many others simplifications, and
9596 // exposes redundancy in the code.
9597 //
9598 // Note that we cannot do the transformation unless we know that the
9599 // introduced loads cannot trap! Something like this is valid as long as
9600 // the condition is always false: load (select bool %C, int* null, int* %G),
9601 // but it would not be valid if we transformed it to load from null
9602 // unconditionally.
9603 //
9604 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
9605 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
9606 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
9607 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
9608 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
9609 SI->getOperand(1)->getName()+".val"), LI);
9610 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
9611 SI->getOperand(2)->getName()+".val"), LI);
9612 return new SelectInst(SI->getCondition(), V1, V2);
9613 }
9614
9615 // load (select (cond, null, P)) -> load P
9616 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
9617 if (C->isNullValue()) {
9618 LI.setOperand(0, SI->getOperand(2));
9619 return &LI;
9620 }
9621
9622 // load (select (cond, P, null)) -> load P
9623 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
9624 if (C->isNullValue()) {
9625 LI.setOperand(0, SI->getOperand(1));
9626 return &LI;
9627 }
9628 }
9629 }
9630 return 0;
9631}
9632
9633/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
9634/// when possible.
9635static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
9636 User *CI = cast<User>(SI.getOperand(1));
9637 Value *CastOp = CI->getOperand(0);
9638
9639 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9640 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9641 const Type *SrcPTy = SrcTy->getElementType();
9642
9643 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
9644 // If the source is an array, the code below will not succeed. Check to
9645 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9646 // constants.
9647 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9648 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9649 if (ASrcTy->getNumElements() != 0) {
9650 Value* Idxs[2];
9651 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9652 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
9653 SrcTy = cast<PointerType>(CastOp->getType());
9654 SrcPTy = SrcTy->getElementType();
9655 }
9656
9657 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
9658 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9659 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
9660
9661 // Okay, we are casting from one integer or pointer type to another of
9662 // the same size. Instead of casting the pointer before
9663 // the store, cast the value to be stored.
9664 Value *NewCast;
9665 Value *SIOp0 = SI.getOperand(0);
9666 Instruction::CastOps opcode = Instruction::BitCast;
9667 const Type* CastSrcTy = SIOp0->getType();
9668 const Type* CastDstTy = SrcPTy;
9669 if (isa<PointerType>(CastDstTy)) {
9670 if (CastSrcTy->isInteger())
9671 opcode = Instruction::IntToPtr;
9672 } else if (isa<IntegerType>(CastDstTy)) {
9673 if (isa<PointerType>(SIOp0->getType()))
9674 opcode = Instruction::PtrToInt;
9675 }
9676 if (Constant *C = dyn_cast<Constant>(SIOp0))
9677 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
9678 else
9679 NewCast = IC.InsertNewInstBefore(
9680 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
9681 SI);
9682 return new StoreInst(NewCast, CastOp);
9683 }
9684 }
9685 }
9686 return 0;
9687}
9688
9689Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
9690 Value *Val = SI.getOperand(0);
9691 Value *Ptr = SI.getOperand(1);
9692
9693 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
9694 EraseInstFromFunction(SI);
9695 ++NumCombined;
9696 return 0;
9697 }
9698
9699 // If the RHS is an alloca with a single use, zapify the store, making the
9700 // alloca dead.
9701 if (Ptr->hasOneUse()) {
9702 if (isa<AllocaInst>(Ptr)) {
9703 EraseInstFromFunction(SI);
9704 ++NumCombined;
9705 return 0;
9706 }
9707
9708 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
9709 if (isa<AllocaInst>(GEP->getOperand(0)) &&
9710 GEP->getOperand(0)->hasOneUse()) {
9711 EraseInstFromFunction(SI);
9712 ++NumCombined;
9713 return 0;
9714 }
9715 }
9716
Dan Gohman5c4d0e12007-07-20 16:34:21 +00009717 // Attempt to improve the alignment.
Chris Lattner47cf3452007-08-09 19:05:49 +00009718 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr, TD);
Dan Gohman5c4d0e12007-07-20 16:34:21 +00009719 if (KnownAlign > SI.getAlignment())
9720 SI.setAlignment(KnownAlign);
9721
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009722 // Do really simple DSE, to catch cases where there are several consequtive
9723 // stores to the same location, separated by a few arithmetic operations. This
9724 // situation often occurs with bitfield accesses.
9725 BasicBlock::iterator BBI = &SI;
9726 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
9727 --ScanInsts) {
9728 --BBI;
9729
9730 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
9731 // Prev store isn't volatile, and stores to the same location?
9732 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
9733 ++NumDeadStore;
9734 ++BBI;
9735 EraseInstFromFunction(*PrevSI);
9736 continue;
9737 }
9738 break;
9739 }
9740
9741 // If this is a load, we have to stop. However, if the loaded value is from
9742 // the pointer we're loading and is producing the pointer we're storing,
9743 // then *this* store is dead (X = load P; store X -> P).
9744 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattner24905f72007-09-07 05:33:03 +00009745 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009746 EraseInstFromFunction(SI);
9747 ++NumCombined;
9748 return 0;
9749 }
9750 // Otherwise, this is a load from some other location. Stores before it
9751 // may not be dead.
9752 break;
9753 }
9754
9755 // Don't skip over loads or things that can modify memory.
9756 if (BBI->mayWriteToMemory())
9757 break;
9758 }
9759
9760
9761 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
9762
9763 // store X, null -> turns into 'unreachable' in SimplifyCFG
9764 if (isa<ConstantPointerNull>(Ptr)) {
9765 if (!isa<UndefValue>(Val)) {
9766 SI.setOperand(0, UndefValue::get(Val->getType()));
9767 if (Instruction *U = dyn_cast<Instruction>(Val))
9768 AddToWorkList(U); // Dropped a use.
9769 ++NumCombined;
9770 }
9771 return 0; // Do not modify these!
9772 }
9773
9774 // store undef, Ptr -> noop
9775 if (isa<UndefValue>(Val)) {
9776 EraseInstFromFunction(SI);
9777 ++NumCombined;
9778 return 0;
9779 }
9780
9781 // If the pointer destination is a cast, see if we can fold the cast into the
9782 // source instead.
9783 if (isa<CastInst>(Ptr))
9784 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9785 return Res;
9786 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
9787 if (CE->isCast())
9788 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9789 return Res;
9790
9791
9792 // If this store is the last instruction in the basic block, and if the block
9793 // ends with an unconditional branch, try to move it to the successor block.
9794 BBI = &SI; ++BBI;
9795 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
9796 if (BI->isUnconditional())
9797 if (SimplifyStoreAtEndOfBlock(SI))
9798 return 0; // xform done!
9799
9800 return 0;
9801}
9802
9803/// SimplifyStoreAtEndOfBlock - Turn things like:
9804/// if () { *P = v1; } else { *P = v2 }
9805/// into a phi node with a store in the successor.
9806///
9807/// Simplify things like:
9808/// *P = v1; if () { *P = v2; }
9809/// into a phi node with a store in the successor.
9810///
9811bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
9812 BasicBlock *StoreBB = SI.getParent();
9813
9814 // Check to see if the successor block has exactly two incoming edges. If
9815 // so, see if the other predecessor contains a store to the same location.
9816 // if so, insert a PHI node (if needed) and move the stores down.
9817 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
9818
9819 // Determine whether Dest has exactly two predecessors and, if so, compute
9820 // the other predecessor.
9821 pred_iterator PI = pred_begin(DestBB);
9822 BasicBlock *OtherBB = 0;
9823 if (*PI != StoreBB)
9824 OtherBB = *PI;
9825 ++PI;
9826 if (PI == pred_end(DestBB))
9827 return false;
9828
9829 if (*PI != StoreBB) {
9830 if (OtherBB)
9831 return false;
9832 OtherBB = *PI;
9833 }
9834 if (++PI != pred_end(DestBB))
9835 return false;
9836
9837
9838 // Verify that the other block ends in a branch and is not otherwise empty.
9839 BasicBlock::iterator BBI = OtherBB->getTerminator();
9840 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
9841 if (!OtherBr || BBI == OtherBB->begin())
9842 return false;
9843
9844 // If the other block ends in an unconditional branch, check for the 'if then
9845 // else' case. there is an instruction before the branch.
9846 StoreInst *OtherStore = 0;
9847 if (OtherBr->isUnconditional()) {
9848 // If this isn't a store, or isn't a store to the same location, bail out.
9849 --BBI;
9850 OtherStore = dyn_cast<StoreInst>(BBI);
9851 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
9852 return false;
9853 } else {
9854 // Otherwise, the other block ended with a conditional branch. If one of the
9855 // destinations is StoreBB, then we have the if/then case.
9856 if (OtherBr->getSuccessor(0) != StoreBB &&
9857 OtherBr->getSuccessor(1) != StoreBB)
9858 return false;
9859
9860 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
9861 // if/then triangle. See if there is a store to the same ptr as SI that
9862 // lives in OtherBB.
9863 for (;; --BBI) {
9864 // Check to see if we find the matching store.
9865 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
9866 if (OtherStore->getOperand(1) != SI.getOperand(1))
9867 return false;
9868 break;
9869 }
9870 // If we find something that may be using the stored value, or if we run
9871 // out of instructions, we can't do the xform.
9872 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
9873 BBI == OtherBB->begin())
9874 return false;
9875 }
9876
9877 // In order to eliminate the store in OtherBr, we have to
9878 // make sure nothing reads the stored value in StoreBB.
9879 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
9880 // FIXME: This should really be AA driven.
9881 if (isa<LoadInst>(I) || I->mayWriteToMemory())
9882 return false;
9883 }
9884 }
9885
9886 // Insert a PHI node now if we need it.
9887 Value *MergedVal = OtherStore->getOperand(0);
9888 if (MergedVal != SI.getOperand(0)) {
9889 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
9890 PN->reserveOperandSpace(2);
9891 PN->addIncoming(SI.getOperand(0), SI.getParent());
9892 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
9893 MergedVal = InsertNewInstBefore(PN, DestBB->front());
9894 }
9895
9896 // Advance to a place where it is safe to insert the new store and
9897 // insert it.
9898 BBI = DestBB->begin();
9899 while (isa<PHINode>(BBI)) ++BBI;
9900 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
9901 OtherStore->isVolatile()), *BBI);
9902
9903 // Nuke the old stores.
9904 EraseInstFromFunction(SI);
9905 EraseInstFromFunction(*OtherStore);
9906 ++NumCombined;
9907 return true;
9908}
9909
9910
9911Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
9912 // Change br (not X), label True, label False to: br X, label False, True
9913 Value *X = 0;
9914 BasicBlock *TrueDest;
9915 BasicBlock *FalseDest;
9916 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
9917 !isa<Constant>(X)) {
9918 // Swap Destinations and condition...
9919 BI.setCondition(X);
9920 BI.setSuccessor(0, FalseDest);
9921 BI.setSuccessor(1, TrueDest);
9922 return &BI;
9923 }
9924
9925 // Cannonicalize fcmp_one -> fcmp_oeq
9926 FCmpInst::Predicate FPred; Value *Y;
9927 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
9928 TrueDest, FalseDest)))
9929 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
9930 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
9931 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
9932 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
9933 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
9934 NewSCC->takeName(I);
9935 // Swap Destinations and condition...
9936 BI.setCondition(NewSCC);
9937 BI.setSuccessor(0, FalseDest);
9938 BI.setSuccessor(1, TrueDest);
9939 RemoveFromWorkList(I);
9940 I->eraseFromParent();
9941 AddToWorkList(NewSCC);
9942 return &BI;
9943 }
9944
9945 // Cannonicalize icmp_ne -> icmp_eq
9946 ICmpInst::Predicate IPred;
9947 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
9948 TrueDest, FalseDest)))
9949 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
9950 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
9951 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
9952 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
9953 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
9954 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
9955 NewSCC->takeName(I);
9956 // Swap Destinations and condition...
9957 BI.setCondition(NewSCC);
9958 BI.setSuccessor(0, FalseDest);
9959 BI.setSuccessor(1, TrueDest);
9960 RemoveFromWorkList(I);
9961 I->eraseFromParent();;
9962 AddToWorkList(NewSCC);
9963 return &BI;
9964 }
9965
9966 return 0;
9967}
9968
9969Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
9970 Value *Cond = SI.getCondition();
9971 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
9972 if (I->getOpcode() == Instruction::Add)
9973 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
9974 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
9975 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
9976 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
9977 AddRHS));
9978 SI.setOperand(0, I->getOperand(0));
9979 AddToWorkList(I);
9980 return &SI;
9981 }
9982 }
9983 return 0;
9984}
9985
9986/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
9987/// is to leave as a vector operation.
9988static bool CheapToScalarize(Value *V, bool isConstant) {
9989 if (isa<ConstantAggregateZero>(V))
9990 return true;
9991 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
9992 if (isConstant) return true;
9993 // If all elts are the same, we can extract.
9994 Constant *Op0 = C->getOperand(0);
9995 for (unsigned i = 1; i < C->getNumOperands(); ++i)
9996 if (C->getOperand(i) != Op0)
9997 return false;
9998 return true;
9999 }
10000 Instruction *I = dyn_cast<Instruction>(V);
10001 if (!I) return false;
10002
10003 // Insert element gets simplified to the inserted element or is deleted if
10004 // this is constant idx extract element and its a constant idx insertelt.
10005 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10006 isa<ConstantInt>(I->getOperand(2)))
10007 return true;
10008 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10009 return true;
10010 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10011 if (BO->hasOneUse() &&
10012 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10013 CheapToScalarize(BO->getOperand(1), isConstant)))
10014 return true;
10015 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10016 if (CI->hasOneUse() &&
10017 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10018 CheapToScalarize(CI->getOperand(1), isConstant)))
10019 return true;
10020
10021 return false;
10022}
10023
10024/// Read and decode a shufflevector mask.
10025///
10026/// It turns undef elements into values that are larger than the number of
10027/// elements in the input.
10028static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10029 unsigned NElts = SVI->getType()->getNumElements();
10030 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10031 return std::vector<unsigned>(NElts, 0);
10032 if (isa<UndefValue>(SVI->getOperand(2)))
10033 return std::vector<unsigned>(NElts, 2*NElts);
10034
10035 std::vector<unsigned> Result;
10036 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
10037 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10038 if (isa<UndefValue>(CP->getOperand(i)))
10039 Result.push_back(NElts*2); // undef -> 8
10040 else
10041 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
10042 return Result;
10043}
10044
10045/// FindScalarElement - Given a vector and an element number, see if the scalar
10046/// value is already around as a register, for example if it were inserted then
10047/// extracted from the vector.
10048static Value *FindScalarElement(Value *V, unsigned EltNo) {
10049 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10050 const VectorType *PTy = cast<VectorType>(V->getType());
10051 unsigned Width = PTy->getNumElements();
10052 if (EltNo >= Width) // Out of range access.
10053 return UndefValue::get(PTy->getElementType());
10054
10055 if (isa<UndefValue>(V))
10056 return UndefValue::get(PTy->getElementType());
10057 else if (isa<ConstantAggregateZero>(V))
10058 return Constant::getNullValue(PTy->getElementType());
10059 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
10060 return CP->getOperand(EltNo);
10061 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10062 // If this is an insert to a variable element, we don't know what it is.
10063 if (!isa<ConstantInt>(III->getOperand(2)))
10064 return 0;
10065 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
10066
10067 // If this is an insert to the element we are looking for, return the
10068 // inserted value.
10069 if (EltNo == IIElt)
10070 return III->getOperand(1);
10071
10072 // Otherwise, the insertelement doesn't modify the value, recurse on its
10073 // vector input.
10074 return FindScalarElement(III->getOperand(0), EltNo);
10075 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
10076 unsigned InEl = getShuffleMask(SVI)[EltNo];
10077 if (InEl < Width)
10078 return FindScalarElement(SVI->getOperand(0), InEl);
10079 else if (InEl < Width*2)
10080 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10081 else
10082 return UndefValue::get(PTy->getElementType());
10083 }
10084
10085 // Otherwise, we don't know.
10086 return 0;
10087}
10088
10089Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
10090
10091 // If vector val is undef, replace extract with scalar undef.
10092 if (isa<UndefValue>(EI.getOperand(0)))
10093 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10094
10095 // If vector val is constant 0, replace extract with scalar 0.
10096 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10097 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10098
10099 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
10100 // If vector val is constant with uniform operands, replace EI
10101 // with that operand
10102 Constant *op0 = C->getOperand(0);
10103 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10104 if (C->getOperand(i) != op0) {
10105 op0 = 0;
10106 break;
10107 }
10108 if (op0)
10109 return ReplaceInstUsesWith(EI, op0);
10110 }
10111
10112 // If extracting a specified index from the vector, see if we can recursively
10113 // find a previously computed scalar that was inserted into the vector.
10114 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10115 unsigned IndexVal = IdxC->getZExtValue();
10116 unsigned VectorWidth =
10117 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10118
10119 // If this is extracting an invalid index, turn this into undef, to avoid
10120 // crashing the code below.
10121 if (IndexVal >= VectorWidth)
10122 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10123
10124 // This instruction only demands the single element from the input vector.
10125 // If the input vector has a single use, simplify it based on this use
10126 // property.
10127 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
10128 uint64_t UndefElts;
10129 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
10130 1 << IndexVal,
10131 UndefElts)) {
10132 EI.setOperand(0, V);
10133 return &EI;
10134 }
10135 }
10136
10137 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
10138 return ReplaceInstUsesWith(EI, Elt);
10139
10140 // If the this extractelement is directly using a bitcast from a vector of
10141 // the same number of elements, see if we can find the source element from
10142 // it. In this case, we will end up needing to bitcast the scalars.
10143 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10144 if (const VectorType *VT =
10145 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10146 if (VT->getNumElements() == VectorWidth)
10147 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10148 return new BitCastInst(Elt, EI.getType());
10149 }
10150 }
10151
10152 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
10153 if (I->hasOneUse()) {
10154 // Push extractelement into predecessor operation if legal and
10155 // profitable to do so
10156 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
10157 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10158 if (CheapToScalarize(BO, isConstantElt)) {
10159 ExtractElementInst *newEI0 =
10160 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10161 EI.getName()+".lhs");
10162 ExtractElementInst *newEI1 =
10163 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10164 EI.getName()+".rhs");
10165 InsertNewInstBefore(newEI0, EI);
10166 InsertNewInstBefore(newEI1, EI);
10167 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
10168 }
10169 } else if (isa<LoadInst>(I)) {
Christopher Lambbb2f2222007-12-17 01:12:55 +000010170 unsigned AS =
10171 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +000010172 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10173 PointerType::get(EI.getType(), AS),EI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010174 GetElementPtrInst *GEP =
10175 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
10176 InsertNewInstBefore(GEP, EI);
10177 return new LoadInst(GEP);
10178 }
10179 }
10180 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10181 // Extracting the inserted element?
10182 if (IE->getOperand(2) == EI.getOperand(1))
10183 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10184 // If the inserted and extracted elements are constants, they must not
10185 // be the same value, extract from the pre-inserted value instead.
10186 if (isa<Constant>(IE->getOperand(2)) &&
10187 isa<Constant>(EI.getOperand(1))) {
10188 AddUsesToWorkList(EI);
10189 EI.setOperand(0, IE->getOperand(0));
10190 return &EI;
10191 }
10192 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10193 // If this is extracting an element from a shufflevector, figure out where
10194 // it came from and extract from the appropriate input element instead.
10195 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10196 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
10197 Value *Src;
10198 if (SrcIdx < SVI->getType()->getNumElements())
10199 Src = SVI->getOperand(0);
10200 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10201 SrcIdx -= SVI->getType()->getNumElements();
10202 Src = SVI->getOperand(1);
10203 } else {
10204 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10205 }
10206 return new ExtractElementInst(Src, SrcIdx);
10207 }
10208 }
10209 }
10210 return 0;
10211}
10212
10213/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10214/// elements from either LHS or RHS, return the shuffle mask and true.
10215/// Otherwise, return false.
10216static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10217 std::vector<Constant*> &Mask) {
10218 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10219 "Invalid CollectSingleShuffleElements");
10220 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10221
10222 if (isa<UndefValue>(V)) {
10223 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10224 return true;
10225 } else if (V == LHS) {
10226 for (unsigned i = 0; i != NumElts; ++i)
10227 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10228 return true;
10229 } else if (V == RHS) {
10230 for (unsigned i = 0; i != NumElts; ++i)
10231 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
10232 return true;
10233 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10234 // If this is an insert of an extract from some other vector, include it.
10235 Value *VecOp = IEI->getOperand(0);
10236 Value *ScalarOp = IEI->getOperand(1);
10237 Value *IdxOp = IEI->getOperand(2);
10238
10239 if (!isa<ConstantInt>(IdxOp))
10240 return false;
10241 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10242
10243 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10244 // Okay, we can handle this if the vector we are insertinting into is
10245 // transitively ok.
10246 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10247 // If so, update the mask to reflect the inserted undef.
10248 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
10249 return true;
10250 }
10251 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10252 if (isa<ConstantInt>(EI->getOperand(1)) &&
10253 EI->getOperand(0)->getType() == V->getType()) {
10254 unsigned ExtractedIdx =
10255 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10256
10257 // This must be extracting from either LHS or RHS.
10258 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10259 // Okay, we can handle this if the vector we are insertinting into is
10260 // transitively ok.
10261 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10262 // If so, update the mask to reflect the inserted value.
10263 if (EI->getOperand(0) == LHS) {
10264 Mask[InsertedIdx & (NumElts-1)] =
10265 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10266 } else {
10267 assert(EI->getOperand(0) == RHS);
10268 Mask[InsertedIdx & (NumElts-1)] =
10269 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
10270
10271 }
10272 return true;
10273 }
10274 }
10275 }
10276 }
10277 }
10278 // TODO: Handle shufflevector here!
10279
10280 return false;
10281}
10282
10283/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10284/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10285/// that computes V and the LHS value of the shuffle.
10286static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
10287 Value *&RHS) {
10288 assert(isa<VectorType>(V->getType()) &&
10289 (RHS == 0 || V->getType() == RHS->getType()) &&
10290 "Invalid shuffle!");
10291 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10292
10293 if (isa<UndefValue>(V)) {
10294 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10295 return V;
10296 } else if (isa<ConstantAggregateZero>(V)) {
10297 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
10298 return V;
10299 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10300 // If this is an insert of an extract from some other vector, include it.
10301 Value *VecOp = IEI->getOperand(0);
10302 Value *ScalarOp = IEI->getOperand(1);
10303 Value *IdxOp = IEI->getOperand(2);
10304
10305 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10306 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10307 EI->getOperand(0)->getType() == V->getType()) {
10308 unsigned ExtractedIdx =
10309 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10310 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10311
10312 // Either the extracted from or inserted into vector must be RHSVec,
10313 // otherwise we'd end up with a shuffle of three inputs.
10314 if (EI->getOperand(0) == RHS || RHS == 0) {
10315 RHS = EI->getOperand(0);
10316 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
10317 Mask[InsertedIdx & (NumElts-1)] =
10318 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
10319 return V;
10320 }
10321
10322 if (VecOp == RHS) {
10323 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
10324 // Everything but the extracted element is replaced with the RHS.
10325 for (unsigned i = 0; i != NumElts; ++i) {
10326 if (i != InsertedIdx)
10327 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
10328 }
10329 return V;
10330 }
10331
10332 // If this insertelement is a chain that comes from exactly these two
10333 // vectors, return the vector and the effective shuffle.
10334 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10335 return EI->getOperand(0);
10336
10337 }
10338 }
10339 }
10340 // TODO: Handle shufflevector here!
10341
10342 // Otherwise, can't do anything fancy. Return an identity vector.
10343 for (unsigned i = 0; i != NumElts; ++i)
10344 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10345 return V;
10346}
10347
10348Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
10349 Value *VecOp = IE.getOperand(0);
10350 Value *ScalarOp = IE.getOperand(1);
10351 Value *IdxOp = IE.getOperand(2);
10352
10353 // Inserting an undef or into an undefined place, remove this.
10354 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
10355 ReplaceInstUsesWith(IE, VecOp);
10356
10357 // If the inserted element was extracted from some other vector, and if the
10358 // indexes are constant, try to turn this into a shufflevector operation.
10359 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10360 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10361 EI->getOperand(0)->getType() == IE.getType()) {
10362 unsigned NumVectorElts = IE.getType()->getNumElements();
10363 unsigned ExtractedIdx =
10364 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10365 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10366
10367 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
10368 return ReplaceInstUsesWith(IE, VecOp);
10369
10370 if (InsertedIdx >= NumVectorElts) // Out of range insert.
10371 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
10372
10373 // If we are extracting a value from a vector, then inserting it right
10374 // back into the same place, just use the input vector.
10375 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
10376 return ReplaceInstUsesWith(IE, VecOp);
10377
10378 // We could theoretically do this for ANY input. However, doing so could
10379 // turn chains of insertelement instructions into a chain of shufflevector
10380 // instructions, and right now we do not merge shufflevectors. As such,
10381 // only do this in a situation where it is clear that there is benefit.
10382 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
10383 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
10384 // the values of VecOp, except then one read from EIOp0.
10385 // Build a new shuffle mask.
10386 std::vector<Constant*> Mask;
10387 if (isa<UndefValue>(VecOp))
10388 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
10389 else {
10390 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
10391 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
10392 NumVectorElts));
10393 }
10394 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10395 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
10396 ConstantVector::get(Mask));
10397 }
10398
10399 // If this insertelement isn't used by some other insertelement, turn it
10400 // (and any insertelements it points to), into one big shuffle.
10401 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
10402 std::vector<Constant*> Mask;
10403 Value *RHS = 0;
10404 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
10405 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
10406 // We now have a shuffle of LHS, RHS, Mask.
10407 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
10408 }
10409 }
10410 }
10411
10412 return 0;
10413}
10414
10415
10416Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
10417 Value *LHS = SVI.getOperand(0);
10418 Value *RHS = SVI.getOperand(1);
10419 std::vector<unsigned> Mask = getShuffleMask(&SVI);
10420
10421 bool MadeChange = false;
10422
10423 // Undefined shuffle mask -> undefined value.
10424 if (isa<UndefValue>(SVI.getOperand(2)))
10425 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
10426
10427 // If we have shuffle(x, undef, mask) and any elements of mask refer to
10428 // the undef, change them to undefs.
10429 if (isa<UndefValue>(SVI.getOperand(1))) {
10430 // Scan to see if there are any references to the RHS. If so, replace them
10431 // with undef element refs and set MadeChange to true.
10432 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10433 if (Mask[i] >= e && Mask[i] != 2*e) {
10434 Mask[i] = 2*e;
10435 MadeChange = true;
10436 }
10437 }
10438
10439 if (MadeChange) {
10440 // Remap any references to RHS to use LHS.
10441 std::vector<Constant*> Elts;
10442 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10443 if (Mask[i] == 2*e)
10444 Elts.push_back(UndefValue::get(Type::Int32Ty));
10445 else
10446 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10447 }
10448 SVI.setOperand(2, ConstantVector::get(Elts));
10449 }
10450 }
10451
10452 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
10453 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
10454 if (LHS == RHS || isa<UndefValue>(LHS)) {
10455 if (isa<UndefValue>(LHS) && LHS == RHS) {
10456 // shuffle(undef,undef,mask) -> undef.
10457 return ReplaceInstUsesWith(SVI, LHS);
10458 }
10459
10460 // Remap any references to RHS to use LHS.
10461 std::vector<Constant*> Elts;
10462 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10463 if (Mask[i] >= 2*e)
10464 Elts.push_back(UndefValue::get(Type::Int32Ty));
10465 else {
10466 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
10467 (Mask[i] < e && isa<UndefValue>(LHS)))
10468 Mask[i] = 2*e; // Turn into undef.
10469 else
10470 Mask[i] &= (e-1); // Force to LHS.
10471 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10472 }
10473 }
10474 SVI.setOperand(0, SVI.getOperand(1));
10475 SVI.setOperand(1, UndefValue::get(RHS->getType()));
10476 SVI.setOperand(2, ConstantVector::get(Elts));
10477 LHS = SVI.getOperand(0);
10478 RHS = SVI.getOperand(1);
10479 MadeChange = true;
10480 }
10481
10482 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
10483 bool isLHSID = true, isRHSID = true;
10484
10485 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10486 if (Mask[i] >= e*2) continue; // Ignore undef values.
10487 // Is this an identity shuffle of the LHS value?
10488 isLHSID &= (Mask[i] == i);
10489
10490 // Is this an identity shuffle of the RHS value?
10491 isRHSID &= (Mask[i]-e == i);
10492 }
10493
10494 // Eliminate identity shuffles.
10495 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
10496 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
10497
10498 // If the LHS is a shufflevector itself, see if we can combine it with this
10499 // one without producing an unusual shuffle. Here we are really conservative:
10500 // we are absolutely afraid of producing a shuffle mask not in the input
10501 // program, because the code gen may not be smart enough to turn a merged
10502 // shuffle into two specific shuffles: it may produce worse code. As such,
10503 // we only merge two shuffles if the result is one of the two input shuffle
10504 // masks. In this case, merging the shuffles just removes one instruction,
10505 // which we know is safe. This is good for things like turning:
10506 // (splat(splat)) -> splat.
10507 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
10508 if (isa<UndefValue>(RHS)) {
10509 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
10510
10511 std::vector<unsigned> NewMask;
10512 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
10513 if (Mask[i] >= 2*e)
10514 NewMask.push_back(2*e);
10515 else
10516 NewMask.push_back(LHSMask[Mask[i]]);
10517
10518 // If the result mask is equal to the src shuffle or this shuffle mask, do
10519 // the replacement.
10520 if (NewMask == LHSMask || NewMask == Mask) {
10521 std::vector<Constant*> Elts;
10522 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
10523 if (NewMask[i] >= e*2) {
10524 Elts.push_back(UndefValue::get(Type::Int32Ty));
10525 } else {
10526 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
10527 }
10528 }
10529 return new ShuffleVectorInst(LHSSVI->getOperand(0),
10530 LHSSVI->getOperand(1),
10531 ConstantVector::get(Elts));
10532 }
10533 }
10534 }
10535
10536 return MadeChange ? &SVI : 0;
10537}
10538
10539
10540
10541
10542/// TryToSinkInstruction - Try to move the specified instruction from its
10543/// current block into the beginning of DestBlock, which can only happen if it's
10544/// safe to move the instruction past all of the instructions between it and the
10545/// end of its block.
10546static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
10547 assert(I->hasOneUse() && "Invariants didn't hold!");
10548
10549 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
10550 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
10551
10552 // Do not sink alloca instructions out of the entry block.
10553 if (isa<AllocaInst>(I) && I->getParent() ==
10554 &DestBlock->getParent()->getEntryBlock())
10555 return false;
10556
10557 // We can only sink load instructions if there is nothing between the load and
10558 // the end of block that could change the value.
10559 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10560 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
10561 Scan != E; ++Scan)
10562 if (Scan->mayWriteToMemory())
10563 return false;
10564 }
10565
10566 BasicBlock::iterator InsertPos = DestBlock->begin();
10567 while (isa<PHINode>(InsertPos)) ++InsertPos;
10568
10569 I->moveBefore(InsertPos);
10570 ++NumSunkInst;
10571 return true;
10572}
10573
10574
10575/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
10576/// all reachable code to the worklist.
10577///
10578/// This has a couple of tricks to make the code faster and more powerful. In
10579/// particular, we constant fold and DCE instructions as we go, to avoid adding
10580/// them to the worklist (this significantly speeds up instcombine on code where
10581/// many instructions are dead or constant). Additionally, if we find a branch
10582/// whose condition is a known constant, we only visit the reachable successors.
10583///
10584static void AddReachableCodeToWorklist(BasicBlock *BB,
10585 SmallPtrSet<BasicBlock*, 64> &Visited,
10586 InstCombiner &IC,
10587 const TargetData *TD) {
10588 std::vector<BasicBlock*> Worklist;
10589 Worklist.push_back(BB);
10590
10591 while (!Worklist.empty()) {
10592 BB = Worklist.back();
10593 Worklist.pop_back();
10594
10595 // We have now visited this block! If we've already been here, ignore it.
10596 if (!Visited.insert(BB)) continue;
10597
10598 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
10599 Instruction *Inst = BBI++;
10600
10601 // DCE instruction if trivially dead.
10602 if (isInstructionTriviallyDead(Inst)) {
10603 ++NumDeadInst;
10604 DOUT << "IC: DCE: " << *Inst;
10605 Inst->eraseFromParent();
10606 continue;
10607 }
10608
10609 // ConstantProp instruction if trivially constant.
10610 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
10611 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
10612 Inst->replaceAllUsesWith(C);
10613 ++NumConstProp;
10614 Inst->eraseFromParent();
10615 continue;
10616 }
Chris Lattnere0f462d2007-07-20 22:06:41 +000010617
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010618 IC.AddToWorkList(Inst);
10619 }
10620
10621 // Recursively visit successors. If this is a branch or switch on a
10622 // constant, only visit the reachable successor.
10623 TerminatorInst *TI = BB->getTerminator();
10624 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
10625 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
10626 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
10627 Worklist.push_back(BI->getSuccessor(!CondVal));
10628 continue;
10629 }
10630 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
10631 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
10632 // See if this is an explicit destination.
10633 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
10634 if (SI->getCaseValue(i) == Cond) {
10635 Worklist.push_back(SI->getSuccessor(i));
10636 continue;
10637 }
10638
10639 // Otherwise it is the default destination.
10640 Worklist.push_back(SI->getSuccessor(0));
10641 continue;
10642 }
10643 }
10644
10645 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
10646 Worklist.push_back(TI->getSuccessor(i));
10647 }
10648}
10649
10650bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
10651 bool Changed = false;
10652 TD = &getAnalysis<TargetData>();
10653
10654 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
10655 << F.getNameStr() << "\n");
10656
10657 {
10658 // Do a depth-first traversal of the function, populate the worklist with
10659 // the reachable instructions. Ignore blocks that are not reachable. Keep
10660 // track of which blocks we visit.
10661 SmallPtrSet<BasicBlock*, 64> Visited;
10662 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
10663
10664 // Do a quick scan over the function. If we find any blocks that are
10665 // unreachable, remove any instructions inside of them. This prevents
10666 // the instcombine code from having to deal with some bad special cases.
10667 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
10668 if (!Visited.count(BB)) {
10669 Instruction *Term = BB->getTerminator();
10670 while (Term != BB->begin()) { // Remove instrs bottom-up
10671 BasicBlock::iterator I = Term; --I;
10672
10673 DOUT << "IC: DCE: " << *I;
10674 ++NumDeadInst;
10675
10676 if (!I->use_empty())
10677 I->replaceAllUsesWith(UndefValue::get(I->getType()));
10678 I->eraseFromParent();
10679 }
10680 }
10681 }
10682
10683 while (!Worklist.empty()) {
10684 Instruction *I = RemoveOneFromWorkList();
10685 if (I == 0) continue; // skip null values.
10686
10687 // Check to see if we can DCE the instruction.
10688 if (isInstructionTriviallyDead(I)) {
10689 // Add operands to the worklist.
10690 if (I->getNumOperands() < 4)
10691 AddUsesToWorkList(*I);
10692 ++NumDeadInst;
10693
10694 DOUT << "IC: DCE: " << *I;
10695
10696 I->eraseFromParent();
10697 RemoveFromWorkList(I);
10698 continue;
10699 }
10700
10701 // Instruction isn't dead, see if we can constant propagate it.
10702 if (Constant *C = ConstantFoldInstruction(I, TD)) {
10703 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
10704
10705 // Add operands to the worklist.
10706 AddUsesToWorkList(*I);
10707 ReplaceInstUsesWith(*I, C);
10708
10709 ++NumConstProp;
10710 I->eraseFromParent();
10711 RemoveFromWorkList(I);
10712 continue;
10713 }
10714
10715 // See if we can trivially sink this instruction to a successor basic block.
10716 if (I->hasOneUse()) {
10717 BasicBlock *BB = I->getParent();
10718 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
10719 if (UserParent != BB) {
10720 bool UserIsSuccessor = false;
10721 // See if the user is one of our successors.
10722 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
10723 if (*SI == UserParent) {
10724 UserIsSuccessor = true;
10725 break;
10726 }
10727
10728 // If the user is one of our immediate successors, and if that successor
10729 // only has us as a predecessors (we'd have to split the critical edge
10730 // otherwise), we can keep going.
10731 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
10732 next(pred_begin(UserParent)) == pred_end(UserParent))
10733 // Okay, the CFG is simple enough, try to sink this instruction.
10734 Changed |= TryToSinkInstruction(I, UserParent);
10735 }
10736 }
10737
10738 // Now that we have an instruction, try combining it to simplify it...
10739#ifndef NDEBUG
10740 std::string OrigI;
10741#endif
10742 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
10743 if (Instruction *Result = visit(*I)) {
10744 ++NumCombined;
10745 // Should we replace the old instruction with a new one?
10746 if (Result != I) {
10747 DOUT << "IC: Old = " << *I
10748 << " New = " << *Result;
10749
10750 // Everything uses the new instruction now.
10751 I->replaceAllUsesWith(Result);
10752
10753 // Push the new instruction and any users onto the worklist.
10754 AddToWorkList(Result);
10755 AddUsersToWorkList(*Result);
10756
10757 // Move the name to the new instruction first.
10758 Result->takeName(I);
10759
10760 // Insert the new instruction into the basic block...
10761 BasicBlock *InstParent = I->getParent();
10762 BasicBlock::iterator InsertPos = I;
10763
10764 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
10765 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
10766 ++InsertPos;
10767
10768 InstParent->getInstList().insert(InsertPos, Result);
10769
10770 // Make sure that we reprocess all operands now that we reduced their
10771 // use counts.
10772 AddUsesToWorkList(*I);
10773
10774 // Instructions can end up on the worklist more than once. Make sure
10775 // we do not process an instruction that has been deleted.
10776 RemoveFromWorkList(I);
10777
10778 // Erase the old instruction.
10779 InstParent->getInstList().erase(I);
10780 } else {
10781#ifndef NDEBUG
10782 DOUT << "IC: Mod = " << OrigI
10783 << " New = " << *I;
10784#endif
10785
10786 // If the instruction was modified, it's possible that it is now dead.
10787 // if so, remove it.
10788 if (isInstructionTriviallyDead(I)) {
10789 // Make sure we process all operands now that we are reducing their
10790 // use counts.
10791 AddUsesToWorkList(*I);
10792
10793 // Instructions may end up in the worklist more than once. Erase all
10794 // occurrences of this instruction.
10795 RemoveFromWorkList(I);
10796 I->eraseFromParent();
10797 } else {
10798 AddToWorkList(I);
10799 AddUsersToWorkList(*I);
10800 }
10801 }
10802 Changed = true;
10803 }
10804 }
10805
10806 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnerb933ea62007-08-05 08:47:58 +000010807
10808 // Do an explicit clear, this shrinks the map if needed.
10809 WorklistMap.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010810 return Changed;
10811}
10812
10813
10814bool InstCombiner::runOnFunction(Function &F) {
10815 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
10816
10817 bool EverMadeChange = false;
10818
10819 // Iterate while there is work to do.
10820 unsigned Iteration = 0;
10821 while (DoOneIteration(F, Iteration++))
10822 EverMadeChange = true;
10823 return EverMadeChange;
10824}
10825
10826FunctionPass *llvm::createInstructionCombiningPass() {
10827 return new InstCombiner();
10828}
10829