blob: 5582f511340b4d5691d3c761b28c56e603fbc7b2 [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"
Nick Lewycky0185bbf2008-02-03 16:33:09 +000048#include "llvm/Support/ConstantRange.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000049#include "llvm/Support/Debug.h"
50#include "llvm/Support/GetElementPtrTypeIterator.h"
51#include "llvm/Support/InstVisitor.h"
52#include "llvm/Support/MathExtras.h"
53#include "llvm/Support/PatternMatch.h"
54#include "llvm/Support/Compiler.h"
55#include "llvm/ADT/DenseMap.h"
56#include "llvm/ADT/SmallVector.h"
57#include "llvm/ADT/SmallPtrSet.h"
58#include "llvm/ADT/Statistic.h"
59#include "llvm/ADT/STLExtras.h"
60#include <algorithm>
61#include <sstream>
62using namespace llvm;
63using namespace llvm::PatternMatch;
64
65STATISTIC(NumCombined , "Number of insts combined");
66STATISTIC(NumConstProp, "Number of constant folds");
67STATISTIC(NumDeadInst , "Number of dead inst eliminated");
68STATISTIC(NumDeadStore, "Number of dead stores eliminated");
69STATISTIC(NumSunkInst , "Number of instructions sunk");
70
71namespace {
72 class VISIBILITY_HIDDEN InstCombiner
73 : public FunctionPass,
74 public InstVisitor<InstCombiner, Instruction*> {
75 // Worklist of all of the instructions that need to be simplified.
76 std::vector<Instruction*> Worklist;
77 DenseMap<Instruction*, unsigned> WorklistMap;
78 TargetData *TD;
79 bool MustPreserveLCSSA;
80 public:
81 static char ID; // Pass identification, replacement for typeid
82 InstCombiner() : FunctionPass((intptr_t)&ID) {}
83
84 /// AddToWorkList - Add the specified instruction to the worklist if it
85 /// isn't already in it.
86 void AddToWorkList(Instruction *I) {
87 if (WorklistMap.insert(std::make_pair(I, Worklist.size())))
88 Worklist.push_back(I);
89 }
90
91 // RemoveFromWorkList - remove I from the worklist if it exists.
92 void RemoveFromWorkList(Instruction *I) {
93 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
94 if (It == WorklistMap.end()) return; // Not in worklist.
95
96 // Don't bother moving everything down, just null out the slot.
97 Worklist[It->second] = 0;
98
99 WorklistMap.erase(It);
100 }
101
102 Instruction *RemoveOneFromWorkList() {
103 Instruction *I = Worklist.back();
104 Worklist.pop_back();
105 WorklistMap.erase(I);
106 return I;
107 }
108
109
110 /// AddUsersToWorkList - When an instruction is simplified, add all users of
111 /// the instruction to the work lists because they might get more simplified
112 /// now.
113 ///
114 void AddUsersToWorkList(Value &I) {
115 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
116 UI != UE; ++UI)
117 AddToWorkList(cast<Instruction>(*UI));
118 }
119
120 /// AddUsesToWorkList - When an instruction is simplified, add operands to
121 /// the work lists because they might get more simplified now.
122 ///
123 void AddUsesToWorkList(Instruction &I) {
124 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
125 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i)))
126 AddToWorkList(Op);
127 }
128
129 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
130 /// dead. Add all of its operands to the worklist, turning them into
131 /// undef's to reduce the number of uses of those instructions.
132 ///
133 /// Return the specified operand before it is turned into an undef.
134 ///
135 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
136 Value *R = I.getOperand(op);
137
138 for (unsigned i = 0, e = I.getNumOperands(); i != e; ++i)
139 if (Instruction *Op = dyn_cast<Instruction>(I.getOperand(i))) {
140 AddToWorkList(Op);
141 // Set the operand to undef to drop the use.
142 I.setOperand(i, UndefValue::get(Op->getType()));
143 }
144
145 return R;
146 }
147
148 public:
149 virtual bool runOnFunction(Function &F);
150
151 bool DoOneIteration(Function &F, unsigned ItNum);
152
153 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
154 AU.addRequired<TargetData>();
155 AU.addPreservedID(LCSSAID);
156 AU.setPreservesCFG();
157 }
158
159 TargetData &getTargetData() const { return *TD; }
160
161 // Visitation implementation - Implement instruction combining for different
162 // instruction types. The semantics are as follows:
163 // Return Value:
164 // null - No change was made
165 // I - Change was made, I is still valid, I may be dead though
166 // otherwise - Change was made, replace I with returned instruction
167 //
168 Instruction *visitAdd(BinaryOperator &I);
169 Instruction *visitSub(BinaryOperator &I);
170 Instruction *visitMul(BinaryOperator &I);
171 Instruction *visitURem(BinaryOperator &I);
172 Instruction *visitSRem(BinaryOperator &I);
173 Instruction *visitFRem(BinaryOperator &I);
174 Instruction *commonRemTransforms(BinaryOperator &I);
175 Instruction *commonIRemTransforms(BinaryOperator &I);
176 Instruction *commonDivTransforms(BinaryOperator &I);
177 Instruction *commonIDivTransforms(BinaryOperator &I);
178 Instruction *visitUDiv(BinaryOperator &I);
179 Instruction *visitSDiv(BinaryOperator &I);
180 Instruction *visitFDiv(BinaryOperator &I);
181 Instruction *visitAnd(BinaryOperator &I);
182 Instruction *visitOr (BinaryOperator &I);
183 Instruction *visitXor(BinaryOperator &I);
184 Instruction *visitShl(BinaryOperator &I);
185 Instruction *visitAShr(BinaryOperator &I);
186 Instruction *visitLShr(BinaryOperator &I);
187 Instruction *commonShiftTransforms(BinaryOperator &I);
188 Instruction *visitFCmpInst(FCmpInst &I);
189 Instruction *visitICmpInst(ICmpInst &I);
190 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
191 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
192 Instruction *LHS,
193 ConstantInt *RHS);
194 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
195 ConstantInt *DivRHS);
196
197 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
198 ICmpInst::Predicate Cond, Instruction &I);
199 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
200 BinaryOperator &I);
201 Instruction *commonCastTransforms(CastInst &CI);
202 Instruction *commonIntCastTransforms(CastInst &CI);
203 Instruction *commonPointerCastTransforms(CastInst &CI);
204 Instruction *visitTrunc(TruncInst &CI);
205 Instruction *visitZExt(ZExtInst &CI);
206 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerdf7e8402008-01-27 05:29:54 +0000207 Instruction *visitFPTrunc(FPTruncInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000208 Instruction *visitFPExt(CastInst &CI);
209 Instruction *visitFPToUI(CastInst &CI);
210 Instruction *visitFPToSI(CastInst &CI);
211 Instruction *visitUIToFP(CastInst &CI);
212 Instruction *visitSIToFP(CastInst &CI);
213 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattner7c1626482008-01-08 07:23:51 +0000214 Instruction *visitIntToPtr(IntToPtrInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000215 Instruction *visitBitCast(BitCastInst &CI);
216 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
217 Instruction *FI);
218 Instruction *visitSelectInst(SelectInst &CI);
219 Instruction *visitCallInst(CallInst &CI);
220 Instruction *visitInvokeInst(InvokeInst &II);
221 Instruction *visitPHINode(PHINode &PN);
222 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
223 Instruction *visitAllocationInst(AllocationInst &AI);
224 Instruction *visitFreeInst(FreeInst &FI);
225 Instruction *visitLoadInst(LoadInst &LI);
226 Instruction *visitStoreInst(StoreInst &SI);
227 Instruction *visitBranchInst(BranchInst &BI);
228 Instruction *visitSwitchInst(SwitchInst &SI);
229 Instruction *visitInsertElementInst(InsertElementInst &IE);
230 Instruction *visitExtractElementInst(ExtractElementInst &EI);
231 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
232
233 // visitInstruction - Specify what to return for unhandled instructions...
234 Instruction *visitInstruction(Instruction &I) { return 0; }
235
236 private:
237 Instruction *visitCallSite(CallSite CS);
238 bool transformConstExprCastCall(CallSite CS);
Duncan Sands74833f22007-09-17 10:26:40 +0000239 Instruction *transformCallThroughTrampoline(CallSite CS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000240
241 public:
242 // InsertNewInstBefore - insert an instruction New before instruction Old
243 // in the program. Add the new instruction to the worklist.
244 //
245 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
246 assert(New && New->getParent() == 0 &&
247 "New instruction already inserted into a basic block!");
248 BasicBlock *BB = Old.getParent();
249 BB->getInstList().insert(&Old, New); // Insert inst
250 AddToWorkList(New);
251 return New;
252 }
253
254 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
255 /// This also adds the cast to the worklist. Finally, this returns the
256 /// cast.
257 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
258 Instruction &Pos) {
259 if (V->getType() == Ty) return V;
260
261 if (Constant *CV = dyn_cast<Constant>(V))
262 return ConstantExpr::getCast(opc, CV, Ty);
263
264 Instruction *C = CastInst::create(opc, V, Ty, V->getName(), &Pos);
265 AddToWorkList(C);
266 return C;
267 }
Chris Lattner13c2d6e2008-01-13 22:23:22 +0000268
269 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
270 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
271 }
272
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000273
274 // ReplaceInstUsesWith - This method is to be used when an instruction is
275 // found to be dead, replacable with another preexisting expression. Here
276 // we add all uses of I to the worklist, replace all uses of I with the new
277 // value, then return I, so that the inst combiner will know that I was
278 // modified.
279 //
280 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
281 AddUsersToWorkList(I); // Add all modified instrs to worklist
282 if (&I != V) {
283 I.replaceAllUsesWith(V);
284 return &I;
285 } else {
286 // If we are replacing the instruction with itself, this must be in a
287 // segment of unreachable code, so just clobber the instruction.
288 I.replaceAllUsesWith(UndefValue::get(I.getType()));
289 return &I;
290 }
291 }
292
293 // UpdateValueUsesWith - This method is to be used when an value is
294 // found to be replacable with another preexisting expression or was
295 // updated. Here we add all uses of I to the worklist, replace all uses of
296 // I with the new value (unless the instruction was just updated), then
297 // return true, so that the inst combiner will know that I was modified.
298 //
299 bool UpdateValueUsesWith(Value *Old, Value *New) {
300 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
301 if (Old != New)
302 Old->replaceAllUsesWith(New);
303 if (Instruction *I = dyn_cast<Instruction>(Old))
304 AddToWorkList(I);
305 if (Instruction *I = dyn_cast<Instruction>(New))
306 AddToWorkList(I);
307 return true;
308 }
309
310 // EraseInstFromFunction - When dealing with an instruction that has side
311 // effects or produces a void value, we can't rely on DCE to delete the
312 // instruction. Instead, visit methods should return the value returned by
313 // this function.
314 Instruction *EraseInstFromFunction(Instruction &I) {
315 assert(I.use_empty() && "Cannot erase instruction that is used!");
316 AddUsesToWorkList(I);
317 RemoveFromWorkList(&I);
318 I.eraseFromParent();
319 return 0; // Don't do anything with FI
320 }
321
322 private:
323 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
324 /// InsertBefore instruction. This is specialized a bit to avoid inserting
325 /// casts that are known to not do anything...
326 ///
327 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
328 Value *V, const Type *DestTy,
329 Instruction *InsertBefore);
330
331 /// SimplifyCommutative - This performs a few simplifications for
332 /// commutative operators.
333 bool SimplifyCommutative(BinaryOperator &I);
334
335 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
336 /// most-complex to least-complex order.
337 bool SimplifyCompare(CmpInst &I);
338
339 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
340 /// on the demanded bits.
341 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
342 APInt& KnownZero, APInt& KnownOne,
343 unsigned Depth = 0);
344
345 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
346 uint64_t &UndefElts, unsigned Depth = 0);
347
348 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
349 // PHI node as operand #0, see if we can fold the instruction into the PHI
350 // (which is only possible if all operands to the PHI are constants).
351 Instruction *FoldOpIntoPhi(Instruction &I);
352
353 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
354 // operator and they all are only used by the PHI, PHI together their
355 // inputs, and do the operation once, to the result of the PHI.
356 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
357 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
358
359
360 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
361 ConstantInt *AndRHS, BinaryOperator &TheAnd);
362
363 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
364 bool isSub, Instruction &I);
365 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
366 bool isSigned, bool Inside, Instruction &IB);
367 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
368 Instruction *MatchBSwap(BinaryOperator &I);
369 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000370 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
371
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000372
373 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
374 };
375
376 char InstCombiner::ID = 0;
377 RegisterPass<InstCombiner> X("instcombine", "Combine redundant instructions");
378}
379
380// getComplexity: Assign a complexity or rank value to LLVM Values...
381// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
382static unsigned getComplexity(Value *V) {
383 if (isa<Instruction>(V)) {
384 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
385 return 3;
386 return 4;
387 }
388 if (isa<Argument>(V)) return 3;
389 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
390}
391
392// isOnlyUse - Return true if this instruction will be deleted if we stop using
393// it.
394static bool isOnlyUse(Value *V) {
395 return V->hasOneUse() || isa<Constant>(V);
396}
397
398// getPromotedType - Return the specified type promoted as it would be to pass
399// though a va_arg area...
400static const Type *getPromotedType(const Type *Ty) {
401 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
402 if (ITy->getBitWidth() < 32)
403 return Type::Int32Ty;
404 }
405 return Ty;
406}
407
408/// getBitCastOperand - If the specified operand is a CastInst or a constant
409/// expression bitcast, return the operand value, otherwise return null.
410static Value *getBitCastOperand(Value *V) {
411 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
412 return I->getOperand(0);
413 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
414 if (CE->getOpcode() == Instruction::BitCast)
415 return CE->getOperand(0);
416 return 0;
417}
418
419/// This function is a wrapper around CastInst::isEliminableCastPair. It
420/// simply extracts arguments and returns what that function returns.
421static Instruction::CastOps
422isEliminableCastPair(
423 const CastInst *CI, ///< The first cast instruction
424 unsigned opcode, ///< The opcode of the second cast instruction
425 const Type *DstTy, ///< The target type for the second cast instruction
426 TargetData *TD ///< The target data for pointer size
427) {
428
429 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
430 const Type *MidTy = CI->getType(); // B from above
431
432 // Get the opcodes of the two Cast instructions
433 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
434 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
435
436 return Instruction::CastOps(
437 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
438 DstTy, TD->getIntPtrType()));
439}
440
441/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
442/// in any code being generated. It does not require codegen if V is simple
443/// enough or if the cast can be folded into other casts.
444static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
445 const Type *Ty, TargetData *TD) {
446 if (V->getType() == Ty || isa<Constant>(V)) return false;
447
448 // If this is another cast that can be eliminated, it isn't codegen either.
449 if (const CastInst *CI = dyn_cast<CastInst>(V))
450 if (isEliminableCastPair(CI, opcode, Ty, TD))
451 return false;
452 return true;
453}
454
455/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
456/// InsertBefore instruction. This is specialized a bit to avoid inserting
457/// casts that are known to not do anything...
458///
459Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
460 Value *V, const Type *DestTy,
461 Instruction *InsertBefore) {
462 if (V->getType() == DestTy) return V;
463 if (Constant *C = dyn_cast<Constant>(V))
464 return ConstantExpr::getCast(opcode, C, DestTy);
465
466 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
467}
468
469// SimplifyCommutative - This performs a few simplifications for commutative
470// operators:
471//
472// 1. Order operands such that they are listed from right (least complex) to
473// left (most complex). This puts constants before unary operators before
474// binary operators.
475//
476// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
477// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
478//
479bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
480 bool Changed = false;
481 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
482 Changed = !I.swapOperands();
483
484 if (!I.isAssociative()) return Changed;
485 Instruction::BinaryOps Opcode = I.getOpcode();
486 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
487 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
488 if (isa<Constant>(I.getOperand(1))) {
489 Constant *Folded = ConstantExpr::get(I.getOpcode(),
490 cast<Constant>(I.getOperand(1)),
491 cast<Constant>(Op->getOperand(1)));
492 I.setOperand(0, Op->getOperand(0));
493 I.setOperand(1, Folded);
494 return true;
495 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
496 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
497 isOnlyUse(Op) && isOnlyUse(Op1)) {
498 Constant *C1 = cast<Constant>(Op->getOperand(1));
499 Constant *C2 = cast<Constant>(Op1->getOperand(1));
500
501 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
502 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
503 Instruction *New = BinaryOperator::create(Opcode, Op->getOperand(0),
504 Op1->getOperand(0),
505 Op1->getName(), &I);
506 AddToWorkList(New);
507 I.setOperand(0, New);
508 I.setOperand(1, Folded);
509 return true;
510 }
511 }
512 return Changed;
513}
514
515/// SimplifyCompare - For a CmpInst this function just orders the operands
516/// so that theyare listed from right (least complex) to left (most complex).
517/// This puts constants before unary operators before binary operators.
518bool InstCombiner::SimplifyCompare(CmpInst &I) {
519 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
520 return false;
521 I.swapOperands();
522 // Compare instructions are not associative so there's nothing else we can do.
523 return true;
524}
525
526// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
527// if the LHS is a constant zero (which is the 'negate' form).
528//
529static inline Value *dyn_castNegVal(Value *V) {
530 if (BinaryOperator::isNeg(V))
531 return BinaryOperator::getNegArgument(V);
532
533 // Constants can be considered to be negated values if they can be folded.
534 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
535 return ConstantExpr::getNeg(C);
536 return 0;
537}
538
539static inline Value *dyn_castNotVal(Value *V) {
540 if (BinaryOperator::isNot(V))
541 return BinaryOperator::getNotArgument(V);
542
543 // Constants can be considered to be not'ed values...
544 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
545 return ConstantInt::get(~C->getValue());
546 return 0;
547}
548
549// dyn_castFoldableMul - If this value is a multiply that can be folded into
550// other computations (because it has a constant operand), return the
551// non-constant operand of the multiply, and set CST to point to the multiplier.
552// Otherwise, return null.
553//
554static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
555 if (V->hasOneUse() && V->getType()->isInteger())
556 if (Instruction *I = dyn_cast<Instruction>(V)) {
557 if (I->getOpcode() == Instruction::Mul)
558 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
559 return I->getOperand(0);
560 if (I->getOpcode() == Instruction::Shl)
561 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
562 // The multiplier is really 1 << CST.
563 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
564 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
565 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
566 return I->getOperand(0);
567 }
568 }
569 return 0;
570}
571
572/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
573/// expression, return it.
574static User *dyn_castGetElementPtr(Value *V) {
575 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
576 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
577 if (CE->getOpcode() == Instruction::GetElementPtr)
578 return cast<User>(V);
579 return false;
580}
581
582/// AddOne - Add one to a ConstantInt
583static ConstantInt *AddOne(ConstantInt *C) {
584 APInt Val(C->getValue());
585 return ConstantInt::get(++Val);
586}
587/// SubOne - Subtract one from a ConstantInt
588static ConstantInt *SubOne(ConstantInt *C) {
589 APInt Val(C->getValue());
590 return ConstantInt::get(--Val);
591}
592/// Add - Add two ConstantInts together
593static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
594 return ConstantInt::get(C1->getValue() + C2->getValue());
595}
596/// And - Bitwise AND two ConstantInts together
597static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
598 return ConstantInt::get(C1->getValue() & C2->getValue());
599}
600/// Subtract - Subtract one ConstantInt from another
601static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
602 return ConstantInt::get(C1->getValue() - C2->getValue());
603}
604/// Multiply - Multiply two ConstantInts together
605static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
606 return ConstantInt::get(C1->getValue() * C2->getValue());
607}
Nick Lewycky9d798f92008-02-18 22:48:05 +0000608/// MultiplyOverflows - True if the multiply can not be expressed in an int
609/// this size.
610static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
611 uint32_t W = C1->getBitWidth();
612 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
613 if (sign) {
614 LHSExt.sext(W * 2);
615 RHSExt.sext(W * 2);
616 } else {
617 LHSExt.zext(W * 2);
618 RHSExt.zext(W * 2);
619 }
620
621 APInt MulExt = LHSExt * RHSExt;
622
623 if (sign) {
624 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
625 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
626 return MulExt.slt(Min) || MulExt.sgt(Max);
627 } else
628 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
629}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000630
631/// ComputeMaskedBits - Determine which of the bits specified in Mask are
632/// known to be either zero or one and return them in the KnownZero/KnownOne
633/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
634/// processing.
635/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
636/// we cannot optimize based on the assumption that it is zero without changing
637/// it to be an explicit zero. If we don't change it to zero, other code could
638/// optimized based on the contradictory assumption that it is non-zero.
639/// Because instcombine aggressively folds operations with undef args anyway,
640/// this won't lose us code quality.
641static void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
642 APInt& KnownOne, unsigned Depth = 0) {
643 assert(V && "No Value?");
644 assert(Depth <= 6 && "Limit Search Depth");
645 uint32_t BitWidth = Mask.getBitWidth();
646 assert(cast<IntegerType>(V->getType())->getBitWidth() == BitWidth &&
647 KnownZero.getBitWidth() == BitWidth &&
648 KnownOne.getBitWidth() == BitWidth &&
649 "V, Mask, KnownOne and KnownZero should have same BitWidth");
650 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
651 // We know all of the bits for a constant!
652 KnownOne = CI->getValue() & Mask;
653 KnownZero = ~KnownOne & Mask;
654 return;
655 }
656
657 if (Depth == 6 || Mask == 0)
658 return; // Limit search depth.
659
660 Instruction *I = dyn_cast<Instruction>(V);
661 if (!I) return;
662
663 KnownZero.clear(); KnownOne.clear(); // Don't know anything.
664 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
665
666 switch (I->getOpcode()) {
667 case Instruction::And: {
668 // If either the LHS or the RHS are Zero, the result is zero.
669 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
670 APInt Mask2(Mask & ~KnownZero);
671 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
672 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
673 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
674
675 // Output known-1 bits are only known if set in both the LHS & RHS.
676 KnownOne &= KnownOne2;
677 // Output known-0 are known to be clear if zero in either the LHS | RHS.
678 KnownZero |= KnownZero2;
679 return;
680 }
681 case Instruction::Or: {
682 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
683 APInt Mask2(Mask & ~KnownOne);
684 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
685 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
686 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
687
688 // Output known-0 bits are only known if clear in both the LHS & RHS.
689 KnownZero &= KnownZero2;
690 // Output known-1 are known to be set if set in either the LHS | RHS.
691 KnownOne |= KnownOne2;
692 return;
693 }
694 case Instruction::Xor: {
695 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
696 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
697 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
698 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
699
700 // Output known-0 bits are known if clear or set in both the LHS & RHS.
701 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
702 // Output known-1 are known to be set if set in only one of the LHS, RHS.
703 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
704 KnownZero = KnownZeroOut;
705 return;
706 }
707 case Instruction::Select:
708 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
709 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
710 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
711 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
712
713 // Only known if known in both the LHS and RHS.
714 KnownOne &= KnownOne2;
715 KnownZero &= KnownZero2;
716 return;
717 case Instruction::FPTrunc:
718 case Instruction::FPExt:
719 case Instruction::FPToUI:
720 case Instruction::FPToSI:
721 case Instruction::SIToFP:
722 case Instruction::PtrToInt:
723 case Instruction::UIToFP:
724 case Instruction::IntToPtr:
725 return; // Can't work with floating point or pointers
726 case Instruction::Trunc: {
727 // All these have integer operands
728 uint32_t SrcBitWidth =
729 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
730 APInt MaskIn(Mask);
731 MaskIn.zext(SrcBitWidth);
732 KnownZero.zext(SrcBitWidth);
733 KnownOne.zext(SrcBitWidth);
734 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
735 KnownZero.trunc(BitWidth);
736 KnownOne.trunc(BitWidth);
737 return;
738 }
739 case Instruction::BitCast: {
740 const Type *SrcTy = I->getOperand(0)->getType();
741 if (SrcTy->isInteger()) {
742 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
743 return;
744 }
745 break;
746 }
747 case Instruction::ZExt: {
748 // Compute the bits in the result that are not present in the input.
749 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
750 uint32_t SrcBitWidth = SrcTy->getBitWidth();
751
752 APInt MaskIn(Mask);
753 MaskIn.trunc(SrcBitWidth);
754 KnownZero.trunc(SrcBitWidth);
755 KnownOne.trunc(SrcBitWidth);
756 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
757 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
758 // The top bits are known to be zero.
759 KnownZero.zext(BitWidth);
760 KnownOne.zext(BitWidth);
761 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
762 return;
763 }
764 case Instruction::SExt: {
765 // Compute the bits in the result that are not present in the input.
766 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
767 uint32_t SrcBitWidth = SrcTy->getBitWidth();
768
769 APInt MaskIn(Mask);
770 MaskIn.trunc(SrcBitWidth);
771 KnownZero.trunc(SrcBitWidth);
772 KnownOne.trunc(SrcBitWidth);
773 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
774 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
775 KnownZero.zext(BitWidth);
776 KnownOne.zext(BitWidth);
777
778 // If the sign bit of the input is known set or clear, then we know the
779 // top bits of the result.
780 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
781 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
782 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
783 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
784 return;
785 }
786 case Instruction::Shl:
787 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
788 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
789 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
790 APInt Mask2(Mask.lshr(ShiftAmt));
791 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
792 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
793 KnownZero <<= ShiftAmt;
794 KnownOne <<= ShiftAmt;
795 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
796 return;
797 }
798 break;
799 case Instruction::LShr:
800 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
801 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
802 // Compute the new bits that are at the top now.
803 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
804
805 // Unsigned shift right.
806 APInt Mask2(Mask.shl(ShiftAmt));
807 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
808 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
809 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
810 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
811 // high bits known zero.
812 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
813 return;
814 }
815 break;
816 case Instruction::AShr:
817 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
818 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
819 // Compute the new bits that are at the top now.
820 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
821
822 // Signed shift right.
823 APInt Mask2(Mask.shl(ShiftAmt));
824 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
825 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
826 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
827 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
828
829 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
830 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
831 KnownZero |= HighBits;
832 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
833 KnownOne |= HighBits;
834 return;
835 }
836 break;
837 }
838}
839
840/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
841/// this predicate to simplify operations downstream. Mask is known to be zero
842/// for bits that V cannot have.
843static bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0) {
844 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
845 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
846 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
847 return (KnownZero & Mask) == Mask;
848}
849
850/// ShrinkDemandedConstant - Check to see if the specified operand of the
851/// specified instruction is a constant integer. If so, check to see if there
852/// are any bits set in the constant that are not demanded. If so, shrink the
853/// constant and return true.
854static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
855 APInt Demanded) {
856 assert(I && "No instruction?");
857 assert(OpNo < I->getNumOperands() && "Operand index too large");
858
859 // If the operand is not a constant integer, nothing to do.
860 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
861 if (!OpC) return false;
862
863 // If there are no bits set that aren't demanded, nothing to do.
864 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
865 if ((~Demanded & OpC->getValue()) == 0)
866 return false;
867
868 // This instruction is producing bits that are not demanded. Shrink the RHS.
869 Demanded &= OpC->getValue();
870 I->setOperand(OpNo, ConstantInt::get(Demanded));
871 return true;
872}
873
874// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
875// set of known zero and one bits, compute the maximum and minimum values that
876// could have the specified known zero and known one bits, returning them in
877// min/max.
878static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
879 const APInt& KnownZero,
880 const APInt& KnownOne,
881 APInt& Min, APInt& Max) {
882 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
883 assert(KnownZero.getBitWidth() == BitWidth &&
884 KnownOne.getBitWidth() == BitWidth &&
885 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
886 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
887 APInt UnknownBits = ~(KnownZero|KnownOne);
888
889 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
890 // bit if it is unknown.
891 Min = KnownOne;
892 Max = KnownOne|UnknownBits;
893
894 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
895 Min.set(BitWidth-1);
896 Max.clear(BitWidth-1);
897 }
898}
899
900// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
901// a set of known zero and one bits, compute the maximum and minimum values that
902// could have the specified known zero and known one bits, returning them in
903// min/max.
904static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnerb933ea62007-08-05 08:47:58 +0000905 const APInt &KnownZero,
906 const APInt &KnownOne,
907 APInt &Min, APInt &Max) {
908 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000909 assert(KnownZero.getBitWidth() == BitWidth &&
910 KnownOne.getBitWidth() == BitWidth &&
911 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
912 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
913 APInt UnknownBits = ~(KnownZero|KnownOne);
914
915 // The minimum value is when the unknown bits are all zeros.
916 Min = KnownOne;
917 // The maximum value is when the unknown bits are all ones.
918 Max = KnownOne|UnknownBits;
919}
920
921/// SimplifyDemandedBits - This function attempts to replace V with a simpler
922/// value based on the demanded bits. When this function is called, it is known
923/// that only the bits set in DemandedMask of the result of V are ever used
924/// downstream. Consequently, depending on the mask and V, it may be possible
925/// to replace V with a constant or one of its operands. In such cases, this
926/// function does the replacement and returns true. In all other cases, it
927/// returns false after analyzing the expression and setting KnownOne and known
928/// to be one in the expression. KnownZero contains all the bits that are known
929/// to be zero in the expression. These are provided to potentially allow the
930/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
931/// the expression. KnownOne and KnownZero always follow the invariant that
932/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
933/// the bits in KnownOne and KnownZero may only be accurate for those bits set
934/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
935/// and KnownOne must all be the same.
936bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
937 APInt& KnownZero, APInt& KnownOne,
938 unsigned Depth) {
939 assert(V != 0 && "Null pointer of Value???");
940 assert(Depth <= 6 && "Limit Search Depth");
941 uint32_t BitWidth = DemandedMask.getBitWidth();
942 const IntegerType *VTy = cast<IntegerType>(V->getType());
943 assert(VTy->getBitWidth() == BitWidth &&
944 KnownZero.getBitWidth() == BitWidth &&
945 KnownOne.getBitWidth() == BitWidth &&
946 "Value *V, DemandedMask, KnownZero and KnownOne \
947 must have same BitWidth");
948 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
949 // We know all of the bits for a constant!
950 KnownOne = CI->getValue() & DemandedMask;
951 KnownZero = ~KnownOne & DemandedMask;
952 return false;
953 }
954
955 KnownZero.clear();
956 KnownOne.clear();
957 if (!V->hasOneUse()) { // Other users may use these bits.
958 if (Depth != 0) { // Not at the root.
959 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
960 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
961 return false;
962 }
963 // If this is the root being simplified, allow it to have multiple uses,
964 // just set the DemandedMask to all bits.
965 DemandedMask = APInt::getAllOnesValue(BitWidth);
966 } else if (DemandedMask == 0) { // Not demanding any bits from V.
967 if (V != UndefValue::get(VTy))
968 return UpdateValueUsesWith(V, UndefValue::get(VTy));
969 return false;
970 } else if (Depth == 6) { // Limit search depth.
971 return false;
972 }
973
974 Instruction *I = dyn_cast<Instruction>(V);
975 if (!I) return false; // Only analyze instructions.
976
977 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
978 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
979 switch (I->getOpcode()) {
980 default: break;
981 case Instruction::And:
982 // If either the LHS or the RHS are Zero, the result is zero.
983 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
984 RHSKnownZero, RHSKnownOne, Depth+1))
985 return true;
986 assert((RHSKnownZero & RHSKnownOne) == 0 &&
987 "Bits known to be one AND zero?");
988
989 // If something is known zero on the RHS, the bits aren't demanded on the
990 // LHS.
991 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
992 LHSKnownZero, LHSKnownOne, Depth+1))
993 return true;
994 assert((LHSKnownZero & LHSKnownOne) == 0 &&
995 "Bits known to be one AND zero?");
996
997 // If all of the demanded bits are known 1 on one side, return the other.
998 // These bits cannot contribute to the result of the 'and'.
999 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1000 (DemandedMask & ~LHSKnownZero))
1001 return UpdateValueUsesWith(I, I->getOperand(0));
1002 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1003 (DemandedMask & ~RHSKnownZero))
1004 return UpdateValueUsesWith(I, I->getOperand(1));
1005
1006 // If all of the demanded bits in the inputs are known zeros, return zero.
1007 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1008 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1009
1010 // If the RHS is a constant, see if we can simplify it.
1011 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1012 return UpdateValueUsesWith(I, I);
1013
1014 // Output known-1 bits are only known if set in both the LHS & RHS.
1015 RHSKnownOne &= LHSKnownOne;
1016 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1017 RHSKnownZero |= LHSKnownZero;
1018 break;
1019 case Instruction::Or:
1020 // If either the LHS or the RHS are One, the result is One.
1021 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1022 RHSKnownZero, RHSKnownOne, Depth+1))
1023 return true;
1024 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1025 "Bits known to be one AND zero?");
1026 // If something is known one on the RHS, the bits aren't demanded on the
1027 // LHS.
1028 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1029 LHSKnownZero, LHSKnownOne, Depth+1))
1030 return true;
1031 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1032 "Bits known to be one AND zero?");
1033
1034 // If all of the demanded bits are known zero on one side, return the other.
1035 // These bits cannot contribute to the result of the 'or'.
1036 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1037 (DemandedMask & ~LHSKnownOne))
1038 return UpdateValueUsesWith(I, I->getOperand(0));
1039 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1040 (DemandedMask & ~RHSKnownOne))
1041 return UpdateValueUsesWith(I, I->getOperand(1));
1042
1043 // If all of the potentially set bits on one side are known to be set on
1044 // the other side, just use the 'other' side.
1045 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1046 (DemandedMask & (~RHSKnownZero)))
1047 return UpdateValueUsesWith(I, I->getOperand(0));
1048 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1049 (DemandedMask & (~LHSKnownZero)))
1050 return UpdateValueUsesWith(I, I->getOperand(1));
1051
1052 // If the RHS is a constant, see if we can simplify it.
1053 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1054 return UpdateValueUsesWith(I, I);
1055
1056 // Output known-0 bits are only known if clear in both the LHS & RHS.
1057 RHSKnownZero &= LHSKnownZero;
1058 // Output known-1 are known to be set if set in either the LHS | RHS.
1059 RHSKnownOne |= LHSKnownOne;
1060 break;
1061 case Instruction::Xor: {
1062 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1063 RHSKnownZero, RHSKnownOne, Depth+1))
1064 return true;
1065 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1066 "Bits known to be one AND zero?");
1067 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1068 LHSKnownZero, LHSKnownOne, Depth+1))
1069 return true;
1070 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1071 "Bits known to be one AND zero?");
1072
1073 // If all of the demanded bits are known zero on one side, return the other.
1074 // These bits cannot contribute to the result of the 'xor'.
1075 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1076 return UpdateValueUsesWith(I, I->getOperand(0));
1077 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1078 return UpdateValueUsesWith(I, I->getOperand(1));
1079
1080 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1081 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1082 (RHSKnownOne & LHSKnownOne);
1083 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1084 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1085 (RHSKnownOne & LHSKnownZero);
1086
1087 // If all of the demanded bits are known to be zero on one side or the
1088 // other, turn this into an *inclusive* or.
1089 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1090 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1091 Instruction *Or =
1092 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1093 I->getName());
1094 InsertNewInstBefore(Or, *I);
1095 return UpdateValueUsesWith(I, Or);
1096 }
1097
1098 // If all of the demanded bits on one side are known, and all of the set
1099 // bits on that side are also known to be set on the other side, turn this
1100 // into an AND, as we know the bits will be cleared.
1101 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1102 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1103 // all known
1104 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1105 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1106 Instruction *And =
1107 BinaryOperator::createAnd(I->getOperand(0), AndC, "tmp");
1108 InsertNewInstBefore(And, *I);
1109 return UpdateValueUsesWith(I, And);
1110 }
1111 }
1112
1113 // If the RHS is a constant, see if we can simplify it.
1114 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1115 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1116 return UpdateValueUsesWith(I, I);
1117
1118 RHSKnownZero = KnownZeroOut;
1119 RHSKnownOne = KnownOneOut;
1120 break;
1121 }
1122 case Instruction::Select:
1123 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1124 RHSKnownZero, RHSKnownOne, Depth+1))
1125 return true;
1126 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1127 LHSKnownZero, LHSKnownOne, Depth+1))
1128 return true;
1129 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1130 "Bits known to be one AND zero?");
1131 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1132 "Bits known to be one AND zero?");
1133
1134 // If the operands are constants, see if we can simplify them.
1135 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1136 return UpdateValueUsesWith(I, I);
1137 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1138 return UpdateValueUsesWith(I, I);
1139
1140 // Only known if known in both the LHS and RHS.
1141 RHSKnownOne &= LHSKnownOne;
1142 RHSKnownZero &= LHSKnownZero;
1143 break;
1144 case Instruction::Trunc: {
1145 uint32_t truncBf =
1146 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1147 DemandedMask.zext(truncBf);
1148 RHSKnownZero.zext(truncBf);
1149 RHSKnownOne.zext(truncBf);
1150 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1151 RHSKnownZero, RHSKnownOne, Depth+1))
1152 return true;
1153 DemandedMask.trunc(BitWidth);
1154 RHSKnownZero.trunc(BitWidth);
1155 RHSKnownOne.trunc(BitWidth);
1156 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1157 "Bits known to be one AND zero?");
1158 break;
1159 }
1160 case Instruction::BitCast:
1161 if (!I->getOperand(0)->getType()->isInteger())
1162 return false;
1163
1164 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1165 RHSKnownZero, RHSKnownOne, Depth+1))
1166 return true;
1167 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1168 "Bits known to be one AND zero?");
1169 break;
1170 case Instruction::ZExt: {
1171 // Compute the bits in the result that are not present in the input.
1172 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1173 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1174
1175 DemandedMask.trunc(SrcBitWidth);
1176 RHSKnownZero.trunc(SrcBitWidth);
1177 RHSKnownOne.trunc(SrcBitWidth);
1178 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1179 RHSKnownZero, RHSKnownOne, Depth+1))
1180 return true;
1181 DemandedMask.zext(BitWidth);
1182 RHSKnownZero.zext(BitWidth);
1183 RHSKnownOne.zext(BitWidth);
1184 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1185 "Bits known to be one AND zero?");
1186 // The top bits are known to be zero.
1187 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1188 break;
1189 }
1190 case Instruction::SExt: {
1191 // Compute the bits in the result that are not present in the input.
1192 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1193 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1194
1195 APInt InputDemandedBits = DemandedMask &
1196 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1197
1198 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1199 // If any of the sign extended bits are demanded, we know that the sign
1200 // bit is demanded.
1201 if ((NewBits & DemandedMask) != 0)
1202 InputDemandedBits.set(SrcBitWidth-1);
1203
1204 InputDemandedBits.trunc(SrcBitWidth);
1205 RHSKnownZero.trunc(SrcBitWidth);
1206 RHSKnownOne.trunc(SrcBitWidth);
1207 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1208 RHSKnownZero, RHSKnownOne, Depth+1))
1209 return true;
1210 InputDemandedBits.zext(BitWidth);
1211 RHSKnownZero.zext(BitWidth);
1212 RHSKnownOne.zext(BitWidth);
1213 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1214 "Bits known to be one AND zero?");
1215
1216 // If the sign bit of the input is known set or clear, then we know the
1217 // top bits of the result.
1218
1219 // If the input sign bit is known zero, or if the NewBits are not demanded
1220 // convert this into a zero extension.
1221 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1222 {
1223 // Convert to ZExt cast
1224 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1225 return UpdateValueUsesWith(I, NewCast);
1226 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1227 RHSKnownOne |= NewBits;
1228 }
1229 break;
1230 }
1231 case Instruction::Add: {
1232 // Figure out what the input bits are. If the top bits of the and result
1233 // are not demanded, then the add doesn't demand them from its input
1234 // either.
1235 uint32_t NLZ = DemandedMask.countLeadingZeros();
1236
1237 // If there is a constant on the RHS, there are a variety of xformations
1238 // we can do.
1239 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1240 // If null, this should be simplified elsewhere. Some of the xforms here
1241 // won't work if the RHS is zero.
1242 if (RHS->isZero())
1243 break;
1244
1245 // If the top bit of the output is demanded, demand everything from the
1246 // input. Otherwise, we demand all the input bits except NLZ top bits.
1247 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1248
1249 // Find information about known zero/one bits in the input.
1250 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1251 LHSKnownZero, LHSKnownOne, Depth+1))
1252 return true;
1253
1254 // If the RHS of the add has bits set that can't affect the input, reduce
1255 // the constant.
1256 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1257 return UpdateValueUsesWith(I, I);
1258
1259 // Avoid excess work.
1260 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1261 break;
1262
1263 // Turn it into OR if input bits are zero.
1264 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1265 Instruction *Or =
1266 BinaryOperator::createOr(I->getOperand(0), I->getOperand(1),
1267 I->getName());
1268 InsertNewInstBefore(Or, *I);
1269 return UpdateValueUsesWith(I, Or);
1270 }
1271
1272 // We can say something about the output known-zero and known-one bits,
1273 // depending on potential carries from the input constant and the
1274 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1275 // bits set and the RHS constant is 0x01001, then we know we have a known
1276 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1277
1278 // To compute this, we first compute the potential carry bits. These are
1279 // the bits which may be modified. I'm not aware of a better way to do
1280 // this scan.
1281 const APInt& RHSVal = RHS->getValue();
1282 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1283
1284 // Now that we know which bits have carries, compute the known-1/0 sets.
1285
1286 // Bits are known one if they are known zero in one operand and one in the
1287 // other, and there is no input carry.
1288 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1289 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1290
1291 // Bits are known zero if they are known zero in both operands and there
1292 // is no input carry.
1293 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1294 } else {
1295 // If the high-bits of this ADD are not demanded, then it does not demand
1296 // the high bits of its LHS or RHS.
1297 if (DemandedMask[BitWidth-1] == 0) {
1298 // Right fill the mask of bits for this ADD to demand the most
1299 // significant bit and all those below it.
1300 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1301 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1302 LHSKnownZero, LHSKnownOne, Depth+1))
1303 return true;
1304 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1305 LHSKnownZero, LHSKnownOne, Depth+1))
1306 return true;
1307 }
1308 }
1309 break;
1310 }
1311 case Instruction::Sub:
1312 // If the high-bits of this SUB are not demanded, then it does not demand
1313 // the high bits of its LHS or RHS.
1314 if (DemandedMask[BitWidth-1] == 0) {
1315 // Right fill the mask of bits for this SUB to demand the most
1316 // significant bit and all those below it.
1317 uint32_t NLZ = DemandedMask.countLeadingZeros();
1318 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1319 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1320 LHSKnownZero, LHSKnownOne, Depth+1))
1321 return true;
1322 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1323 LHSKnownZero, LHSKnownOne, Depth+1))
1324 return true;
1325 }
1326 break;
1327 case Instruction::Shl:
1328 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1329 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1330 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1331 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1332 RHSKnownZero, RHSKnownOne, Depth+1))
1333 return true;
1334 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1335 "Bits known to be one AND zero?");
1336 RHSKnownZero <<= ShiftAmt;
1337 RHSKnownOne <<= ShiftAmt;
1338 // low bits known zero.
1339 if (ShiftAmt)
1340 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1341 }
1342 break;
1343 case Instruction::LShr:
1344 // For a logical shift right
1345 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1346 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1347
1348 // Unsigned shift right.
1349 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1350 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1351 RHSKnownZero, RHSKnownOne, Depth+1))
1352 return true;
1353 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1354 "Bits known to be one AND zero?");
1355 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1356 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1357 if (ShiftAmt) {
1358 // Compute the new bits that are at the top now.
1359 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1360 RHSKnownZero |= HighBits; // high bits known zero.
1361 }
1362 }
1363 break;
1364 case Instruction::AShr:
1365 // If this is an arithmetic shift right and only the low-bit is set, we can
1366 // always convert this into a logical shr, even if the shift amount is
1367 // variable. The low bit of the shift cannot be an input sign bit unless
1368 // the shift amount is >= the size of the datatype, which is undefined.
1369 if (DemandedMask == 1) {
1370 // Perform the logical shift right.
1371 Value *NewVal = BinaryOperator::createLShr(
1372 I->getOperand(0), I->getOperand(1), I->getName());
1373 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1374 return UpdateValueUsesWith(I, NewVal);
1375 }
1376
1377 // If the sign bit is the only bit demanded by this ashr, then there is no
1378 // need to do it, the shift doesn't change the high bit.
1379 if (DemandedMask.isSignBit())
1380 return UpdateValueUsesWith(I, I->getOperand(0));
1381
1382 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1383 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1384
1385 // Signed shift right.
1386 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1387 // If any of the "high bits" are demanded, we should set the sign bit as
1388 // demanded.
1389 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1390 DemandedMaskIn.set(BitWidth-1);
1391 if (SimplifyDemandedBits(I->getOperand(0),
1392 DemandedMaskIn,
1393 RHSKnownZero, RHSKnownOne, Depth+1))
1394 return true;
1395 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1396 "Bits known to be one AND zero?");
1397 // Compute the new bits that are at the top now.
1398 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1399 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1400 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1401
1402 // Handle the sign bits.
1403 APInt SignBit(APInt::getSignBit(BitWidth));
1404 // Adjust to where it is now in the mask.
1405 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1406
1407 // If the input sign bit is known to be zero, or if none of the top bits
1408 // are demanded, turn this into an unsigned shift right.
1409 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
1410 (HighBits & ~DemandedMask) == HighBits) {
1411 // Perform the logical shift right.
1412 Value *NewVal = BinaryOperator::createLShr(
1413 I->getOperand(0), SA, I->getName());
1414 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1415 return UpdateValueUsesWith(I, NewVal);
1416 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1417 RHSKnownOne |= HighBits;
1418 }
1419 }
1420 break;
1421 }
1422
1423 // If the client is only demanding bits that we know, return the known
1424 // constant.
1425 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1426 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1427 return false;
1428}
1429
1430
1431/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1432/// 64 or fewer elements. DemandedElts contains the set of elements that are
1433/// actually used by the caller. This method analyzes which elements of the
1434/// operand are undef and returns that information in UndefElts.
1435///
1436/// If the information about demanded elements can be used to simplify the
1437/// operation, the operation is simplified, then the resultant value is
1438/// returned. This returns null if no change was made.
1439Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1440 uint64_t &UndefElts,
1441 unsigned Depth) {
1442 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1443 assert(VWidth <= 64 && "Vector too wide to analyze!");
1444 uint64_t EltMask = ~0ULL >> (64-VWidth);
1445 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1446 "Invalid DemandedElts!");
1447
1448 if (isa<UndefValue>(V)) {
1449 // If the entire vector is undefined, just return this info.
1450 UndefElts = EltMask;
1451 return 0;
1452 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1453 UndefElts = EltMask;
1454 return UndefValue::get(V->getType());
1455 }
1456
1457 UndefElts = 0;
1458 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1459 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1460 Constant *Undef = UndefValue::get(EltTy);
1461
1462 std::vector<Constant*> Elts;
1463 for (unsigned i = 0; i != VWidth; ++i)
1464 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1465 Elts.push_back(Undef);
1466 UndefElts |= (1ULL << i);
1467 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1468 Elts.push_back(Undef);
1469 UndefElts |= (1ULL << i);
1470 } else { // Otherwise, defined.
1471 Elts.push_back(CP->getOperand(i));
1472 }
1473
1474 // If we changed the constant, return it.
1475 Constant *NewCP = ConstantVector::get(Elts);
1476 return NewCP != CP ? NewCP : 0;
1477 } else if (isa<ConstantAggregateZero>(V)) {
1478 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1479 // set to undef.
1480 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1481 Constant *Zero = Constant::getNullValue(EltTy);
1482 Constant *Undef = UndefValue::get(EltTy);
1483 std::vector<Constant*> Elts;
1484 for (unsigned i = 0; i != VWidth; ++i)
1485 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1486 UndefElts = DemandedElts ^ EltMask;
1487 return ConstantVector::get(Elts);
1488 }
1489
1490 if (!V->hasOneUse()) { // Other users may use these bits.
1491 if (Depth != 0) { // Not at the root.
1492 // TODO: Just compute the UndefElts information recursively.
1493 return false;
1494 }
1495 return false;
1496 } else if (Depth == 10) { // Limit search depth.
1497 return false;
1498 }
1499
1500 Instruction *I = dyn_cast<Instruction>(V);
1501 if (!I) return false; // Only analyze instructions.
1502
1503 bool MadeChange = false;
1504 uint64_t UndefElts2;
1505 Value *TmpV;
1506 switch (I->getOpcode()) {
1507 default: break;
1508
1509 case Instruction::InsertElement: {
1510 // If this is a variable index, we don't know which element it overwrites.
1511 // demand exactly the same input as we produce.
1512 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1513 if (Idx == 0) {
1514 // Note that we can't propagate undef elt info, because we don't know
1515 // which elt is getting updated.
1516 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1517 UndefElts2, Depth+1);
1518 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1519 break;
1520 }
1521
1522 // If this is inserting an element that isn't demanded, remove this
1523 // insertelement.
1524 unsigned IdxNo = Idx->getZExtValue();
1525 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1526 return AddSoonDeadInstToWorklist(*I, 0);
1527
1528 // Otherwise, the element inserted overwrites whatever was there, so the
1529 // input demanded set is simpler than the output set.
1530 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1531 DemandedElts & ~(1ULL << IdxNo),
1532 UndefElts, Depth+1);
1533 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1534
1535 // The inserted element is defined.
1536 UndefElts |= 1ULL << IdxNo;
1537 break;
1538 }
1539 case Instruction::BitCast: {
1540 // Vector->vector casts only.
1541 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1542 if (!VTy) break;
1543 unsigned InVWidth = VTy->getNumElements();
1544 uint64_t InputDemandedElts = 0;
1545 unsigned Ratio;
1546
1547 if (VWidth == InVWidth) {
1548 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1549 // elements as are demanded of us.
1550 Ratio = 1;
1551 InputDemandedElts = DemandedElts;
1552 } else if (VWidth > InVWidth) {
1553 // Untested so far.
1554 break;
1555
1556 // If there are more elements in the result than there are in the source,
1557 // then an input element is live if any of the corresponding output
1558 // elements are live.
1559 Ratio = VWidth/InVWidth;
1560 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1561 if (DemandedElts & (1ULL << OutIdx))
1562 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1563 }
1564 } else {
1565 // Untested so far.
1566 break;
1567
1568 // If there are more elements in the source than there are in the result,
1569 // then an input element is live if the corresponding output element is
1570 // live.
1571 Ratio = InVWidth/VWidth;
1572 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1573 if (DemandedElts & (1ULL << InIdx/Ratio))
1574 InputDemandedElts |= 1ULL << InIdx;
1575 }
1576
1577 // div/rem demand all inputs, because they don't want divide by zero.
1578 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1579 UndefElts2, Depth+1);
1580 if (TmpV) {
1581 I->setOperand(0, TmpV);
1582 MadeChange = true;
1583 }
1584
1585 UndefElts = UndefElts2;
1586 if (VWidth > InVWidth) {
1587 assert(0 && "Unimp");
1588 // If there are more elements in the result than there are in the source,
1589 // then an output element is undef if the corresponding input element is
1590 // undef.
1591 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1592 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1593 UndefElts |= 1ULL << OutIdx;
1594 } else if (VWidth < InVWidth) {
1595 assert(0 && "Unimp");
1596 // If there are more elements in the source than there are in the result,
1597 // then a result element is undef if all of the corresponding input
1598 // elements are undef.
1599 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1600 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1601 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1602 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1603 }
1604 break;
1605 }
1606 case Instruction::And:
1607 case Instruction::Or:
1608 case Instruction::Xor:
1609 case Instruction::Add:
1610 case Instruction::Sub:
1611 case Instruction::Mul:
1612 // div/rem demand all inputs, because they don't want divide by zero.
1613 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1614 UndefElts, Depth+1);
1615 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1616 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1617 UndefElts2, Depth+1);
1618 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1619
1620 // Output elements are undefined if both are undefined. Consider things
1621 // like undef&0. The result is known zero, not undef.
1622 UndefElts &= UndefElts2;
1623 break;
1624
1625 case Instruction::Call: {
1626 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1627 if (!II) break;
1628 switch (II->getIntrinsicID()) {
1629 default: break;
1630
1631 // Binary vector operations that work column-wise. A dest element is a
1632 // function of the corresponding input elements from the two inputs.
1633 case Intrinsic::x86_sse_sub_ss:
1634 case Intrinsic::x86_sse_mul_ss:
1635 case Intrinsic::x86_sse_min_ss:
1636 case Intrinsic::x86_sse_max_ss:
1637 case Intrinsic::x86_sse2_sub_sd:
1638 case Intrinsic::x86_sse2_mul_sd:
1639 case Intrinsic::x86_sse2_min_sd:
1640 case Intrinsic::x86_sse2_max_sd:
1641 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1642 UndefElts, Depth+1);
1643 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1644 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1645 UndefElts2, Depth+1);
1646 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1647
1648 // If only the low elt is demanded and this is a scalarizable intrinsic,
1649 // scalarize it now.
1650 if (DemandedElts == 1) {
1651 switch (II->getIntrinsicID()) {
1652 default: break;
1653 case Intrinsic::x86_sse_sub_ss:
1654 case Intrinsic::x86_sse_mul_ss:
1655 case Intrinsic::x86_sse2_sub_sd:
1656 case Intrinsic::x86_sse2_mul_sd:
1657 // TODO: Lower MIN/MAX/ABS/etc
1658 Value *LHS = II->getOperand(1);
1659 Value *RHS = II->getOperand(2);
1660 // Extract the element as scalars.
1661 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1662 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1663
1664 switch (II->getIntrinsicID()) {
1665 default: assert(0 && "Case stmts out of sync!");
1666 case Intrinsic::x86_sse_sub_ss:
1667 case Intrinsic::x86_sse2_sub_sd:
1668 TmpV = InsertNewInstBefore(BinaryOperator::createSub(LHS, RHS,
1669 II->getName()), *II);
1670 break;
1671 case Intrinsic::x86_sse_mul_ss:
1672 case Intrinsic::x86_sse2_mul_sd:
1673 TmpV = InsertNewInstBefore(BinaryOperator::createMul(LHS, RHS,
1674 II->getName()), *II);
1675 break;
1676 }
1677
1678 Instruction *New =
1679 new InsertElementInst(UndefValue::get(II->getType()), TmpV, 0U,
1680 II->getName());
1681 InsertNewInstBefore(New, *II);
1682 AddSoonDeadInstToWorklist(*II, 0);
1683 return New;
1684 }
1685 }
1686
1687 // Output elements are undefined if both are undefined. Consider things
1688 // like undef&0. The result is known zero, not undef.
1689 UndefElts &= UndefElts2;
1690 break;
1691 }
1692 break;
1693 }
1694 }
1695 return MadeChange ? I : 0;
1696}
1697
Nick Lewycky2de09a92007-09-06 02:40:25 +00001698/// @returns true if the specified compare predicate is
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001699/// true when both operands are equal...
Nick Lewycky2de09a92007-09-06 02:40:25 +00001700/// @brief Determine if the icmp Predicate is true when both operands are equal
1701static bool isTrueWhenEqual(ICmpInst::Predicate pred) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001702 return pred == ICmpInst::ICMP_EQ || pred == ICmpInst::ICMP_UGE ||
1703 pred == ICmpInst::ICMP_SGE || pred == ICmpInst::ICMP_ULE ||
1704 pred == ICmpInst::ICMP_SLE;
1705}
1706
Nick Lewycky2de09a92007-09-06 02:40:25 +00001707/// @returns true if the specified compare instruction is
1708/// true when both operands are equal...
1709/// @brief Determine if the ICmpInst returns true when both operands are equal
1710static bool isTrueWhenEqual(ICmpInst &ICI) {
1711 return isTrueWhenEqual(ICI.getPredicate());
1712}
1713
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001714/// AssociativeOpt - Perform an optimization on an associative operator. This
1715/// function is designed to check a chain of associative operators for a
1716/// potential to apply a certain optimization. Since the optimization may be
1717/// applicable if the expression was reassociated, this checks the chain, then
1718/// reassociates the expression as necessary to expose the optimization
1719/// opportunity. This makes use of a special Functor, which must define
1720/// 'shouldApply' and 'apply' methods.
1721///
1722template<typename Functor>
1723Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
1724 unsigned Opcode = Root.getOpcode();
1725 Value *LHS = Root.getOperand(0);
1726
1727 // Quick check, see if the immediate LHS matches...
1728 if (F.shouldApply(LHS))
1729 return F.apply(Root);
1730
1731 // Otherwise, if the LHS is not of the same opcode as the root, return.
1732 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1733 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1734 // Should we apply this transform to the RHS?
1735 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1736
1737 // If not to the RHS, check to see if we should apply to the LHS...
1738 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1739 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1740 ShouldApply = true;
1741 }
1742
1743 // If the functor wants to apply the optimization to the RHS of LHSI,
1744 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1745 if (ShouldApply) {
1746 BasicBlock *BB = Root.getParent();
1747
1748 // Now all of the instructions are in the current basic block, go ahead
1749 // and perform the reassociation.
1750 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1751
1752 // First move the selected RHS to the LHS of the root...
1753 Root.setOperand(0, LHSI->getOperand(1));
1754
1755 // Make what used to be the LHS of the root be the user of the root...
1756 Value *ExtraOperand = TmpLHSI->getOperand(1);
1757 if (&Root == TmpLHSI) {
1758 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1759 return 0;
1760 }
1761 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1762 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
1763 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
1764 BasicBlock::iterator ARI = &Root; ++ARI;
1765 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
1766 ARI = Root;
1767
1768 // Now propagate the ExtraOperand down the chain of instructions until we
1769 // get to LHSI.
1770 while (TmpLHSI != LHSI) {
1771 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1772 // Move the instruction to immediately before the chain we are
1773 // constructing to avoid breaking dominance properties.
1774 NextLHSI->getParent()->getInstList().remove(NextLHSI);
1775 BB->getInstList().insert(ARI, NextLHSI);
1776 ARI = NextLHSI;
1777
1778 Value *NextOp = NextLHSI->getOperand(1);
1779 NextLHSI->setOperand(1, ExtraOperand);
1780 TmpLHSI = NextLHSI;
1781 ExtraOperand = NextOp;
1782 }
1783
1784 // Now that the instructions are reassociated, have the functor perform
1785 // the transformation...
1786 return F.apply(Root);
1787 }
1788
1789 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1790 }
1791 return 0;
1792}
1793
1794
1795// AddRHS - Implements: X + X --> X << 1
1796struct AddRHS {
1797 Value *RHS;
1798 AddRHS(Value *rhs) : RHS(rhs) {}
1799 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1800 Instruction *apply(BinaryOperator &Add) const {
1801 return BinaryOperator::createShl(Add.getOperand(0),
1802 ConstantInt::get(Add.getType(), 1));
1803 }
1804};
1805
1806// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1807// iff C1&C2 == 0
1808struct AddMaskingAnd {
1809 Constant *C2;
1810 AddMaskingAnd(Constant *c) : C2(c) {}
1811 bool shouldApply(Value *LHS) const {
1812 ConstantInt *C1;
1813 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1814 ConstantExpr::getAnd(C1, C2)->isNullValue();
1815 }
1816 Instruction *apply(BinaryOperator &Add) const {
1817 return BinaryOperator::createOr(Add.getOperand(0), Add.getOperand(1));
1818 }
1819};
1820
1821static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1822 InstCombiner *IC) {
1823 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
1824 if (Constant *SOC = dyn_cast<Constant>(SO))
1825 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
1826
1827 return IC->InsertNewInstBefore(CastInst::create(
1828 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
1829 }
1830
1831 // Figure out if the constant is the left or the right argument.
1832 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1833 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1834
1835 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1836 if (ConstIsRHS)
1837 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1838 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1839 }
1840
1841 Value *Op0 = SO, *Op1 = ConstOperand;
1842 if (!ConstIsRHS)
1843 std::swap(Op0, Op1);
1844 Instruction *New;
1845 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1846 New = BinaryOperator::create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
1847 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1848 New = CmpInst::create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
1849 SO->getName()+".cmp");
1850 else {
1851 assert(0 && "Unknown binary instruction type!");
1852 abort();
1853 }
1854 return IC->InsertNewInstBefore(New, I);
1855}
1856
1857// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1858// constant as the other operand, try to fold the binary operator into the
1859// select arguments. This also works for Cast instructions, which obviously do
1860// not have a second operand.
1861static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1862 InstCombiner *IC) {
1863 // Don't modify shared select instructions
1864 if (!SI->hasOneUse()) return 0;
1865 Value *TV = SI->getOperand(1);
1866 Value *FV = SI->getOperand(2);
1867
1868 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1869 // Bool selects with constant operands can be folded to logical ops.
1870 if (SI->getType() == Type::Int1Ty) return 0;
1871
1872 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1873 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1874
1875 return new SelectInst(SI->getCondition(), SelectTrueVal,
1876 SelectFalseVal);
1877 }
1878 return 0;
1879}
1880
1881
1882/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1883/// node as operand #0, see if we can fold the instruction into the PHI (which
1884/// is only possible if all operands to the PHI are constants).
1885Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1886 PHINode *PN = cast<PHINode>(I.getOperand(0));
1887 unsigned NumPHIValues = PN->getNumIncomingValues();
1888 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1889
1890 // Check to see if all of the operands of the PHI are constants. If there is
1891 // one non-constant value, remember the BB it is. If there is more than one
1892 // or if *it* is a PHI, bail out.
1893 BasicBlock *NonConstBB = 0;
1894 for (unsigned i = 0; i != NumPHIValues; ++i)
1895 if (!isa<Constant>(PN->getIncomingValue(i))) {
1896 if (NonConstBB) return 0; // More than one non-const value.
1897 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1898 NonConstBB = PN->getIncomingBlock(i);
1899
1900 // If the incoming non-constant value is in I's block, we have an infinite
1901 // loop.
1902 if (NonConstBB == I.getParent())
1903 return 0;
1904 }
1905
1906 // If there is exactly one non-constant value, we can insert a copy of the
1907 // operation in that block. However, if this is a critical edge, we would be
1908 // inserting the computation one some other paths (e.g. inside a loop). Only
1909 // do this if the pred block is unconditionally branching into the phi block.
1910 if (NonConstBB) {
1911 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1912 if (!BI || !BI->isUnconditional()) return 0;
1913 }
1914
1915 // Okay, we can do the transformation: create the new PHI node.
1916 PHINode *NewPN = new PHINode(I.getType(), "");
1917 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1918 InsertNewInstBefore(NewPN, *PN);
1919 NewPN->takeName(PN);
1920
1921 // Next, add all of the operands to the PHI.
1922 if (I.getNumOperands() == 2) {
1923 Constant *C = cast<Constant>(I.getOperand(1));
1924 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00001925 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001926 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1927 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1928 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1929 else
1930 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1931 } else {
1932 assert(PN->getIncomingBlock(i) == NonConstBB);
1933 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
1934 InV = BinaryOperator::create(BO->getOpcode(),
1935 PN->getIncomingValue(i), C, "phitmp",
1936 NonConstBB->getTerminator());
1937 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1938 InV = CmpInst::create(CI->getOpcode(),
1939 CI->getPredicate(),
1940 PN->getIncomingValue(i), C, "phitmp",
1941 NonConstBB->getTerminator());
1942 else
1943 assert(0 && "Unknown binop!");
1944
1945 AddToWorkList(cast<Instruction>(InV));
1946 }
1947 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1948 }
1949 } else {
1950 CastInst *CI = cast<CastInst>(&I);
1951 const Type *RetTy = CI->getType();
1952 for (unsigned i = 0; i != NumPHIValues; ++i) {
1953 Value *InV;
1954 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1955 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1956 } else {
1957 assert(PN->getIncomingBlock(i) == NonConstBB);
1958 InV = CastInst::create(CI->getOpcode(), PN->getIncomingValue(i),
1959 I.getType(), "phitmp",
1960 NonConstBB->getTerminator());
1961 AddToWorkList(cast<Instruction>(InV));
1962 }
1963 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1964 }
1965 }
1966 return ReplaceInstUsesWith(I, NewPN);
1967}
1968
Chris Lattner55476162008-01-29 06:52:45 +00001969
1970/// CannotBeNegativeZero - Return true if we can prove that the specified FP
1971/// value is never equal to -0.0.
1972///
1973/// Note that this function will need to be revisited when we support nondefault
1974/// rounding modes!
1975///
1976static bool CannotBeNegativeZero(const Value *V) {
1977 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
1978 return !CFP->getValueAPF().isNegZero();
1979
1980 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
1981 if (const Instruction *I = dyn_cast<Instruction>(V)) {
1982 if (I->getOpcode() == Instruction::Add &&
1983 isa<ConstantFP>(I->getOperand(1)) &&
1984 cast<ConstantFP>(I->getOperand(1))->isNullValue())
1985 return true;
1986
1987 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
1988 if (II->getIntrinsicID() == Intrinsic::sqrt)
1989 return CannotBeNegativeZero(II->getOperand(1));
1990
1991 if (const CallInst *CI = dyn_cast<CallInst>(I))
1992 if (const Function *F = CI->getCalledFunction()) {
1993 if (F->isDeclaration()) {
1994 switch (F->getNameLen()) {
1995 case 3: // abs(x) != -0.0
1996 if (!strcmp(F->getNameStart(), "abs")) return true;
1997 break;
1998 case 4: // abs[lf](x) != -0.0
1999 if (!strcmp(F->getNameStart(), "absf")) return true;
2000 if (!strcmp(F->getNameStart(), "absl")) return true;
2001 break;
2002 }
2003 }
2004 }
2005 }
2006
2007 return false;
2008}
2009
2010
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002011Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2012 bool Changed = SimplifyCommutative(I);
2013 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2014
2015 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2016 // X + undef -> undef
2017 if (isa<UndefValue>(RHS))
2018 return ReplaceInstUsesWith(I, RHS);
2019
2020 // X + 0 --> X
2021 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
2022 if (RHSC->isNullValue())
2023 return ReplaceInstUsesWith(I, LHS);
2024 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen2fc20782007-09-14 22:26:36 +00002025 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2026 (I.getType())->getValueAPF()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002027 return ReplaceInstUsesWith(I, LHS);
2028 }
2029
2030 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2031 // X + (signbit) --> X ^ signbit
2032 const APInt& Val = CI->getValue();
2033 uint32_t BitWidth = Val.getBitWidth();
2034 if (Val == APInt::getSignBit(BitWidth))
2035 return BinaryOperator::createXor(LHS, RHS);
2036
2037 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2038 // (X & 254)+1 -> (X&254)|1
2039 if (!isa<VectorType>(I.getType())) {
2040 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2041 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2042 KnownZero, KnownOne))
2043 return &I;
2044 }
2045 }
2046
2047 if (isa<PHINode>(LHS))
2048 if (Instruction *NV = FoldOpIntoPhi(I))
2049 return NV;
2050
2051 ConstantInt *XorRHS = 0;
2052 Value *XorLHS = 0;
2053 if (isa<ConstantInt>(RHSC) &&
2054 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2055 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2056 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2057
2058 uint32_t Size = TySizeBits / 2;
2059 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2060 APInt CFF80Val(-C0080Val);
2061 do {
2062 if (TySizeBits > Size) {
2063 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2064 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2065 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2066 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2067 // This is a sign extend if the top bits are known zero.
2068 if (!MaskedValueIsZero(XorLHS,
2069 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2070 Size = 0; // Not a sign ext, but can't be any others either.
2071 break;
2072 }
2073 }
2074 Size >>= 1;
2075 C0080Val = APIntOps::lshr(C0080Val, Size);
2076 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2077 } while (Size >= 1);
2078
2079 // FIXME: This shouldn't be necessary. When the backends can handle types
2080 // with funny bit widths then this whole cascade of if statements should
2081 // be removed. It is just here to get the size of the "middle" type back
2082 // up to something that the back ends can handle.
2083 const Type *MiddleType = 0;
2084 switch (Size) {
2085 default: break;
2086 case 32: MiddleType = Type::Int32Ty; break;
2087 case 16: MiddleType = Type::Int16Ty; break;
2088 case 8: MiddleType = Type::Int8Ty; break;
2089 }
2090 if (MiddleType) {
2091 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2092 InsertNewInstBefore(NewTrunc, I);
2093 return new SExtInst(NewTrunc, I.getType(), I.getName());
2094 }
2095 }
2096 }
2097
2098 // X + X --> X << 1
2099 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
2100 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2101
2102 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2103 if (RHSI->getOpcode() == Instruction::Sub)
2104 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2105 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2106 }
2107 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2108 if (LHSI->getOpcode() == Instruction::Sub)
2109 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2110 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2111 }
2112 }
2113
2114 // -A + B --> B - A
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002115 // -A + -B --> -(A + B)
2116 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattner322a9192008-02-18 17:50:16 +00002117 if (LHS->getType()->isIntOrIntVector()) {
2118 if (Value *RHSV = dyn_castNegVal(RHS)) {
2119 Instruction *NewAdd = BinaryOperator::createAdd(LHSV, RHSV, "sum");
2120 InsertNewInstBefore(NewAdd, I);
2121 return BinaryOperator::createNeg(NewAdd);
2122 }
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002123 }
2124
2125 return BinaryOperator::createSub(RHS, LHSV);
2126 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002127
2128 // A + -B --> A - B
2129 if (!isa<Constant>(RHS))
2130 if (Value *V = dyn_castNegVal(RHS))
2131 return BinaryOperator::createSub(LHS, V);
2132
2133
2134 ConstantInt *C2;
2135 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2136 if (X == RHS) // X*C + X --> X * (C+1)
2137 return BinaryOperator::createMul(RHS, AddOne(C2));
2138
2139 // X*C1 + X*C2 --> X * (C1+C2)
2140 ConstantInt *C1;
2141 if (X == dyn_castFoldableMul(RHS, C1))
2142 return BinaryOperator::createMul(X, Add(C1, C2));
2143 }
2144
2145 // X + X*C --> X * (C+1)
2146 if (dyn_castFoldableMul(RHS, C2) == LHS)
2147 return BinaryOperator::createMul(LHS, AddOne(C2));
2148
2149 // X + ~X --> -1 since ~X = -X-1
2150 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2151 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2152
2153
2154 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2155 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2156 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2157 return R;
2158
Nick Lewycky83598a72008-02-03 07:42:09 +00002159 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky5d03b512008-02-03 08:19:11 +00002160 if (I.getType()->isIntOrIntVector()) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002161 Value *W, *X, *Y, *Z;
2162 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2163 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2164 if (W != Y) {
2165 if (W == Z) {
2166 std::swap(Y, Z);
2167 } else if (Y == X) {
2168 std::swap(W, X);
2169 } else if (X == Z) {
2170 std::swap(Y, Z);
2171 std::swap(W, X);
2172 }
2173 }
2174
2175 if (W == Y) {
2176 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, Z,
2177 LHS->getName()), I);
2178 return BinaryOperator::createMul(W, NewAdd);
2179 }
2180 }
2181 }
2182
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002183 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2184 Value *X = 0;
2185 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
2186 return BinaryOperator::createSub(SubOne(CRHS), X);
2187
2188 // (X & FF00) + xx00 -> (X+xx00) & FF00
2189 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2190 Constant *Anded = And(CRHS, C2);
2191 if (Anded == CRHS) {
2192 // See if all bits from the first bit set in the Add RHS up are included
2193 // in the mask. First, get the rightmost bit.
2194 const APInt& AddRHSV = CRHS->getValue();
2195
2196 // Form a mask of all bits from the lowest bit added through the top.
2197 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2198
2199 // See if the and mask includes all of these bits.
2200 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2201
2202 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2203 // Okay, the xform is safe. Insert the new add pronto.
2204 Value *NewAdd = InsertNewInstBefore(BinaryOperator::createAdd(X, CRHS,
2205 LHS->getName()), I);
2206 return BinaryOperator::createAnd(NewAdd, C2);
2207 }
2208 }
2209 }
2210
2211 // Try to fold constant add into select arguments.
2212 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2213 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2214 return R;
2215 }
2216
2217 // add (cast *A to intptrtype) B ->
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002218 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002219 {
2220 CastInst *CI = dyn_cast<CastInst>(LHS);
2221 Value *Other = RHS;
2222 if (!CI) {
2223 CI = dyn_cast<CastInst>(RHS);
2224 Other = LHS;
2225 }
2226 if (CI && CI->getType()->isSized() &&
2227 (CI->getType()->getPrimitiveSizeInBits() ==
2228 TD->getIntPtrType()->getPrimitiveSizeInBits())
2229 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00002230 unsigned AS =
2231 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +00002232 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2233 PointerType::get(Type::Int8Ty, AS), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002234 I2 = InsertNewInstBefore(new GetElementPtrInst(I2, Other, "ctg2"), I);
2235 return new PtrToIntInst(I2, CI->getType());
2236 }
2237 }
Christopher Lamb244ec282007-12-18 09:34:41 +00002238
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002239 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb244ec282007-12-18 09:34:41 +00002240 {
2241 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2242 Value *Other = RHS;
2243 if (!SI) {
2244 SI = dyn_cast<SelectInst>(RHS);
2245 Other = LHS;
2246 }
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002247 if (SI && SI->hasOneUse()) {
Christopher Lamb244ec282007-12-18 09:34:41 +00002248 Value *TV = SI->getTrueValue();
2249 Value *FV = SI->getFalseValue();
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002250 Value *A, *N;
Christopher Lamb244ec282007-12-18 09:34:41 +00002251
2252 // Can we fold the add into the argument of the select?
2253 // We check both true and false select arguments for a matching subtract.
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002254 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2255 A == Other) // Fold the add into the true select value.
2256 return new SelectInst(SI->getCondition(), N, A);
2257 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2258 A == Other) // Fold the add into the false select value.
2259 return new SelectInst(SI->getCondition(), A, N);
Christopher Lamb244ec282007-12-18 09:34:41 +00002260 }
2261 }
Chris Lattner55476162008-01-29 06:52:45 +00002262
2263 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2264 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2265 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2266 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002267
2268 return Changed ? &I : 0;
2269}
2270
2271// isSignBit - Return true if the value represented by the constant only has the
2272// highest order bit set.
2273static bool isSignBit(ConstantInt *CI) {
2274 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
2275 return CI->getValue() == APInt::getSignBit(NumBits);
2276}
2277
2278Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2279 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2280
2281 if (Op0 == Op1) // sub X, X -> 0
2282 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2283
2284 // If this is a 'B = x-(-A)', change to B = x+A...
2285 if (Value *V = dyn_castNegVal(Op1))
2286 return BinaryOperator::createAdd(Op0, V);
2287
2288 if (isa<UndefValue>(Op0))
2289 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2290 if (isa<UndefValue>(Op1))
2291 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2292
2293 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2294 // Replace (-1 - A) with (~A)...
2295 if (C->isAllOnesValue())
2296 return BinaryOperator::createNot(Op1);
2297
2298 // C - ~X == X + (1+C)
2299 Value *X = 0;
2300 if (match(Op1, m_Not(m_Value(X))))
2301 return BinaryOperator::createAdd(X, AddOne(C));
2302
2303 // -(X >>u 31) -> (X >>s 31)
2304 // -(X >>s 31) -> (X >>u 31)
2305 if (C->isZero()) {
2306 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1))
2307 if (SI->getOpcode() == Instruction::LShr) {
2308 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2309 // Check to see if we are shifting out everything but the sign bit.
2310 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2311 SI->getType()->getPrimitiveSizeInBits()-1) {
2312 // Ok, the transformation is safe. Insert AShr.
2313 return BinaryOperator::create(Instruction::AShr,
2314 SI->getOperand(0), CU, SI->getName());
2315 }
2316 }
2317 }
2318 else if (SI->getOpcode() == Instruction::AShr) {
2319 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2320 // Check to see if we are shifting out everything but the sign bit.
2321 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2322 SI->getType()->getPrimitiveSizeInBits()-1) {
2323 // Ok, the transformation is safe. Insert LShr.
2324 return BinaryOperator::createLShr(
2325 SI->getOperand(0), CU, SI->getName());
2326 }
2327 }
2328 }
2329 }
2330
2331 // Try to fold constant sub into select arguments.
2332 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2333 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2334 return R;
2335
2336 if (isa<PHINode>(Op0))
2337 if (Instruction *NV = FoldOpIntoPhi(I))
2338 return NV;
2339 }
2340
2341 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2342 if (Op1I->getOpcode() == Instruction::Add &&
2343 !Op0->getType()->isFPOrFPVector()) {
2344 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2345 return BinaryOperator::createNeg(Op1I->getOperand(1), I.getName());
2346 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2347 return BinaryOperator::createNeg(Op1I->getOperand(0), I.getName());
2348 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2349 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2350 // C1-(X+C2) --> (C1-C2)-X
2351 return BinaryOperator::createSub(Subtract(CI1, CI2),
2352 Op1I->getOperand(0));
2353 }
2354 }
2355
2356 if (Op1I->hasOneUse()) {
2357 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2358 // is not used by anyone else...
2359 //
2360 if (Op1I->getOpcode() == Instruction::Sub &&
2361 !Op1I->getType()->isFPOrFPVector()) {
2362 // Swap the two operands of the subexpr...
2363 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2364 Op1I->setOperand(0, IIOp1);
2365 Op1I->setOperand(1, IIOp0);
2366
2367 // Create the new top level add instruction...
2368 return BinaryOperator::createAdd(Op0, Op1);
2369 }
2370
2371 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2372 //
2373 if (Op1I->getOpcode() == Instruction::And &&
2374 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2375 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2376
2377 Value *NewNot =
2378 InsertNewInstBefore(BinaryOperator::createNot(OtherOp, "B.not"), I);
2379 return BinaryOperator::createAnd(Op0, NewNot);
2380 }
2381
2382 // 0 - (X sdiv C) -> (X sdiv -C)
2383 if (Op1I->getOpcode() == Instruction::SDiv)
2384 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2385 if (CSI->isZero())
2386 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
2387 return BinaryOperator::createSDiv(Op1I->getOperand(0),
2388 ConstantExpr::getNeg(DivRHS));
2389
2390 // X - X*C --> X * (1-C)
2391 ConstantInt *C2 = 0;
2392 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2393 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
2394 return BinaryOperator::createMul(Op0, CP1);
2395 }
Dan Gohmanda338742007-09-17 17:31:57 +00002396
2397 // X - ((X / Y) * Y) --> X % Y
2398 if (Op1I->getOpcode() == Instruction::Mul)
2399 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2400 if (Op0 == I->getOperand(0) &&
2401 Op1I->getOperand(1) == I->getOperand(1)) {
2402 if (I->getOpcode() == Instruction::SDiv)
2403 return BinaryOperator::createSRem(Op0, Op1I->getOperand(1));
2404 if (I->getOpcode() == Instruction::UDiv)
2405 return BinaryOperator::createURem(Op0, Op1I->getOperand(1));
2406 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002407 }
2408 }
2409
2410 if (!Op0->getType()->isFPOrFPVector())
2411 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2412 if (Op0I->getOpcode() == Instruction::Add) {
2413 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2414 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2415 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2416 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2417 } else if (Op0I->getOpcode() == Instruction::Sub) {
2418 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2419 return BinaryOperator::createNeg(Op0I->getOperand(1), I.getName());
2420 }
2421
2422 ConstantInt *C1;
2423 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2424 if (X == Op1) // X*C - X --> X * (C-1)
2425 return BinaryOperator::createMul(Op1, SubOne(C1));
2426
2427 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2428 if (X == dyn_castFoldableMul(Op1, C2))
2429 return BinaryOperator::createMul(Op1, Subtract(C1, C2));
2430 }
2431 return 0;
2432}
2433
2434/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2435/// comparison only checks the sign bit. If it only checks the sign bit, set
2436/// TrueIfSigned if the result of the comparison is true when the input value is
2437/// signed.
2438static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2439 bool &TrueIfSigned) {
2440 switch (pred) {
2441 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2442 TrueIfSigned = true;
2443 return RHS->isZero();
2444 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2445 TrueIfSigned = true;
2446 return RHS->isAllOnesValue();
2447 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2448 TrueIfSigned = false;
2449 return RHS->isAllOnesValue();
2450 case ICmpInst::ICMP_UGT:
2451 // True if LHS u> RHS and RHS == high-bit-mask - 1
2452 TrueIfSigned = true;
2453 return RHS->getValue() ==
2454 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2455 case ICmpInst::ICMP_UGE:
2456 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2457 TrueIfSigned = true;
2458 return RHS->getValue() ==
2459 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
2460 default:
2461 return false;
2462 }
2463}
2464
2465Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2466 bool Changed = SimplifyCommutative(I);
2467 Value *Op0 = I.getOperand(0);
2468
2469 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2470 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2471
2472 // Simplify mul instructions with a constant RHS...
2473 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2474 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2475
2476 // ((X << C1)*C2) == (X * (C2 << C1))
2477 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2478 if (SI->getOpcode() == Instruction::Shl)
2479 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
2480 return BinaryOperator::createMul(SI->getOperand(0),
2481 ConstantExpr::getShl(CI, ShOp));
2482
2483 if (CI->isZero())
2484 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2485 if (CI->equalsInt(1)) // X * 1 == X
2486 return ReplaceInstUsesWith(I, Op0);
2487 if (CI->isAllOnesValue()) // X * -1 == 0 - X
2488 return BinaryOperator::createNeg(Op0, I.getName());
2489
2490 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2491 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
2492 return BinaryOperator::createShl(Op0,
2493 ConstantInt::get(Op0->getType(), Val.logBase2()));
2494 }
2495 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2496 if (Op1F->isNullValue())
2497 return ReplaceInstUsesWith(I, Op1);
2498
2499 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2500 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen2fc20782007-09-14 22:26:36 +00002501 // We need a better interface for long double here.
2502 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2503 if (Op1F->isExactlyValue(1.0))
2504 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002505 }
2506
2507 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2508 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
2509 isa<ConstantInt>(Op0I->getOperand(1))) {
2510 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
2511 Instruction *Add = BinaryOperator::createMul(Op0I->getOperand(0),
2512 Op1, "tmp");
2513 InsertNewInstBefore(Add, I);
2514 Value *C1C2 = ConstantExpr::getMul(Op1,
2515 cast<Constant>(Op0I->getOperand(1)));
2516 return BinaryOperator::createAdd(Add, C1C2);
2517
2518 }
2519
2520 // Try to fold constant mul into select arguments.
2521 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2522 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2523 return R;
2524
2525 if (isa<PHINode>(Op0))
2526 if (Instruction *NV = FoldOpIntoPhi(I))
2527 return NV;
2528 }
2529
2530 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2531 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
2532 return BinaryOperator::createMul(Op0v, Op1v);
2533
2534 // If one of the operands of the multiply is a cast from a boolean value, then
2535 // we know the bool is either zero or one, so this is a 'masking' multiply.
2536 // See if we can simplify things based on how the boolean was originally
2537 // formed.
2538 CastInst *BoolCast = 0;
2539 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2540 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2541 BoolCast = CI;
2542 if (!BoolCast)
2543 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2544 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2545 BoolCast = CI;
2546 if (BoolCast) {
2547 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2548 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2549 const Type *SCOpTy = SCIOp0->getType();
2550 bool TIS = false;
2551
2552 // If the icmp is true iff the sign bit of X is set, then convert this
2553 // multiply into a shift/and combination.
2554 if (isa<ConstantInt>(SCIOp1) &&
2555 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2556 TIS) {
2557 // Shift the X value right to turn it into "all signbits".
2558 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2559 SCOpTy->getPrimitiveSizeInBits()-1);
2560 Value *V =
2561 InsertNewInstBefore(
2562 BinaryOperator::create(Instruction::AShr, SCIOp0, Amt,
2563 BoolCast->getOperand(0)->getName()+
2564 ".mask"), I);
2565
2566 // If the multiply type is not the same as the source type, sign extend
2567 // or truncate to the multiply type.
2568 if (I.getType() != V->getType()) {
2569 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2570 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2571 Instruction::CastOps opcode =
2572 (SrcBits == DstBits ? Instruction::BitCast :
2573 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2574 V = InsertCastBefore(opcode, V, I.getType(), I);
2575 }
2576
2577 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
2578 return BinaryOperator::createAnd(V, OtherOp);
2579 }
2580 }
2581 }
2582
2583 return Changed ? &I : 0;
2584}
2585
2586/// This function implements the transforms on div instructions that work
2587/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2588/// used by the visitors to those instructions.
2589/// @brief Transforms common to all three div instructions
2590Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2591 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2592
2593 // undef / X -> 0
2594 if (isa<UndefValue>(Op0))
2595 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2596
2597 // X / undef -> undef
2598 if (isa<UndefValue>(Op1))
2599 return ReplaceInstUsesWith(I, Op1);
2600
Chris Lattner5be238b2008-01-28 00:58:18 +00002601 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2602 // This does not apply for fdiv.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002603 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner5be238b2008-01-28 00:58:18 +00002604 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2605 // the same basic block, then we replace the select with Y, and the
2606 // condition of the select with false (if the cond value is in the same BB).
2607 // If the select has uses other than the div, this allows them to be
2608 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2609 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002610 if (ST->isNullValue()) {
2611 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2612 if (CondI && CondI->getParent() == I.getParent())
2613 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2614 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2615 I.setOperand(1, SI->getOperand(2));
2616 else
2617 UpdateValueUsesWith(SI, SI->getOperand(2));
2618 return &I;
2619 }
2620
Chris Lattner5be238b2008-01-28 00:58:18 +00002621 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2622 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002623 if (ST->isNullValue()) {
2624 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2625 if (CondI && CondI->getParent() == I.getParent())
2626 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2627 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2628 I.setOperand(1, SI->getOperand(1));
2629 else
2630 UpdateValueUsesWith(SI, SI->getOperand(1));
2631 return &I;
2632 }
2633 }
2634
2635 return 0;
2636}
2637
2638/// This function implements the transforms common to both integer division
2639/// instructions (udiv and sdiv). It is called by the visitors to those integer
2640/// division instructions.
2641/// @brief Common integer divide transforms
2642Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2643 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2644
2645 if (Instruction *Common = commonDivTransforms(I))
2646 return Common;
2647
2648 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2649 // div X, 1 == X
2650 if (RHS->equalsInt(1))
2651 return ReplaceInstUsesWith(I, Op0);
2652
2653 // (X / C1) / C2 -> X / (C1*C2)
2654 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2655 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2656 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewycky9d798f92008-02-18 22:48:05 +00002657 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2658 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2659 else
2660 return BinaryOperator::create(I.getOpcode(), LHS->getOperand(0),
2661 Multiply(RHS, LHSRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002662 }
2663
2664 if (!RHS->isZero()) { // avoid X udiv 0
2665 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2666 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2667 return R;
2668 if (isa<PHINode>(Op0))
2669 if (Instruction *NV = FoldOpIntoPhi(I))
2670 return NV;
2671 }
2672 }
2673
2674 // 0 / X == 0, we don't need to preserve faults!
2675 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2676 if (LHS->equalsInt(0))
2677 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2678
2679 return 0;
2680}
2681
2682Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2683 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2684
2685 // Handle the integer div common cases
2686 if (Instruction *Common = commonIDivTransforms(I))
2687 return Common;
2688
2689 // X udiv C^2 -> X >> C
2690 // Check to see if this is an unsigned division with an exact power of 2,
2691 // if so, convert to a right shift.
2692 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
2693 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
2694 return BinaryOperator::createLShr(Op0,
2695 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
2696 }
2697
2698 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2699 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2700 if (RHSI->getOpcode() == Instruction::Shl &&
2701 isa<ConstantInt>(RHSI->getOperand(0))) {
2702 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2703 if (C1.isPowerOf2()) {
2704 Value *N = RHSI->getOperand(1);
2705 const Type *NTy = N->getType();
2706 if (uint32_t C2 = C1.logBase2()) {
2707 Constant *C2V = ConstantInt::get(NTy, C2);
2708 N = InsertNewInstBefore(BinaryOperator::createAdd(N, C2V, "tmp"), I);
2709 }
2710 return BinaryOperator::createLShr(Op0, N);
2711 }
2712 }
2713 }
2714
2715 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2716 // where C1&C2 are powers of two.
2717 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2718 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2719 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2720 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2721 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2722 // Compute the shift amounts
2723 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2724 // Construct the "on true" case of the select
2725 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
2726 Instruction *TSI = BinaryOperator::createLShr(
2727 Op0, TC, SI->getName()+".t");
2728 TSI = InsertNewInstBefore(TSI, I);
2729
2730 // Construct the "on false" case of the select
2731 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
2732 Instruction *FSI = BinaryOperator::createLShr(
2733 Op0, FC, SI->getName()+".f");
2734 FSI = InsertNewInstBefore(FSI, I);
2735
2736 // construct the select instruction and return it.
2737 return new SelectInst(SI->getOperand(0), TSI, FSI, SI->getName());
2738 }
2739 }
2740 return 0;
2741}
2742
2743Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2744 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2745
2746 // Handle the integer div common cases
2747 if (Instruction *Common = commonIDivTransforms(I))
2748 return Common;
2749
2750 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2751 // sdiv X, -1 == -X
2752 if (RHS->isAllOnesValue())
2753 return BinaryOperator::createNeg(Op0);
2754
2755 // -X/C -> X/-C
2756 if (Value *LHSNeg = dyn_castNegVal(Op0))
2757 return BinaryOperator::createSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
2758 }
2759
2760 // If the sign bits of both operands are zero (i.e. we can prove they are
2761 // unsigned inputs), turn this into a udiv.
2762 if (I.getType()->isInteger()) {
2763 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2764 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmandb3dd962007-11-05 23:16:33 +00002765 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002766 return BinaryOperator::createUDiv(Op0, Op1, I.getName());
2767 }
2768 }
2769
2770 return 0;
2771}
2772
2773Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2774 return commonDivTransforms(I);
2775}
2776
2777/// GetFactor - If we can prove that the specified value is at least a multiple
2778/// of some factor, return that factor.
2779static Constant *GetFactor(Value *V) {
2780 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
2781 return CI;
2782
2783 // Unless we can be tricky, we know this is a multiple of 1.
2784 Constant *Result = ConstantInt::get(V->getType(), 1);
2785
2786 Instruction *I = dyn_cast<Instruction>(V);
2787 if (!I) return Result;
2788
2789 if (I->getOpcode() == Instruction::Mul) {
2790 // Handle multiplies by a constant, etc.
2791 return ConstantExpr::getMul(GetFactor(I->getOperand(0)),
2792 GetFactor(I->getOperand(1)));
2793 } else if (I->getOpcode() == Instruction::Shl) {
2794 // (X<<C) -> X * (1 << C)
2795 if (Constant *ShRHS = dyn_cast<Constant>(I->getOperand(1))) {
2796 ShRHS = ConstantExpr::getShl(Result, ShRHS);
2797 return ConstantExpr::getMul(GetFactor(I->getOperand(0)), ShRHS);
2798 }
2799 } else if (I->getOpcode() == Instruction::And) {
2800 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
2801 // X & 0xFFF0 is known to be a multiple of 16.
2802 uint32_t Zeros = RHS->getValue().countTrailingZeros();
Chris Lattnera03930e2007-11-23 22:35:18 +00002803 if (Zeros != V->getType()->getPrimitiveSizeInBits())// don't shift by "32"
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002804 return ConstantExpr::getShl(Result,
2805 ConstantInt::get(Result->getType(), Zeros));
2806 }
2807 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
2808 // Only handle int->int casts.
2809 if (!CI->isIntegerCast())
2810 return Result;
2811 Value *Op = CI->getOperand(0);
2812 return ConstantExpr::getCast(CI->getOpcode(), GetFactor(Op), V->getType());
2813 }
2814 return Result;
2815}
2816
2817/// This function implements the transforms on rem instructions that work
2818/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2819/// is used by the visitors to those instructions.
2820/// @brief Transforms common to all three rem instructions
2821Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2822 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2823
2824 // 0 % X == 0, we don't need to preserve faults!
2825 if (Constant *LHS = dyn_cast<Constant>(Op0))
2826 if (LHS->isNullValue())
2827 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2828
2829 if (isa<UndefValue>(Op0)) // undef % X -> 0
2830 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2831 if (isa<UndefValue>(Op1))
2832 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2833
2834 // Handle cases involving: rem X, (select Cond, Y, Z)
2835 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2836 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
2837 // the same basic block, then we replace the select with Y, and the
2838 // condition of the select with false (if the cond value is in the same
2839 // BB). If the select has uses other than the div, this allows them to be
2840 // simplified also.
2841 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2842 if (ST->isNullValue()) {
2843 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2844 if (CondI && CondI->getParent() == I.getParent())
2845 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2846 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2847 I.setOperand(1, SI->getOperand(2));
2848 else
2849 UpdateValueUsesWith(SI, SI->getOperand(2));
2850 return &I;
2851 }
2852 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
2853 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2854 if (ST->isNullValue()) {
2855 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2856 if (CondI && CondI->getParent() == I.getParent())
2857 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
2858 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2859 I.setOperand(1, SI->getOperand(1));
2860 else
2861 UpdateValueUsesWith(SI, SI->getOperand(1));
2862 return &I;
2863 }
2864 }
2865
2866 return 0;
2867}
2868
2869/// This function implements the transforms common to both integer remainder
2870/// instructions (urem and srem). It is called by the visitors to those integer
2871/// remainder instructions.
2872/// @brief Common integer remainder transforms
2873Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2874 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2875
2876 if (Instruction *common = commonRemTransforms(I))
2877 return common;
2878
2879 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2880 // X % 0 == undef, we don't need to preserve faults!
2881 if (RHS->equalsInt(0))
2882 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2883
2884 if (RHS->equalsInt(1)) // X % 1 == 0
2885 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2886
2887 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2888 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2889 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2890 return R;
2891 } else if (isa<PHINode>(Op0I)) {
2892 if (Instruction *NV = FoldOpIntoPhi(I))
2893 return NV;
2894 }
2895 // (X * C1) % C2 --> 0 iff C1 % C2 == 0
2896 if (ConstantExpr::getSRem(GetFactor(Op0I), RHS)->isNullValue())
2897 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2898 }
2899 }
2900
2901 return 0;
2902}
2903
2904Instruction *InstCombiner::visitURem(BinaryOperator &I) {
2905 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2906
2907 if (Instruction *common = commonIRemTransforms(I))
2908 return common;
2909
2910 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2911 // X urem C^2 -> X and C
2912 // Check to see if this is an unsigned remainder with an exact power of 2,
2913 // if so, convert to a bitwise and.
2914 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
2915 if (C->getValue().isPowerOf2())
2916 return BinaryOperator::createAnd(Op0, SubOne(C));
2917 }
2918
2919 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
2920 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
2921 if (RHSI->getOpcode() == Instruction::Shl &&
2922 isa<ConstantInt>(RHSI->getOperand(0))) {
2923 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
2924 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
2925 Value *Add = InsertNewInstBefore(BinaryOperator::createAdd(RHSI, N1,
2926 "tmp"), I);
2927 return BinaryOperator::createAnd(Op0, Add);
2928 }
2929 }
2930 }
2931
2932 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
2933 // where C1&C2 are powers of two.
2934 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
2935 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2936 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2937 // STO == 0 and SFO == 0 handled above.
2938 if ((STO->getValue().isPowerOf2()) &&
2939 (SFO->getValue().isPowerOf2())) {
2940 Value *TrueAnd = InsertNewInstBefore(
2941 BinaryOperator::createAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
2942 Value *FalseAnd = InsertNewInstBefore(
2943 BinaryOperator::createAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
2944 return new SelectInst(SI->getOperand(0), TrueAnd, FalseAnd);
2945 }
2946 }
2947 }
2948
2949 return 0;
2950}
2951
2952Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
2953 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2954
Dan Gohmandb3dd962007-11-05 23:16:33 +00002955 // Handle the integer rem common cases
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002956 if (Instruction *common = commonIRemTransforms(I))
2957 return common;
2958
2959 if (Value *RHSNeg = dyn_castNegVal(Op1))
2960 if (!isa<ConstantInt>(RHSNeg) ||
2961 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
2962 // X % -Y -> X % Y
2963 AddUsesToWorkList(I);
2964 I.setOperand(1, RHSNeg);
2965 return &I;
2966 }
2967
Dan Gohmandb3dd962007-11-05 23:16:33 +00002968 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002969 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00002970 if (I.getType()->isInteger()) {
2971 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2972 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
2973 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
2974 return BinaryOperator::createURem(Op0, Op1, I.getName());
2975 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002976 }
2977
2978 return 0;
2979}
2980
2981Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
2982 return commonRemTransforms(I);
2983}
2984
2985// isMaxValueMinusOne - return true if this is Max-1
2986static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
2987 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
2988 if (!isSigned)
2989 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
2990 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
2991}
2992
2993// isMinValuePlusOne - return true if this is Min+1
2994static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
2995 if (!isSigned)
2996 return C->getValue() == 1; // unsigned
2997
2998 // Calculate 1111111111000000000000
2999 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3000 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
3001}
3002
3003// isOneBitSet - Return true if there is exactly one bit set in the specified
3004// constant.
3005static bool isOneBitSet(const ConstantInt *CI) {
3006 return CI->getValue().isPowerOf2();
3007}
3008
3009// isHighOnes - Return true if the constant is of the form 1+0+.
3010// This is the same as lowones(~X).
3011static bool isHighOnes(const ConstantInt *CI) {
3012 return (~CI->getValue() + 1).isPowerOf2();
3013}
3014
3015/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3016/// are carefully arranged to allow folding of expressions such as:
3017///
3018/// (A < B) | (A > B) --> (A != B)
3019///
3020/// Note that this is only valid if the first and second predicates have the
3021/// same sign. Is illegal to do: (A u< B) | (A s> B)
3022///
3023/// Three bits are used to represent the condition, as follows:
3024/// 0 A > B
3025/// 1 A == B
3026/// 2 A < B
3027///
3028/// <=> Value Definition
3029/// 000 0 Always false
3030/// 001 1 A > B
3031/// 010 2 A == B
3032/// 011 3 A >= B
3033/// 100 4 A < B
3034/// 101 5 A != B
3035/// 110 6 A <= B
3036/// 111 7 Always true
3037///
3038static unsigned getICmpCode(const ICmpInst *ICI) {
3039 switch (ICI->getPredicate()) {
3040 // False -> 0
3041 case ICmpInst::ICMP_UGT: return 1; // 001
3042 case ICmpInst::ICMP_SGT: return 1; // 001
3043 case ICmpInst::ICMP_EQ: return 2; // 010
3044 case ICmpInst::ICMP_UGE: return 3; // 011
3045 case ICmpInst::ICMP_SGE: return 3; // 011
3046 case ICmpInst::ICMP_ULT: return 4; // 100
3047 case ICmpInst::ICMP_SLT: return 4; // 100
3048 case ICmpInst::ICMP_NE: return 5; // 101
3049 case ICmpInst::ICMP_ULE: return 6; // 110
3050 case ICmpInst::ICMP_SLE: return 6; // 110
3051 // True -> 7
3052 default:
3053 assert(0 && "Invalid ICmp predicate!");
3054 return 0;
3055 }
3056}
3057
3058/// getICmpValue - This is the complement of getICmpCode, which turns an
3059/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00003060/// new ICmp instruction. The sign is passed in to determine which kind
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003061/// of predicate to use in new icmp instructions.
3062static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3063 switch (code) {
3064 default: assert(0 && "Illegal ICmp code!");
3065 case 0: return ConstantInt::getFalse();
3066 case 1:
3067 if (sign)
3068 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3069 else
3070 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3071 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3072 case 3:
3073 if (sign)
3074 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3075 else
3076 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3077 case 4:
3078 if (sign)
3079 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3080 else
3081 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3082 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3083 case 6:
3084 if (sign)
3085 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3086 else
3087 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3088 case 7: return ConstantInt::getTrue();
3089 }
3090}
3091
3092static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3093 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3094 (ICmpInst::isSignedPredicate(p1) &&
3095 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3096 (ICmpInst::isSignedPredicate(p2) &&
3097 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3098}
3099
3100namespace {
3101// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3102struct FoldICmpLogical {
3103 InstCombiner &IC;
3104 Value *LHS, *RHS;
3105 ICmpInst::Predicate pred;
3106 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3107 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3108 pred(ICI->getPredicate()) {}
3109 bool shouldApply(Value *V) const {
3110 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3111 if (PredicatesFoldable(pred, ICI->getPredicate()))
3112 return (ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS ||
3113 ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS);
3114 return false;
3115 }
3116 Instruction *apply(Instruction &Log) const {
3117 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3118 if (ICI->getOperand(0) != LHS) {
3119 assert(ICI->getOperand(1) == LHS);
3120 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3121 }
3122
3123 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3124 unsigned LHSCode = getICmpCode(ICI);
3125 unsigned RHSCode = getICmpCode(RHSICI);
3126 unsigned Code;
3127 switch (Log.getOpcode()) {
3128 case Instruction::And: Code = LHSCode & RHSCode; break;
3129 case Instruction::Or: Code = LHSCode | RHSCode; break;
3130 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3131 default: assert(0 && "Illegal logical opcode!"); return 0;
3132 }
3133
3134 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3135 ICmpInst::isSignedPredicate(ICI->getPredicate());
3136
3137 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3138 if (Instruction *I = dyn_cast<Instruction>(RV))
3139 return I;
3140 // Otherwise, it's a constant boolean value...
3141 return IC.ReplaceInstUsesWith(Log, RV);
3142 }
3143};
3144} // end anonymous namespace
3145
3146// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3147// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3148// guaranteed to be a binary operator.
3149Instruction *InstCombiner::OptAndOp(Instruction *Op,
3150 ConstantInt *OpRHS,
3151 ConstantInt *AndRHS,
3152 BinaryOperator &TheAnd) {
3153 Value *X = Op->getOperand(0);
3154 Constant *Together = 0;
3155 if (!Op->isShift())
3156 Together = And(AndRHS, OpRHS);
3157
3158 switch (Op->getOpcode()) {
3159 case Instruction::Xor:
3160 if (Op->hasOneUse()) {
3161 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
3162 Instruction *And = BinaryOperator::createAnd(X, AndRHS);
3163 InsertNewInstBefore(And, TheAnd);
3164 And->takeName(Op);
3165 return BinaryOperator::createXor(And, Together);
3166 }
3167 break;
3168 case Instruction::Or:
3169 if (Together == AndRHS) // (X | C) & C --> C
3170 return ReplaceInstUsesWith(TheAnd, AndRHS);
3171
3172 if (Op->hasOneUse() && Together != OpRHS) {
3173 // (X | C1) & C2 --> (X | (C1&C2)) & C2
3174 Instruction *Or = BinaryOperator::createOr(X, Together);
3175 InsertNewInstBefore(Or, TheAnd);
3176 Or->takeName(Op);
3177 return BinaryOperator::createAnd(Or, AndRHS);
3178 }
3179 break;
3180 case Instruction::Add:
3181 if (Op->hasOneUse()) {
3182 // Adding a one to a single bit bit-field should be turned into an XOR
3183 // of the bit. First thing to check is to see if this AND is with a
3184 // single bit constant.
3185 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3186
3187 // If there is only one bit set...
3188 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3189 // Ok, at this point, we know that we are masking the result of the
3190 // ADD down to exactly one bit. If the constant we are adding has
3191 // no bits set below this bit, then we can eliminate the ADD.
3192 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3193
3194 // Check to see if any bits below the one bit set in AndRHSV are set.
3195 if ((AddRHS & (AndRHSV-1)) == 0) {
3196 // If not, the only thing that can effect the output of the AND is
3197 // the bit specified by AndRHSV. If that bit is set, the effect of
3198 // the XOR is to toggle the bit. If it is clear, then the ADD has
3199 // no effect.
3200 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3201 TheAnd.setOperand(0, X);
3202 return &TheAnd;
3203 } else {
3204 // Pull the XOR out of the AND.
3205 Instruction *NewAnd = BinaryOperator::createAnd(X, AndRHS);
3206 InsertNewInstBefore(NewAnd, TheAnd);
3207 NewAnd->takeName(Op);
3208 return BinaryOperator::createXor(NewAnd, AndRHS);
3209 }
3210 }
3211 }
3212 }
3213 break;
3214
3215 case Instruction::Shl: {
3216 // We know that the AND will not produce any of the bits shifted in, so if
3217 // the anded constant includes them, clear them now!
3218 //
3219 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3220 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3221 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3222 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3223
3224 if (CI->getValue() == ShlMask) {
3225 // Masking out bits that the shift already masks
3226 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3227 } else if (CI != AndRHS) { // Reducing bits set in and.
3228 TheAnd.setOperand(1, CI);
3229 return &TheAnd;
3230 }
3231 break;
3232 }
3233 case Instruction::LShr:
3234 {
3235 // We know that the AND will not produce any of the bits shifted in, so if
3236 // the anded constant includes them, clear them now! This only applies to
3237 // unsigned shifts, because a signed shr may bring in set bits!
3238 //
3239 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3240 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3241 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3242 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3243
3244 if (CI->getValue() == ShrMask) {
3245 // Masking out bits that the shift already masks.
3246 return ReplaceInstUsesWith(TheAnd, Op);
3247 } else if (CI != AndRHS) {
3248 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3249 return &TheAnd;
3250 }
3251 break;
3252 }
3253 case Instruction::AShr:
3254 // Signed shr.
3255 // See if this is shifting in some sign extension, then masking it out
3256 // with an and.
3257 if (Op->hasOneUse()) {
3258 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3259 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3260 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3261 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3262 if (C == AndRHS) { // Masking out bits shifted in.
3263 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3264 // Make the argument unsigned.
3265 Value *ShVal = Op->getOperand(0);
3266 ShVal = InsertNewInstBefore(
3267 BinaryOperator::createLShr(ShVal, OpRHS,
3268 Op->getName()), TheAnd);
3269 return BinaryOperator::createAnd(ShVal, AndRHS, TheAnd.getName());
3270 }
3271 }
3272 break;
3273 }
3274 return 0;
3275}
3276
3277
3278/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3279/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3280/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3281/// whether to treat the V, Lo and HI as signed or not. IB is the location to
3282/// insert new instructions.
3283Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3284 bool isSigned, bool Inside,
3285 Instruction &IB) {
3286 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3287 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3288 "Lo is not <= Hi in range emission code!");
3289
3290 if (Inside) {
3291 if (Lo == Hi) // Trivially false.
3292 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3293
3294 // V >= Min && V < Hi --> V < Hi
3295 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3296 ICmpInst::Predicate pred = (isSigned ?
3297 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3298 return new ICmpInst(pred, V, Hi);
3299 }
3300
3301 // Emit V-Lo <u Hi-Lo
3302 Constant *NegLo = ConstantExpr::getNeg(Lo);
3303 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3304 InsertNewInstBefore(Add, IB);
3305 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3306 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3307 }
3308
3309 if (Lo == Hi) // Trivially true.
3310 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3311
3312 // V < Min || V >= Hi -> V > Hi-1
3313 Hi = SubOne(cast<ConstantInt>(Hi));
3314 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3315 ICmpInst::Predicate pred = (isSigned ?
3316 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3317 return new ICmpInst(pred, V, Hi);
3318 }
3319
3320 // Emit V-Lo >u Hi-1-Lo
3321 // Note that Hi has already had one subtracted from it, above.
3322 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
3323 Instruction *Add = BinaryOperator::createAdd(V, NegLo, V->getName()+".off");
3324 InsertNewInstBefore(Add, IB);
3325 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3326 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3327}
3328
3329// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3330// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3331// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3332// not, since all 1s are not contiguous.
3333static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3334 const APInt& V = Val->getValue();
3335 uint32_t BitWidth = Val->getType()->getBitWidth();
3336 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3337
3338 // look for the first zero bit after the run of ones
3339 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3340 // look for the first non-zero bit
3341 ME = V.getActiveBits();
3342 return true;
3343}
3344
3345/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3346/// where isSub determines whether the operator is a sub. If we can fold one of
3347/// the following xforms:
3348///
3349/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3350/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3351/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3352///
3353/// return (A +/- B).
3354///
3355Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3356 ConstantInt *Mask, bool isSub,
3357 Instruction &I) {
3358 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3359 if (!LHSI || LHSI->getNumOperands() != 2 ||
3360 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3361
3362 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3363
3364 switch (LHSI->getOpcode()) {
3365 default: return 0;
3366 case Instruction::And:
3367 if (And(N, Mask) == Mask) {
3368 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3369 if ((Mask->getValue().countLeadingZeros() +
3370 Mask->getValue().countPopulation()) ==
3371 Mask->getValue().getBitWidth())
3372 break;
3373
3374 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3375 // part, we don't need any explicit masks to take them out of A. If that
3376 // is all N is, ignore it.
3377 uint32_t MB = 0, ME = 0;
3378 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3379 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3380 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3381 if (MaskedValueIsZero(RHS, Mask))
3382 break;
3383 }
3384 }
3385 return 0;
3386 case Instruction::Or:
3387 case Instruction::Xor:
3388 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3389 if ((Mask->getValue().countLeadingZeros() +
3390 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3391 && And(N, Mask)->isZero())
3392 break;
3393 return 0;
3394 }
3395
3396 Instruction *New;
3397 if (isSub)
3398 New = BinaryOperator::createSub(LHSI->getOperand(0), RHS, "fold");
3399 else
3400 New = BinaryOperator::createAdd(LHSI->getOperand(0), RHS, "fold");
3401 return InsertNewInstBefore(New, I);
3402}
3403
3404Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3405 bool Changed = SimplifyCommutative(I);
3406 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3407
3408 if (isa<UndefValue>(Op1)) // X & undef -> 0
3409 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3410
3411 // and X, X = X
3412 if (Op0 == Op1)
3413 return ReplaceInstUsesWith(I, Op1);
3414
3415 // See if we can simplify any instructions used by the instruction whose sole
3416 // purpose is to compute bits we don't care about.
3417 if (!isa<VectorType>(I.getType())) {
3418 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3419 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3420 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3421 KnownZero, KnownOne))
3422 return &I;
3423 } else {
3424 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3425 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
3426 return ReplaceInstUsesWith(I, I.getOperand(0));
3427 } else if (isa<ConstantAggregateZero>(Op1)) {
3428 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
3429 }
3430 }
3431
3432 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3433 const APInt& AndRHSMask = AndRHS->getValue();
3434 APInt NotAndRHS(~AndRHSMask);
3435
3436 // Optimize a variety of ((val OP C1) & C2) combinations...
3437 if (isa<BinaryOperator>(Op0)) {
3438 Instruction *Op0I = cast<Instruction>(Op0);
3439 Value *Op0LHS = Op0I->getOperand(0);
3440 Value *Op0RHS = Op0I->getOperand(1);
3441 switch (Op0I->getOpcode()) {
3442 case Instruction::Xor:
3443 case Instruction::Or:
3444 // If the mask is only needed on one incoming arm, push it up.
3445 if (Op0I->hasOneUse()) {
3446 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3447 // Not masking anything out for the LHS, move to RHS.
3448 Instruction *NewRHS = BinaryOperator::createAnd(Op0RHS, AndRHS,
3449 Op0RHS->getName()+".masked");
3450 InsertNewInstBefore(NewRHS, I);
3451 return BinaryOperator::create(
3452 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3453 }
3454 if (!isa<Constant>(Op0RHS) &&
3455 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3456 // Not masking anything out for the RHS, move to LHS.
3457 Instruction *NewLHS = BinaryOperator::createAnd(Op0LHS, AndRHS,
3458 Op0LHS->getName()+".masked");
3459 InsertNewInstBefore(NewLHS, I);
3460 return BinaryOperator::create(
3461 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3462 }
3463 }
3464
3465 break;
3466 case Instruction::Add:
3467 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3468 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3469 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3470 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
3471 return BinaryOperator::createAnd(V, AndRHS);
3472 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
3473 return BinaryOperator::createAnd(V, AndRHS); // Add commutes
3474 break;
3475
3476 case Instruction::Sub:
3477 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3478 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3479 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3480 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
3481 return BinaryOperator::createAnd(V, AndRHS);
3482 break;
3483 }
3484
3485 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3486 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3487 return Res;
3488 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3489 // If this is an integer truncation or change from signed-to-unsigned, and
3490 // if the source is an and/or with immediate, transform it. This
3491 // frequently occurs for bitfield accesses.
3492 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3493 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3494 CastOp->getNumOperands() == 2)
3495 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1)))
3496 if (CastOp->getOpcode() == Instruction::And) {
3497 // Change: and (cast (and X, C1) to T), C2
3498 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3499 // This will fold the two constants together, which may allow
3500 // other simplifications.
3501 Instruction *NewCast = CastInst::createTruncOrBitCast(
3502 CastOp->getOperand(0), I.getType(),
3503 CastOp->getName()+".shrunk");
3504 NewCast = InsertNewInstBefore(NewCast, I);
3505 // trunc_or_bitcast(C1)&C2
3506 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3507 C3 = ConstantExpr::getAnd(C3, AndRHS);
3508 return BinaryOperator::createAnd(NewCast, C3);
3509 } else if (CastOp->getOpcode() == Instruction::Or) {
3510 // Change: and (cast (or X, C1) to T), C2
3511 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3512 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3513 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3514 return ReplaceInstUsesWith(I, AndRHS);
3515 }
3516 }
3517 }
3518
3519 // Try to fold constant and into select arguments.
3520 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3521 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3522 return R;
3523 if (isa<PHINode>(Op0))
3524 if (Instruction *NV = FoldOpIntoPhi(I))
3525 return NV;
3526 }
3527
3528 Value *Op0NotVal = dyn_castNotVal(Op0);
3529 Value *Op1NotVal = dyn_castNotVal(Op1);
3530
3531 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3532 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3533
3534 // (~A & ~B) == (~(A | B)) - De Morgan's Law
3535 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
3536 Instruction *Or = BinaryOperator::createOr(Op0NotVal, Op1NotVal,
3537 I.getName()+".demorgan");
3538 InsertNewInstBefore(Or, I);
3539 return BinaryOperator::createNot(Or);
3540 }
3541
3542 {
3543 Value *A = 0, *B = 0, *C = 0, *D = 0;
3544 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3545 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3546 return ReplaceInstUsesWith(I, Op1);
3547
3548 // (A|B) & ~(A&B) -> A^B
3549 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3550 if ((A == C && B == D) || (A == D && B == C))
3551 return BinaryOperator::createXor(A, B);
3552 }
3553 }
3554
3555 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3556 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3557 return ReplaceInstUsesWith(I, Op0);
3558
3559 // ~(A&B) & (A|B) -> A^B
3560 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3561 if ((A == C && B == D) || (A == D && B == C))
3562 return BinaryOperator::createXor(A, B);
3563 }
3564 }
3565
3566 if (Op0->hasOneUse() &&
3567 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3568 if (A == Op1) { // (A^B)&A -> A&(A^B)
3569 I.swapOperands(); // Simplify below
3570 std::swap(Op0, Op1);
3571 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3572 cast<BinaryOperator>(Op0)->swapOperands();
3573 I.swapOperands(); // Simplify below
3574 std::swap(Op0, Op1);
3575 }
3576 }
3577 if (Op1->hasOneUse() &&
3578 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3579 if (B == Op0) { // B&(A^B) -> B&(B^A)
3580 cast<BinaryOperator>(Op1)->swapOperands();
3581 std::swap(A, B);
3582 }
3583 if (A == Op0) { // A&(A^B) -> A & ~B
3584 Instruction *NotB = BinaryOperator::createNot(B, "tmp");
3585 InsertNewInstBefore(NotB, I);
3586 return BinaryOperator::createAnd(A, NotB);
3587 }
3588 }
3589 }
3590
3591 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3592 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3593 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3594 return R;
3595
3596 Value *LHSVal, *RHSVal;
3597 ConstantInt *LHSCst, *RHSCst;
3598 ICmpInst::Predicate LHSCC, RHSCC;
3599 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3600 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3601 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3602 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3603 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3604 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3605 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner205ad1d2007-11-22 23:47:13 +00003606 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3607
3608 // Don't try to fold ICMP_SLT + ICMP_ULT.
3609 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3610 ICmpInst::isSignedPredicate(LHSCC) ==
3611 ICmpInst::isSignedPredicate(RHSCC))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003612 // Ensure that the larger constant is on the RHS.
Chris Lattnerda628ca2008-01-13 20:59:02 +00003613 ICmpInst::Predicate GT;
3614 if (ICmpInst::isSignedPredicate(LHSCC) ||
3615 (ICmpInst::isEquality(LHSCC) &&
3616 ICmpInst::isSignedPredicate(RHSCC)))
3617 GT = ICmpInst::ICMP_SGT;
3618 else
3619 GT = ICmpInst::ICMP_UGT;
3620
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003621 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3622 ICmpInst *LHS = cast<ICmpInst>(Op0);
3623 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3624 std::swap(LHS, RHS);
3625 std::swap(LHSCst, RHSCst);
3626 std::swap(LHSCC, RHSCC);
3627 }
3628
3629 // At this point, we know we have have two icmp instructions
3630 // comparing a value against two constants and and'ing the result
3631 // together. Because of the above check, we know that we only have
3632 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3633 // (from the FoldICmpLogical check above), that the two constants
3634 // are not equal and that the larger constant is on the RHS
3635 assert(LHSCst != RHSCst && "Compares not folded above?");
3636
3637 switch (LHSCC) {
3638 default: assert(0 && "Unknown integer condition code!");
3639 case ICmpInst::ICMP_EQ:
3640 switch (RHSCC) {
3641 default: assert(0 && "Unknown integer condition code!");
3642 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3643 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3644 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3645 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3646 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3647 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3648 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3649 return ReplaceInstUsesWith(I, LHS);
3650 }
3651 case ICmpInst::ICMP_NE:
3652 switch (RHSCC) {
3653 default: assert(0 && "Unknown integer condition code!");
3654 case ICmpInst::ICMP_ULT:
3655 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3656 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
3657 break; // (X != 13 & X u< 15) -> no change
3658 case ICmpInst::ICMP_SLT:
3659 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3660 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
3661 break; // (X != 13 & X s< 15) -> no change
3662 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3663 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3664 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3665 return ReplaceInstUsesWith(I, RHS);
3666 case ICmpInst::ICMP_NE:
3667 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3668 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3669 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
3670 LHSVal->getName()+".off");
3671 InsertNewInstBefore(Add, I);
3672 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3673 ConstantInt::get(Add->getType(), 1));
3674 }
3675 break; // (X != 13 & X != 15) -> no change
3676 }
3677 break;
3678 case ICmpInst::ICMP_ULT:
3679 switch (RHSCC) {
3680 default: assert(0 && "Unknown integer condition code!");
3681 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3682 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3683 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3684 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3685 break;
3686 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3687 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3688 return ReplaceInstUsesWith(I, LHS);
3689 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3690 break;
3691 }
3692 break;
3693 case ICmpInst::ICMP_SLT:
3694 switch (RHSCC) {
3695 default: assert(0 && "Unknown integer condition code!");
3696 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3697 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3698 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3699 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3700 break;
3701 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3702 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3703 return ReplaceInstUsesWith(I, LHS);
3704 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3705 break;
3706 }
3707 break;
3708 case ICmpInst::ICMP_UGT:
3709 switch (RHSCC) {
3710 default: assert(0 && "Unknown integer condition code!");
3711 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
3712 return ReplaceInstUsesWith(I, LHS);
3713 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3714 return ReplaceInstUsesWith(I, RHS);
3715 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3716 break;
3717 case ICmpInst::ICMP_NE:
3718 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3719 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3720 break; // (X u> 13 & X != 15) -> no change
3721 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
3722 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
3723 true, I);
3724 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3725 break;
3726 }
3727 break;
3728 case ICmpInst::ICMP_SGT:
3729 switch (RHSCC) {
3730 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerab0fc252007-11-16 06:04:17 +00003731 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003732 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3733 return ReplaceInstUsesWith(I, RHS);
3734 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3735 break;
3736 case ICmpInst::ICMP_NE:
3737 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3738 return new ICmpInst(LHSCC, LHSVal, RHSCst);
3739 break; // (X s> 13 & X != 15) -> no change
3740 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
3741 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
3742 true, I);
3743 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3744 break;
3745 }
3746 break;
3747 }
3748 }
3749 }
3750
3751 // fold (and (cast A), (cast B)) -> (cast (and A, B))
3752 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
3753 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
3754 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
3755 const Type *SrcTy = Op0C->getOperand(0)->getType();
3756 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
3757 // Only do this if the casts both really cause code to be generated.
3758 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
3759 I.getType(), TD) &&
3760 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
3761 I.getType(), TD)) {
3762 Instruction *NewOp = BinaryOperator::createAnd(Op0C->getOperand(0),
3763 Op1C->getOperand(0),
3764 I.getName());
3765 InsertNewInstBefore(NewOp, I);
3766 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
3767 }
3768 }
3769
3770 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
3771 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
3772 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
3773 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
3774 SI0->getOperand(1) == SI1->getOperand(1) &&
3775 (SI0->hasOneUse() || SI1->hasOneUse())) {
3776 Instruction *NewOp =
3777 InsertNewInstBefore(BinaryOperator::createAnd(SI0->getOperand(0),
3778 SI1->getOperand(0),
3779 SI0->getName()), I);
3780 return BinaryOperator::create(SI1->getOpcode(), NewOp,
3781 SI1->getOperand(1));
3782 }
3783 }
3784
Chris Lattner91882432007-10-24 05:38:08 +00003785 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
3786 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
3787 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
3788 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
3789 RHS->getPredicate() == FCmpInst::FCMP_ORD)
3790 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
3791 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
3792 // If either of the constants are nans, then the whole thing returns
3793 // false.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00003794 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00003795 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3796 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
3797 RHS->getOperand(0));
3798 }
3799 }
3800 }
3801
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003802 return Changed ? &I : 0;
3803}
3804
3805/// CollectBSwapParts - Look to see if the specified value defines a single byte
3806/// in the result. If it does, and if the specified byte hasn't been filled in
3807/// yet, fill it in and return false.
3808static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
3809 Instruction *I = dyn_cast<Instruction>(V);
3810 if (I == 0) return true;
3811
3812 // If this is an or instruction, it is an inner node of the bswap.
3813 if (I->getOpcode() == Instruction::Or)
3814 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
3815 CollectBSwapParts(I->getOperand(1), ByteValues);
3816
3817 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
3818 // If this is a shift by a constant int, and it is "24", then its operand
3819 // defines a byte. We only handle unsigned types here.
3820 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
3821 // Not shifting the entire input by N-1 bytes?
3822 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
3823 8*(ByteValues.size()-1))
3824 return true;
3825
3826 unsigned DestNo;
3827 if (I->getOpcode() == Instruction::Shl) {
3828 // X << 24 defines the top byte with the lowest of the input bytes.
3829 DestNo = ByteValues.size()-1;
3830 } else {
3831 // X >>u 24 defines the low byte with the highest of the input bytes.
3832 DestNo = 0;
3833 }
3834
3835 // If the destination byte value is already defined, the values are or'd
3836 // together, which isn't a bswap (unless it's an or of the same bits).
3837 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
3838 return true;
3839 ByteValues[DestNo] = I->getOperand(0);
3840 return false;
3841 }
3842
3843 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
3844 // don't have this.
3845 Value *Shift = 0, *ShiftLHS = 0;
3846 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
3847 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
3848 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
3849 return true;
3850 Instruction *SI = cast<Instruction>(Shift);
3851
3852 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
3853 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
3854 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
3855 return true;
3856
3857 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
3858 unsigned DestByte;
3859 if (AndAmt->getValue().getActiveBits() > 64)
3860 return true;
3861 uint64_t AndAmtVal = AndAmt->getZExtValue();
3862 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
3863 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
3864 break;
3865 // Unknown mask for bswap.
3866 if (DestByte == ByteValues.size()) return true;
3867
3868 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
3869 unsigned SrcByte;
3870 if (SI->getOpcode() == Instruction::Shl)
3871 SrcByte = DestByte - ShiftBytes;
3872 else
3873 SrcByte = DestByte + ShiftBytes;
3874
3875 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
3876 if (SrcByte != ByteValues.size()-DestByte-1)
3877 return true;
3878
3879 // If the destination byte value is already defined, the values are or'd
3880 // together, which isn't a bswap (unless it's an or of the same bits).
3881 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
3882 return true;
3883 ByteValues[DestByte] = SI->getOperand(0);
3884 return false;
3885}
3886
3887/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
3888/// If so, insert the new bswap intrinsic and return it.
3889Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
3890 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
3891 if (!ITy || ITy->getBitWidth() % 16)
3892 return 0; // Can only bswap pairs of bytes. Can't do vectors.
3893
3894 /// ByteValues - For each byte of the result, we keep track of which value
3895 /// defines each byte.
3896 SmallVector<Value*, 8> ByteValues;
3897 ByteValues.resize(ITy->getBitWidth()/8);
3898
3899 // Try to find all the pieces corresponding to the bswap.
3900 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
3901 CollectBSwapParts(I.getOperand(1), ByteValues))
3902 return 0;
3903
3904 // Check to see if all of the bytes come from the same value.
3905 Value *V = ByteValues[0];
3906 if (V == 0) return 0; // Didn't find a byte? Must be zero.
3907
3908 // Check to make sure that all of the bytes come from the same value.
3909 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
3910 if (ByteValues[i] != V)
3911 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00003912 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003913 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00003914 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003915 return new CallInst(F, V);
3916}
3917
3918
3919Instruction *InstCombiner::visitOr(BinaryOperator &I) {
3920 bool Changed = SimplifyCommutative(I);
3921 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3922
3923 if (isa<UndefValue>(Op1)) // X | undef -> -1
3924 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
3925
3926 // or X, X = X
3927 if (Op0 == Op1)
3928 return ReplaceInstUsesWith(I, Op0);
3929
3930 // See if we can simplify any instructions used by the instruction whose sole
3931 // purpose is to compute bits we don't care about.
3932 if (!isa<VectorType>(I.getType())) {
3933 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3934 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3935 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3936 KnownZero, KnownOne))
3937 return &I;
3938 } else if (isa<ConstantAggregateZero>(Op1)) {
3939 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
3940 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3941 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
3942 return ReplaceInstUsesWith(I, I.getOperand(1));
3943 }
3944
3945
3946
3947 // or X, -1 == -1
3948 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3949 ConstantInt *C1 = 0; Value *X = 0;
3950 // (X & C1) | C2 --> (X | C2) & (C1|C2)
3951 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3952 Instruction *Or = BinaryOperator::createOr(X, RHS);
3953 InsertNewInstBefore(Or, I);
3954 Or->takeName(Op0);
3955 return BinaryOperator::createAnd(Or,
3956 ConstantInt::get(RHS->getValue() | C1->getValue()));
3957 }
3958
3959 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
3960 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
3961 Instruction *Or = BinaryOperator::createOr(X, RHS);
3962 InsertNewInstBefore(Or, I);
3963 Or->takeName(Op0);
3964 return BinaryOperator::createXor(Or,
3965 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
3966 }
3967
3968 // Try to fold constant and into select arguments.
3969 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3970 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3971 return R;
3972 if (isa<PHINode>(Op0))
3973 if (Instruction *NV = FoldOpIntoPhi(I))
3974 return NV;
3975 }
3976
3977 Value *A = 0, *B = 0;
3978 ConstantInt *C1 = 0, *C2 = 0;
3979
3980 if (match(Op0, m_And(m_Value(A), m_Value(B))))
3981 if (A == Op1 || B == Op1) // (A & ?) | A --> A
3982 return ReplaceInstUsesWith(I, Op1);
3983 if (match(Op1, m_And(m_Value(A), m_Value(B))))
3984 if (A == Op0 || B == Op0) // A | (A & ?) --> A
3985 return ReplaceInstUsesWith(I, Op0);
3986
3987 // (A | B) | C and A | (B | C) -> bswap if possible.
3988 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
3989 if (match(Op0, m_Or(m_Value(), m_Value())) ||
3990 match(Op1, m_Or(m_Value(), m_Value())) ||
3991 (match(Op0, m_Shift(m_Value(), m_Value())) &&
3992 match(Op1, m_Shift(m_Value(), m_Value())))) {
3993 if (Instruction *BSwap = MatchBSwap(I))
3994 return BSwap;
3995 }
3996
3997 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
3998 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
3999 MaskedValueIsZero(Op1, C1->getValue())) {
4000 Instruction *NOr = BinaryOperator::createOr(A, Op1);
4001 InsertNewInstBefore(NOr, I);
4002 NOr->takeName(Op0);
4003 return BinaryOperator::createXor(NOr, C1);
4004 }
4005
4006 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4007 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4008 MaskedValueIsZero(Op0, C1->getValue())) {
4009 Instruction *NOr = BinaryOperator::createOr(A, Op0);
4010 InsertNewInstBefore(NOr, I);
4011 NOr->takeName(Op0);
4012 return BinaryOperator::createXor(NOr, C1);
4013 }
4014
4015 // (A & C)|(B & D)
4016 Value *C = 0, *D = 0;
4017 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4018 match(Op1, m_And(m_Value(B), m_Value(D)))) {
4019 Value *V1 = 0, *V2 = 0, *V3 = 0;
4020 C1 = dyn_cast<ConstantInt>(C);
4021 C2 = dyn_cast<ConstantInt>(D);
4022 if (C1 && C2) { // (A & C1)|(B & C2)
4023 // If we have: ((V + N) & C1) | (V & C2)
4024 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4025 // replace with V+N.
4026 if (C1->getValue() == ~C2->getValue()) {
4027 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4028 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4029 // Add commutes, try both ways.
4030 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4031 return ReplaceInstUsesWith(I, A);
4032 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4033 return ReplaceInstUsesWith(I, A);
4034 }
4035 // Or commutes, try both ways.
4036 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4037 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4038 // Add commutes, try both ways.
4039 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4040 return ReplaceInstUsesWith(I, B);
4041 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4042 return ReplaceInstUsesWith(I, B);
4043 }
4044 }
4045 V1 = 0; V2 = 0; V3 = 0;
4046 }
4047
4048 // Check to see if we have any common things being and'ed. If so, find the
4049 // terms for V1 & (V2|V3).
4050 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4051 if (A == B) // (A & C)|(A & D) == A & (C|D)
4052 V1 = A, V2 = C, V3 = D;
4053 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4054 V1 = A, V2 = B, V3 = C;
4055 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4056 V1 = C, V2 = A, V3 = D;
4057 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4058 V1 = C, V2 = A, V3 = B;
4059
4060 if (V1) {
4061 Value *Or =
4062 InsertNewInstBefore(BinaryOperator::createOr(V2, V3, "tmp"), I);
4063 return BinaryOperator::createAnd(V1, Or);
4064 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004065 }
4066 }
4067
4068 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4069 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4070 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4071 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4072 SI0->getOperand(1) == SI1->getOperand(1) &&
4073 (SI0->hasOneUse() || SI1->hasOneUse())) {
4074 Instruction *NewOp =
4075 InsertNewInstBefore(BinaryOperator::createOr(SI0->getOperand(0),
4076 SI1->getOperand(0),
4077 SI0->getName()), I);
4078 return BinaryOperator::create(SI1->getOpcode(), NewOp,
4079 SI1->getOperand(1));
4080 }
4081 }
4082
4083 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4084 if (A == Op1) // ~A | A == -1
4085 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4086 } else {
4087 A = 0;
4088 }
4089 // Note, A is still live here!
4090 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4091 if (Op0 == B)
4092 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4093
4094 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4095 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
4096 Value *And = InsertNewInstBefore(BinaryOperator::createAnd(A, B,
4097 I.getName()+".demorgan"), I);
4098 return BinaryOperator::createNot(And);
4099 }
4100 }
4101
4102 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4103 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4104 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4105 return R;
4106
4107 Value *LHSVal, *RHSVal;
4108 ConstantInt *LHSCst, *RHSCst;
4109 ICmpInst::Predicate LHSCC, RHSCC;
4110 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4111 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4112 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4113 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4114 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4115 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4116 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4117 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4118 // We can't fold (ugt x, C) | (sgt x, C2).
4119 PredicatesFoldable(LHSCC, RHSCC)) {
4120 // Ensure that the larger constant is on the RHS.
4121 ICmpInst *LHS = cast<ICmpInst>(Op0);
4122 bool NeedsSwap;
4123 if (ICmpInst::isSignedPredicate(LHSCC))
4124 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4125 else
4126 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4127
4128 if (NeedsSwap) {
4129 std::swap(LHS, RHS);
4130 std::swap(LHSCst, RHSCst);
4131 std::swap(LHSCC, RHSCC);
4132 }
4133
4134 // At this point, we know we have have two icmp instructions
4135 // comparing a value against two constants and or'ing the result
4136 // together. Because of the above check, we know that we only have
4137 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4138 // FoldICmpLogical check above), that the two constants are not
4139 // equal.
4140 assert(LHSCst != RHSCst && "Compares not folded above?");
4141
4142 switch (LHSCC) {
4143 default: assert(0 && "Unknown integer condition code!");
4144 case ICmpInst::ICMP_EQ:
4145 switch (RHSCC) {
4146 default: assert(0 && "Unknown integer condition code!");
4147 case ICmpInst::ICMP_EQ:
4148 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4149 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4150 Instruction *Add = BinaryOperator::createAdd(LHSVal, AddCST,
4151 LHSVal->getName()+".off");
4152 InsertNewInstBefore(Add, I);
4153 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4154 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4155 }
4156 break; // (X == 13 | X == 15) -> no change
4157 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4158 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4159 break;
4160 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4161 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4162 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4163 return ReplaceInstUsesWith(I, RHS);
4164 }
4165 break;
4166 case ICmpInst::ICMP_NE:
4167 switch (RHSCC) {
4168 default: assert(0 && "Unknown integer condition code!");
4169 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4170 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4171 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4172 return ReplaceInstUsesWith(I, LHS);
4173 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4174 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4175 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4176 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4177 }
4178 break;
4179 case ICmpInst::ICMP_ULT:
4180 switch (RHSCC) {
4181 default: assert(0 && "Unknown integer condition code!");
4182 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4183 break;
4184 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner26376862007-11-01 02:18:41 +00004185 // If RHSCst is [us]MAXINT, it is always false. Not handling
4186 // this can cause overflow.
4187 if (RHSCst->isMaxValue(false))
4188 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004189 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4190 false, I);
4191 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4192 break;
4193 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4194 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4195 return ReplaceInstUsesWith(I, RHS);
4196 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4197 break;
4198 }
4199 break;
4200 case ICmpInst::ICMP_SLT:
4201 switch (RHSCC) {
4202 default: assert(0 && "Unknown integer condition code!");
4203 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4204 break;
4205 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner26376862007-11-01 02:18:41 +00004206 // If RHSCst is [us]MAXINT, it is always false. Not handling
4207 // this can cause overflow.
4208 if (RHSCst->isMaxValue(true))
4209 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004210 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4211 false, I);
4212 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4213 break;
4214 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4215 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4216 return ReplaceInstUsesWith(I, RHS);
4217 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4218 break;
4219 }
4220 break;
4221 case ICmpInst::ICMP_UGT:
4222 switch (RHSCC) {
4223 default: assert(0 && "Unknown integer condition code!");
4224 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4225 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4226 return ReplaceInstUsesWith(I, LHS);
4227 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4228 break;
4229 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4230 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4231 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4232 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4233 break;
4234 }
4235 break;
4236 case ICmpInst::ICMP_SGT:
4237 switch (RHSCC) {
4238 default: assert(0 && "Unknown integer condition code!");
4239 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4240 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4241 return ReplaceInstUsesWith(I, LHS);
4242 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4243 break;
4244 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4245 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4246 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4247 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4248 break;
4249 }
4250 break;
4251 }
4252 }
4253 }
4254
4255 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004256 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004257 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4258 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
4259 const Type *SrcTy = Op0C->getOperand(0)->getType();
4260 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4261 // Only do this if the casts both really cause code to be generated.
4262 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4263 I.getType(), TD) &&
4264 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4265 I.getType(), TD)) {
4266 Instruction *NewOp = BinaryOperator::createOr(Op0C->getOperand(0),
4267 Op1C->getOperand(0),
4268 I.getName());
4269 InsertNewInstBefore(NewOp, I);
4270 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4271 }
4272 }
Chris Lattner91882432007-10-24 05:38:08 +00004273 }
4274
4275
4276 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4277 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4278 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4279 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
4280 RHS->getPredicate() == FCmpInst::FCMP_UNO)
4281 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4282 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4283 // If either of the constants are nans, then the whole thing returns
4284 // true.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00004285 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00004286 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4287
4288 // Otherwise, no need to compare the two constants, compare the
4289 // rest.
4290 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4291 RHS->getOperand(0));
4292 }
4293 }
4294 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004295
4296 return Changed ? &I : 0;
4297}
4298
4299// XorSelf - Implements: X ^ X --> 0
4300struct XorSelf {
4301 Value *RHS;
4302 XorSelf(Value *rhs) : RHS(rhs) {}
4303 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4304 Instruction *apply(BinaryOperator &Xor) const {
4305 return &Xor;
4306 }
4307};
4308
4309
4310Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4311 bool Changed = SimplifyCommutative(I);
4312 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4313
4314 if (isa<UndefValue>(Op1))
4315 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
4316
4317 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4318 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00004319 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004320 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4321 }
4322
4323 // See if we can simplify any instructions used by the instruction whose sole
4324 // purpose is to compute bits we don't care about.
4325 if (!isa<VectorType>(I.getType())) {
4326 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4327 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4328 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4329 KnownZero, KnownOne))
4330 return &I;
4331 } else if (isa<ConstantAggregateZero>(Op1)) {
4332 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
4333 }
4334
4335 // Is this a ~ operation?
4336 if (Value *NotOp = dyn_castNotVal(&I)) {
4337 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4338 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4339 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4340 if (Op0I->getOpcode() == Instruction::And ||
4341 Op0I->getOpcode() == Instruction::Or) {
4342 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4343 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4344 Instruction *NotY =
4345 BinaryOperator::createNot(Op0I->getOperand(1),
4346 Op0I->getOperand(1)->getName()+".not");
4347 InsertNewInstBefore(NotY, I);
4348 if (Op0I->getOpcode() == Instruction::And)
4349 return BinaryOperator::createOr(Op0NotVal, NotY);
4350 else
4351 return BinaryOperator::createAnd(Op0NotVal, NotY);
4352 }
4353 }
4354 }
4355 }
4356
4357
4358 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky1405e922007-08-06 20:04:16 +00004359 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4360 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4361 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004362 return new ICmpInst(ICI->getInversePredicate(),
4363 ICI->getOperand(0), ICI->getOperand(1));
4364
Nick Lewycky1405e922007-08-06 20:04:16 +00004365 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4366 return new FCmpInst(FCI->getInversePredicate(),
4367 FCI->getOperand(0), FCI->getOperand(1));
4368 }
4369
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004370 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4371 // ~(c-X) == X-c-1 == X+(-c-1)
4372 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4373 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4374 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4375 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4376 ConstantInt::get(I.getType(), 1));
4377 return BinaryOperator::createAdd(Op0I->getOperand(1), ConstantRHS);
4378 }
4379
4380 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4381 if (Op0I->getOpcode() == Instruction::Add) {
4382 // ~(X-c) --> (-c-1)-X
4383 if (RHS->isAllOnesValue()) {
4384 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
4385 return BinaryOperator::createSub(
4386 ConstantExpr::getSub(NegOp0CI,
4387 ConstantInt::get(I.getType(), 1)),
4388 Op0I->getOperand(0));
4389 } else if (RHS->getValue().isSignBit()) {
4390 // (X + C) ^ signbit -> (X + C + signbit)
4391 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
4392 return BinaryOperator::createAdd(Op0I->getOperand(0), C);
4393
4394 }
4395 } else if (Op0I->getOpcode() == Instruction::Or) {
4396 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4397 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4398 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4399 // Anything in both C1 and C2 is known to be zero, remove it from
4400 // NewRHS.
4401 Constant *CommonBits = And(Op0CI, RHS);
4402 NewRHS = ConstantExpr::getAnd(NewRHS,
4403 ConstantExpr::getNot(CommonBits));
4404 AddToWorkList(Op0I);
4405 I.setOperand(0, Op0I->getOperand(0));
4406 I.setOperand(1, NewRHS);
4407 return &I;
4408 }
4409 }
4410 }
4411
4412 // Try to fold constant and into select arguments.
4413 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4414 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4415 return R;
4416 if (isa<PHINode>(Op0))
4417 if (Instruction *NV = FoldOpIntoPhi(I))
4418 return NV;
4419 }
4420
4421 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
4422 if (X == Op1)
4423 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4424
4425 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
4426 if (X == Op0)
4427 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4428
4429
4430 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4431 if (Op1I) {
4432 Value *A, *B;
4433 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4434 if (A == Op0) { // B^(B|A) == (A|B)^B
4435 Op1I->swapOperands();
4436 I.swapOperands();
4437 std::swap(Op0, Op1);
4438 } else if (B == Op0) { // B^(A|B) == (A|B)^B
4439 I.swapOperands(); // Simplified below.
4440 std::swap(Op0, Op1);
4441 }
4442 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4443 if (Op0 == A) // A^(A^B) == B
4444 return ReplaceInstUsesWith(I, B);
4445 else if (Op0 == B) // A^(B^A) == B
4446 return ReplaceInstUsesWith(I, A);
4447 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4448 if (A == Op0) { // A^(A&B) -> A^(B&A)
4449 Op1I->swapOperands();
4450 std::swap(A, B);
4451 }
4452 if (B == Op0) { // A^(B&A) -> (B&A)^A
4453 I.swapOperands(); // Simplified below.
4454 std::swap(Op0, Op1);
4455 }
4456 }
4457 }
4458
4459 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4460 if (Op0I) {
4461 Value *A, *B;
4462 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4463 if (A == Op1) // (B|A)^B == (A|B)^B
4464 std::swap(A, B);
4465 if (B == Op1) { // (A|B)^B == A & ~B
4466 Instruction *NotB =
4467 InsertNewInstBefore(BinaryOperator::createNot(Op1, "tmp"), I);
4468 return BinaryOperator::createAnd(A, NotB);
4469 }
4470 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4471 if (Op1 == A) // (A^B)^A == B
4472 return ReplaceInstUsesWith(I, B);
4473 else if (Op1 == B) // (B^A)^A == B
4474 return ReplaceInstUsesWith(I, A);
4475 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4476 if (A == Op1) // (A&B)^A -> (B&A)^A
4477 std::swap(A, B);
4478 if (B == Op1 && // (B&A)^A == ~B & A
4479 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
4480 Instruction *N =
4481 InsertNewInstBefore(BinaryOperator::createNot(A, "tmp"), I);
4482 return BinaryOperator::createAnd(N, Op1);
4483 }
4484 }
4485 }
4486
4487 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4488 if (Op0I && Op1I && Op0I->isShift() &&
4489 Op0I->getOpcode() == Op1I->getOpcode() &&
4490 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4491 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4492 Instruction *NewOp =
4493 InsertNewInstBefore(BinaryOperator::createXor(Op0I->getOperand(0),
4494 Op1I->getOperand(0),
4495 Op0I->getName()), I);
4496 return BinaryOperator::create(Op1I->getOpcode(), NewOp,
4497 Op1I->getOperand(1));
4498 }
4499
4500 if (Op0I && Op1I) {
4501 Value *A, *B, *C, *D;
4502 // (A & B)^(A | B) -> A ^ B
4503 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4504 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4505 if ((A == C && B == D) || (A == D && B == C))
4506 return BinaryOperator::createXor(A, B);
4507 }
4508 // (A | B)^(A & B) -> A ^ B
4509 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4510 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4511 if ((A == C && B == D) || (A == D && B == C))
4512 return BinaryOperator::createXor(A, B);
4513 }
4514
4515 // (A & B)^(C & D)
4516 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4517 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4518 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4519 // (X & Y)^(X & Y) -> (Y^Z) & X
4520 Value *X = 0, *Y = 0, *Z = 0;
4521 if (A == C)
4522 X = A, Y = B, Z = D;
4523 else if (A == D)
4524 X = A, Y = B, Z = C;
4525 else if (B == C)
4526 X = B, Y = A, Z = D;
4527 else if (B == D)
4528 X = B, Y = A, Z = C;
4529
4530 if (X) {
4531 Instruction *NewOp =
4532 InsertNewInstBefore(BinaryOperator::createXor(Y, Z, Op0->getName()), I);
4533 return BinaryOperator::createAnd(NewOp, X);
4534 }
4535 }
4536 }
4537
4538 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4539 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4540 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4541 return R;
4542
4543 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004544 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004545 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4546 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4547 const Type *SrcTy = Op0C->getOperand(0)->getType();
4548 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4549 // Only do this if the casts both really cause code to be generated.
4550 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4551 I.getType(), TD) &&
4552 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4553 I.getType(), TD)) {
4554 Instruction *NewOp = BinaryOperator::createXor(Op0C->getOperand(0),
4555 Op1C->getOperand(0),
4556 I.getName());
4557 InsertNewInstBefore(NewOp, I);
4558 return CastInst::create(Op0C->getOpcode(), NewOp, I.getType());
4559 }
4560 }
Chris Lattner91882432007-10-24 05:38:08 +00004561 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004562 return Changed ? &I : 0;
4563}
4564
4565/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4566/// overflowed for this type.
4567static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4568 ConstantInt *In2, bool IsSigned = false) {
4569 Result = cast<ConstantInt>(Add(In1, In2));
4570
4571 if (IsSigned)
4572 if (In2->getValue().isNegative())
4573 return Result->getValue().sgt(In1->getValue());
4574 else
4575 return Result->getValue().slt(In1->getValue());
4576 else
4577 return Result->getValue().ult(In1->getValue());
4578}
4579
4580/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4581/// code necessary to compute the offset from the base pointer (without adding
4582/// in the base pointer). Return the result as a signed integer of intptr size.
4583static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4584 TargetData &TD = IC.getTargetData();
4585 gep_type_iterator GTI = gep_type_begin(GEP);
4586 const Type *IntPtrTy = TD.getIntPtrType();
4587 Value *Result = Constant::getNullValue(IntPtrTy);
4588
4589 // Build a mask for high order bits.
4590 unsigned IntPtrWidth = TD.getPointerSize()*8;
4591 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4592
4593 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4594 Value *Op = GEP->getOperand(i);
Duncan Sandsf99fdc62007-11-01 20:53:16 +00004595 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004596 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4597 if (OpC->isZero()) continue;
4598
4599 // Handle a struct index, which adds its field offset to the pointer.
4600 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4601 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4602
4603 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4604 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4605 else
4606 Result = IC.InsertNewInstBefore(
4607 BinaryOperator::createAdd(Result,
4608 ConstantInt::get(IntPtrTy, Size),
4609 GEP->getName()+".offs"), I);
4610 continue;
4611 }
4612
4613 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4614 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4615 Scale = ConstantExpr::getMul(OC, Scale);
4616 if (Constant *RC = dyn_cast<Constant>(Result))
4617 Result = ConstantExpr::getAdd(RC, Scale);
4618 else {
4619 // Emit an add instruction.
4620 Result = IC.InsertNewInstBefore(
4621 BinaryOperator::createAdd(Result, Scale,
4622 GEP->getName()+".offs"), I);
4623 }
4624 continue;
4625 }
4626 // Convert to correct type.
4627 if (Op->getType() != IntPtrTy) {
4628 if (Constant *OpC = dyn_cast<Constant>(Op))
4629 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4630 else
4631 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4632 Op->getName()+".c"), I);
4633 }
4634 if (Size != 1) {
4635 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4636 if (Constant *OpC = dyn_cast<Constant>(Op))
4637 Op = ConstantExpr::getMul(OpC, Scale);
4638 else // We'll let instcombine(mul) convert this to a shl if possible.
4639 Op = IC.InsertNewInstBefore(BinaryOperator::createMul(Op, Scale,
4640 GEP->getName()+".idx"), I);
4641 }
4642
4643 // Emit an add instruction.
4644 if (isa<Constant>(Op) && isa<Constant>(Result))
4645 Result = ConstantExpr::getAdd(cast<Constant>(Op),
4646 cast<Constant>(Result));
4647 else
4648 Result = IC.InsertNewInstBefore(BinaryOperator::createAdd(Op, Result,
4649 GEP->getName()+".offs"), I);
4650 }
4651 return Result;
4652}
4653
4654/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
4655/// else. At this point we know that the GEP is on the LHS of the comparison.
4656Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
4657 ICmpInst::Predicate Cond,
4658 Instruction &I) {
4659 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
4660
4661 if (CastInst *CI = dyn_cast<CastInst>(RHS))
4662 if (isa<PointerType>(CI->getOperand(0)->getType()))
4663 RHS = CI->getOperand(0);
4664
4665 Value *PtrBase = GEPLHS->getOperand(0);
4666 if (PtrBase == RHS) {
Chris Lattneraf97d022008-02-05 04:45:32 +00004667 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
4668 // This transformation is valid because we know pointers can't overflow.
4669 Value *Offset = EmitGEPOffset(GEPLHS, I, *this);
4670 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
4671 Constant::getNullValue(Offset->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004672 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
4673 // If the base pointers are different, but the indices are the same, just
4674 // compare the base pointer.
4675 if (PtrBase != GEPRHS->getOperand(0)) {
4676 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
4677 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
4678 GEPRHS->getOperand(0)->getType();
4679 if (IndicesTheSame)
4680 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4681 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4682 IndicesTheSame = false;
4683 break;
4684 }
4685
4686 // If all indices are the same, just compare the base pointers.
4687 if (IndicesTheSame)
4688 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
4689 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
4690
4691 // Otherwise, the base pointers are different and the indices are
4692 // different, bail out.
4693 return 0;
4694 }
4695
4696 // If one of the GEPs has all zero indices, recurse.
4697 bool AllZeros = true;
4698 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
4699 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
4700 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
4701 AllZeros = false;
4702 break;
4703 }
4704 if (AllZeros)
4705 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
4706 ICmpInst::getSwappedPredicate(Cond), I);
4707
4708 // If the other GEP has all zero indices, recurse.
4709 AllZeros = true;
4710 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4711 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
4712 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
4713 AllZeros = false;
4714 break;
4715 }
4716 if (AllZeros)
4717 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
4718
4719 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
4720 // If the GEPs only differ by one index, compare it.
4721 unsigned NumDifferences = 0; // Keep track of # differences.
4722 unsigned DiffOperand = 0; // The operand that differs.
4723 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
4724 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
4725 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
4726 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
4727 // Irreconcilable differences.
4728 NumDifferences = 2;
4729 break;
4730 } else {
4731 if (NumDifferences++) break;
4732 DiffOperand = i;
4733 }
4734 }
4735
4736 if (NumDifferences == 0) // SAME GEP?
4737 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky2de09a92007-09-06 02:40:25 +00004738 ConstantInt::get(Type::Int1Ty,
4739 isTrueWhenEqual(Cond)));
4740
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004741 else if (NumDifferences == 1) {
4742 Value *LHSV = GEPLHS->getOperand(DiffOperand);
4743 Value *RHSV = GEPRHS->getOperand(DiffOperand);
4744 // Make sure we do a signed comparison here.
4745 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
4746 }
4747 }
4748
4749 // Only lower this if the icmp is the only user of the GEP or if we expect
4750 // the result to fold to a constant!
4751 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
4752 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
4753 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
4754 Value *L = EmitGEPOffset(GEPLHS, I, *this);
4755 Value *R = EmitGEPOffset(GEPRHS, I, *this);
4756 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
4757 }
4758 }
4759 return 0;
4760}
4761
4762Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
4763 bool Changed = SimplifyCompare(I);
4764 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4765
4766 // Fold trivial predicates.
4767 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
4768 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
4769 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
4770 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4771
4772 // Simplify 'fcmp pred X, X'
4773 if (Op0 == Op1) {
4774 switch (I.getPredicate()) {
4775 default: assert(0 && "Unknown predicate!");
4776 case FCmpInst::FCMP_UEQ: // True if unordered or equal
4777 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
4778 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
4779 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
4780 case FCmpInst::FCMP_OGT: // True if ordered and greater than
4781 case FCmpInst::FCMP_OLT: // True if ordered and less than
4782 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
4783 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
4784
4785 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
4786 case FCmpInst::FCMP_ULT: // True if unordered or less than
4787 case FCmpInst::FCMP_UGT: // True if unordered or greater than
4788 case FCmpInst::FCMP_UNE: // True if unordered or not equal
4789 // Canonicalize these to be 'fcmp uno %X, 0.0'.
4790 I.setPredicate(FCmpInst::FCMP_UNO);
4791 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4792 return &I;
4793
4794 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
4795 case FCmpInst::FCMP_OEQ: // True if ordered and equal
4796 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
4797 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
4798 // Canonicalize these to be 'fcmp ord %X, 0.0'.
4799 I.setPredicate(FCmpInst::FCMP_ORD);
4800 I.setOperand(1, Constant::getNullValue(Op0->getType()));
4801 return &I;
4802 }
4803 }
4804
4805 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
4806 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
4807
4808 // Handle fcmp with constant RHS
4809 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
4810 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
4811 switch (LHSI->getOpcode()) {
4812 case Instruction::PHI:
4813 if (Instruction *NV = FoldOpIntoPhi(I))
4814 return NV;
4815 break;
4816 case Instruction::Select:
4817 // If either operand of the select is a constant, we can fold the
4818 // comparison into the select arms, which will cause one to be
4819 // constant folded and the select turned into a bitwise or.
4820 Value *Op1 = 0, *Op2 = 0;
4821 if (LHSI->hasOneUse()) {
4822 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
4823 // Fold the known value into the constant operand.
4824 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4825 // Insert a new FCmp of the other select operand.
4826 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4827 LHSI->getOperand(2), RHSC,
4828 I.getName()), I);
4829 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
4830 // Fold the known value into the constant operand.
4831 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
4832 // Insert a new FCmp of the other select operand.
4833 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
4834 LHSI->getOperand(1), RHSC,
4835 I.getName()), I);
4836 }
4837 }
4838
4839 if (Op1)
4840 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
4841 break;
4842 }
4843 }
4844
4845 return Changed ? &I : 0;
4846}
4847
4848Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
4849 bool Changed = SimplifyCompare(I);
4850 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4851 const Type *Ty = Op0->getType();
4852
4853 // icmp X, X
4854 if (Op0 == Op1)
4855 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4856 isTrueWhenEqual(I)));
4857
4858 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
4859 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lambf78cd322007-12-18 21:32:20 +00004860
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004861 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
4862 // addresses never equal each other! We already know that Op0 != Op1.
4863 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
4864 isa<ConstantPointerNull>(Op0)) &&
4865 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
4866 isa<ConstantPointerNull>(Op1)))
4867 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
4868 !isTrueWhenEqual(I)));
4869
4870 // icmp's with boolean values can always be turned into bitwise operations
4871 if (Ty == Type::Int1Ty) {
4872 switch (I.getPredicate()) {
4873 default: assert(0 && "Invalid icmp instruction!");
4874 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
4875 Instruction *Xor = BinaryOperator::createXor(Op0, Op1, I.getName()+"tmp");
4876 InsertNewInstBefore(Xor, I);
4877 return BinaryOperator::createNot(Xor);
4878 }
4879 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
4880 return BinaryOperator::createXor(Op0, Op1);
4881
4882 case ICmpInst::ICMP_UGT:
4883 case ICmpInst::ICMP_SGT:
4884 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
4885 // FALL THROUGH
4886 case ICmpInst::ICMP_ULT:
4887 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
4888 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4889 InsertNewInstBefore(Not, I);
4890 return BinaryOperator::createAnd(Not, Op1);
4891 }
4892 case ICmpInst::ICMP_UGE:
4893 case ICmpInst::ICMP_SGE:
4894 std::swap(Op0, Op1); // Change icmp ge -> icmp le
4895 // FALL THROUGH
4896 case ICmpInst::ICMP_ULE:
4897 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
4898 Instruction *Not = BinaryOperator::createNot(Op0, I.getName()+"tmp");
4899 InsertNewInstBefore(Not, I);
4900 return BinaryOperator::createOr(Not, Op1);
4901 }
4902 }
4903 }
4904
4905 // See if we are doing a comparison between a constant and an instruction that
4906 // can be folded into the comparison.
4907 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lambfa6b3102007-12-20 07:21:11 +00004908 Value *A, *B;
4909
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00004910 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
4911 if (I.isEquality() && CI->isNullValue() &&
4912 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
4913 // (icmp cond A B) if cond is equality
4914 return new ICmpInst(I.getPredicate(), A, B);
Owen Anderson42f61ed2007-12-28 07:42:12 +00004915 }
Christopher Lambfa6b3102007-12-20 07:21:11 +00004916
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004917 switch (I.getPredicate()) {
4918 default: break;
4919 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
4920 if (CI->isMinValue(false))
4921 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4922 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
4923 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
4924 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
4925 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4926 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
4927 if (CI->isMinValue(true))
4928 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
4929 ConstantInt::getAllOnesValue(Op0->getType()));
4930
4931 break;
4932
4933 case ICmpInst::ICMP_SLT:
4934 if (CI->isMinValue(true)) // A <s MIN -> FALSE
4935 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4936 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
4937 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4938 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
4939 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
4940 break;
4941
4942 case ICmpInst::ICMP_UGT:
4943 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
4944 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4945 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
4946 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4947 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
4948 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4949
4950 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
4951 if (CI->isMaxValue(true))
4952 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
4953 ConstantInt::getNullValue(Op0->getType()));
4954 break;
4955
4956 case ICmpInst::ICMP_SGT:
4957 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
4958 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4959 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
4960 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
4961 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
4962 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
4963 break;
4964
4965 case ICmpInst::ICMP_ULE:
4966 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
4967 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4968 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
4969 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4970 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
4971 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4972 break;
4973
4974 case ICmpInst::ICMP_SLE:
4975 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
4976 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4977 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
4978 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4979 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
4980 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
4981 break;
4982
4983 case ICmpInst::ICMP_UGE:
4984 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
4985 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4986 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
4987 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4988 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
4989 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4990 break;
4991
4992 case ICmpInst::ICMP_SGE:
4993 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
4994 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4995 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
4996 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
4997 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
4998 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
4999 break;
5000 }
5001
5002 // If we still have a icmp le or icmp ge instruction, turn it into the
5003 // appropriate icmp lt or icmp gt instruction. Since the border cases have
5004 // already been handled above, this requires little checking.
5005 //
5006 switch (I.getPredicate()) {
5007 default: break;
5008 case ICmpInst::ICMP_ULE:
5009 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5010 case ICmpInst::ICMP_SLE:
5011 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5012 case ICmpInst::ICMP_UGE:
5013 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5014 case ICmpInst::ICMP_SGE:
5015 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5016 }
5017
5018 // See if we can fold the comparison based on bits known to be zero or one
5019 // in the input. If this comparison is a normal comparison, it demands all
5020 // bits, if it is a sign bit comparison, it only demands the sign bit.
5021
5022 bool UnusedBit;
5023 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5024
5025 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5026 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5027 if (SimplifyDemandedBits(Op0,
5028 isSignBit ? APInt::getSignBit(BitWidth)
5029 : APInt::getAllOnesValue(BitWidth),
5030 KnownZero, KnownOne, 0))
5031 return &I;
5032
5033 // Given the known and unknown bits, compute a range that the LHS could be
5034 // in.
5035 if ((KnownOne | KnownZero) != 0) {
5036 // Compute the Min, Max and RHS values based on the known bits. For the
5037 // EQ and NE we use unsigned values.
5038 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5039 const APInt& RHSVal = CI->getValue();
5040 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5041 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5042 Max);
5043 } else {
5044 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5045 Max);
5046 }
5047 switch (I.getPredicate()) { // LE/GE have been folded already.
5048 default: assert(0 && "Unknown icmp opcode!");
5049 case ICmpInst::ICMP_EQ:
5050 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5051 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5052 break;
5053 case ICmpInst::ICMP_NE:
5054 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5055 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5056 break;
5057 case ICmpInst::ICMP_ULT:
5058 if (Max.ult(RHSVal))
5059 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5060 if (Min.uge(RHSVal))
5061 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5062 break;
5063 case ICmpInst::ICMP_UGT:
5064 if (Min.ugt(RHSVal))
5065 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5066 if (Max.ule(RHSVal))
5067 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5068 break;
5069 case ICmpInst::ICMP_SLT:
5070 if (Max.slt(RHSVal))
5071 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5072 if (Min.sgt(RHSVal))
5073 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5074 break;
5075 case ICmpInst::ICMP_SGT:
5076 if (Min.sgt(RHSVal))
5077 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5078 if (Max.sle(RHSVal))
5079 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5080 break;
5081 }
5082 }
5083
5084 // Since the RHS is a ConstantInt (CI), if the left hand side is an
5085 // instruction, see if that instruction also has constants so that the
5086 // instruction can be folded into the icmp
5087 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5088 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5089 return Res;
5090 }
5091
5092 // Handle icmp with constant (but not simple integer constant) RHS
5093 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5094 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5095 switch (LHSI->getOpcode()) {
5096 case Instruction::GetElementPtr:
5097 if (RHSC->isNullValue()) {
5098 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5099 bool isAllZeros = true;
5100 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5101 if (!isa<Constant>(LHSI->getOperand(i)) ||
5102 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5103 isAllZeros = false;
5104 break;
5105 }
5106 if (isAllZeros)
5107 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5108 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5109 }
5110 break;
5111
5112 case Instruction::PHI:
5113 if (Instruction *NV = FoldOpIntoPhi(I))
5114 return NV;
5115 break;
5116 case Instruction::Select: {
5117 // If either operand of the select is a constant, we can fold the
5118 // comparison into the select arms, which will cause one to be
5119 // constant folded and the select turned into a bitwise or.
5120 Value *Op1 = 0, *Op2 = 0;
5121 if (LHSI->hasOneUse()) {
5122 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5123 // Fold the known value into the constant operand.
5124 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5125 // Insert a new ICmp of the other select operand.
5126 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5127 LHSI->getOperand(2), RHSC,
5128 I.getName()), I);
5129 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5130 // Fold the known value into the constant operand.
5131 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5132 // Insert a new ICmp of the other select operand.
5133 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5134 LHSI->getOperand(1), RHSC,
5135 I.getName()), I);
5136 }
5137 }
5138
5139 if (Op1)
5140 return new SelectInst(LHSI->getOperand(0), Op1, Op2);
5141 break;
5142 }
5143 case Instruction::Malloc:
5144 // If we have (malloc != null), and if the malloc has a single use, we
5145 // can assume it is successful and remove the malloc.
5146 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5147 AddToWorkList(LHSI);
5148 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
5149 !isTrueWhenEqual(I)));
5150 }
5151 break;
5152 }
5153 }
5154
5155 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5156 if (User *GEP = dyn_castGetElementPtr(Op0))
5157 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5158 return NI;
5159 if (User *GEP = dyn_castGetElementPtr(Op1))
5160 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5161 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5162 return NI;
5163
5164 // Test to see if the operands of the icmp are casted versions of other
5165 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5166 // now.
5167 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5168 if (isa<PointerType>(Op0->getType()) &&
5169 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
5170 // We keep moving the cast from the left operand over to the right
5171 // operand, where it can often be eliminated completely.
5172 Op0 = CI->getOperand(0);
5173
5174 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5175 // so eliminate it as well.
5176 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5177 Op1 = CI2->getOperand(0);
5178
5179 // If Op1 is a constant, we can fold the cast into the constant.
5180 if (Op0->getType() != Op1->getType())
5181 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5182 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5183 } else {
5184 // Otherwise, cast the RHS right before the icmp
Chris Lattner13c2d6e2008-01-13 22:23:22 +00005185 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005186 }
5187 return new ICmpInst(I.getPredicate(), Op0, Op1);
5188 }
5189 }
5190
5191 if (isa<CastInst>(Op0)) {
5192 // Handle the special case of: icmp (cast bool to X), <cst>
5193 // This comes up when you have code like
5194 // int X = A < B;
5195 // if (X) ...
5196 // For generality, we handle any zero-extension of any operand comparison
5197 // with a constant or another cast from the same type.
5198 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5199 if (Instruction *R = visitICmpInstWithCastAndCast(I))
5200 return R;
5201 }
5202
5203 if (I.isEquality()) {
5204 Value *A, *B, *C, *D;
5205 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5206 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5207 Value *OtherVal = A == Op1 ? B : A;
5208 return new ICmpInst(I.getPredicate(), OtherVal,
5209 Constant::getNullValue(A->getType()));
5210 }
5211
5212 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5213 // A^c1 == C^c2 --> A == C^(c1^c2)
5214 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5215 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5216 if (Op1->hasOneUse()) {
5217 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
5218 Instruction *Xor = BinaryOperator::createXor(C, NC, "tmp");
5219 return new ICmpInst(I.getPredicate(), A,
5220 InsertNewInstBefore(Xor, I));
5221 }
5222
5223 // A^B == A^D -> B == D
5224 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5225 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5226 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5227 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5228 }
5229 }
5230
5231 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5232 (A == Op0 || B == Op0)) {
5233 // A == (A^B) -> B == 0
5234 Value *OtherVal = A == Op0 ? B : A;
5235 return new ICmpInst(I.getPredicate(), OtherVal,
5236 Constant::getNullValue(A->getType()));
5237 }
5238 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5239 // (A-B) == A -> B == 0
5240 return new ICmpInst(I.getPredicate(), B,
5241 Constant::getNullValue(B->getType()));
5242 }
5243 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5244 // A == (A-B) -> B == 0
5245 return new ICmpInst(I.getPredicate(), B,
5246 Constant::getNullValue(B->getType()));
5247 }
5248
5249 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5250 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5251 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5252 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5253 Value *X = 0, *Y = 0, *Z = 0;
5254
5255 if (A == C) {
5256 X = B; Y = D; Z = A;
5257 } else if (A == D) {
5258 X = B; Y = C; Z = A;
5259 } else if (B == C) {
5260 X = A; Y = D; Z = B;
5261 } else if (B == D) {
5262 X = A; Y = C; Z = B;
5263 }
5264
5265 if (X) { // Build (X^Y) & Z
5266 Op1 = InsertNewInstBefore(BinaryOperator::createXor(X, Y, "tmp"), I);
5267 Op1 = InsertNewInstBefore(BinaryOperator::createAnd(Op1, Z, "tmp"), I);
5268 I.setOperand(0, Op1);
5269 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5270 return &I;
5271 }
5272 }
5273 }
5274 return Changed ? &I : 0;
5275}
5276
5277
5278/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5279/// and CmpRHS are both known to be integer constants.
5280Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5281 ConstantInt *DivRHS) {
5282 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5283 const APInt &CmpRHSV = CmpRHS->getValue();
5284
5285 // FIXME: If the operand types don't match the type of the divide
5286 // then don't attempt this transform. The code below doesn't have the
5287 // logic to deal with a signed divide and an unsigned compare (and
5288 // vice versa). This is because (x /s C1) <s C2 produces different
5289 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5290 // (x /u C1) <u C2. Simply casting the operands and result won't
5291 // work. :( The if statement below tests that condition and bails
5292 // if it finds it.
5293 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5294 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5295 return 0;
5296 if (DivRHS->isZero())
5297 return 0; // The ProdOV computation fails on divide by zero.
5298
5299 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5300 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5301 // C2 (CI). By solving for X we can turn this into a range check
5302 // instead of computing a divide.
5303 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5304
5305 // Determine if the product overflows by seeing if the product is
5306 // not equal to the divide. Make sure we do the same kind of divide
5307 // as in the LHS instruction that we're folding.
5308 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5309 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5310
5311 // Get the ICmp opcode
5312 ICmpInst::Predicate Pred = ICI.getPredicate();
5313
5314 // Figure out the interval that is being checked. For example, a comparison
5315 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5316 // Compute this interval based on the constants involved and the signedness of
5317 // the compare/divide. This computes a half-open interval, keeping track of
5318 // whether either value in the interval overflows. After analysis each
5319 // overflow variable is set to 0 if it's corresponding bound variable is valid
5320 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5321 int LoOverflow = 0, HiOverflow = 0;
5322 ConstantInt *LoBound = 0, *HiBound = 0;
5323
5324
5325 if (!DivIsSigned) { // udiv
5326 // e.g. X/5 op 3 --> [15, 20)
5327 LoBound = Prod;
5328 HiOverflow = LoOverflow = ProdOV;
5329 if (!HiOverflow)
5330 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman5dceed12008-02-13 22:09:18 +00005331 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005332 if (CmpRHSV == 0) { // (X / pos) op 0
5333 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
5334 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5335 HiBound = DivRHS;
Dan Gohman5dceed12008-02-13 22:09:18 +00005336 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005337 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5338 HiOverflow = LoOverflow = ProdOV;
5339 if (!HiOverflow)
5340 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5341 } else { // (X / pos) op neg
5342 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
5343 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5344 LoOverflow = AddWithOverflow(LoBound, Prod,
5345 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5346 HiBound = AddOne(Prod);
5347 HiOverflow = ProdOV ? -1 : 0;
5348 }
Dan Gohman5dceed12008-02-13 22:09:18 +00005349 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005350 if (CmpRHSV == 0) { // (X / neg) op 0
5351 // e.g. X/-5 op 0 --> [-4, 5)
5352 LoBound = AddOne(DivRHS);
5353 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5354 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5355 HiOverflow = 1; // [INTMIN+1, overflow)
5356 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5357 }
Dan Gohman5dceed12008-02-13 22:09:18 +00005358 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005359 // e.g. X/-5 op 3 --> [-19, -14)
5360 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5361 if (!LoOverflow)
5362 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5363 HiBound = AddOne(Prod);
5364 } else { // (X / neg) op neg
5365 // e.g. X/-5 op -3 --> [15, 20)
5366 LoBound = Prod;
5367 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
5368 HiBound = Subtract(Prod, DivRHS);
5369 }
5370
5371 // Dividing by a negative swaps the condition. LT <-> GT
5372 Pred = ICmpInst::getSwappedPredicate(Pred);
5373 }
5374
5375 Value *X = DivI->getOperand(0);
5376 switch (Pred) {
5377 default: assert(0 && "Unhandled icmp opcode!");
5378 case ICmpInst::ICMP_EQ:
5379 if (LoOverflow && HiOverflow)
5380 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5381 else if (HiOverflow)
5382 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5383 ICmpInst::ICMP_UGE, X, LoBound);
5384 else if (LoOverflow)
5385 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5386 ICmpInst::ICMP_ULT, X, HiBound);
5387 else
5388 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
5389 case ICmpInst::ICMP_NE:
5390 if (LoOverflow && HiOverflow)
5391 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5392 else if (HiOverflow)
5393 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5394 ICmpInst::ICMP_ULT, X, LoBound);
5395 else if (LoOverflow)
5396 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5397 ICmpInst::ICMP_UGE, X, HiBound);
5398 else
5399 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
5400 case ICmpInst::ICMP_ULT:
5401 case ICmpInst::ICMP_SLT:
5402 if (LoOverflow == +1) // Low bound is greater than input range.
5403 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5404 if (LoOverflow == -1) // Low bound is less than input range.
5405 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5406 return new ICmpInst(Pred, X, LoBound);
5407 case ICmpInst::ICMP_UGT:
5408 case ICmpInst::ICMP_SGT:
5409 if (HiOverflow == +1) // High bound greater than input range.
5410 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5411 else if (HiOverflow == -1) // High bound less than input range.
5412 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5413 if (Pred == ICmpInst::ICMP_UGT)
5414 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5415 else
5416 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5417 }
5418}
5419
5420
5421/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5422///
5423Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5424 Instruction *LHSI,
5425 ConstantInt *RHS) {
5426 const APInt &RHSV = RHS->getValue();
5427
5428 switch (LHSI->getOpcode()) {
5429 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
5430 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5431 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5432 // fold the xor.
5433 if (ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0 ||
5434 ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue()) {
5435 Value *CompareVal = LHSI->getOperand(0);
5436
5437 // If the sign bit of the XorCST is not set, there is no change to
5438 // the operation, just stop using the Xor.
5439 if (!XorCST->getValue().isNegative()) {
5440 ICI.setOperand(0, CompareVal);
5441 AddToWorkList(LHSI);
5442 return &ICI;
5443 }
5444
5445 // Was the old condition true if the operand is positive?
5446 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5447
5448 // If so, the new one isn't.
5449 isTrueIfPositive ^= true;
5450
5451 if (isTrueIfPositive)
5452 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5453 else
5454 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5455 }
5456 }
5457 break;
5458 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5459 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5460 LHSI->getOperand(0)->hasOneUse()) {
5461 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5462
5463 // If the LHS is an AND of a truncating cast, we can widen the
5464 // and/compare to be the input width without changing the value
5465 // produced, eliminating a cast.
5466 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5467 // We can do this transformation if either the AND constant does not
5468 // have its sign bit set or if it is an equality comparison.
5469 // Extending a relational comparison when we're checking the sign
5470 // bit would not work.
5471 if (Cast->hasOneUse() &&
Dan Gohman5dceed12008-02-13 22:09:18 +00005472 (ICI.isEquality() || AndCST->getValue().isNonNegative() &&
5473 RHSV.isNonNegative())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005474 uint32_t BitWidth =
5475 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5476 APInt NewCST = AndCST->getValue();
5477 NewCST.zext(BitWidth);
5478 APInt NewCI = RHSV;
5479 NewCI.zext(BitWidth);
5480 Instruction *NewAnd =
5481 BinaryOperator::createAnd(Cast->getOperand(0),
5482 ConstantInt::get(NewCST),LHSI->getName());
5483 InsertNewInstBefore(NewAnd, ICI);
5484 return new ICmpInst(ICI.getPredicate(), NewAnd,
5485 ConstantInt::get(NewCI));
5486 }
5487 }
5488
5489 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5490 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5491 // happens a LOT in code produced by the C front-end, for bitfield
5492 // access.
5493 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5494 if (Shift && !Shift->isShift())
5495 Shift = 0;
5496
5497 ConstantInt *ShAmt;
5498 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5499 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5500 const Type *AndTy = AndCST->getType(); // Type of the and.
5501
5502 // We can fold this as long as we can't shift unknown bits
5503 // into the mask. This can only happen with signed shift
5504 // rights, as they sign-extend.
5505 if (ShAmt) {
5506 bool CanFold = Shift->isLogicalShift();
5507 if (!CanFold) {
5508 // To test for the bad case of the signed shr, see if any
5509 // of the bits shifted in could be tested after the mask.
5510 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5511 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5512
5513 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5514 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
5515 AndCST->getValue()) == 0)
5516 CanFold = true;
5517 }
5518
5519 if (CanFold) {
5520 Constant *NewCst;
5521 if (Shift->getOpcode() == Instruction::Shl)
5522 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
5523 else
5524 NewCst = ConstantExpr::getShl(RHS, ShAmt);
5525
5526 // Check to see if we are shifting out any of the bits being
5527 // compared.
5528 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
5529 // If we shifted bits out, the fold is not going to work out.
5530 // As a special case, check to see if this means that the
5531 // result is always true or false now.
5532 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5533 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5534 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5535 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5536 } else {
5537 ICI.setOperand(1, NewCst);
5538 Constant *NewAndCST;
5539 if (Shift->getOpcode() == Instruction::Shl)
5540 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
5541 else
5542 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
5543 LHSI->setOperand(1, NewAndCST);
5544 LHSI->setOperand(0, Shift->getOperand(0));
5545 AddToWorkList(Shift); // Shift is dead.
5546 AddUsesToWorkList(ICI);
5547 return &ICI;
5548 }
5549 }
5550 }
5551
5552 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
5553 // preferable because it allows the C<<Y expression to be hoisted out
5554 // of a loop if Y is invariant and X is not.
5555 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
5556 ICI.isEquality() && !Shift->isArithmeticShift() &&
5557 isa<Instruction>(Shift->getOperand(0))) {
5558 // Compute C << Y.
5559 Value *NS;
5560 if (Shift->getOpcode() == Instruction::LShr) {
5561 NS = BinaryOperator::createShl(AndCST,
5562 Shift->getOperand(1), "tmp");
5563 } else {
5564 // Insert a logical shift.
5565 NS = BinaryOperator::createLShr(AndCST,
5566 Shift->getOperand(1), "tmp");
5567 }
5568 InsertNewInstBefore(cast<Instruction>(NS), ICI);
5569
5570 // Compute X & (C << Y).
5571 Instruction *NewAnd =
5572 BinaryOperator::createAnd(Shift->getOperand(0), NS, LHSI->getName());
5573 InsertNewInstBefore(NewAnd, ICI);
5574
5575 ICI.setOperand(0, NewAnd);
5576 return &ICI;
5577 }
5578 }
5579 break;
5580
5581 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
5582 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5583 if (!ShAmt) break;
5584
5585 uint32_t TypeBits = RHSV.getBitWidth();
5586
5587 // Check that the shift amount is in range. If not, don't perform
5588 // undefined shifts. When the shift is visited it will be
5589 // simplified.
5590 if (ShAmt->uge(TypeBits))
5591 break;
5592
5593 if (ICI.isEquality()) {
5594 // If we are comparing against bits always shifted out, the
5595 // comparison cannot succeed.
5596 Constant *Comp =
5597 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
5598 if (Comp != RHS) {// Comparing against a bit that we know is zero.
5599 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5600 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5601 return ReplaceInstUsesWith(ICI, Cst);
5602 }
5603
5604 if (LHSI->hasOneUse()) {
5605 // Otherwise strength reduce the shift into an and.
5606 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5607 Constant *Mask =
5608 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
5609
5610 Instruction *AndI =
5611 BinaryOperator::createAnd(LHSI->getOperand(0),
5612 Mask, LHSI->getName()+".mask");
5613 Value *And = InsertNewInstBefore(AndI, ICI);
5614 return new ICmpInst(ICI.getPredicate(), And,
5615 ConstantInt::get(RHSV.lshr(ShAmtVal)));
5616 }
5617 }
5618
5619 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
5620 bool TrueIfSigned = false;
5621 if (LHSI->hasOneUse() &&
5622 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
5623 // (X << 31) <s 0 --> (X&1) != 0
5624 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
5625 (TypeBits-ShAmt->getZExtValue()-1));
5626 Instruction *AndI =
5627 BinaryOperator::createAnd(LHSI->getOperand(0),
5628 Mask, LHSI->getName()+".mask");
5629 Value *And = InsertNewInstBefore(AndI, ICI);
5630
5631 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
5632 And, Constant::getNullValue(And->getType()));
5633 }
5634 break;
5635 }
5636
5637 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
5638 case Instruction::AShr: {
5639 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5640 if (!ShAmt) break;
5641
5642 if (ICI.isEquality()) {
5643 // Check that the shift amount is in range. If not, don't perform
5644 // undefined shifts. When the shift is visited it will be
5645 // simplified.
5646 uint32_t TypeBits = RHSV.getBitWidth();
5647 if (ShAmt->uge(TypeBits))
5648 break;
5649 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
5650
5651 // If we are comparing against bits always shifted out, the
5652 // comparison cannot succeed.
5653 APInt Comp = RHSV << ShAmtVal;
5654 if (LHSI->getOpcode() == Instruction::LShr)
5655 Comp = Comp.lshr(ShAmtVal);
5656 else
5657 Comp = Comp.ashr(ShAmtVal);
5658
5659 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
5660 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5661 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
5662 return ReplaceInstUsesWith(ICI, Cst);
5663 }
5664
5665 if (LHSI->hasOneUse() || RHSV == 0) {
5666 // Otherwise strength reduce the shift into an and.
5667 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
5668 Constant *Mask = ConstantInt::get(Val);
5669
5670 Instruction *AndI =
5671 BinaryOperator::createAnd(LHSI->getOperand(0),
5672 Mask, LHSI->getName()+".mask");
5673 Value *And = InsertNewInstBefore(AndI, ICI);
5674 return new ICmpInst(ICI.getPredicate(), And,
5675 ConstantExpr::getShl(RHS, ShAmt));
5676 }
5677 }
5678 break;
5679 }
5680
5681 case Instruction::SDiv:
5682 case Instruction::UDiv:
5683 // Fold: icmp pred ([us]div X, C1), C2 -> range test
5684 // Fold this div into the comparison, producing a range check.
5685 // Determine, based on the divide type, what the range is being
5686 // checked. If there is an overflow on the low or high side, remember
5687 // it, otherwise compute the range [low, hi) bounding the new value.
5688 // See: InsertRangeTest above for the kinds of replacements possible.
5689 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
5690 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
5691 DivRHS))
5692 return R;
5693 break;
Nick Lewycky0185bbf2008-02-03 16:33:09 +00005694
5695 case Instruction::Add:
5696 // Fold: icmp pred (add, X, C1), C2
5697
5698 if (!ICI.isEquality()) {
5699 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
5700 if (!LHSC) break;
5701 const APInt &LHSV = LHSC->getValue();
5702
5703 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
5704 .subtract(LHSV);
5705
5706 if (ICI.isSignedPredicate()) {
5707 if (CR.getLower().isSignBit()) {
5708 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
5709 ConstantInt::get(CR.getUpper()));
5710 } else if (CR.getUpper().isSignBit()) {
5711 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
5712 ConstantInt::get(CR.getLower()));
5713 }
5714 } else {
5715 if (CR.getLower().isMinValue()) {
5716 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
5717 ConstantInt::get(CR.getUpper()));
5718 } else if (CR.getUpper().isMinValue()) {
5719 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
5720 ConstantInt::get(CR.getLower()));
5721 }
5722 }
5723 }
5724 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005725 }
5726
5727 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
5728 if (ICI.isEquality()) {
5729 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
5730
5731 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
5732 // the second operand is a constant, simplify a bit.
5733 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
5734 switch (BO->getOpcode()) {
5735 case Instruction::SRem:
5736 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
5737 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
5738 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
5739 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
5740 Instruction *NewRem =
5741 BinaryOperator::createURem(BO->getOperand(0), BO->getOperand(1),
5742 BO->getName());
5743 InsertNewInstBefore(NewRem, ICI);
5744 return new ICmpInst(ICI.getPredicate(), NewRem,
5745 Constant::getNullValue(BO->getType()));
5746 }
5747 }
5748 break;
5749 case Instruction::Add:
5750 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
5751 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5752 if (BO->hasOneUse())
5753 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5754 Subtract(RHS, BOp1C));
5755 } else if (RHSV == 0) {
5756 // Replace ((add A, B) != 0) with (A != -B) if A or B is
5757 // efficiently invertible, or if the add has just this one use.
5758 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
5759
5760 if (Value *NegVal = dyn_castNegVal(BOp1))
5761 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
5762 else if (Value *NegVal = dyn_castNegVal(BOp0))
5763 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
5764 else if (BO->hasOneUse()) {
5765 Instruction *Neg = BinaryOperator::createNeg(BOp1);
5766 InsertNewInstBefore(Neg, ICI);
5767 Neg->takeName(BO);
5768 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
5769 }
5770 }
5771 break;
5772 case Instruction::Xor:
5773 // For the xor case, we can xor two constants together, eliminating
5774 // the explicit xor.
5775 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
5776 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5777 ConstantExpr::getXor(RHS, BOC));
5778
5779 // FALLTHROUGH
5780 case Instruction::Sub:
5781 // Replace (([sub|xor] A, B) != 0) with (A != B)
5782 if (RHSV == 0)
5783 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
5784 BO->getOperand(1));
5785 break;
5786
5787 case Instruction::Or:
5788 // If bits are being or'd in that are not present in the constant we
5789 // are comparing against, then the comparison could never succeed!
5790 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
5791 Constant *NotCI = ConstantExpr::getNot(RHS);
5792 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
5793 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5794 isICMP_NE));
5795 }
5796 break;
5797
5798 case Instruction::And:
5799 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
5800 // If bits are being compared against that are and'd out, then the
5801 // comparison can never succeed!
5802 if ((RHSV & ~BOC->getValue()) != 0)
5803 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
5804 isICMP_NE));
5805
5806 // If we have ((X & C) == C), turn it into ((X & C) != 0).
5807 if (RHS == BOC && RHSV.isPowerOf2())
5808 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
5809 ICmpInst::ICMP_NE, LHSI,
5810 Constant::getNullValue(RHS->getType()));
5811
5812 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
5813 if (isSignBit(BOC)) {
5814 Value *X = BO->getOperand(0);
5815 Constant *Zero = Constant::getNullValue(X->getType());
5816 ICmpInst::Predicate pred = isICMP_NE ?
5817 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
5818 return new ICmpInst(pred, X, Zero);
5819 }
5820
5821 // ((X & ~7) == 0) --> X < 8
5822 if (RHSV == 0 && isHighOnes(BOC)) {
5823 Value *X = BO->getOperand(0);
5824 Constant *NegX = ConstantExpr::getNeg(BOC);
5825 ICmpInst::Predicate pred = isICMP_NE ?
5826 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
5827 return new ICmpInst(pred, X, NegX);
5828 }
5829 }
5830 default: break;
5831 }
5832 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
5833 // Handle icmp {eq|ne} <intrinsic>, intcst.
5834 if (II->getIntrinsicID() == Intrinsic::bswap) {
5835 AddToWorkList(II);
5836 ICI.setOperand(0, II->getOperand(1));
5837 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
5838 return &ICI;
5839 }
5840 }
5841 } else { // Not a ICMP_EQ/ICMP_NE
5842 // If the LHS is a cast from an integral value of the same size,
5843 // then since we know the RHS is a constant, try to simlify.
5844 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
5845 Value *CastOp = Cast->getOperand(0);
5846 const Type *SrcTy = CastOp->getType();
5847 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
5848 if (SrcTy->isInteger() &&
5849 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
5850 // If this is an unsigned comparison, try to make the comparison use
5851 // smaller constant values.
5852 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
5853 // X u< 128 => X s> -1
5854 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
5855 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
5856 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
5857 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
5858 // X u> 127 => X s< 0
5859 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
5860 Constant::getNullValue(SrcTy));
5861 }
5862 }
5863 }
5864 }
5865 return 0;
5866}
5867
5868/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
5869/// We only handle extending casts so far.
5870///
5871Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
5872 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
5873 Value *LHSCIOp = LHSCI->getOperand(0);
5874 const Type *SrcTy = LHSCIOp->getType();
5875 const Type *DestTy = LHSCI->getType();
5876 Value *RHSCIOp;
5877
5878 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
5879 // integer type is the same size as the pointer type.
5880 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
5881 getTargetData().getPointerSizeInBits() ==
5882 cast<IntegerType>(DestTy)->getBitWidth()) {
5883 Value *RHSOp = 0;
5884 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
5885 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
5886 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
5887 RHSOp = RHSC->getOperand(0);
5888 // If the pointer types don't match, insert a bitcast.
5889 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner13c2d6e2008-01-13 22:23:22 +00005890 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005891 }
5892
5893 if (RHSOp)
5894 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
5895 }
5896
5897 // The code below only handles extension cast instructions, so far.
5898 // Enforce this.
5899 if (LHSCI->getOpcode() != Instruction::ZExt &&
5900 LHSCI->getOpcode() != Instruction::SExt)
5901 return 0;
5902
5903 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
5904 bool isSignedCmp = ICI.isSignedPredicate();
5905
5906 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
5907 // Not an extension from the same type?
5908 RHSCIOp = CI->getOperand(0);
5909 if (RHSCIOp->getType() != LHSCIOp->getType())
5910 return 0;
5911
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00005912 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005913 // and the other is a zext), then we can't handle this.
5914 if (CI->getOpcode() != LHSCI->getOpcode())
5915 return 0;
5916
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00005917 // Deal with equality cases early.
5918 if (ICI.isEquality())
5919 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5920
5921 // A signed comparison of sign extended values simplifies into a
5922 // signed comparison.
5923 if (isSignedCmp && isSignedExt)
5924 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
5925
5926 // The other three cases all fold into an unsigned comparison.
5927 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005928 }
5929
5930 // If we aren't dealing with a constant on the RHS, exit early
5931 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
5932 if (!CI)
5933 return 0;
5934
5935 // Compute the constant that would happen if we truncated to SrcTy then
5936 // reextended to DestTy.
5937 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
5938 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
5939
5940 // If the re-extended constant didn't change...
5941 if (Res2 == CI) {
5942 // Make sure that sign of the Cmp and the sign of the Cast are the same.
5943 // For example, we might have:
5944 // %A = sext short %X to uint
5945 // %B = icmp ugt uint %A, 1330
5946 // It is incorrect to transform this into
5947 // %B = icmp ugt short %X, 1330
5948 // because %A may have negative value.
5949 //
5950 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
5951 // OR operation is EQ/NE.
5952 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
5953 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
5954 else
5955 return 0;
5956 }
5957
5958 // The re-extended constant changed so the constant cannot be represented
5959 // in the shorter type. Consequently, we cannot emit a simple comparison.
5960
5961 // First, handle some easy cases. We know the result cannot be equal at this
5962 // point so handle the ICI.isEquality() cases
5963 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
5964 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5965 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
5966 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5967
5968 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
5969 // should have been folded away previously and not enter in here.
5970 Value *Result;
5971 if (isSignedCmp) {
5972 // We're performing a signed comparison.
5973 if (cast<ConstantInt>(CI)->getValue().isNegative())
5974 Result = ConstantInt::getFalse(); // X < (small) --> false
5975 else
5976 Result = ConstantInt::getTrue(); // X < (large) --> true
5977 } else {
5978 // We're performing an unsigned comparison.
5979 if (isSignedExt) {
5980 // We're performing an unsigned comp with a sign extended value.
5981 // This is true if the input is >= 0. [aka >s -1]
5982 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
5983 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
5984 NegOne, ICI.getName()), ICI);
5985 } else {
5986 // Unsigned extend & unsigned compare -> always true.
5987 Result = ConstantInt::getTrue();
5988 }
5989 }
5990
5991 // Finally, return the value computed.
5992 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
5993 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
5994 return ReplaceInstUsesWith(ICI, Result);
5995 } else {
5996 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
5997 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
5998 "ICmp should be folded!");
5999 if (Constant *CI = dyn_cast<Constant>(Result))
6000 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6001 else
6002 return BinaryOperator::createNot(Result);
6003 }
6004}
6005
6006Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6007 return commonShiftTransforms(I);
6008}
6009
6010Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6011 return commonShiftTransforms(I);
6012}
6013
6014Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00006015 if (Instruction *R = commonShiftTransforms(I))
6016 return R;
6017
6018 Value *Op0 = I.getOperand(0);
6019
6020 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6021 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6022 if (CSI->isAllOnesValue())
6023 return ReplaceInstUsesWith(I, CSI);
6024
6025 // See if we can turn a signed shr into an unsigned shr.
6026 if (MaskedValueIsZero(Op0,
6027 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
6028 return BinaryOperator::createLShr(Op0, I.getOperand(1));
6029
6030 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006031}
6032
6033Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6034 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6035 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6036
6037 // shl X, 0 == X and shr X, 0 == X
6038 // shl 0, X == 0 and shr 0, X == 0
6039 if (Op1 == Constant::getNullValue(Op1->getType()) ||
6040 Op0 == Constant::getNullValue(Op0->getType()))
6041 return ReplaceInstUsesWith(I, Op0);
6042
6043 if (isa<UndefValue>(Op0)) {
6044 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6045 return ReplaceInstUsesWith(I, Op0);
6046 else // undef << X -> 0, undef >>u X -> 0
6047 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6048 }
6049 if (isa<UndefValue>(Op1)) {
6050 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6051 return ReplaceInstUsesWith(I, Op0);
6052 else // X << undef, X >>u undef -> 0
6053 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6054 }
6055
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006056 // Try to fold constant and into select arguments.
6057 if (isa<Constant>(Op0))
6058 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6059 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6060 return R;
6061
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006062 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6063 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6064 return Res;
6065 return 0;
6066}
6067
6068Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6069 BinaryOperator &I) {
6070 bool isLeftShift = I.getOpcode() == Instruction::Shl;
6071
6072 // See if we can simplify any instructions used by the instruction whose sole
6073 // purpose is to compute bits we don't care about.
6074 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6075 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6076 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6077 KnownZero, KnownOne))
6078 return &I;
6079
6080 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6081 // of a signed value.
6082 //
6083 if (Op1->uge(TypeBits)) {
6084 if (I.getOpcode() != Instruction::AShr)
6085 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6086 else {
6087 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6088 return &I;
6089 }
6090 }
6091
6092 // ((X*C1) << C2) == (X * (C1 << C2))
6093 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6094 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6095 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
6096 return BinaryOperator::createMul(BO->getOperand(0),
6097 ConstantExpr::getShl(BOOp, Op1));
6098
6099 // Try to fold constant and into select arguments.
6100 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6101 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6102 return R;
6103 if (isa<PHINode>(Op0))
6104 if (Instruction *NV = FoldOpIntoPhi(I))
6105 return NV;
6106
Chris Lattnerc6d1f642007-12-22 09:07:47 +00006107 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6108 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6109 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6110 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6111 // place. Don't try to do this transformation in this case. Also, we
6112 // require that the input operand is a shift-by-constant so that we have
6113 // confidence that the shifts will get folded together. We could do this
6114 // xform in more cases, but it is unlikely to be profitable.
6115 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6116 isa<ConstantInt>(TrOp->getOperand(1))) {
6117 // Okay, we'll do this xform. Make the shift of shift.
6118 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
6119 Instruction *NSh = BinaryOperator::create(I.getOpcode(), TrOp, ShAmt,
6120 I.getName());
6121 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6122
6123 // For logical shifts, the truncation has the effect of making the high
6124 // part of the register be zeros. Emulate this by inserting an AND to
6125 // clear the top bits as needed. This 'and' will usually be zapped by
6126 // other xforms later if dead.
6127 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6128 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6129 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6130
6131 // The mask we constructed says what the trunc would do if occurring
6132 // between the shifts. We want to know the effect *after* the second
6133 // shift. We know that it is a logical shift by a constant, so adjust the
6134 // mask as appropriate.
6135 if (I.getOpcode() == Instruction::Shl)
6136 MaskV <<= Op1->getZExtValue();
6137 else {
6138 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6139 MaskV = MaskV.lshr(Op1->getZExtValue());
6140 }
6141
6142 Instruction *And = BinaryOperator::createAnd(NSh, ConstantInt::get(MaskV),
6143 TI->getName());
6144 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6145
6146 // Return the value truncated to the interesting size.
6147 return new TruncInst(And, I.getType());
6148 }
6149 }
6150
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006151 if (Op0->hasOneUse()) {
6152 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6153 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6154 Value *V1, *V2;
6155 ConstantInt *CC;
6156 switch (Op0BO->getOpcode()) {
6157 default: break;
6158 case Instruction::Add:
6159 case Instruction::And:
6160 case Instruction::Or:
6161 case Instruction::Xor: {
6162 // These operators commute.
6163 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
6164 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6165 match(Op0BO->getOperand(1),
6166 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6167 Instruction *YS = BinaryOperator::createShl(
6168 Op0BO->getOperand(0), Op1,
6169 Op0BO->getName());
6170 InsertNewInstBefore(YS, I); // (Y << C)
6171 Instruction *X =
6172 BinaryOperator::create(Op0BO->getOpcode(), YS, V1,
6173 Op0BO->getOperand(1)->getName());
6174 InsertNewInstBefore(X, I); // (X + (Y << C))
6175 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6176 return BinaryOperator::createAnd(X, ConstantInt::get(
6177 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6178 }
6179
6180 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
6181 Value *Op0BOOp1 = Op0BO->getOperand(1);
6182 if (isLeftShift && Op0BOOp1->hasOneUse() &&
6183 match(Op0BOOp1,
6184 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6185 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6186 V2 == Op1) {
6187 Instruction *YS = BinaryOperator::createShl(
6188 Op0BO->getOperand(0), Op1,
6189 Op0BO->getName());
6190 InsertNewInstBefore(YS, I); // (Y << C)
6191 Instruction *XM =
6192 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
6193 V1->getName()+".mask");
6194 InsertNewInstBefore(XM, I); // X & (CC << C)
6195
6196 return BinaryOperator::create(Op0BO->getOpcode(), YS, XM);
6197 }
6198 }
6199
6200 // FALL THROUGH.
6201 case Instruction::Sub: {
6202 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6203 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6204 match(Op0BO->getOperand(0),
6205 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
6206 Instruction *YS = BinaryOperator::createShl(
6207 Op0BO->getOperand(1), Op1,
6208 Op0BO->getName());
6209 InsertNewInstBefore(YS, I); // (Y << C)
6210 Instruction *X =
6211 BinaryOperator::create(Op0BO->getOpcode(), V1, YS,
6212 Op0BO->getOperand(0)->getName());
6213 InsertNewInstBefore(X, I); // (X + (Y << C))
6214 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
6215 return BinaryOperator::createAnd(X, ConstantInt::get(
6216 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6217 }
6218
6219 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
6220 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6221 match(Op0BO->getOperand(0),
6222 m_And(m_Shr(m_Value(V1), m_Value(V2)),
6223 m_ConstantInt(CC))) && V2 == Op1 &&
6224 cast<BinaryOperator>(Op0BO->getOperand(0))
6225 ->getOperand(0)->hasOneUse()) {
6226 Instruction *YS = BinaryOperator::createShl(
6227 Op0BO->getOperand(1), Op1,
6228 Op0BO->getName());
6229 InsertNewInstBefore(YS, I); // (Y << C)
6230 Instruction *XM =
6231 BinaryOperator::createAnd(V1, ConstantExpr::getShl(CC, Op1),
6232 V1->getName()+".mask");
6233 InsertNewInstBefore(XM, I); // X & (CC << C)
6234
6235 return BinaryOperator::create(Op0BO->getOpcode(), XM, YS);
6236 }
6237
6238 break;
6239 }
6240 }
6241
6242
6243 // If the operand is an bitwise operator with a constant RHS, and the
6244 // shift is the only use, we can pull it out of the shift.
6245 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6246 bool isValid = true; // Valid only for And, Or, Xor
6247 bool highBitSet = false; // Transform if high bit of constant set?
6248
6249 switch (Op0BO->getOpcode()) {
6250 default: isValid = false; break; // Do not perform transform!
6251 case Instruction::Add:
6252 isValid = isLeftShift;
6253 break;
6254 case Instruction::Or:
6255 case Instruction::Xor:
6256 highBitSet = false;
6257 break;
6258 case Instruction::And:
6259 highBitSet = true;
6260 break;
6261 }
6262
6263 // If this is a signed shift right, and the high bit is modified
6264 // by the logical operation, do not perform the transformation.
6265 // The highBitSet boolean indicates the value of the high bit of
6266 // the constant which would cause it to be modified for this
6267 // operation.
6268 //
Chris Lattner15b76e32007-12-06 06:25:04 +00006269 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006270 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006271
6272 if (isValid) {
6273 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6274
6275 Instruction *NewShift =
6276 BinaryOperator::create(I.getOpcode(), Op0BO->getOperand(0), Op1);
6277 InsertNewInstBefore(NewShift, I);
6278 NewShift->takeName(Op0BO);
6279
6280 return BinaryOperator::create(Op0BO->getOpcode(), NewShift,
6281 NewRHS);
6282 }
6283 }
6284 }
6285 }
6286
6287 // Find out if this is a shift of a shift by a constant.
6288 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6289 if (ShiftOp && !ShiftOp->isShift())
6290 ShiftOp = 0;
6291
6292 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6293 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6294 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6295 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6296 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6297 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6298 Value *X = ShiftOp->getOperand(0);
6299
6300 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
6301 if (AmtSum > TypeBits)
6302 AmtSum = TypeBits;
6303
6304 const IntegerType *Ty = cast<IntegerType>(I.getType());
6305
6306 // Check for (X << c1) << c2 and (X >> c1) >> c2
6307 if (I.getOpcode() == ShiftOp->getOpcode()) {
6308 return BinaryOperator::create(I.getOpcode(), X,
6309 ConstantInt::get(Ty, AmtSum));
6310 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6311 I.getOpcode() == Instruction::AShr) {
6312 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
6313 return BinaryOperator::createLShr(X, ConstantInt::get(Ty, AmtSum));
6314 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6315 I.getOpcode() == Instruction::LShr) {
6316 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6317 Instruction *Shift =
6318 BinaryOperator::createAShr(X, ConstantInt::get(Ty, AmtSum));
6319 InsertNewInstBefore(Shift, I);
6320
6321 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6322 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6323 }
6324
6325 // Okay, if we get here, one shift must be left, and the other shift must be
6326 // right. See if the amounts are equal.
6327 if (ShiftAmt1 == ShiftAmt2) {
6328 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6329 if (I.getOpcode() == Instruction::Shl) {
6330 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
6331 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
6332 }
6333 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6334 if (I.getOpcode() == Instruction::LShr) {
6335 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
6336 return BinaryOperator::createAnd(X, ConstantInt::get(Mask));
6337 }
6338 // We can simplify ((X << C) >>s C) into a trunc + sext.
6339 // NOTE: we could do this for any C, but that would make 'unusual' integer
6340 // types. For now, just stick to ones well-supported by the code
6341 // generators.
6342 const Type *SExtType = 0;
6343 switch (Ty->getBitWidth() - ShiftAmt1) {
6344 case 1 :
6345 case 8 :
6346 case 16 :
6347 case 32 :
6348 case 64 :
6349 case 128:
6350 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6351 break;
6352 default: break;
6353 }
6354 if (SExtType) {
6355 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6356 InsertNewInstBefore(NewTrunc, I);
6357 return new SExtInst(NewTrunc, Ty);
6358 }
6359 // Otherwise, we can't handle it yet.
6360 } else if (ShiftAmt1 < ShiftAmt2) {
6361 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
6362
6363 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6364 if (I.getOpcode() == Instruction::Shl) {
6365 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6366 ShiftOp->getOpcode() == Instruction::AShr);
6367 Instruction *Shift =
6368 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6369 InsertNewInstBefore(Shift, I);
6370
6371 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6372 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6373 }
6374
6375 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
6376 if (I.getOpcode() == Instruction::LShr) {
6377 assert(ShiftOp->getOpcode() == Instruction::Shl);
6378 Instruction *Shift =
6379 BinaryOperator::createLShr(X, ConstantInt::get(Ty, ShiftDiff));
6380 InsertNewInstBefore(Shift, I);
6381
6382 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6383 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6384 }
6385
6386 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6387 } else {
6388 assert(ShiftAmt2 < ShiftAmt1);
6389 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6390
6391 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6392 if (I.getOpcode() == Instruction::Shl) {
6393 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6394 ShiftOp->getOpcode() == Instruction::AShr);
6395 Instruction *Shift =
6396 BinaryOperator::create(ShiftOp->getOpcode(), X,
6397 ConstantInt::get(Ty, ShiftDiff));
6398 InsertNewInstBefore(Shift, I);
6399
6400 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
6401 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6402 }
6403
6404 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
6405 if (I.getOpcode() == Instruction::LShr) {
6406 assert(ShiftOp->getOpcode() == Instruction::Shl);
6407 Instruction *Shift =
6408 BinaryOperator::createShl(X, ConstantInt::get(Ty, ShiftDiff));
6409 InsertNewInstBefore(Shift, I);
6410
6411 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
6412 return BinaryOperator::createAnd(Shift, ConstantInt::get(Mask));
6413 }
6414
6415 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6416 }
6417 }
6418 return 0;
6419}
6420
6421
6422/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6423/// expression. If so, decompose it, returning some value X, such that Val is
6424/// X*Scale+Offset.
6425///
6426static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6427 int &Offset) {
6428 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6429 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6430 Offset = CI->getZExtValue();
Chris Lattnerc59171a2007-10-12 05:30:59 +00006431 Scale = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006432 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattnerc59171a2007-10-12 05:30:59 +00006433 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6434 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6435 if (I->getOpcode() == Instruction::Shl) {
6436 // This is a value scaled by '1 << the shift amt'.
6437 Scale = 1U << RHS->getZExtValue();
6438 Offset = 0;
6439 return I->getOperand(0);
6440 } else if (I->getOpcode() == Instruction::Mul) {
6441 // This value is scaled by 'RHS'.
6442 Scale = RHS->getZExtValue();
6443 Offset = 0;
6444 return I->getOperand(0);
6445 } else if (I->getOpcode() == Instruction::Add) {
6446 // We have X+C. Check to see if we really have (X*C2)+C1,
6447 // where C1 is divisible by C2.
6448 unsigned SubScale;
6449 Value *SubVal =
6450 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6451 Offset += RHS->getZExtValue();
6452 Scale = SubScale;
6453 return SubVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006454 }
6455 }
6456 }
6457
6458 // Otherwise, we can't look past this.
6459 Scale = 1;
6460 Offset = 0;
6461 return Val;
6462}
6463
6464
6465/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6466/// try to eliminate the cast by moving the type information into the alloc.
6467Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6468 AllocationInst &AI) {
6469 const PointerType *PTy = cast<PointerType>(CI.getType());
6470
6471 // Remove any uses of AI that are dead.
6472 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6473
6474 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6475 Instruction *User = cast<Instruction>(*UI++);
6476 if (isInstructionTriviallyDead(User)) {
6477 while (UI != E && *UI == User)
6478 ++UI; // If this instruction uses AI more than once, don't break UI.
6479
6480 ++NumDeadInst;
6481 DOUT << "IC: DCE: " << *User;
6482 EraseInstFromFunction(*User);
6483 }
6484 }
6485
6486 // Get the type really allocated and the type casted to.
6487 const Type *AllocElTy = AI.getAllocatedType();
6488 const Type *CastElTy = PTy->getElementType();
6489 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6490
6491 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6492 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6493 if (CastElTyAlign < AllocElTyAlign) return 0;
6494
6495 // If the allocation has multiple uses, only promote it if we are strictly
6496 // increasing the alignment of the resultant allocation. If we keep it the
6497 // same, we open the door to infinite loops of various kinds.
6498 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6499
Duncan Sandsf99fdc62007-11-01 20:53:16 +00006500 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6501 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006502 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6503
6504 // See if we can satisfy the modulus by pulling a scale out of the array
6505 // size argument.
6506 unsigned ArraySizeScale;
6507 int ArrayOffset;
6508 Value *NumElements = // See if the array size is a decomposable linear expr.
6509 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
6510
6511 // If we can now satisfy the modulus, by using a non-1 scale, we really can
6512 // do the xform.
6513 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
6514 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
6515
6516 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
6517 Value *Amt = 0;
6518 if (Scale == 1) {
6519 Amt = NumElements;
6520 } else {
6521 // If the allocation size is constant, form a constant mul expression
6522 Amt = ConstantInt::get(Type::Int32Ty, Scale);
6523 if (isa<ConstantInt>(NumElements))
6524 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
6525 // otherwise multiply the amount and the number of elements
6526 else if (Scale != 1) {
6527 Instruction *Tmp = BinaryOperator::createMul(Amt, NumElements, "tmp");
6528 Amt = InsertNewInstBefore(Tmp, AI);
6529 }
6530 }
6531
6532 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
6533 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
6534 Instruction *Tmp = BinaryOperator::createAdd(Amt, Off, "tmp");
6535 Amt = InsertNewInstBefore(Tmp, AI);
6536 }
6537
6538 AllocationInst *New;
6539 if (isa<MallocInst>(AI))
6540 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
6541 else
6542 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
6543 InsertNewInstBefore(New, AI);
6544 New->takeName(&AI);
6545
6546 // If the allocation has multiple uses, insert a cast and change all things
6547 // that used it to use the new cast. This will also hack on CI, but it will
6548 // die soon.
6549 if (!AI.hasOneUse()) {
6550 AddUsesToWorkList(AI);
6551 // New is the allocation instruction, pointer typed. AI is the original
6552 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
6553 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
6554 InsertNewInstBefore(NewCast, AI);
6555 AI.replaceAllUsesWith(NewCast);
6556 }
6557 return ReplaceInstUsesWith(CI, New);
6558}
6559
6560/// CanEvaluateInDifferentType - Return true if we can take the specified value
6561/// and return it as type Ty without inserting any new casts and without
6562/// changing the computed value. This is used by code that tries to decide
6563/// whether promoting or shrinking integer operations to wider or smaller types
6564/// will allow us to eliminate a truncate or extend.
6565///
6566/// This is a truncation operation if Ty is smaller than V->getType(), or an
6567/// extension operation if Ty is larger.
6568static bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Chris Lattneref70bb82007-08-02 06:11:14 +00006569 unsigned CastOpc, int &NumCastsRemoved) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006570 // We can always evaluate constants in another type.
6571 if (isa<ConstantInt>(V))
6572 return true;
6573
6574 Instruction *I = dyn_cast<Instruction>(V);
6575 if (!I) return false;
6576
6577 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
6578
Chris Lattneref70bb82007-08-02 06:11:14 +00006579 // If this is an extension or truncate, we can often eliminate it.
6580 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
6581 // If this is a cast from the destination type, we can trivially eliminate
6582 // it, and this will remove a cast overall.
6583 if (I->getOperand(0)->getType() == Ty) {
6584 // If the first operand is itself a cast, and is eliminable, do not count
6585 // this as an eliminable cast. We would prefer to eliminate those two
6586 // casts first.
6587 if (!isa<CastInst>(I->getOperand(0)))
6588 ++NumCastsRemoved;
6589 return true;
6590 }
6591 }
6592
6593 // We can't extend or shrink something that has multiple uses: doing so would
6594 // require duplicating the instruction in general, which isn't profitable.
6595 if (!I->hasOneUse()) return false;
6596
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006597 switch (I->getOpcode()) {
6598 case Instruction::Add:
6599 case Instruction::Sub:
6600 case Instruction::And:
6601 case Instruction::Or:
6602 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006603 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00006604 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6605 NumCastsRemoved) &&
6606 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6607 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006608
Nick Lewyckyc52646a2008-01-22 05:08:48 +00006609 case Instruction::Mul:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00006610 // A multiply can be truncated by truncating its operands.
6611 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
6612 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6613 NumCastsRemoved) &&
6614 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
6615 NumCastsRemoved);
6616
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006617 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006618 // If we are truncating the result of this SHL, and if it's a shift of a
6619 // constant amount, we can always perform a SHL in a smaller type.
6620 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6621 uint32_t BitWidth = Ty->getBitWidth();
6622 if (BitWidth < OrigTy->getBitWidth() &&
6623 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00006624 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6625 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006626 }
6627 break;
6628 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006629 // If this is a truncate of a logical shr, we can truncate it to a smaller
6630 // lshr iff we know that the bits we would otherwise be shifting in are
6631 // already zeros.
6632 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
6633 uint32_t OrigBitWidth = OrigTy->getBitWidth();
6634 uint32_t BitWidth = Ty->getBitWidth();
6635 if (BitWidth < OrigBitWidth &&
6636 MaskedValueIsZero(I->getOperand(0),
6637 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
6638 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00006639 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
6640 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006641 }
6642 }
6643 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006644 case Instruction::ZExt:
6645 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00006646 case Instruction::Trunc:
6647 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00006648 // can safely replace it. Note that replacing it does not reduce the number
6649 // of casts in the input.
6650 if (I->getOpcode() == CastOpc)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006651 return true;
Chris Lattner2799b2f2007-09-10 23:46:29 +00006652
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006653 break;
6654 default:
6655 // TODO: Can handle more cases here.
6656 break;
6657 }
6658
6659 return false;
6660}
6661
6662/// EvaluateInDifferentType - Given an expression that
6663/// CanEvaluateInDifferentType returns true for, actually insert the code to
6664/// evaluate the expression.
6665Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
6666 bool isSigned) {
6667 if (Constant *C = dyn_cast<Constant>(V))
6668 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
6669
6670 // Otherwise, it must be an instruction.
6671 Instruction *I = cast<Instruction>(V);
6672 Instruction *Res = 0;
6673 switch (I->getOpcode()) {
6674 case Instruction::Add:
6675 case Instruction::Sub:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00006676 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006677 case Instruction::And:
6678 case Instruction::Or:
6679 case Instruction::Xor:
6680 case Instruction::AShr:
6681 case Instruction::LShr:
6682 case Instruction::Shl: {
6683 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
6684 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
6685 Res = BinaryOperator::create((Instruction::BinaryOps)I->getOpcode(),
6686 LHS, RHS, I->getName());
6687 break;
6688 }
6689 case Instruction::Trunc:
6690 case Instruction::ZExt:
6691 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006692 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00006693 // just return the source. There's no need to insert it because it is not
6694 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006695 if (I->getOperand(0)->getType() == Ty)
6696 return I->getOperand(0);
6697
Chris Lattneref70bb82007-08-02 06:11:14 +00006698 // Otherwise, must be the same type of case, so just reinsert a new one.
6699 Res = CastInst::create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
6700 Ty, I->getName());
6701 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006702 default:
6703 // TODO: Can handle more cases here.
6704 assert(0 && "Unreachable!");
6705 break;
6706 }
6707
6708 return InsertNewInstBefore(Res, *I);
6709}
6710
6711/// @brief Implement the transforms common to all CastInst visitors.
6712Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
6713 Value *Src = CI.getOperand(0);
6714
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006715 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
6716 // eliminate it now.
6717 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
6718 if (Instruction::CastOps opc =
6719 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
6720 // The first cast (CSrc) is eliminable so we need to fix up or replace
6721 // the second cast (CI). CSrc will then have a good chance of being dead.
6722 return CastInst::create(opc, CSrc->getOperand(0), CI.getType());
6723 }
6724 }
6725
6726 // If we are casting a select then fold the cast into the select
6727 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
6728 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
6729 return NV;
6730
6731 // If we are casting a PHI then fold the cast into the PHI
6732 if (isa<PHINode>(Src))
6733 if (Instruction *NV = FoldOpIntoPhi(CI))
6734 return NV;
6735
6736 return 0;
6737}
6738
6739/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
6740Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
6741 Value *Src = CI.getOperand(0);
6742
6743 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
6744 // If casting the result of a getelementptr instruction with no offset, turn
6745 // this into a cast of the original pointer!
6746 if (GEP->hasAllZeroIndices()) {
6747 // Changing the cast operand is usually not a good idea but it is safe
6748 // here because the pointer operand is being replaced with another
6749 // pointer operand so the opcode doesn't need to change.
6750 AddToWorkList(GEP);
6751 CI.setOperand(0, GEP->getOperand(0));
6752 return &CI;
6753 }
6754
6755 // If the GEP has a single use, and the base pointer is a bitcast, and the
6756 // GEP computes a constant offset, see if we can convert these three
6757 // instructions into fewer. This typically happens with unions and other
6758 // non-type-safe code.
6759 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
6760 if (GEP->hasAllConstantIndices()) {
6761 // We are guaranteed to get a constant from EmitGEPOffset.
6762 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
6763 int64_t Offset = OffsetV->getSExtValue();
6764
6765 // Get the base pointer input of the bitcast, and the type it points to.
6766 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
6767 const Type *GEPIdxTy =
6768 cast<PointerType>(OrigBase->getType())->getElementType();
6769 if (GEPIdxTy->isSized()) {
6770 SmallVector<Value*, 8> NewIndices;
6771
6772 // Start with the index over the outer type. Note that the type size
6773 // might be zero (even if the offset isn't zero) if the indexed type
6774 // is something like [0 x {int, int}]
6775 const Type *IntPtrTy = TD->getIntPtrType();
6776 int64_t FirstIdx = 0;
Duncan Sandsf99fdc62007-11-01 20:53:16 +00006777 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006778 FirstIdx = Offset/TySize;
6779 Offset %= TySize;
6780
6781 // Handle silly modulus not returning values values [0..TySize).
6782 if (Offset < 0) {
6783 --FirstIdx;
6784 Offset += TySize;
6785 assert(Offset >= 0);
6786 }
6787 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
6788 }
6789
6790 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
6791
6792 // Index into the types. If we fail, set OrigBase to null.
6793 while (Offset) {
6794 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
6795 const StructLayout *SL = TD->getStructLayout(STy);
6796 if (Offset < (int64_t)SL->getSizeInBytes()) {
6797 unsigned Elt = SL->getElementContainingOffset(Offset);
6798 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
6799
6800 Offset -= SL->getElementOffset(Elt);
6801 GEPIdxTy = STy->getElementType(Elt);
6802 } else {
6803 // Otherwise, we can't index into this, bail out.
6804 Offset = 0;
6805 OrigBase = 0;
6806 }
6807 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
6808 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sandsf99fdc62007-11-01 20:53:16 +00006809 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006810 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
6811 Offset %= EltSize;
6812 } else {
6813 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
6814 }
6815 GEPIdxTy = STy->getElementType();
6816 } else {
6817 // Otherwise, we can't index into this, bail out.
6818 Offset = 0;
6819 OrigBase = 0;
6820 }
6821 }
6822 if (OrigBase) {
6823 // If we were able to index down into an element, create the GEP
6824 // and bitcast the result. This eliminates one bitcast, potentially
6825 // two.
David Greene393be882007-09-04 15:46:09 +00006826 Instruction *NGEP = new GetElementPtrInst(OrigBase,
6827 NewIndices.begin(),
6828 NewIndices.end(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006829 InsertNewInstBefore(NGEP, CI);
6830 NGEP->takeName(GEP);
6831
6832 if (isa<BitCastInst>(CI))
6833 return new BitCastInst(NGEP, CI.getType());
6834 assert(isa<PtrToIntInst>(CI));
6835 return new PtrToIntInst(NGEP, CI.getType());
6836 }
6837 }
6838 }
6839 }
6840 }
6841
6842 return commonCastTransforms(CI);
6843}
6844
6845
6846
6847/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
6848/// integer types. This function implements the common transforms for all those
6849/// cases.
6850/// @brief Implement the transforms common to CastInst with integer operands
6851Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
6852 if (Instruction *Result = commonCastTransforms(CI))
6853 return Result;
6854
6855 Value *Src = CI.getOperand(0);
6856 const Type *SrcTy = Src->getType();
6857 const Type *DestTy = CI.getType();
6858 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
6859 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
6860
6861 // See if we can simplify any instructions used by the LHS whose sole
6862 // purpose is to compute bits we don't care about.
6863 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
6864 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
6865 KnownZero, KnownOne))
6866 return &CI;
6867
6868 // If the source isn't an instruction or has more than one use then we
6869 // can't do anything more.
6870 Instruction *SrcI = dyn_cast<Instruction>(Src);
6871 if (!SrcI || !Src->hasOneUse())
6872 return 0;
6873
6874 // Attempt to propagate the cast into the instruction for int->int casts.
6875 int NumCastsRemoved = 0;
6876 if (!isa<BitCastInst>(CI) &&
6877 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattneref70bb82007-08-02 06:11:14 +00006878 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006879 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00006880 // eliminates the cast, so it is always a win. If this is a zero-extension,
6881 // we need to do an AND to maintain the clear top-part of the computation,
6882 // so we require that the input have eliminated at least one cast. If this
6883 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006884 // require that two casts have been eliminated.
6885 bool DoXForm;
6886 switch (CI.getOpcode()) {
6887 default:
6888 // All the others use floating point so we shouldn't actually
6889 // get here because of the check above.
6890 assert(0 && "Unknown cast type");
6891 case Instruction::Trunc:
6892 DoXForm = true;
6893 break;
6894 case Instruction::ZExt:
6895 DoXForm = NumCastsRemoved >= 1;
6896 break;
6897 case Instruction::SExt:
6898 DoXForm = NumCastsRemoved >= 2;
6899 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006900 }
6901
6902 if (DoXForm) {
6903 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
6904 CI.getOpcode() == Instruction::SExt);
6905 assert(Res->getType() == DestTy);
6906 switch (CI.getOpcode()) {
6907 default: assert(0 && "Unknown cast type!");
6908 case Instruction::Trunc:
6909 case Instruction::BitCast:
6910 // Just replace this cast with the result.
6911 return ReplaceInstUsesWith(CI, Res);
6912 case Instruction::ZExt: {
6913 // We need to emit an AND to clear the high bits.
6914 assert(SrcBitSize < DestBitSize && "Not a zext?");
6915 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
6916 SrcBitSize));
6917 return BinaryOperator::createAnd(Res, C);
6918 }
6919 case Instruction::SExt:
6920 // We need to emit a cast to truncate, then a cast to sext.
6921 return CastInst::create(Instruction::SExt,
6922 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
6923 CI), DestTy);
6924 }
6925 }
6926 }
6927
6928 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
6929 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
6930
6931 switch (SrcI->getOpcode()) {
6932 case Instruction::Add:
6933 case Instruction::Mul:
6934 case Instruction::And:
6935 case Instruction::Or:
6936 case Instruction::Xor:
6937 // If we are discarding information, rewrite.
6938 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
6939 // Don't insert two casts if they cannot be eliminated. We allow
6940 // two casts to be inserted if the sizes are the same. This could
6941 // only be converting signedness, which is a noop.
6942 if (DestBitSize == SrcBitSize ||
6943 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
6944 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6945 Instruction::CastOps opcode = CI.getOpcode();
6946 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6947 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6948 return BinaryOperator::create(
6949 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6950 }
6951 }
6952
6953 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
6954 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
6955 SrcI->getOpcode() == Instruction::Xor &&
6956 Op1 == ConstantInt::getTrue() &&
6957 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
6958 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
6959 return BinaryOperator::createXor(New, ConstantInt::get(CI.getType(), 1));
6960 }
6961 break;
6962 case Instruction::SDiv:
6963 case Instruction::UDiv:
6964 case Instruction::SRem:
6965 case Instruction::URem:
6966 // If we are just changing the sign, rewrite.
6967 if (DestBitSize == SrcBitSize) {
6968 // Don't insert two casts if they cannot be eliminated. We allow
6969 // two casts to be inserted if the sizes are the same. This could
6970 // only be converting signedness, which is a noop.
6971 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
6972 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
6973 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
6974 Op0, DestTy, SrcI);
6975 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
6976 Op1, DestTy, SrcI);
6977 return BinaryOperator::create(
6978 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
6979 }
6980 }
6981 break;
6982
6983 case Instruction::Shl:
6984 // Allow changing the sign of the source operand. Do not allow
6985 // changing the size of the shift, UNLESS the shift amount is a
6986 // constant. We must not change variable sized shifts to a smaller
6987 // size, because it is undefined to shift more bits out than exist
6988 // in the value.
6989 if (DestBitSize == SrcBitSize ||
6990 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
6991 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
6992 Instruction::BitCast : Instruction::Trunc);
6993 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
6994 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
6995 return BinaryOperator::createShl(Op0c, Op1c);
6996 }
6997 break;
6998 case Instruction::AShr:
6999 // If this is a signed shr, and if all bits shifted in are about to be
7000 // truncated off, turn it into an unsigned shr to allow greater
7001 // simplifications.
7002 if (DestBitSize < SrcBitSize &&
7003 isa<ConstantInt>(Op1)) {
7004 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7005 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7006 // Insert the new logical shift right.
7007 return BinaryOperator::createLShr(Op0, Op1);
7008 }
7009 }
7010 break;
7011 }
7012 return 0;
7013}
7014
7015Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7016 if (Instruction *Result = commonIntCastTransforms(CI))
7017 return Result;
7018
7019 Value *Src = CI.getOperand(0);
7020 const Type *Ty = CI.getType();
7021 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7022 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7023
7024 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7025 switch (SrcI->getOpcode()) {
7026 default: break;
7027 case Instruction::LShr:
7028 // We can shrink lshr to something smaller if we know the bits shifted in
7029 // are already zeros.
7030 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7031 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7032
7033 // Get a mask for the bits shifting in.
7034 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7035 Value* SrcIOp0 = SrcI->getOperand(0);
7036 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7037 if (ShAmt >= DestBitWidth) // All zeros.
7038 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7039
7040 // Okay, we can shrink this. Truncate the input, then return a new
7041 // shift.
7042 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7043 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7044 Ty, CI);
7045 return BinaryOperator::createLShr(V1, V2);
7046 }
7047 } else { // This is a variable shr.
7048
7049 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7050 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7051 // loop-invariant and CSE'd.
7052 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7053 Value *One = ConstantInt::get(SrcI->getType(), 1);
7054
7055 Value *V = InsertNewInstBefore(
7056 BinaryOperator::createShl(One, SrcI->getOperand(1),
7057 "tmp"), CI);
7058 V = InsertNewInstBefore(BinaryOperator::createAnd(V,
7059 SrcI->getOperand(0),
7060 "tmp"), CI);
7061 Value *Zero = Constant::getNullValue(V->getType());
7062 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7063 }
7064 }
7065 break;
7066 }
7067 }
7068
7069 return 0;
7070}
7071
7072Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
7073 // If one of the common conversion will work ..
7074 if (Instruction *Result = commonIntCastTransforms(CI))
7075 return Result;
7076
7077 Value *Src = CI.getOperand(0);
7078
7079 // If this is a cast of a cast
7080 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7081 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7082 // types and if the sizes are just right we can convert this into a logical
7083 // 'and' which will be much cheaper than the pair of casts.
7084 if (isa<TruncInst>(CSrc)) {
7085 // Get the sizes of the types involved
7086 Value *A = CSrc->getOperand(0);
7087 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7088 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7089 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
7090 // If we're actually extending zero bits and the trunc is a no-op
7091 if (MidSize < DstSize && SrcSize == DstSize) {
7092 // Replace both of the casts with an And of the type mask.
7093 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
7094 Constant *AndConst = ConstantInt::get(AndValue);
7095 Instruction *And =
7096 BinaryOperator::createAnd(CSrc->getOperand(0), AndConst);
7097 // Unfortunately, if the type changed, we need to cast it back.
7098 if (And->getType() != CI.getType()) {
7099 And->setName(CSrc->getName()+".mask");
7100 InsertNewInstBefore(And, CI);
7101 And = CastInst::createIntegerCast(And, CI.getType(), false/*ZExt*/);
7102 }
7103 return And;
7104 }
7105 }
7106 }
7107
7108 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7109 // If we are just checking for a icmp eq of a single bit and zext'ing it
7110 // to an integer, then shift the bit to the appropriate place and then
7111 // cast to integer to avoid the comparison.
7112 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7113 const APInt &Op1CV = Op1C->getValue();
7114
7115 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7116 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7117 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7118 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7119 Value *In = ICI->getOperand(0);
7120 Value *Sh = ConstantInt::get(In->getType(),
7121 In->getType()->getPrimitiveSizeInBits()-1);
7122 In = InsertNewInstBefore(BinaryOperator::createLShr(In, Sh,
7123 In->getName()+".lobit"),
7124 CI);
7125 if (In->getType() != CI.getType())
7126 In = CastInst::createIntegerCast(In, CI.getType(),
7127 false/*ZExt*/, "tmp", &CI);
7128
7129 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7130 Constant *One = ConstantInt::get(In->getType(), 1);
7131 In = InsertNewInstBefore(BinaryOperator::createXor(In, One,
7132 In->getName()+".not"),
7133 CI);
7134 }
7135
7136 return ReplaceInstUsesWith(CI, In);
7137 }
7138
7139
7140
7141 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7142 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7143 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7144 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7145 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7146 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7147 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7148 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7149 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7150 // This only works for EQ and NE
7151 ICI->isEquality()) {
7152 // If Op1C some other power of two, convert:
7153 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7154 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7155 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7156 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7157
7158 APInt KnownZeroMask(~KnownZero);
7159 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7160 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7161 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7162 // (X&4) == 2 --> false
7163 // (X&4) != 2 --> true
7164 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7165 Res = ConstantExpr::getZExt(Res, CI.getType());
7166 return ReplaceInstUsesWith(CI, Res);
7167 }
7168
7169 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7170 Value *In = ICI->getOperand(0);
7171 if (ShiftAmt) {
7172 // Perform a logical shr by shiftamt.
7173 // Insert the shift to put the result in the low bit.
7174 In = InsertNewInstBefore(
7175 BinaryOperator::createLShr(In,
7176 ConstantInt::get(In->getType(), ShiftAmt),
7177 In->getName()+".lobit"), CI);
7178 }
7179
7180 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7181 Constant *One = ConstantInt::get(In->getType(), 1);
7182 In = BinaryOperator::createXor(In, One, "tmp");
7183 InsertNewInstBefore(cast<Instruction>(In), CI);
7184 }
7185
7186 if (CI.getType() == In->getType())
7187 return ReplaceInstUsesWith(CI, In);
7188 else
7189 return CastInst::createIntegerCast(In, CI.getType(), false/*ZExt*/);
7190 }
7191 }
7192 }
7193 }
7194 return 0;
7195}
7196
7197Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7198 if (Instruction *I = commonIntCastTransforms(CI))
7199 return I;
7200
7201 Value *Src = CI.getOperand(0);
7202
7203 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7204 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7205 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7206 // If we are just checking for a icmp eq of a single bit and zext'ing it
7207 // to an integer, then shift the bit to the appropriate place and then
7208 // cast to integer to avoid the comparison.
7209 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7210 const APInt &Op1CV = Op1C->getValue();
7211
7212 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7213 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7214 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7215 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7216 Value *In = ICI->getOperand(0);
7217 Value *Sh = ConstantInt::get(In->getType(),
7218 In->getType()->getPrimitiveSizeInBits()-1);
7219 In = InsertNewInstBefore(BinaryOperator::createAShr(In, Sh,
7220 In->getName()+".lobit"),
7221 CI);
7222 if (In->getType() != CI.getType())
7223 In = CastInst::createIntegerCast(In, CI.getType(),
7224 true/*SExt*/, "tmp", &CI);
7225
7226 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
7227 In = InsertNewInstBefore(BinaryOperator::createNot(In,
7228 In->getName()+".not"), CI);
7229
7230 return ReplaceInstUsesWith(CI, In);
7231 }
7232 }
7233 }
7234
7235 return 0;
7236}
7237
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007238/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7239/// in the specified FP type without changing its value.
7240static Constant *FitsInFPType(ConstantFP *CFP, const Type *FPTy,
7241 const fltSemantics &Sem) {
7242 APFloat F = CFP->getValueAPF();
7243 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
7244 return ConstantFP::get(FPTy, F);
7245 return 0;
7246}
7247
7248/// LookThroughFPExtensions - If this is an fp extension instruction, look
7249/// through it until we get the source value.
7250static Value *LookThroughFPExtensions(Value *V) {
7251 if (Instruction *I = dyn_cast<Instruction>(V))
7252 if (I->getOpcode() == Instruction::FPExt)
7253 return LookThroughFPExtensions(I->getOperand(0));
7254
7255 // If this value is a constant, return the constant in the smallest FP type
7256 // that can accurately represent it. This allows us to turn
7257 // (float)((double)X+2.0) into x+2.0f.
7258 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7259 if (CFP->getType() == Type::PPC_FP128Ty)
7260 return V; // No constant folding of this.
7261 // See if the value can be truncated to float and then reextended.
7262 if (Value *V = FitsInFPType(CFP, Type::FloatTy, APFloat::IEEEsingle))
7263 return V;
7264 if (CFP->getType() == Type::DoubleTy)
7265 return V; // Won't shrink.
7266 if (Value *V = FitsInFPType(CFP, Type::DoubleTy, APFloat::IEEEdouble))
7267 return V;
7268 // Don't try to shrink to various long double types.
7269 }
7270
7271 return V;
7272}
7273
7274Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7275 if (Instruction *I = commonCastTransforms(CI))
7276 return I;
7277
7278 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7279 // smaller than the destination type, we can eliminate the truncate by doing
7280 // the add as the smaller type. This applies to add/sub/mul/div as well as
7281 // many builtins (sqrt, etc).
7282 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7283 if (OpI && OpI->hasOneUse()) {
7284 switch (OpI->getOpcode()) {
7285 default: break;
7286 case Instruction::Add:
7287 case Instruction::Sub:
7288 case Instruction::Mul:
7289 case Instruction::FDiv:
7290 case Instruction::FRem:
7291 const Type *SrcTy = OpI->getType();
7292 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7293 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7294 if (LHSTrunc->getType() != SrcTy &&
7295 RHSTrunc->getType() != SrcTy) {
7296 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7297 // If the source types were both smaller than the destination type of
7298 // the cast, do this xform.
7299 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7300 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7301 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7302 CI.getType(), CI);
7303 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7304 CI.getType(), CI);
7305 return BinaryOperator::create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
7306 }
7307 }
7308 break;
7309 }
7310 }
7311 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007312}
7313
7314Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7315 return commonCastTransforms(CI);
7316}
7317
7318Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
7319 return commonCastTransforms(CI);
7320}
7321
7322Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
7323 return commonCastTransforms(CI);
7324}
7325
7326Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7327 return commonCastTransforms(CI);
7328}
7329
7330Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7331 return commonCastTransforms(CI);
7332}
7333
7334Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7335 return commonPointerCastTransforms(CI);
7336}
7337
Chris Lattner7c1626482008-01-08 07:23:51 +00007338Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7339 if (Instruction *I = commonCastTransforms(CI))
7340 return I;
7341
7342 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7343 if (!DestPointee->isSized()) return 0;
7344
7345 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7346 ConstantInt *Cst;
7347 Value *X;
7348 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7349 m_ConstantInt(Cst)))) {
7350 // If the source and destination operands have the same type, see if this
7351 // is a single-index GEP.
7352 if (X->getType() == CI.getType()) {
7353 // Get the size of the pointee type.
7354 uint64_t Size = TD->getABITypeSizeInBits(DestPointee);
7355
7356 // Convert the constant to intptr type.
7357 APInt Offset = Cst->getValue();
7358 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7359
7360 // If Offset is evenly divisible by Size, we can do this xform.
7361 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7362 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7363 return new GetElementPtrInst(X, ConstantInt::get(Offset));
7364 }
7365 }
7366 // TODO: Could handle other cases, e.g. where add is indexing into field of
7367 // struct etc.
7368 } else if (CI.getOperand(0)->hasOneUse() &&
7369 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7370 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7371 // "inttoptr+GEP" instead of "add+intptr".
7372
7373 // Get the size of the pointee type.
7374 uint64_t Size = TD->getABITypeSize(DestPointee);
7375
7376 // Convert the constant to intptr type.
7377 APInt Offset = Cst->getValue();
7378 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7379
7380 // If Offset is evenly divisible by Size, we can do this xform.
7381 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7382 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7383
7384 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7385 "tmp"), CI);
7386 return new GetElementPtrInst(P, ConstantInt::get(Offset), "tmp");
7387 }
7388 }
7389 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007390}
7391
7392Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
7393 // If the operands are integer typed then apply the integer transforms,
7394 // otherwise just apply the common ones.
7395 Value *Src = CI.getOperand(0);
7396 const Type *SrcTy = Src->getType();
7397 const Type *DestTy = CI.getType();
7398
7399 if (SrcTy->isInteger() && DestTy->isInteger()) {
7400 if (Instruction *Result = commonIntCastTransforms(CI))
7401 return Result;
7402 } else if (isa<PointerType>(SrcTy)) {
7403 if (Instruction *I = commonPointerCastTransforms(CI))
7404 return I;
7405 } else {
7406 if (Instruction *Result = commonCastTransforms(CI))
7407 return Result;
7408 }
7409
7410
7411 // Get rid of casts from one type to the same type. These are useless and can
7412 // be replaced by the operand.
7413 if (DestTy == Src->getType())
7414 return ReplaceInstUsesWith(CI, Src);
7415
7416 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7417 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7418 const Type *DstElTy = DstPTy->getElementType();
7419 const Type *SrcElTy = SrcPTy->getElementType();
7420
7421 // If we are casting a malloc or alloca to a pointer to a type of the same
7422 // size, rewrite the allocation instruction to allocate the "right" type.
7423 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7424 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7425 return V;
7426
7427 // If the source and destination are pointers, and this cast is equivalent
7428 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
7429 // This can enhance SROA and other transforms that want type-safe pointers.
7430 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7431 unsigned NumZeros = 0;
7432 while (SrcElTy != DstElTy &&
7433 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7434 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7435 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7436 ++NumZeros;
7437 }
7438
7439 // If we found a path from the src to dest, create the getelementptr now.
7440 if (SrcElTy == DstElTy) {
7441 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Chuck Rose III27d49792007-09-05 20:36:41 +00007442 return new GetElementPtrInst(Src, Idxs.begin(), Idxs.end(), "",
7443 ((Instruction*) NULL));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007444 }
7445 }
7446
7447 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7448 if (SVI->hasOneUse()) {
7449 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7450 // a bitconvert to a vector with the same # elts.
7451 if (isa<VectorType>(DestTy) &&
7452 cast<VectorType>(DestTy)->getNumElements() ==
7453 SVI->getType()->getNumElements()) {
7454 CastInst *Tmp;
7455 // If either of the operands is a cast from CI.getType(), then
7456 // evaluating the shuffle in the casted destination's type will allow
7457 // us to eliminate at least one cast.
7458 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7459 Tmp->getOperand(0)->getType() == DestTy) ||
7460 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7461 Tmp->getOperand(0)->getType() == DestTy)) {
7462 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7463 SVI->getOperand(0), DestTy, &CI);
7464 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7465 SVI->getOperand(1), DestTy, &CI);
7466 // Return a new shuffle vector. Use the same element ID's, as we
7467 // know the vector types match #elts.
7468 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
7469 }
7470 }
7471 }
7472 }
7473 return 0;
7474}
7475
7476/// GetSelectFoldableOperands - We want to turn code that looks like this:
7477/// %C = or %A, %B
7478/// %D = select %cond, %C, %A
7479/// into:
7480/// %C = select %cond, %B, 0
7481/// %D = or %A, %C
7482///
7483/// Assuming that the specified instruction is an operand to the select, return
7484/// a bitmask indicating which operands of this instruction are foldable if they
7485/// equal the other incoming value of the select.
7486///
7487static unsigned GetSelectFoldableOperands(Instruction *I) {
7488 switch (I->getOpcode()) {
7489 case Instruction::Add:
7490 case Instruction::Mul:
7491 case Instruction::And:
7492 case Instruction::Or:
7493 case Instruction::Xor:
7494 return 3; // Can fold through either operand.
7495 case Instruction::Sub: // Can only fold on the amount subtracted.
7496 case Instruction::Shl: // Can only fold on the shift amount.
7497 case Instruction::LShr:
7498 case Instruction::AShr:
7499 return 1;
7500 default:
7501 return 0; // Cannot fold
7502 }
7503}
7504
7505/// GetSelectFoldableConstant - For the same transformation as the previous
7506/// function, return the identity constant that goes into the select.
7507static Constant *GetSelectFoldableConstant(Instruction *I) {
7508 switch (I->getOpcode()) {
7509 default: assert(0 && "This cannot happen!"); abort();
7510 case Instruction::Add:
7511 case Instruction::Sub:
7512 case Instruction::Or:
7513 case Instruction::Xor:
7514 case Instruction::Shl:
7515 case Instruction::LShr:
7516 case Instruction::AShr:
7517 return Constant::getNullValue(I->getType());
7518 case Instruction::And:
7519 return Constant::getAllOnesValue(I->getType());
7520 case Instruction::Mul:
7521 return ConstantInt::get(I->getType(), 1);
7522 }
7523}
7524
7525/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
7526/// have the same opcode and only one use each. Try to simplify this.
7527Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
7528 Instruction *FI) {
7529 if (TI->getNumOperands() == 1) {
7530 // If this is a non-volatile load or a cast from the same type,
7531 // merge.
7532 if (TI->isCast()) {
7533 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
7534 return 0;
7535 } else {
7536 return 0; // unknown unary op.
7537 }
7538
7539 // Fold this by inserting a select from the input values.
7540 SelectInst *NewSI = new SelectInst(SI.getCondition(), TI->getOperand(0),
7541 FI->getOperand(0), SI.getName()+".v");
7542 InsertNewInstBefore(NewSI, SI);
7543 return CastInst::create(Instruction::CastOps(TI->getOpcode()), NewSI,
7544 TI->getType());
7545 }
7546
7547 // Only handle binary operators here.
7548 if (!isa<BinaryOperator>(TI))
7549 return 0;
7550
7551 // Figure out if the operations have any operands in common.
7552 Value *MatchOp, *OtherOpT, *OtherOpF;
7553 bool MatchIsOpZero;
7554 if (TI->getOperand(0) == FI->getOperand(0)) {
7555 MatchOp = TI->getOperand(0);
7556 OtherOpT = TI->getOperand(1);
7557 OtherOpF = FI->getOperand(1);
7558 MatchIsOpZero = true;
7559 } else if (TI->getOperand(1) == FI->getOperand(1)) {
7560 MatchOp = TI->getOperand(1);
7561 OtherOpT = TI->getOperand(0);
7562 OtherOpF = FI->getOperand(0);
7563 MatchIsOpZero = false;
7564 } else if (!TI->isCommutative()) {
7565 return 0;
7566 } else if (TI->getOperand(0) == FI->getOperand(1)) {
7567 MatchOp = TI->getOperand(0);
7568 OtherOpT = TI->getOperand(1);
7569 OtherOpF = FI->getOperand(0);
7570 MatchIsOpZero = true;
7571 } else if (TI->getOperand(1) == FI->getOperand(0)) {
7572 MatchOp = TI->getOperand(1);
7573 OtherOpT = TI->getOperand(0);
7574 OtherOpF = FI->getOperand(1);
7575 MatchIsOpZero = true;
7576 } else {
7577 return 0;
7578 }
7579
7580 // If we reach here, they do have operations in common.
7581 SelectInst *NewSI = new SelectInst(SI.getCondition(), OtherOpT,
7582 OtherOpF, SI.getName()+".v");
7583 InsertNewInstBefore(NewSI, SI);
7584
7585 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
7586 if (MatchIsOpZero)
7587 return BinaryOperator::create(BO->getOpcode(), MatchOp, NewSI);
7588 else
7589 return BinaryOperator::create(BO->getOpcode(), NewSI, MatchOp);
7590 }
7591 assert(0 && "Shouldn't get here");
7592 return 0;
7593}
7594
7595Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
7596 Value *CondVal = SI.getCondition();
7597 Value *TrueVal = SI.getTrueValue();
7598 Value *FalseVal = SI.getFalseValue();
7599
7600 // select true, X, Y -> X
7601 // select false, X, Y -> Y
7602 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
7603 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
7604
7605 // select C, X, X -> X
7606 if (TrueVal == FalseVal)
7607 return ReplaceInstUsesWith(SI, TrueVal);
7608
7609 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
7610 return ReplaceInstUsesWith(SI, FalseVal);
7611 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
7612 return ReplaceInstUsesWith(SI, TrueVal);
7613 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
7614 if (isa<Constant>(TrueVal))
7615 return ReplaceInstUsesWith(SI, TrueVal);
7616 else
7617 return ReplaceInstUsesWith(SI, FalseVal);
7618 }
7619
7620 if (SI.getType() == Type::Int1Ty) {
7621 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
7622 if (C->getZExtValue()) {
7623 // Change: A = select B, true, C --> A = or B, C
7624 return BinaryOperator::createOr(CondVal, FalseVal);
7625 } else {
7626 // Change: A = select B, false, C --> A = and !B, C
7627 Value *NotCond =
7628 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7629 "not."+CondVal->getName()), SI);
7630 return BinaryOperator::createAnd(NotCond, FalseVal);
7631 }
7632 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
7633 if (C->getZExtValue() == false) {
7634 // Change: A = select B, C, false --> A = and B, C
7635 return BinaryOperator::createAnd(CondVal, TrueVal);
7636 } else {
7637 // Change: A = select B, C, true --> A = or !B, C
7638 Value *NotCond =
7639 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7640 "not."+CondVal->getName()), SI);
7641 return BinaryOperator::createOr(NotCond, TrueVal);
7642 }
7643 }
Chris Lattner53f85a72007-11-25 21:27:53 +00007644
7645 // select a, b, a -> a&b
7646 // select a, a, b -> a|b
7647 if (CondVal == TrueVal)
7648 return BinaryOperator::createOr(CondVal, FalseVal);
7649 else if (CondVal == FalseVal)
7650 return BinaryOperator::createAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007651 }
7652
7653 // Selecting between two integer constants?
7654 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
7655 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
7656 // select C, 1, 0 -> zext C to int
7657 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
7658 return CastInst::create(Instruction::ZExt, CondVal, SI.getType());
7659 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
7660 // select C, 0, 1 -> zext !C to int
7661 Value *NotCond =
7662 InsertNewInstBefore(BinaryOperator::createNot(CondVal,
7663 "not."+CondVal->getName()), SI);
7664 return CastInst::create(Instruction::ZExt, NotCond, SI.getType());
7665 }
7666
7667 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
7668
7669 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
7670
7671 // (x <s 0) ? -1 : 0 -> ashr x, 31
7672 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
7673 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
7674 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
7675 // The comparison constant and the result are not neccessarily the
7676 // same width. Make an all-ones value by inserting a AShr.
7677 Value *X = IC->getOperand(0);
7678 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
7679 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
7680 Instruction *SRA = BinaryOperator::create(Instruction::AShr, X,
7681 ShAmt, "ones");
7682 InsertNewInstBefore(SRA, SI);
7683
7684 // Finally, convert to the type of the select RHS. We figure out
7685 // if this requires a SExt, Trunc or BitCast based on the sizes.
7686 Instruction::CastOps opc = Instruction::BitCast;
7687 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
7688 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
7689 if (SRASize < SISize)
7690 opc = Instruction::SExt;
7691 else if (SRASize > SISize)
7692 opc = Instruction::Trunc;
7693 return CastInst::create(opc, SRA, SI.getType());
7694 }
7695 }
7696
7697
7698 // If one of the constants is zero (we know they can't both be) and we
7699 // have an icmp instruction with zero, and we have an 'and' with the
7700 // non-constant value, eliminate this whole mess. This corresponds to
7701 // cases like this: ((X & 27) ? 27 : 0)
7702 if (TrueValC->isZero() || FalseValC->isZero())
7703 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
7704 cast<Constant>(IC->getOperand(1))->isNullValue())
7705 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
7706 if (ICA->getOpcode() == Instruction::And &&
7707 isa<ConstantInt>(ICA->getOperand(1)) &&
7708 (ICA->getOperand(1) == TrueValC ||
7709 ICA->getOperand(1) == FalseValC) &&
7710 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
7711 // Okay, now we know that everything is set up, we just don't
7712 // know whether we have a icmp_ne or icmp_eq and whether the
7713 // true or false val is the zero.
7714 bool ShouldNotVal = !TrueValC->isZero();
7715 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
7716 Value *V = ICA;
7717 if (ShouldNotVal)
7718 V = InsertNewInstBefore(BinaryOperator::create(
7719 Instruction::Xor, V, ICA->getOperand(1)), SI);
7720 return ReplaceInstUsesWith(SI, V);
7721 }
7722 }
7723 }
7724
7725 // See if we are selecting two values based on a comparison of the two values.
7726 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
7727 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
7728 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen2e1b7692007-10-03 17:45:27 +00007729 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7730 // This is not safe in general for floating point:
7731 // consider X== -0, Y== +0.
7732 // It becomes safe if either operand is a nonzero constant.
7733 ConstantFP *CFPt, *CFPf;
7734 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7735 !CFPt->getValueAPF().isZero()) ||
7736 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7737 !CFPf->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007738 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen2e1b7692007-10-03 17:45:27 +00007739 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007740 // Transform (X != Y) ? X : Y -> X
7741 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7742 return ReplaceInstUsesWith(SI, TrueVal);
7743 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7744
7745 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
7746 // Transform (X == Y) ? Y : X -> X
Dale Johannesen2e1b7692007-10-03 17:45:27 +00007747 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
7748 // This is not safe in general for floating point:
7749 // consider X== -0, Y== +0.
7750 // It becomes safe if either operand is a nonzero constant.
7751 ConstantFP *CFPt, *CFPf;
7752 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
7753 !CFPt->getValueAPF().isZero()) ||
7754 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
7755 !CFPf->getValueAPF().isZero()))
7756 return ReplaceInstUsesWith(SI, FalseVal);
7757 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007758 // Transform (X != Y) ? Y : X -> Y
7759 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
7760 return ReplaceInstUsesWith(SI, TrueVal);
7761 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7762 }
7763 }
7764
7765 // See if we are selecting two values based on a comparison of the two values.
7766 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
7767 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
7768 // Transform (X == Y) ? X : Y -> Y
7769 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7770 return ReplaceInstUsesWith(SI, FalseVal);
7771 // Transform (X != Y) ? X : Y -> X
7772 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7773 return ReplaceInstUsesWith(SI, TrueVal);
7774 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7775
7776 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
7777 // Transform (X == Y) ? Y : X -> X
7778 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
7779 return ReplaceInstUsesWith(SI, FalseVal);
7780 // Transform (X != Y) ? Y : X -> Y
7781 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
7782 return ReplaceInstUsesWith(SI, TrueVal);
7783 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
7784 }
7785 }
7786
7787 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
7788 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
7789 if (TI->hasOneUse() && FI->hasOneUse()) {
7790 Instruction *AddOp = 0, *SubOp = 0;
7791
7792 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
7793 if (TI->getOpcode() == FI->getOpcode())
7794 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
7795 return IV;
7796
7797 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
7798 // even legal for FP.
7799 if (TI->getOpcode() == Instruction::Sub &&
7800 FI->getOpcode() == Instruction::Add) {
7801 AddOp = FI; SubOp = TI;
7802 } else if (FI->getOpcode() == Instruction::Sub &&
7803 TI->getOpcode() == Instruction::Add) {
7804 AddOp = TI; SubOp = FI;
7805 }
7806
7807 if (AddOp) {
7808 Value *OtherAddOp = 0;
7809 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
7810 OtherAddOp = AddOp->getOperand(1);
7811 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
7812 OtherAddOp = AddOp->getOperand(0);
7813 }
7814
7815 if (OtherAddOp) {
7816 // So at this point we know we have (Y -> OtherAddOp):
7817 // select C, (add X, Y), (sub X, Z)
7818 Value *NegVal; // Compute -Z
7819 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
7820 NegVal = ConstantExpr::getNeg(C);
7821 } else {
7822 NegVal = InsertNewInstBefore(
7823 BinaryOperator::createNeg(SubOp->getOperand(1), "tmp"), SI);
7824 }
7825
7826 Value *NewTrueOp = OtherAddOp;
7827 Value *NewFalseOp = NegVal;
7828 if (AddOp != TI)
7829 std::swap(NewTrueOp, NewFalseOp);
7830 Instruction *NewSel =
7831 new SelectInst(CondVal, NewTrueOp,NewFalseOp,SI.getName()+".p");
7832
7833 NewSel = InsertNewInstBefore(NewSel, SI);
7834 return BinaryOperator::createAdd(SubOp->getOperand(0), NewSel);
7835 }
7836 }
7837 }
7838
7839 // See if we can fold the select into one of our operands.
7840 if (SI.getType()->isInteger()) {
7841 // See the comment above GetSelectFoldableOperands for a description of the
7842 // transformation we are doing here.
7843 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
7844 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
7845 !isa<Constant>(FalseVal))
7846 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
7847 unsigned OpToFold = 0;
7848 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
7849 OpToFold = 1;
7850 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
7851 OpToFold = 2;
7852 }
7853
7854 if (OpToFold) {
7855 Constant *C = GetSelectFoldableConstant(TVI);
7856 Instruction *NewSel =
7857 new SelectInst(SI.getCondition(), TVI->getOperand(2-OpToFold), C);
7858 InsertNewInstBefore(NewSel, SI);
7859 NewSel->takeName(TVI);
7860 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
7861 return BinaryOperator::create(BO->getOpcode(), FalseVal, NewSel);
7862 else {
7863 assert(0 && "Unknown instruction!!");
7864 }
7865 }
7866 }
7867
7868 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
7869 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
7870 !isa<Constant>(TrueVal))
7871 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
7872 unsigned OpToFold = 0;
7873 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
7874 OpToFold = 1;
7875 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
7876 OpToFold = 2;
7877 }
7878
7879 if (OpToFold) {
7880 Constant *C = GetSelectFoldableConstant(FVI);
7881 Instruction *NewSel =
7882 new SelectInst(SI.getCondition(), C, FVI->getOperand(2-OpToFold));
7883 InsertNewInstBefore(NewSel, SI);
7884 NewSel->takeName(FVI);
7885 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
7886 return BinaryOperator::create(BO->getOpcode(), TrueVal, NewSel);
7887 else
7888 assert(0 && "Unknown instruction!!");
7889 }
7890 }
7891 }
7892
7893 if (BinaryOperator::isNot(CondVal)) {
7894 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
7895 SI.setOperand(1, FalseVal);
7896 SI.setOperand(2, TrueVal);
7897 return &SI;
7898 }
7899
7900 return 0;
7901}
7902
Chris Lattner47cf3452007-08-09 19:05:49 +00007903/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
7904/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
7905/// and it is more than the alignment of the ultimate object, see if we can
7906/// increase the alignment of the ultimate object, making this check succeed.
7907static unsigned GetOrEnforceKnownAlignment(Value *V, TargetData *TD,
7908 unsigned PrefAlign = 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007909 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
7910 unsigned Align = GV->getAlignment();
Andrew Lenharthdae02012007-11-08 18:45:15 +00007911 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007912 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
Chris Lattner47cf3452007-08-09 19:05:49 +00007913
7914 // If there is a large requested alignment and we can, bump up the alignment
7915 // of the global.
7916 if (PrefAlign > Align && GV->hasInitializer()) {
7917 GV->setAlignment(PrefAlign);
7918 Align = PrefAlign;
7919 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007920 return Align;
7921 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
7922 unsigned Align = AI->getAlignment();
7923 if (Align == 0 && TD) {
7924 if (isa<AllocaInst>(AI))
7925 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
7926 else if (isa<MallocInst>(AI)) {
7927 // Malloc returns maximally aligned memory.
7928 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
7929 Align =
7930 std::max(Align,
7931 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
7932 Align =
7933 std::max(Align,
7934 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
7935 }
7936 }
Chris Lattner47cf3452007-08-09 19:05:49 +00007937
7938 // If there is a requested alignment and if this is an alloca, round up. We
7939 // don't do this for malloc, because some systems can't respect the request.
7940 if (PrefAlign > Align && isa<AllocaInst>(AI)) {
7941 AI->setAlignment(PrefAlign);
7942 Align = PrefAlign;
7943 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007944 return Align;
7945 } else if (isa<BitCastInst>(V) ||
7946 (isa<ConstantExpr>(V) &&
7947 cast<ConstantExpr>(V)->getOpcode() == Instruction::BitCast)) {
Chris Lattner47cf3452007-08-09 19:05:49 +00007948 return GetOrEnforceKnownAlignment(cast<User>(V)->getOperand(0),
7949 TD, PrefAlign);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007950 } else if (User *GEPI = dyn_castGetElementPtr(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007951 // If all indexes are zero, it is just the alignment of the base pointer.
7952 bool AllZeroOperands = true;
7953 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
7954 if (!isa<Constant>(GEPI->getOperand(i)) ||
7955 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
7956 AllZeroOperands = false;
7957 break;
7958 }
Chris Lattner47cf3452007-08-09 19:05:49 +00007959
7960 if (AllZeroOperands) {
7961 // Treat this like a bitcast.
7962 return GetOrEnforceKnownAlignment(GEPI->getOperand(0), TD, PrefAlign);
7963 }
7964
7965 unsigned BaseAlignment = GetOrEnforceKnownAlignment(GEPI->getOperand(0),TD);
7966 if (BaseAlignment == 0) return 0;
7967
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007968 // Otherwise, if the base alignment is >= the alignment we expect for the
7969 // base pointer type, then we know that the resultant pointer is aligned at
7970 // least as much as its type requires.
7971 if (!TD) return 0;
7972
7973 const Type *BasePtrTy = GEPI->getOperand(0)->getType();
7974 const PointerType *PtrTy = cast<PointerType>(BasePtrTy);
Lauro Ramos Venancio55da3352007-07-31 20:13:21 +00007975 unsigned Align = TD->getABITypeAlignment(PtrTy->getElementType());
7976 if (Align <= BaseAlignment) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007977 const Type *GEPTy = GEPI->getType();
7978 const PointerType *GEPPtrTy = cast<PointerType>(GEPTy);
Lauro Ramos Venancio55da3352007-07-31 20:13:21 +00007979 Align = std::min(Align, (unsigned)
7980 TD->getABITypeAlignment(GEPPtrTy->getElementType()));
7981 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007982 }
7983 return 0;
7984 }
7985 return 0;
7986}
7987
Chris Lattner00ae5132008-01-13 23:50:23 +00007988Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
7989 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1), TD);
7990 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2), TD);
7991 unsigned MinAlign = std::min(DstAlign, SrcAlign);
7992 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
7993
7994 if (CopyAlign < MinAlign) {
7995 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
7996 return MI;
7997 }
7998
7999 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8000 // load/store.
8001 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8002 if (MemOpLength == 0) return 0;
8003
Chris Lattnerc669fb62008-01-14 00:28:35 +00008004 // Source and destination pointer types are always "i8*" for intrinsic. See
8005 // if the size is something we can handle with a single primitive load/store.
8006 // A single load+store correctly handles overlapping memory in the memmove
8007 // case.
Chris Lattner00ae5132008-01-13 23:50:23 +00008008 unsigned Size = MemOpLength->getZExtValue();
8009 if (Size == 0 || Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +00008010 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +00008011
Chris Lattnerc669fb62008-01-14 00:28:35 +00008012 // Use an integer load+store unless we can find something better.
Chris Lattner00ae5132008-01-13 23:50:23 +00008013 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattnerc669fb62008-01-14 00:28:35 +00008014
8015 // Memcpy forces the use of i8* for the source and destination. That means
8016 // that if you're using memcpy to move one double around, you'll get a cast
8017 // from double* to i8*. We'd much rather use a double load+store rather than
8018 // an i64 load+store, here because this improves the odds that the source or
8019 // dest address will be promotable. See if we can find a better type than the
8020 // integer datatype.
8021 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8022 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8023 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8024 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8025 // down through these levels if so.
8026 while (!SrcETy->isFirstClassType()) {
8027 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8028 if (STy->getNumElements() == 1)
8029 SrcETy = STy->getElementType(0);
8030 else
8031 break;
8032 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8033 if (ATy->getNumElements() == 1)
8034 SrcETy = ATy->getElementType();
8035 else
8036 break;
8037 } else
8038 break;
8039 }
8040
8041 if (SrcETy->isFirstClassType())
8042 NewPtrTy = PointerType::getUnqual(SrcETy);
8043 }
8044 }
8045
8046
Chris Lattner00ae5132008-01-13 23:50:23 +00008047 // If the memcpy/memmove provides better alignment info than we can
8048 // infer, use it.
8049 SrcAlign = std::max(SrcAlign, CopyAlign);
8050 DstAlign = std::max(DstAlign, CopyAlign);
8051
8052 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8053 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattnerc669fb62008-01-14 00:28:35 +00008054 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8055 InsertNewInstBefore(L, *MI);
8056 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8057
8058 // Set the size of the copy to 0, it will be deleted on the next iteration.
8059 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8060 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +00008061}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008062
8063/// visitCallInst - CallInst simplification. This mostly only handles folding
8064/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8065/// the heavy lifting.
8066///
8067Instruction *InstCombiner::visitCallInst(CallInst &CI) {
8068 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8069 if (!II) return visitCallSite(&CI);
8070
8071 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8072 // visitCallSite.
8073 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
8074 bool Changed = false;
8075
8076 // memmove/cpy/set of zero bytes is a noop.
8077 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8078 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8079
8080 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
8081 if (CI->getZExtValue() == 1) {
8082 // Replace the instruction with just byte operations. We would
8083 // transform other cases to loads/stores, but we don't know if
8084 // alignment is sufficient.
8085 }
8086 }
8087
8088 // If we have a memmove and the source operation is a constant global,
8089 // then the source and dest pointers can't alias, so we can change this
8090 // into a call to memcpy.
Chris Lattner00ae5132008-01-13 23:50:23 +00008091 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008092 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8093 if (GVSrc->isConstant()) {
8094 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008095 Intrinsic::ID MemCpyID;
8096 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8097 MemCpyID = Intrinsic::memcpy_i32;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008098 else
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008099 MemCpyID = Intrinsic::memcpy_i64;
8100 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008101 Changed = true;
8102 }
8103 }
8104
8105 // If we can determine a pointer alignment that is bigger than currently
8106 // set, update the alignment.
8107 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +00008108 if (Instruction *I = SimplifyMemTransfer(MI))
8109 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008110 } else if (isa<MemSetInst>(MI)) {
Chris Lattner47cf3452007-08-09 19:05:49 +00008111 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest(), TD);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008112 if (MI->getAlignment()->getZExtValue() < Alignment) {
8113 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8114 Changed = true;
8115 }
8116 }
8117
8118 if (Changed) return II;
8119 } else {
8120 switch (II->getIntrinsicID()) {
8121 default: break;
8122 case Intrinsic::ppc_altivec_lvx:
8123 case Intrinsic::ppc_altivec_lvxl:
8124 case Intrinsic::x86_sse_loadu_ps:
8125 case Intrinsic::x86_sse2_loadu_pd:
8126 case Intrinsic::x86_sse2_loadu_dq:
8127 // Turn PPC lvx -> load if the pointer is known aligned.
8128 // Turn X86 loadups -> load if the pointer is known aligned.
Chris Lattner47cf3452007-08-09 19:05:49 +00008129 if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008130 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8131 PointerType::getUnqual(II->getType()),
8132 CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008133 return new LoadInst(Ptr);
8134 }
8135 break;
8136 case Intrinsic::ppc_altivec_stvx:
8137 case Intrinsic::ppc_altivec_stvxl:
8138 // Turn stvx -> store if the pointer is known aligned.
Chris Lattner47cf3452007-08-09 19:05:49 +00008139 if (GetOrEnforceKnownAlignment(II->getOperand(2), TD, 16) >= 16) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00008140 const Type *OpPtrTy =
8141 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008142 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008143 return new StoreInst(II->getOperand(1), Ptr);
8144 }
8145 break;
8146 case Intrinsic::x86_sse_storeu_ps:
8147 case Intrinsic::x86_sse2_storeu_pd:
8148 case Intrinsic::x86_sse2_storeu_dq:
8149 case Intrinsic::x86_sse2_storel_dq:
8150 // Turn X86 storeu -> store if the pointer is known aligned.
Chris Lattner47cf3452007-08-09 19:05:49 +00008151 if (GetOrEnforceKnownAlignment(II->getOperand(1), TD, 16) >= 16) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00008152 const Type *OpPtrTy =
8153 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008154 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008155 return new StoreInst(II->getOperand(2), Ptr);
8156 }
8157 break;
8158
8159 case Intrinsic::x86_sse_cvttss2si: {
8160 // These intrinsics only demands the 0th element of its input vector. If
8161 // we can simplify the input based on that, do so now.
8162 uint64_t UndefElts;
8163 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8164 UndefElts)) {
8165 II->setOperand(1, V);
8166 return II;
8167 }
8168 break;
8169 }
8170
8171 case Intrinsic::ppc_altivec_vperm:
8172 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8173 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8174 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8175
8176 // Check that all of the elements are integer constants or undefs.
8177 bool AllEltsOk = true;
8178 for (unsigned i = 0; i != 16; ++i) {
8179 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8180 !isa<UndefValue>(Mask->getOperand(i))) {
8181 AllEltsOk = false;
8182 break;
8183 }
8184 }
8185
8186 if (AllEltsOk) {
8187 // Cast the input vectors to byte vectors.
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008188 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8189 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008190 Value *Result = UndefValue::get(Op0->getType());
8191
8192 // Only extract each element once.
8193 Value *ExtractedElts[32];
8194 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8195
8196 for (unsigned i = 0; i != 16; ++i) {
8197 if (isa<UndefValue>(Mask->getOperand(i)))
8198 continue;
8199 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8200 Idx &= 31; // Match the hardware behavior.
8201
8202 if (ExtractedElts[Idx] == 0) {
8203 Instruction *Elt =
8204 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8205 InsertNewInstBefore(Elt, CI);
8206 ExtractedElts[Idx] = Elt;
8207 }
8208
8209 // Insert this value into the result vector.
8210 Result = new InsertElementInst(Result, ExtractedElts[Idx], i,"tmp");
8211 InsertNewInstBefore(cast<Instruction>(Result), CI);
8212 }
8213 return CastInst::create(Instruction::BitCast, Result, CI.getType());
8214 }
8215 }
8216 break;
8217
8218 case Intrinsic::stackrestore: {
8219 // If the save is right next to the restore, remove the restore. This can
8220 // happen when variable allocas are DCE'd.
8221 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8222 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8223 BasicBlock::iterator BI = SS;
8224 if (&*++BI == II)
8225 return EraseInstFromFunction(CI);
8226 }
8227 }
8228
Chris Lattner416d91c2008-02-18 06:12:38 +00008229 // Scan down this block to see if there is another stack restore in the
8230 // same block without an intervening call/alloca.
8231 BasicBlock::iterator BI = II;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008232 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattner416d91c2008-02-18 06:12:38 +00008233 bool CannotRemove = false;
8234 for (++BI; &*BI != TI; ++BI) {
8235 if (isa<AllocaInst>(BI)) {
8236 CannotRemove = true;
8237 break;
8238 }
8239 if (isa<CallInst>(BI)) {
8240 if (!isa<IntrinsicInst>(BI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008241 CannotRemove = true;
8242 break;
8243 }
Chris Lattner416d91c2008-02-18 06:12:38 +00008244 // If there is a stackrestore below this one, remove this one.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008245 return EraseInstFromFunction(CI);
Chris Lattner416d91c2008-02-18 06:12:38 +00008246 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008247 }
Chris Lattner416d91c2008-02-18 06:12:38 +00008248
8249 // If the stack restore is in a return/unwind block and if there are no
8250 // allocas or calls between the restore and the return, nuke the restore.
8251 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8252 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008253 break;
8254 }
8255 }
8256 }
8257
8258 return visitCallSite(II);
8259}
8260
8261// InvokeInst simplification
8262//
8263Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8264 return visitCallSite(&II);
8265}
8266
8267// visitCallSite - Improvements for call and invoke instructions.
8268//
8269Instruction *InstCombiner::visitCallSite(CallSite CS) {
8270 bool Changed = false;
8271
8272 // If the callee is a constexpr cast of a function, attempt to move the cast
8273 // to the arguments of the call/invoke.
8274 if (transformConstExprCastCall(CS)) return 0;
8275
8276 Value *Callee = CS.getCalledValue();
8277
8278 if (Function *CalleeF = dyn_cast<Function>(Callee))
8279 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8280 Instruction *OldCall = CS.getInstruction();
8281 // If the call and callee calling conventions don't match, this call must
8282 // be unreachable, as the call is undefined.
8283 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00008284 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8285 OldCall);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008286 if (!OldCall->use_empty())
8287 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8288 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8289 return EraseInstFromFunction(*OldCall);
8290 return 0;
8291 }
8292
8293 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8294 // This instruction is not reachable, just remove it. We insert a store to
8295 // undef so that we know that this code is not reachable, despite the fact
8296 // that we can't modify the CFG here.
8297 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00008298 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008299 CS.getInstruction());
8300
8301 if (!CS.getInstruction()->use_empty())
8302 CS.getInstruction()->
8303 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8304
8305 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8306 // Don't break the CFG, insert a dummy cond branch.
8307 new BranchInst(II->getNormalDest(), II->getUnwindDest(),
8308 ConstantInt::getTrue(), II);
8309 }
8310 return EraseInstFromFunction(*CS.getInstruction());
8311 }
8312
Duncan Sands74833f22007-09-17 10:26:40 +00008313 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8314 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8315 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8316 return transformCallThroughTrampoline(CS);
8317
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008318 const PointerType *PTy = cast<PointerType>(Callee->getType());
8319 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8320 if (FTy->isVarArg()) {
8321 // See if we can optimize any arguments passed through the varargs area of
8322 // the call.
8323 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
8324 E = CS.arg_end(); I != E; ++I)
8325 if (CastInst *CI = dyn_cast<CastInst>(*I)) {
8326 // If this cast does not effect the value passed through the varargs
8327 // area, we can eliminate the use of the cast.
8328 Value *Op = CI->getOperand(0);
8329 if (CI->isLosslessCast()) {
8330 *I = Op;
8331 Changed = true;
8332 }
8333 }
8334 }
8335
Duncan Sands2937e352007-12-19 21:13:37 +00008336 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +00008337 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +00008338 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +00008339 Changed = true;
8340 }
8341
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008342 return Changed ? CS.getInstruction() : 0;
8343}
8344
8345// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8346// attempt to move the cast to the arguments of the call/invoke.
8347//
8348bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8349 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8350 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
8351 if (CE->getOpcode() != Instruction::BitCast ||
8352 !isa<Function>(CE->getOperand(0)))
8353 return false;
8354 Function *Callee = cast<Function>(CE->getOperand(0));
8355 Instruction *Caller = CS.getInstruction();
Duncan Sandsc849e662008-01-06 18:27:01 +00008356 const ParamAttrsList* CallerPAL = CS.getParamAttrs();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008357
8358 // Okay, this is a cast from a function to a different type. Unless doing so
8359 // would cause a type conversion of one of our arguments, change this call to
8360 // be a direct call with arguments casted to the appropriate types.
8361 //
8362 const FunctionType *FT = Callee->getFunctionType();
8363 const Type *OldRetTy = Caller->getType();
8364
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008365 // Check to see if we are changing the return type...
8366 if (OldRetTy != FT->getReturnType()) {
8367 if (Callee->isDeclaration() && !Caller->use_empty() &&
8368 // Conversion is ok if changing from pointer to int of same size.
8369 !(isa<PointerType>(FT->getReturnType()) &&
8370 TD->getIntPtrType() == OldRetTy))
8371 return false; // Cannot transform this return value.
8372
Duncan Sands5c489582008-01-06 10:12:28 +00008373 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +00008374 // void -> non-void is handled specially
Duncan Sands4ced1f82008-01-13 08:02:44 +00008375 FT->getReturnType() != Type::VoidTy &&
8376 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +00008377 return false; // Cannot transform this return value.
8378
Duncan Sandsdbe97dc2008-01-07 17:16:06 +00008379 if (CallerPAL && !Caller->use_empty()) {
8380 uint16_t RAttrs = CallerPAL->getParamAttrs(0);
8381 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
8382 return false; // Attribute not compatible with transformed value.
8383 }
Duncan Sandsc849e662008-01-06 18:27:01 +00008384
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008385 // If the callsite is an invoke instruction, and the return value is used by
8386 // a PHI node in a successor, we cannot change the return type of the call
8387 // because there is no place to put the cast instruction (without breaking
8388 // the critical edge). Bail out in this case.
8389 if (!Caller->use_empty())
8390 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8391 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8392 UI != E; ++UI)
8393 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8394 if (PN->getParent() == II->getNormalDest() ||
8395 PN->getParent() == II->getUnwindDest())
8396 return false;
8397 }
8398
8399 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8400 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
8401
8402 CallSite::arg_iterator AI = CS.arg_begin();
8403 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8404 const Type *ParamTy = FT->getParamType(i);
8405 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +00008406
8407 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +00008408 return false; // Cannot transform this parameter value.
8409
Duncan Sandsdbe97dc2008-01-07 17:16:06 +00008410 if (CallerPAL) {
8411 uint16_t PAttrs = CallerPAL->getParamAttrs(i + 1);
8412 if (PAttrs & ParamAttr::typeIncompatible(ParamTy))
8413 return false; // Attribute not compatible with transformed value.
8414 }
Duncan Sands5c489582008-01-06 10:12:28 +00008415
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008416 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sands5c489582008-01-06 10:12:28 +00008417 // Some conversions are safe even if we do not have a body.
8418 // Either we can cast directly, or we can upconvert the argument
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008419 bool isConvertible = ActTy == ParamTy ||
8420 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
8421 (ParamTy->isInteger() && ActTy->isInteger() &&
8422 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
8423 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
8424 && c->getValue().isStrictlyPositive());
8425 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008426 }
8427
8428 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
8429 Callee->isDeclaration())
8430 return false; // Do not delete arguments unless we have a function body...
8431
Duncan Sands4ced1f82008-01-13 08:02:44 +00008432 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() && CallerPAL)
Duncan Sandsc849e662008-01-06 18:27:01 +00008433 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +00008434 // won't be dropping them. Check that these extra arguments have attributes
8435 // that are compatible with being a vararg call argument.
8436 for (unsigned i = CallerPAL->size(); i; --i) {
8437 if (CallerPAL->getParamIndex(i - 1) <= FT->getNumParams())
8438 break;
8439 uint16_t PAttrs = CallerPAL->getParamAttrsAtIndex(i - 1);
8440 if (PAttrs & ParamAttr::VarArgsIncompatible)
8441 return false;
8442 }
Duncan Sandsc849e662008-01-06 18:27:01 +00008443
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008444 // Okay, we decided that this is a safe thing to do: go ahead and start
8445 // inserting cast instructions as necessary...
8446 std::vector<Value*> Args;
8447 Args.reserve(NumActualArgs);
Duncan Sandsc849e662008-01-06 18:27:01 +00008448 ParamAttrsVector attrVec;
8449 attrVec.reserve(NumCommonArgs);
8450
8451 // Get any return attributes.
8452 uint16_t RAttrs = CallerPAL ? CallerPAL->getParamAttrs(0) : 0;
8453
8454 // If the return value is not being used, the type may not be compatible
8455 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sandsdbe97dc2008-01-07 17:16:06 +00008456 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsc849e662008-01-06 18:27:01 +00008457
8458 // Add the new return attributes.
8459 if (RAttrs)
8460 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008461
8462 AI = CS.arg_begin();
8463 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
8464 const Type *ParamTy = FT->getParamType(i);
8465 if ((*AI)->getType() == ParamTy) {
8466 Args.push_back(*AI);
8467 } else {
8468 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
8469 false, ParamTy, false);
8470 CastInst *NewCast = CastInst::create(opcode, *AI, ParamTy, "tmp");
8471 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
8472 }
Duncan Sandsc849e662008-01-06 18:27:01 +00008473
8474 // Add any parameter attributes.
8475 uint16_t PAttrs = CallerPAL ? CallerPAL->getParamAttrs(i + 1) : 0;
8476 if (PAttrs)
8477 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008478 }
8479
8480 // If the function takes more arguments than the call was taking, add them
8481 // now...
8482 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
8483 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
8484
8485 // If we are removing arguments to the function, emit an obnoxious warning...
8486 if (FT->getNumParams() < NumActualArgs)
8487 if (!FT->isVarArg()) {
8488 cerr << "WARNING: While resolving call to function '"
8489 << Callee->getName() << "' arguments were dropped!\n";
8490 } else {
8491 // Add all of the arguments in their promoted form to the arg list...
8492 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
8493 const Type *PTy = getPromotedType((*AI)->getType());
8494 if (PTy != (*AI)->getType()) {
8495 // Must promote to pass through va_arg area!
8496 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
8497 PTy, false);
8498 Instruction *Cast = CastInst::create(opcode, *AI, PTy, "tmp");
8499 InsertNewInstBefore(Cast, *Caller);
8500 Args.push_back(Cast);
8501 } else {
8502 Args.push_back(*AI);
8503 }
Duncan Sandsc849e662008-01-06 18:27:01 +00008504
Duncan Sands4ced1f82008-01-13 08:02:44 +00008505 // Add any parameter attributes.
8506 uint16_t PAttrs = CallerPAL ? CallerPAL->getParamAttrs(i + 1) : 0;
8507 if (PAttrs)
8508 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
8509 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008510 }
8511
8512 if (FT->getReturnType() == Type::VoidTy)
8513 Caller->setName(""); // Void type should not have a name.
8514
Duncan Sandsc849e662008-01-06 18:27:01 +00008515 const ParamAttrsList* NewCallerPAL = ParamAttrsList::get(attrVec);
8516
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008517 Instruction *NC;
8518 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8519 NC = new InvokeInst(Callee, II->getNormalDest(), II->getUnwindDest(),
David Greene8278ef52007-08-27 19:04:21 +00008520 Args.begin(), Args.end(), Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +00008521 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsc849e662008-01-06 18:27:01 +00008522 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008523 } else {
Chris Lattner03dc7d72007-08-02 16:53:43 +00008524 NC = new CallInst(Callee, Args.begin(), Args.end(),
8525 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008526 CallInst *CI = cast<CallInst>(Caller);
8527 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008528 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008529 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsc849e662008-01-06 18:27:01 +00008530 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008531 }
8532
8533 // Insert a cast of the return type as necessary.
8534 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +00008535 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008536 if (NV->getType() != Type::VoidTy) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008537 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +00008538 OldRetTy, false);
8539 NV = NC = CastInst::create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008540
8541 // If this is an invoke instruction, we should insert it after the first
8542 // non-phi, instruction in the normal successor block.
8543 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8544 BasicBlock::iterator I = II->getNormalDest()->begin();
8545 while (isa<PHINode>(I)) ++I;
8546 InsertNewInstBefore(NC, *I);
8547 } else {
8548 // Otherwise, it's a call, just insert cast right after the call instr
8549 InsertNewInstBefore(NC, *Caller);
8550 }
8551 AddUsersToWorkList(*Caller);
8552 } else {
8553 NV = UndefValue::get(Caller->getType());
8554 }
8555 }
8556
8557 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8558 Caller->replaceAllUsesWith(NV);
8559 Caller->eraseFromParent();
8560 RemoveFromWorkList(Caller);
8561 return true;
8562}
8563
Duncan Sands74833f22007-09-17 10:26:40 +00008564// transformCallThroughTrampoline - Turn a call to a function created by the
8565// init_trampoline intrinsic into a direct call to the underlying function.
8566//
8567Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
8568 Value *Callee = CS.getCalledValue();
8569 const PointerType *PTy = cast<PointerType>(Callee->getType());
8570 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Duncan Sands48b81112008-01-14 19:52:09 +00008571 const ParamAttrsList *Attrs = CS.getParamAttrs();
8572
8573 // If the call already has the 'nest' attribute somewhere then give up -
8574 // otherwise 'nest' would occur twice after splicing in the chain.
8575 if (Attrs && Attrs->hasAttrSomewhere(ParamAttr::Nest))
8576 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +00008577
8578 IntrinsicInst *Tramp =
8579 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
8580
8581 Function *NestF =
8582 cast<Function>(IntrinsicInst::StripPointerCasts(Tramp->getOperand(2)));
8583 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
8584 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
8585
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008586 if (const ParamAttrsList *NestAttrs = NestF->getParamAttrs()) {
Duncan Sands74833f22007-09-17 10:26:40 +00008587 unsigned NestIdx = 1;
8588 const Type *NestTy = 0;
8589 uint16_t NestAttr = 0;
8590
8591 // Look for a parameter marked with the 'nest' attribute.
8592 for (FunctionType::param_iterator I = NestFTy->param_begin(),
8593 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
8594 if (NestAttrs->paramHasAttr(NestIdx, ParamAttr::Nest)) {
8595 // Record the parameter type and any other attributes.
8596 NestTy = *I;
8597 NestAttr = NestAttrs->getParamAttrs(NestIdx);
8598 break;
8599 }
8600
8601 if (NestTy) {
8602 Instruction *Caller = CS.getInstruction();
8603 std::vector<Value*> NewArgs;
8604 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
8605
Duncan Sands48b81112008-01-14 19:52:09 +00008606 ParamAttrsVector NewAttrs;
8607 NewAttrs.reserve(Attrs ? Attrs->size() + 1 : 1);
8608
Duncan Sands74833f22007-09-17 10:26:40 +00008609 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +00008610 // mean appending it. Likewise for attributes.
8611
8612 // Add any function result attributes.
8613 uint16_t Attr = Attrs ? Attrs->getParamAttrs(0) : 0;
8614 if (Attr)
8615 NewAttrs.push_back (ParamAttrsWithIndex::get(0, Attr));
8616
Duncan Sands74833f22007-09-17 10:26:40 +00008617 {
8618 unsigned Idx = 1;
8619 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
8620 do {
8621 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +00008622 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00008623 Value *NestVal = Tramp->getOperand(3);
8624 if (NestVal->getType() != NestTy)
8625 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
8626 NewArgs.push_back(NestVal);
Duncan Sands48b81112008-01-14 19:52:09 +00008627 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +00008628 }
8629
8630 if (I == E)
8631 break;
8632
Duncan Sands48b81112008-01-14 19:52:09 +00008633 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00008634 NewArgs.push_back(*I);
Duncan Sands48b81112008-01-14 19:52:09 +00008635 Attr = Attrs ? Attrs->getParamAttrs(Idx) : 0;
8636 if (Attr)
8637 NewAttrs.push_back
8638 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +00008639
8640 ++Idx, ++I;
8641 } while (1);
8642 }
8643
8644 // The trampoline may have been bitcast to a bogus type (FTy).
8645 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +00008646 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +00008647
Duncan Sands74833f22007-09-17 10:26:40 +00008648 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +00008649 NewTypes.reserve(FTy->getNumParams()+1);
8650
Duncan Sands74833f22007-09-17 10:26:40 +00008651 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +00008652 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +00008653 {
8654 unsigned Idx = 1;
8655 FunctionType::param_iterator I = FTy->param_begin(),
8656 E = FTy->param_end();
8657
8658 do {
Duncan Sands48b81112008-01-14 19:52:09 +00008659 if (Idx == NestIdx)
8660 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +00008661 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +00008662
8663 if (I == E)
8664 break;
8665
Duncan Sands48b81112008-01-14 19:52:09 +00008666 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +00008667 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +00008668
8669 ++Idx, ++I;
8670 } while (1);
8671 }
8672
8673 // Replace the trampoline call with a direct call. Let the generic
8674 // code sort out any function type mismatches.
8675 FunctionType *NewFTy =
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008676 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lambbb2f2222007-12-17 01:12:55 +00008677 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
8678 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008679 const ParamAttrsList *NewPAL = ParamAttrsList::get(NewAttrs);
Duncan Sands74833f22007-09-17 10:26:40 +00008680
8681 Instruction *NewCaller;
8682 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
8683 NewCaller = new InvokeInst(NewCallee,
8684 II->getNormalDest(), II->getUnwindDest(),
8685 NewArgs.begin(), NewArgs.end(),
8686 Caller->getName(), Caller);
8687 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008688 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00008689 } else {
8690 NewCaller = new CallInst(NewCallee, NewArgs.begin(), NewArgs.end(),
8691 Caller->getName(), Caller);
8692 if (cast<CallInst>(Caller)->isTailCall())
8693 cast<CallInst>(NewCaller)->setTailCall();
8694 cast<CallInst>(NewCaller)->
8695 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00008696 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00008697 }
8698 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
8699 Caller->replaceAllUsesWith(NewCaller);
8700 Caller->eraseFromParent();
8701 RemoveFromWorkList(Caller);
8702 return 0;
8703 }
8704 }
8705
8706 // Replace the trampoline call with a direct call. Since there is no 'nest'
8707 // parameter, there is no need to adjust the argument list. Let the generic
8708 // code sort out any function type mismatches.
8709 Constant *NewCallee =
8710 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
8711 CS.setCalledFunction(NewCallee);
8712 return CS.getInstruction();
8713}
8714
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008715/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
8716/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
8717/// and a single binop.
8718Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
8719 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8720 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
8721 isa<CmpInst>(FirstInst));
8722 unsigned Opc = FirstInst->getOpcode();
8723 Value *LHSVal = FirstInst->getOperand(0);
8724 Value *RHSVal = FirstInst->getOperand(1);
8725
8726 const Type *LHSType = LHSVal->getType();
8727 const Type *RHSType = RHSVal->getType();
8728
8729 // Scan to see if all operands are the same opcode, all have one use, and all
8730 // kill their operands (i.e. the operands have one use).
8731 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
8732 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
8733 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
8734 // Verify type of the LHS matches so we don't fold cmp's of different
8735 // types or GEP's with different index types.
8736 I->getOperand(0)->getType() != LHSType ||
8737 I->getOperand(1)->getType() != RHSType)
8738 return 0;
8739
8740 // If they are CmpInst instructions, check their predicates
8741 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
8742 if (cast<CmpInst>(I)->getPredicate() !=
8743 cast<CmpInst>(FirstInst)->getPredicate())
8744 return 0;
8745
8746 // Keep track of which operand needs a phi node.
8747 if (I->getOperand(0) != LHSVal) LHSVal = 0;
8748 if (I->getOperand(1) != RHSVal) RHSVal = 0;
8749 }
8750
8751 // Otherwise, this is safe to transform, determine if it is profitable.
8752
8753 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
8754 // Indexes are often folded into load/store instructions, so we don't want to
8755 // hide them behind a phi.
8756 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
8757 return 0;
8758
8759 Value *InLHS = FirstInst->getOperand(0);
8760 Value *InRHS = FirstInst->getOperand(1);
8761 PHINode *NewLHS = 0, *NewRHS = 0;
8762 if (LHSVal == 0) {
8763 NewLHS = new PHINode(LHSType, FirstInst->getOperand(0)->getName()+".pn");
8764 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
8765 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
8766 InsertNewInstBefore(NewLHS, PN);
8767 LHSVal = NewLHS;
8768 }
8769
8770 if (RHSVal == 0) {
8771 NewRHS = new PHINode(RHSType, FirstInst->getOperand(1)->getName()+".pn");
8772 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
8773 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
8774 InsertNewInstBefore(NewRHS, PN);
8775 RHSVal = NewRHS;
8776 }
8777
8778 // Add all operands to the new PHIs.
8779 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8780 if (NewLHS) {
8781 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8782 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
8783 }
8784 if (NewRHS) {
8785 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
8786 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
8787 }
8788 }
8789
8790 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
8791 return BinaryOperator::create(BinOp->getOpcode(), LHSVal, RHSVal);
8792 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8793 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
8794 RHSVal);
8795 else {
8796 assert(isa<GetElementPtrInst>(FirstInst));
8797 return new GetElementPtrInst(LHSVal, RHSVal);
8798 }
8799}
8800
8801/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
8802/// of the block that defines it. This means that it must be obvious the value
8803/// of the load is not changed from the point of the load to the end of the
8804/// block it is in.
8805///
8806/// Finally, it is safe, but not profitable, to sink a load targetting a
8807/// non-address-taken alloca. Doing so will cause us to not promote the alloca
8808/// to a register.
8809static bool isSafeToSinkLoad(LoadInst *L) {
8810 BasicBlock::iterator BBI = L, E = L->getParent()->end();
8811
8812 for (++BBI; BBI != E; ++BBI)
8813 if (BBI->mayWriteToMemory())
8814 return false;
8815
8816 // Check for non-address taken alloca. If not address-taken already, it isn't
8817 // profitable to do this xform.
8818 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
8819 bool isAddressTaken = false;
8820 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
8821 UI != E; ++UI) {
8822 if (isa<LoadInst>(UI)) continue;
8823 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
8824 // If storing TO the alloca, then the address isn't taken.
8825 if (SI->getOperand(1) == AI) continue;
8826 }
8827 isAddressTaken = true;
8828 break;
8829 }
8830
8831 if (!isAddressTaken)
8832 return false;
8833 }
8834
8835 return true;
8836}
8837
8838
8839// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
8840// operator and they all are only used by the PHI, PHI together their
8841// inputs, and do the operation once, to the result of the PHI.
8842Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
8843 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
8844
8845 // Scan the instruction, looking for input operations that can be folded away.
8846 // If all input operands to the phi are the same instruction (e.g. a cast from
8847 // the same type or "+42") we can pull the operation through the PHI, reducing
8848 // code size and simplifying code.
8849 Constant *ConstantOp = 0;
8850 const Type *CastSrcTy = 0;
8851 bool isVolatile = false;
8852 if (isa<CastInst>(FirstInst)) {
8853 CastSrcTy = FirstInst->getOperand(0)->getType();
8854 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
8855 // Can fold binop, compare or shift here if the RHS is a constant,
8856 // otherwise call FoldPHIArgBinOpIntoPHI.
8857 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
8858 if (ConstantOp == 0)
8859 return FoldPHIArgBinOpIntoPHI(PN);
8860 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
8861 isVolatile = LI->isVolatile();
8862 // We can't sink the load if the loaded value could be modified between the
8863 // load and the PHI.
8864 if (LI->getParent() != PN.getIncomingBlock(0) ||
8865 !isSafeToSinkLoad(LI))
8866 return 0;
8867 } else if (isa<GetElementPtrInst>(FirstInst)) {
8868 if (FirstInst->getNumOperands() == 2)
8869 return FoldPHIArgBinOpIntoPHI(PN);
8870 // Can't handle general GEPs yet.
8871 return 0;
8872 } else {
8873 return 0; // Cannot fold this operation.
8874 }
8875
8876 // Check to see if all arguments are the same operation.
8877 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8878 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
8879 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
8880 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
8881 return 0;
8882 if (CastSrcTy) {
8883 if (I->getOperand(0)->getType() != CastSrcTy)
8884 return 0; // Cast operation must match.
8885 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
8886 // We can't sink the load if the loaded value could be modified between
8887 // the load and the PHI.
8888 if (LI->isVolatile() != isVolatile ||
8889 LI->getParent() != PN.getIncomingBlock(i) ||
8890 !isSafeToSinkLoad(LI))
8891 return 0;
8892 } else if (I->getOperand(1) != ConstantOp) {
8893 return 0;
8894 }
8895 }
8896
8897 // Okay, they are all the same operation. Create a new PHI node of the
8898 // correct type, and PHI together all of the LHS's of the instructions.
8899 PHINode *NewPN = new PHINode(FirstInst->getOperand(0)->getType(),
8900 PN.getName()+".in");
8901 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
8902
8903 Value *InVal = FirstInst->getOperand(0);
8904 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
8905
8906 // Add all operands to the new PHI.
8907 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
8908 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
8909 if (NewInVal != InVal)
8910 InVal = 0;
8911 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
8912 }
8913
8914 Value *PhiVal;
8915 if (InVal) {
8916 // The new PHI unions all of the same values together. This is really
8917 // common, so we handle it intelligently here for compile-time speed.
8918 PhiVal = InVal;
8919 delete NewPN;
8920 } else {
8921 InsertNewInstBefore(NewPN, PN);
8922 PhiVal = NewPN;
8923 }
8924
8925 // Insert and return the new operation.
8926 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
8927 return CastInst::create(FirstCI->getOpcode(), PhiVal, PN.getType());
8928 else if (isa<LoadInst>(FirstInst))
8929 return new LoadInst(PhiVal, "", isVolatile);
8930 else if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
8931 return BinaryOperator::create(BinOp->getOpcode(), PhiVal, ConstantOp);
8932 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
8933 return CmpInst::create(CIOp->getOpcode(), CIOp->getPredicate(),
8934 PhiVal, ConstantOp);
8935 else
8936 assert(0 && "Unknown operation");
8937 return 0;
8938}
8939
8940/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
8941/// that is dead.
8942static bool DeadPHICycle(PHINode *PN,
8943 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
8944 if (PN->use_empty()) return true;
8945 if (!PN->hasOneUse()) return false;
8946
8947 // Remember this node, and if we find the cycle, return.
8948 if (!PotentiallyDeadPHIs.insert(PN))
8949 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +00008950
8951 // Don't scan crazily complex things.
8952 if (PotentiallyDeadPHIs.size() == 16)
8953 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008954
8955 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
8956 return DeadPHICycle(PU, PotentiallyDeadPHIs);
8957
8958 return false;
8959}
8960
Chris Lattner27b695d2007-11-06 21:52:06 +00008961/// PHIsEqualValue - Return true if this phi node is always equal to
8962/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
8963/// z = some value; x = phi (y, z); y = phi (x, z)
8964static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
8965 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
8966 // See if we already saw this PHI node.
8967 if (!ValueEqualPHIs.insert(PN))
8968 return true;
8969
8970 // Don't scan crazily complex things.
8971 if (ValueEqualPHIs.size() == 16)
8972 return false;
8973
8974 // Scan the operands to see if they are either phi nodes or are equal to
8975 // the value.
8976 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
8977 Value *Op = PN->getIncomingValue(i);
8978 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
8979 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
8980 return false;
8981 } else if (Op != NonPhiInVal)
8982 return false;
8983 }
8984
8985 return true;
8986}
8987
8988
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008989// PHINode simplification
8990//
8991Instruction *InstCombiner::visitPHINode(PHINode &PN) {
8992 // If LCSSA is around, don't mess with Phi nodes
8993 if (MustPreserveLCSSA) return 0;
8994
8995 if (Value *V = PN.hasConstantValue())
8996 return ReplaceInstUsesWith(PN, V);
8997
8998 // If all PHI operands are the same operation, pull them through the PHI,
8999 // reducing code size.
9000 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9001 PN.getIncomingValue(0)->hasOneUse())
9002 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9003 return Result;
9004
9005 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9006 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9007 // PHI)... break the cycle.
9008 if (PN.hasOneUse()) {
9009 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9010 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
9011 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
9012 PotentiallyDeadPHIs.insert(&PN);
9013 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9014 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9015 }
9016
9017 // If this phi has a single use, and if that use just computes a value for
9018 // the next iteration of a loop, delete the phi. This occurs with unused
9019 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9020 // common case here is good because the only other things that catch this
9021 // are induction variable analysis (sometimes) and ADCE, which is only run
9022 // late.
9023 if (PHIUser->hasOneUse() &&
9024 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9025 PHIUser->use_back() == &PN) {
9026 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9027 }
9028 }
9029
Chris Lattner27b695d2007-11-06 21:52:06 +00009030 // We sometimes end up with phi cycles that non-obviously end up being the
9031 // same value, for example:
9032 // z = some value; x = phi (y, z); y = phi (x, z)
9033 // where the phi nodes don't necessarily need to be in the same block. Do a
9034 // quick check to see if the PHI node only contains a single non-phi value, if
9035 // so, scan to see if the phi cycle is actually equal to that value.
9036 {
9037 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9038 // Scan for the first non-phi operand.
9039 while (InValNo != NumOperandVals &&
9040 isa<PHINode>(PN.getIncomingValue(InValNo)))
9041 ++InValNo;
9042
9043 if (InValNo != NumOperandVals) {
9044 Value *NonPhiInVal = PN.getOperand(InValNo);
9045
9046 // Scan the rest of the operands to see if there are any conflicts, if so
9047 // there is no need to recursively scan other phis.
9048 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9049 Value *OpVal = PN.getIncomingValue(InValNo);
9050 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9051 break;
9052 }
9053
9054 // If we scanned over all operands, then we have one unique value plus
9055 // phi values. Scan PHI nodes to see if they all merge in each other or
9056 // the value.
9057 if (InValNo == NumOperandVals) {
9058 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9059 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9060 return ReplaceInstUsesWith(PN, NonPhiInVal);
9061 }
9062 }
9063 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009064 return 0;
9065}
9066
9067static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9068 Instruction *InsertPoint,
9069 InstCombiner *IC) {
9070 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9071 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
9072 // We must cast correctly to the pointer type. Ensure that we
9073 // sign extend the integer value if it is smaller as this is
9074 // used for address computation.
9075 Instruction::CastOps opcode =
9076 (VTySize < PtrSize ? Instruction::SExt :
9077 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9078 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
9079}
9080
9081
9082Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
9083 Value *PtrOp = GEP.getOperand(0);
9084 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
9085 // If so, eliminate the noop.
9086 if (GEP.getNumOperands() == 1)
9087 return ReplaceInstUsesWith(GEP, PtrOp);
9088
9089 if (isa<UndefValue>(GEP.getOperand(0)))
9090 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9091
9092 bool HasZeroPointerIndex = false;
9093 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9094 HasZeroPointerIndex = C->isNullValue();
9095
9096 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
9097 return ReplaceInstUsesWith(GEP, PtrOp);
9098
9099 // Eliminate unneeded casts for indices.
9100 bool MadeChange = false;
9101
9102 gep_type_iterator GTI = gep_type_begin(GEP);
9103 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
9104 if (isa<SequentialType>(*GTI)) {
9105 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
9106 if (CI->getOpcode() == Instruction::ZExt ||
9107 CI->getOpcode() == Instruction::SExt) {
9108 const Type *SrcTy = CI->getOperand(0)->getType();
9109 // We can eliminate a cast from i32 to i64 iff the target
9110 // is a 32-bit pointer target.
9111 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9112 MadeChange = true;
9113 GEP.setOperand(i, CI->getOperand(0));
9114 }
9115 }
9116 }
9117 // If we are using a wider index than needed for this platform, shrink it
9118 // to what we need. If the incoming value needs a cast instruction,
9119 // insert it. This explicit cast can make subsequent optimizations more
9120 // obvious.
9121 Value *Op = GEP.getOperand(i);
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009122 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009123 if (Constant *C = dyn_cast<Constant>(Op)) {
9124 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
9125 MadeChange = true;
9126 } else {
9127 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9128 GEP);
9129 GEP.setOperand(i, Op);
9130 MadeChange = true;
9131 }
9132 }
9133 }
9134 if (MadeChange) return &GEP;
9135
9136 // If this GEP instruction doesn't move the pointer, and if the input operand
9137 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9138 // real input to the dest type.
Chris Lattnerc59171a2007-10-12 05:30:59 +00009139 if (GEP.hasAllZeroIndices()) {
9140 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9141 // If the bitcast is of an allocation, and the allocation will be
9142 // converted to match the type of the cast, don't touch this.
9143 if (isa<AllocationInst>(BCI->getOperand(0))) {
9144 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattner551a5872007-10-12 18:05:47 +00009145 if (Instruction *I = visitBitCast(*BCI)) {
9146 if (I != BCI) {
9147 I->takeName(BCI);
9148 BCI->getParent()->getInstList().insert(BCI, I);
9149 ReplaceInstUsesWith(*BCI, I);
9150 }
Chris Lattnerc59171a2007-10-12 05:30:59 +00009151 return &GEP;
Chris Lattner551a5872007-10-12 18:05:47 +00009152 }
Chris Lattnerc59171a2007-10-12 05:30:59 +00009153 }
9154 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9155 }
9156 }
9157
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009158 // Combine Indices - If the source pointer to this getelementptr instruction
9159 // is a getelementptr instruction, combine the indices of the two
9160 // getelementptr instructions into a single instruction.
9161 //
9162 SmallVector<Value*, 8> SrcGEPOperands;
9163 if (User *Src = dyn_castGetElementPtr(PtrOp))
9164 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
9165
9166 if (!SrcGEPOperands.empty()) {
9167 // Note that if our source is a gep chain itself that we wait for that
9168 // chain to be resolved before we perform this transformation. This
9169 // avoids us creating a TON of code in some cases.
9170 //
9171 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9172 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9173 return 0; // Wait until our source is folded to completion.
9174
9175 SmallVector<Value*, 8> Indices;
9176
9177 // Find out whether the last index in the source GEP is a sequential idx.
9178 bool EndsWithSequential = false;
9179 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9180 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
9181 EndsWithSequential = !isa<StructType>(*I);
9182
9183 // Can we combine the two pointer arithmetics offsets?
9184 if (EndsWithSequential) {
9185 // Replace: gep (gep %P, long B), long A, ...
9186 // With: T = long A+B; gep %P, T, ...
9187 //
9188 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
9189 if (SO1 == Constant::getNullValue(SO1->getType())) {
9190 Sum = GO1;
9191 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9192 Sum = SO1;
9193 } else {
9194 // If they aren't the same type, convert both to an integer of the
9195 // target's pointer size.
9196 if (SO1->getType() != GO1->getType()) {
9197 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
9198 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
9199 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
9200 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
9201 } else {
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009202 unsigned PS = TD->getPointerSizeInBits();
9203 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009204 // Convert GO1 to SO1's type.
9205 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
9206
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009207 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009208 // Convert SO1 to GO1's type.
9209 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
9210 } else {
9211 const Type *PT = TD->getIntPtrType();
9212 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9213 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
9214 }
9215 }
9216 }
9217 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9218 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9219 else {
9220 Sum = BinaryOperator::createAdd(SO1, GO1, PtrOp->getName()+".sum");
9221 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
9222 }
9223 }
9224
9225 // Recycle the GEP we already have if possible.
9226 if (SrcGEPOperands.size() == 2) {
9227 GEP.setOperand(0, SrcGEPOperands[0]);
9228 GEP.setOperand(1, Sum);
9229 return &GEP;
9230 } else {
9231 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9232 SrcGEPOperands.end()-1);
9233 Indices.push_back(Sum);
9234 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9235 }
9236 } else if (isa<Constant>(*GEP.idx_begin()) &&
9237 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
9238 SrcGEPOperands.size() != 1) {
9239 // Otherwise we can do the fold if the first index of the GEP is a zero
9240 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9241 SrcGEPOperands.end());
9242 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9243 }
9244
9245 if (!Indices.empty())
David Greene393be882007-09-04 15:46:09 +00009246 return new GetElementPtrInst(SrcGEPOperands[0], Indices.begin(),
9247 Indices.end(), GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009248
9249 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
9250 // GEP of global variable. If all of the indices for this GEP are
9251 // constants, we can promote this to a constexpr instead of an instruction.
9252
9253 // Scan for nonconstants...
9254 SmallVector<Constant*, 8> Indices;
9255 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9256 for (; I != E && isa<Constant>(*I); ++I)
9257 Indices.push_back(cast<Constant>(*I));
9258
9259 if (I == E) { // If they are all constants...
9260 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9261 &Indices[0],Indices.size());
9262
9263 // Replace all uses of the GEP with the new constexpr...
9264 return ReplaceInstUsesWith(GEP, CE);
9265 }
9266 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
9267 if (!isa<PointerType>(X->getType())) {
9268 // Not interesting. Source pointer must be a cast from pointer.
9269 } else if (HasZeroPointerIndex) {
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009270 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9271 // into : GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009272 //
9273 // This occurs when the program declares an array extern like "int X[];"
9274 //
9275 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9276 const PointerType *XTy = cast<PointerType>(X->getType());
9277 if (const ArrayType *XATy =
9278 dyn_cast<ArrayType>(XTy->getElementType()))
9279 if (const ArrayType *CATy =
9280 dyn_cast<ArrayType>(CPTy->getElementType()))
9281 if (CATy->getElementType() == XATy->getElementType()) {
9282 // At this point, we know that the cast source type is a pointer
9283 // to an array of the same type as the destination pointer
9284 // array. Because the array type is never stepped over (there
9285 // is a leading zero) we can fold the cast into this GEP.
9286 GEP.setOperand(0, X);
9287 return &GEP;
9288 }
9289 } else if (GEP.getNumOperands() == 2) {
9290 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009291 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9292 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009293 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9294 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9295 if (isa<ArrayType>(SrcElTy) &&
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009296 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9297 TD->getABITypeSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +00009298 Value *Idx[2];
9299 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9300 Idx[1] = GEP.getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009301 Value *V = InsertNewInstBefore(
David Greene393be882007-09-04 15:46:09 +00009302 new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName()), GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009303 // V and GEP are both pointer types --> BitCast
9304 return new BitCastInst(V, GEP.getType());
9305 }
9306
9307 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009308 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009309 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009310 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009311
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009312 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009313 uint64_t ArrayEltSize =
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009314 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009315
9316 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9317 // allow either a mul, shift, or constant here.
9318 Value *NewIdx = 0;
9319 ConstantInt *Scale = 0;
9320 if (ArrayEltSize == 1) {
9321 NewIdx = GEP.getOperand(1);
9322 Scale = ConstantInt::get(NewIdx->getType(), 1);
9323 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
9324 NewIdx = ConstantInt::get(CI->getType(), 1);
9325 Scale = CI;
9326 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9327 if (Inst->getOpcode() == Instruction::Shl &&
9328 isa<ConstantInt>(Inst->getOperand(1))) {
9329 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9330 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9331 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
9332 NewIdx = Inst->getOperand(0);
9333 } else if (Inst->getOpcode() == Instruction::Mul &&
9334 isa<ConstantInt>(Inst->getOperand(1))) {
9335 Scale = cast<ConstantInt>(Inst->getOperand(1));
9336 NewIdx = Inst->getOperand(0);
9337 }
9338 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009339
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009340 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009341 // out, perform the transformation. Note, we don't know whether Scale is
9342 // signed or not. We'll use unsigned version of division/modulo
9343 // operation after making sure Scale doesn't have the sign bit set.
9344 if (Scale && Scale->getSExtValue() >= 0LL &&
9345 Scale->getZExtValue() % ArrayEltSize == 0) {
9346 Scale = ConstantInt::get(Scale->getType(),
9347 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009348 if (Scale->getZExtValue() != 1) {
9349 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009350 false /*ZExt*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009351 Instruction *Sc = BinaryOperator::createMul(NewIdx, C, "idxscale");
9352 NewIdx = InsertNewInstBefore(Sc, GEP);
9353 }
9354
9355 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +00009356 Value *Idx[2];
9357 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9358 Idx[1] = NewIdx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009359 Instruction *NewGEP =
David Greene393be882007-09-04 15:46:09 +00009360 new GetElementPtrInst(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009361 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9362 // The NewGEP must be pointer typed, so must the old one -> BitCast
9363 return new BitCastInst(NewGEP, GEP.getType());
9364 }
9365 }
9366 }
9367 }
9368
9369 return 0;
9370}
9371
9372Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9373 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
9374 if (AI.isArrayAllocation()) // Check C != 1
9375 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9376 const Type *NewTy =
9377 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
9378 AllocationInst *New = 0;
9379
9380 // Create and insert the replacement instruction...
9381 if (isa<MallocInst>(AI))
9382 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
9383 else {
9384 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
9385 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
9386 }
9387
9388 InsertNewInstBefore(New, AI);
9389
9390 // Scan to the end of the allocation instructions, to skip over a block of
9391 // allocas if possible...
9392 //
9393 BasicBlock::iterator It = New;
9394 while (isa<AllocationInst>(*It)) ++It;
9395
9396 // Now that I is pointing to the first non-allocation-inst in the block,
9397 // insert our getelementptr instruction...
9398 //
9399 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greene393be882007-09-04 15:46:09 +00009400 Value *Idx[2];
9401 Idx[0] = NullIdx;
9402 Idx[1] = NullIdx;
9403 Value *V = new GetElementPtrInst(New, Idx, Idx + 2,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009404 New->getName()+".sub", It);
9405
9406 // Now make everything use the getelementptr instead of the original
9407 // allocation.
9408 return ReplaceInstUsesWith(AI, V);
9409 } else if (isa<UndefValue>(AI.getArraySize())) {
9410 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9411 }
9412
9413 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
9414 // Note that we only do this for alloca's, because malloc should allocate and
9415 // return a unique pointer, even for a zero byte allocation.
9416 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009417 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009418 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
9419
9420 return 0;
9421}
9422
9423Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
9424 Value *Op = FI.getOperand(0);
9425
9426 // free undef -> unreachable.
9427 if (isa<UndefValue>(Op)) {
9428 // Insert a new store to null because we cannot modify the CFG here.
9429 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00009430 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009431 return EraseInstFromFunction(FI);
9432 }
9433
9434 // If we have 'free null' delete the instruction. This can happen in stl code
9435 // when lots of inlining happens.
9436 if (isa<ConstantPointerNull>(Op))
9437 return EraseInstFromFunction(FI);
9438
9439 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
9440 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
9441 FI.setOperand(0, CI->getOperand(0));
9442 return &FI;
9443 }
9444
9445 // Change free (gep X, 0,0,0,0) into free(X)
9446 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9447 if (GEPI->hasAllZeroIndices()) {
9448 AddToWorkList(GEPI);
9449 FI.setOperand(0, GEPI->getOperand(0));
9450 return &FI;
9451 }
9452 }
9453
9454 // Change free(malloc) into nothing, if the malloc has a single use.
9455 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
9456 if (MI->hasOneUse()) {
9457 EraseInstFromFunction(FI);
9458 return EraseInstFromFunction(*MI);
9459 }
9460
9461 return 0;
9462}
9463
9464
9465/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patela0f8ea82007-10-18 19:52:32 +00009466static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
9467 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009468 User *CI = cast<User>(LI.getOperand(0));
9469 Value *CastOp = CI->getOperand(0);
9470
Devang Patela0f8ea82007-10-18 19:52:32 +00009471 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
9472 // Instead of loading constant c string, use corresponding integer value
9473 // directly if string length is small enough.
9474 const std::string &Str = CE->getOperand(0)->getStringValue();
9475 if (!Str.empty()) {
9476 unsigned len = Str.length();
9477 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
9478 unsigned numBits = Ty->getPrimitiveSizeInBits();
9479 // Replace LI with immediate integer store.
9480 if ((numBits >> 3) == len + 1) {
9481 APInt StrVal(numBits, 0);
9482 APInt SingleChar(numBits, 0);
9483 if (TD->isLittleEndian()) {
9484 for (signed i = len-1; i >= 0; i--) {
9485 SingleChar = (uint64_t) Str[i];
9486 StrVal = (StrVal << 8) | SingleChar;
9487 }
9488 } else {
9489 for (unsigned i = 0; i < len; i++) {
9490 SingleChar = (uint64_t) Str[i];
9491 StrVal = (StrVal << 8) | SingleChar;
9492 }
9493 // Append NULL at the end.
9494 SingleChar = 0;
9495 StrVal = (StrVal << 8) | SingleChar;
9496 }
9497 Value *NL = ConstantInt::get(StrVal);
9498 return IC.ReplaceInstUsesWith(LI, NL);
9499 }
9500 }
9501 }
9502
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009503 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9504 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9505 const Type *SrcPTy = SrcTy->getElementType();
9506
9507 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
9508 isa<VectorType>(DestPTy)) {
9509 // If the source is an array, the code below will not succeed. Check to
9510 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9511 // constants.
9512 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9513 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9514 if (ASrcTy->getNumElements() != 0) {
9515 Value *Idxs[2];
9516 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9517 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
9518 SrcTy = cast<PointerType>(CastOp->getType());
9519 SrcPTy = SrcTy->getElementType();
9520 }
9521
9522 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
9523 isa<VectorType>(SrcPTy)) &&
9524 // Do not allow turning this into a load of an integer, which is then
9525 // casted to a pointer, this pessimizes pointer analysis a lot.
9526 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
9527 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9528 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
9529
9530 // Okay, we are casting from one integer or pointer type to another of
9531 // the same size. Instead of casting the pointer before the load, cast
9532 // the result of the loaded value.
9533 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
9534 CI->getName(),
9535 LI.isVolatile()),LI);
9536 // Now cast the result of the load.
9537 return new BitCastInst(NewLoad, LI.getType());
9538 }
9539 }
9540 }
9541 return 0;
9542}
9543
9544/// isSafeToLoadUnconditionally - Return true if we know that executing a load
9545/// from this value cannot trap. If it is not obviously safe to load from the
9546/// specified pointer, we do a quick local scan of the basic block containing
9547/// ScanFrom, to determine if the address is already accessed.
9548static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands9b27dbe2007-09-19 10:10:31 +00009549 // If it is an alloca it is always safe to load from.
9550 if (isa<AllocaInst>(V)) return true;
9551
Duncan Sandse40a94a2007-09-19 10:25:38 +00009552 // If it is a global variable it is mostly safe to load from.
Duncan Sands9b27dbe2007-09-19 10:10:31 +00009553 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sandse40a94a2007-09-19 10:25:38 +00009554 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands9b27dbe2007-09-19 10:10:31 +00009555 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009556
9557 // Otherwise, be a little bit agressive by scanning the local block where we
9558 // want to check to see if the pointer is already being loaded or stored
9559 // from/to. If so, the previous load or store would have already trapped,
9560 // so there is no harm doing an extra load (also, CSE will later eliminate
9561 // the load entirely).
9562 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
9563
9564 while (BBI != E) {
9565 --BBI;
9566
9567 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
9568 if (LI->getOperand(0) == V) return true;
9569 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9570 if (SI->getOperand(1) == V) return true;
9571
9572 }
9573 return false;
9574}
9575
Chris Lattner0270a112007-08-11 18:48:48 +00009576/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
9577/// until we find the underlying object a pointer is referring to or something
9578/// we don't understand. Note that the returned pointer may be offset from the
9579/// input, because we ignore GEP indices.
9580static Value *GetUnderlyingObject(Value *Ptr) {
9581 while (1) {
9582 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
9583 if (CE->getOpcode() == Instruction::BitCast ||
9584 CE->getOpcode() == Instruction::GetElementPtr)
9585 Ptr = CE->getOperand(0);
9586 else
9587 return Ptr;
9588 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
9589 Ptr = BCI->getOperand(0);
9590 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
9591 Ptr = GEP->getOperand(0);
9592 } else {
9593 return Ptr;
9594 }
9595 }
9596}
9597
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009598Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
9599 Value *Op = LI.getOperand(0);
9600
Dan Gohman5c4d0e12007-07-20 16:34:21 +00009601 // Attempt to improve the alignment.
Chris Lattner47cf3452007-08-09 19:05:49 +00009602 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op, TD);
Dan Gohman5c4d0e12007-07-20 16:34:21 +00009603 if (KnownAlign > LI.getAlignment())
9604 LI.setAlignment(KnownAlign);
9605
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009606 // load (cast X) --> cast (load X) iff safe
9607 if (isa<CastInst>(Op))
Devang Patela0f8ea82007-10-18 19:52:32 +00009608 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009609 return Res;
9610
9611 // None of the following transforms are legal for volatile loads.
9612 if (LI.isVolatile()) return 0;
9613
9614 if (&LI.getParent()->front() != &LI) {
9615 BasicBlock::iterator BBI = &LI; --BBI;
9616 // If the instruction immediately before this is a store to the same
9617 // address, do a simple form of store->load forwarding.
9618 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
9619 if (SI->getOperand(1) == LI.getOperand(0))
9620 return ReplaceInstUsesWith(LI, SI->getOperand(0));
9621 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
9622 if (LIB->getOperand(0) == LI.getOperand(0))
9623 return ReplaceInstUsesWith(LI, LIB);
9624 }
9625
Christopher Lamb2c175392007-12-29 07:56:53 +00009626 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
9627 const Value *GEPI0 = GEPI->getOperand(0);
9628 // TODO: Consider a target hook for valid address spaces for this xform.
9629 if (isa<ConstantPointerNull>(GEPI0) &&
9630 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009631 // Insert a new store to null instruction before the load to indicate
9632 // that this code is not reachable. We do this instead of inserting
9633 // an unreachable instruction directly because we cannot modify the
9634 // CFG.
9635 new StoreInst(UndefValue::get(LI.getType()),
9636 Constant::getNullValue(Op->getType()), &LI);
9637 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9638 }
Christopher Lamb2c175392007-12-29 07:56:53 +00009639 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009640
9641 if (Constant *C = dyn_cast<Constant>(Op)) {
9642 // load null/undef -> undef
Christopher Lamb2c175392007-12-29 07:56:53 +00009643 // TODO: Consider a target hook for valid address spaces for this xform.
9644 if (isa<UndefValue>(C) || (C->isNullValue() &&
9645 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009646 // Insert a new store to null instruction before the load to indicate that
9647 // this code is not reachable. We do this instead of inserting an
9648 // unreachable instruction directly because we cannot modify the CFG.
9649 new StoreInst(UndefValue::get(LI.getType()),
9650 Constant::getNullValue(Op->getType()), &LI);
9651 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9652 }
9653
9654 // Instcombine load (constant global) into the value loaded.
9655 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
9656 if (GV->isConstant() && !GV->isDeclaration())
9657 return ReplaceInstUsesWith(LI, GV->getInitializer());
9658
9659 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
9660 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
9661 if (CE->getOpcode() == Instruction::GetElementPtr) {
9662 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
9663 if (GV->isConstant() && !GV->isDeclaration())
9664 if (Constant *V =
9665 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
9666 return ReplaceInstUsesWith(LI, V);
9667 if (CE->getOperand(0)->isNullValue()) {
9668 // Insert a new store to null instruction before the load to indicate
9669 // that this code is not reachable. We do this instead of inserting
9670 // an unreachable instruction directly because we cannot modify the
9671 // CFG.
9672 new StoreInst(UndefValue::get(LI.getType()),
9673 Constant::getNullValue(Op->getType()), &LI);
9674 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9675 }
9676
9677 } else if (CE->isCast()) {
Devang Patela0f8ea82007-10-18 19:52:32 +00009678 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009679 return Res;
9680 }
9681 }
Chris Lattner0270a112007-08-11 18:48:48 +00009682
9683 // If this load comes from anywhere in a constant global, and if the global
9684 // is all undef or zero, we know what it loads.
9685 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
9686 if (GV->isConstant() && GV->hasInitializer()) {
9687 if (GV->getInitializer()->isNullValue())
9688 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
9689 else if (isa<UndefValue>(GV->getInitializer()))
9690 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
9691 }
9692 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009693
9694 if (Op->hasOneUse()) {
9695 // Change select and PHI nodes to select values instead of addresses: this
9696 // helps alias analysis out a lot, allows many others simplifications, and
9697 // exposes redundancy in the code.
9698 //
9699 // Note that we cannot do the transformation unless we know that the
9700 // introduced loads cannot trap! Something like this is valid as long as
9701 // the condition is always false: load (select bool %C, int* null, int* %G),
9702 // but it would not be valid if we transformed it to load from null
9703 // unconditionally.
9704 //
9705 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
9706 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
9707 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
9708 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
9709 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
9710 SI->getOperand(1)->getName()+".val"), LI);
9711 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
9712 SI->getOperand(2)->getName()+".val"), LI);
9713 return new SelectInst(SI->getCondition(), V1, V2);
9714 }
9715
9716 // load (select (cond, null, P)) -> load P
9717 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
9718 if (C->isNullValue()) {
9719 LI.setOperand(0, SI->getOperand(2));
9720 return &LI;
9721 }
9722
9723 // load (select (cond, P, null)) -> load P
9724 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
9725 if (C->isNullValue()) {
9726 LI.setOperand(0, SI->getOperand(1));
9727 return &LI;
9728 }
9729 }
9730 }
9731 return 0;
9732}
9733
9734/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
9735/// when possible.
9736static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
9737 User *CI = cast<User>(SI.getOperand(1));
9738 Value *CastOp = CI->getOperand(0);
9739
9740 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
9741 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
9742 const Type *SrcPTy = SrcTy->getElementType();
9743
9744 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
9745 // If the source is an array, the code below will not succeed. Check to
9746 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
9747 // constants.
9748 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
9749 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
9750 if (ASrcTy->getNumElements() != 0) {
9751 Value* Idxs[2];
9752 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
9753 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
9754 SrcTy = cast<PointerType>(CastOp->getType());
9755 SrcPTy = SrcTy->getElementType();
9756 }
9757
9758 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
9759 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
9760 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
9761
9762 // Okay, we are casting from one integer or pointer type to another of
9763 // the same size. Instead of casting the pointer before
9764 // the store, cast the value to be stored.
9765 Value *NewCast;
9766 Value *SIOp0 = SI.getOperand(0);
9767 Instruction::CastOps opcode = Instruction::BitCast;
9768 const Type* CastSrcTy = SIOp0->getType();
9769 const Type* CastDstTy = SrcPTy;
9770 if (isa<PointerType>(CastDstTy)) {
9771 if (CastSrcTy->isInteger())
9772 opcode = Instruction::IntToPtr;
9773 } else if (isa<IntegerType>(CastDstTy)) {
9774 if (isa<PointerType>(SIOp0->getType()))
9775 opcode = Instruction::PtrToInt;
9776 }
9777 if (Constant *C = dyn_cast<Constant>(SIOp0))
9778 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
9779 else
9780 NewCast = IC.InsertNewInstBefore(
9781 CastInst::create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
9782 SI);
9783 return new StoreInst(NewCast, CastOp);
9784 }
9785 }
9786 }
9787 return 0;
9788}
9789
9790Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
9791 Value *Val = SI.getOperand(0);
9792 Value *Ptr = SI.getOperand(1);
9793
9794 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
9795 EraseInstFromFunction(SI);
9796 ++NumCombined;
9797 return 0;
9798 }
9799
9800 // If the RHS is an alloca with a single use, zapify the store, making the
9801 // alloca dead.
9802 if (Ptr->hasOneUse()) {
9803 if (isa<AllocaInst>(Ptr)) {
9804 EraseInstFromFunction(SI);
9805 ++NumCombined;
9806 return 0;
9807 }
9808
9809 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
9810 if (isa<AllocaInst>(GEP->getOperand(0)) &&
9811 GEP->getOperand(0)->hasOneUse()) {
9812 EraseInstFromFunction(SI);
9813 ++NumCombined;
9814 return 0;
9815 }
9816 }
9817
Dan Gohman5c4d0e12007-07-20 16:34:21 +00009818 // Attempt to improve the alignment.
Chris Lattner47cf3452007-08-09 19:05:49 +00009819 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr, TD);
Dan Gohman5c4d0e12007-07-20 16:34:21 +00009820 if (KnownAlign > SI.getAlignment())
9821 SI.setAlignment(KnownAlign);
9822
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009823 // Do really simple DSE, to catch cases where there are several consequtive
9824 // stores to the same location, separated by a few arithmetic operations. This
9825 // situation often occurs with bitfield accesses.
9826 BasicBlock::iterator BBI = &SI;
9827 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
9828 --ScanInsts) {
9829 --BBI;
9830
9831 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
9832 // Prev store isn't volatile, and stores to the same location?
9833 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
9834 ++NumDeadStore;
9835 ++BBI;
9836 EraseInstFromFunction(*PrevSI);
9837 continue;
9838 }
9839 break;
9840 }
9841
9842 // If this is a load, we have to stop. However, if the loaded value is from
9843 // the pointer we're loading and is producing the pointer we're storing,
9844 // then *this* store is dead (X = load P; store X -> P).
9845 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattner24905f72007-09-07 05:33:03 +00009846 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009847 EraseInstFromFunction(SI);
9848 ++NumCombined;
9849 return 0;
9850 }
9851 // Otherwise, this is a load from some other location. Stores before it
9852 // may not be dead.
9853 break;
9854 }
9855
9856 // Don't skip over loads or things that can modify memory.
9857 if (BBI->mayWriteToMemory())
9858 break;
9859 }
9860
9861
9862 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
9863
9864 // store X, null -> turns into 'unreachable' in SimplifyCFG
9865 if (isa<ConstantPointerNull>(Ptr)) {
9866 if (!isa<UndefValue>(Val)) {
9867 SI.setOperand(0, UndefValue::get(Val->getType()));
9868 if (Instruction *U = dyn_cast<Instruction>(Val))
9869 AddToWorkList(U); // Dropped a use.
9870 ++NumCombined;
9871 }
9872 return 0; // Do not modify these!
9873 }
9874
9875 // store undef, Ptr -> noop
9876 if (isa<UndefValue>(Val)) {
9877 EraseInstFromFunction(SI);
9878 ++NumCombined;
9879 return 0;
9880 }
9881
9882 // If the pointer destination is a cast, see if we can fold the cast into the
9883 // source instead.
9884 if (isa<CastInst>(Ptr))
9885 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9886 return Res;
9887 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
9888 if (CE->isCast())
9889 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
9890 return Res;
9891
9892
9893 // If this store is the last instruction in the basic block, and if the block
9894 // ends with an unconditional branch, try to move it to the successor block.
9895 BBI = &SI; ++BBI;
9896 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
9897 if (BI->isUnconditional())
9898 if (SimplifyStoreAtEndOfBlock(SI))
9899 return 0; // xform done!
9900
9901 return 0;
9902}
9903
9904/// SimplifyStoreAtEndOfBlock - Turn things like:
9905/// if () { *P = v1; } else { *P = v2 }
9906/// into a phi node with a store in the successor.
9907///
9908/// Simplify things like:
9909/// *P = v1; if () { *P = v2; }
9910/// into a phi node with a store in the successor.
9911///
9912bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
9913 BasicBlock *StoreBB = SI.getParent();
9914
9915 // Check to see if the successor block has exactly two incoming edges. If
9916 // so, see if the other predecessor contains a store to the same location.
9917 // if so, insert a PHI node (if needed) and move the stores down.
9918 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
9919
9920 // Determine whether Dest has exactly two predecessors and, if so, compute
9921 // the other predecessor.
9922 pred_iterator PI = pred_begin(DestBB);
9923 BasicBlock *OtherBB = 0;
9924 if (*PI != StoreBB)
9925 OtherBB = *PI;
9926 ++PI;
9927 if (PI == pred_end(DestBB))
9928 return false;
9929
9930 if (*PI != StoreBB) {
9931 if (OtherBB)
9932 return false;
9933 OtherBB = *PI;
9934 }
9935 if (++PI != pred_end(DestBB))
9936 return false;
9937
9938
9939 // Verify that the other block ends in a branch and is not otherwise empty.
9940 BasicBlock::iterator BBI = OtherBB->getTerminator();
9941 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
9942 if (!OtherBr || BBI == OtherBB->begin())
9943 return false;
9944
9945 // If the other block ends in an unconditional branch, check for the 'if then
9946 // else' case. there is an instruction before the branch.
9947 StoreInst *OtherStore = 0;
9948 if (OtherBr->isUnconditional()) {
9949 // If this isn't a store, or isn't a store to the same location, bail out.
9950 --BBI;
9951 OtherStore = dyn_cast<StoreInst>(BBI);
9952 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
9953 return false;
9954 } else {
9955 // Otherwise, the other block ended with a conditional branch. If one of the
9956 // destinations is StoreBB, then we have the if/then case.
9957 if (OtherBr->getSuccessor(0) != StoreBB &&
9958 OtherBr->getSuccessor(1) != StoreBB)
9959 return false;
9960
9961 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
9962 // if/then triangle. See if there is a store to the same ptr as SI that
9963 // lives in OtherBB.
9964 for (;; --BBI) {
9965 // Check to see if we find the matching store.
9966 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
9967 if (OtherStore->getOperand(1) != SI.getOperand(1))
9968 return false;
9969 break;
9970 }
9971 // If we find something that may be using the stored value, or if we run
9972 // out of instructions, we can't do the xform.
9973 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
9974 BBI == OtherBB->begin())
9975 return false;
9976 }
9977
9978 // In order to eliminate the store in OtherBr, we have to
9979 // make sure nothing reads the stored value in StoreBB.
9980 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
9981 // FIXME: This should really be AA driven.
9982 if (isa<LoadInst>(I) || I->mayWriteToMemory())
9983 return false;
9984 }
9985 }
9986
9987 // Insert a PHI node now if we need it.
9988 Value *MergedVal = OtherStore->getOperand(0);
9989 if (MergedVal != SI.getOperand(0)) {
9990 PHINode *PN = new PHINode(MergedVal->getType(), "storemerge");
9991 PN->reserveOperandSpace(2);
9992 PN->addIncoming(SI.getOperand(0), SI.getParent());
9993 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
9994 MergedVal = InsertNewInstBefore(PN, DestBB->front());
9995 }
9996
9997 // Advance to a place where it is safe to insert the new store and
9998 // insert it.
9999 BBI = DestBB->begin();
10000 while (isa<PHINode>(BBI)) ++BBI;
10001 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10002 OtherStore->isVolatile()), *BBI);
10003
10004 // Nuke the old stores.
10005 EraseInstFromFunction(SI);
10006 EraseInstFromFunction(*OtherStore);
10007 ++NumCombined;
10008 return true;
10009}
10010
10011
10012Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10013 // Change br (not X), label True, label False to: br X, label False, True
10014 Value *X = 0;
10015 BasicBlock *TrueDest;
10016 BasicBlock *FalseDest;
10017 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10018 !isa<Constant>(X)) {
10019 // Swap Destinations and condition...
10020 BI.setCondition(X);
10021 BI.setSuccessor(0, FalseDest);
10022 BI.setSuccessor(1, TrueDest);
10023 return &BI;
10024 }
10025
10026 // Cannonicalize fcmp_one -> fcmp_oeq
10027 FCmpInst::Predicate FPred; Value *Y;
10028 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10029 TrueDest, FalseDest)))
10030 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10031 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10032 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
10033 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
10034 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10035 NewSCC->takeName(I);
10036 // Swap Destinations and condition...
10037 BI.setCondition(NewSCC);
10038 BI.setSuccessor(0, FalseDest);
10039 BI.setSuccessor(1, TrueDest);
10040 RemoveFromWorkList(I);
10041 I->eraseFromParent();
10042 AddToWorkList(NewSCC);
10043 return &BI;
10044 }
10045
10046 // Cannonicalize icmp_ne -> icmp_eq
10047 ICmpInst::Predicate IPred;
10048 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10049 TrueDest, FalseDest)))
10050 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10051 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10052 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10053 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
10054 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
10055 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10056 NewSCC->takeName(I);
10057 // Swap Destinations and condition...
10058 BI.setCondition(NewSCC);
10059 BI.setSuccessor(0, FalseDest);
10060 BI.setSuccessor(1, TrueDest);
10061 RemoveFromWorkList(I);
10062 I->eraseFromParent();;
10063 AddToWorkList(NewSCC);
10064 return &BI;
10065 }
10066
10067 return 0;
10068}
10069
10070Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10071 Value *Cond = SI.getCondition();
10072 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10073 if (I->getOpcode() == Instruction::Add)
10074 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10075 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10076 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
10077 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
10078 AddRHS));
10079 SI.setOperand(0, I->getOperand(0));
10080 AddToWorkList(I);
10081 return &SI;
10082 }
10083 }
10084 return 0;
10085}
10086
10087/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10088/// is to leave as a vector operation.
10089static bool CheapToScalarize(Value *V, bool isConstant) {
10090 if (isa<ConstantAggregateZero>(V))
10091 return true;
10092 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
10093 if (isConstant) return true;
10094 // If all elts are the same, we can extract.
10095 Constant *Op0 = C->getOperand(0);
10096 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10097 if (C->getOperand(i) != Op0)
10098 return false;
10099 return true;
10100 }
10101 Instruction *I = dyn_cast<Instruction>(V);
10102 if (!I) return false;
10103
10104 // Insert element gets simplified to the inserted element or is deleted if
10105 // this is constant idx extract element and its a constant idx insertelt.
10106 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10107 isa<ConstantInt>(I->getOperand(2)))
10108 return true;
10109 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10110 return true;
10111 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10112 if (BO->hasOneUse() &&
10113 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10114 CheapToScalarize(BO->getOperand(1), isConstant)))
10115 return true;
10116 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10117 if (CI->hasOneUse() &&
10118 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10119 CheapToScalarize(CI->getOperand(1), isConstant)))
10120 return true;
10121
10122 return false;
10123}
10124
10125/// Read and decode a shufflevector mask.
10126///
10127/// It turns undef elements into values that are larger than the number of
10128/// elements in the input.
10129static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10130 unsigned NElts = SVI->getType()->getNumElements();
10131 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10132 return std::vector<unsigned>(NElts, 0);
10133 if (isa<UndefValue>(SVI->getOperand(2)))
10134 return std::vector<unsigned>(NElts, 2*NElts);
10135
10136 std::vector<unsigned> Result;
10137 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
10138 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10139 if (isa<UndefValue>(CP->getOperand(i)))
10140 Result.push_back(NElts*2); // undef -> 8
10141 else
10142 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
10143 return Result;
10144}
10145
10146/// FindScalarElement - Given a vector and an element number, see if the scalar
10147/// value is already around as a register, for example if it were inserted then
10148/// extracted from the vector.
10149static Value *FindScalarElement(Value *V, unsigned EltNo) {
10150 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10151 const VectorType *PTy = cast<VectorType>(V->getType());
10152 unsigned Width = PTy->getNumElements();
10153 if (EltNo >= Width) // Out of range access.
10154 return UndefValue::get(PTy->getElementType());
10155
10156 if (isa<UndefValue>(V))
10157 return UndefValue::get(PTy->getElementType());
10158 else if (isa<ConstantAggregateZero>(V))
10159 return Constant::getNullValue(PTy->getElementType());
10160 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
10161 return CP->getOperand(EltNo);
10162 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10163 // If this is an insert to a variable element, we don't know what it is.
10164 if (!isa<ConstantInt>(III->getOperand(2)))
10165 return 0;
10166 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
10167
10168 // If this is an insert to the element we are looking for, return the
10169 // inserted value.
10170 if (EltNo == IIElt)
10171 return III->getOperand(1);
10172
10173 // Otherwise, the insertelement doesn't modify the value, recurse on its
10174 // vector input.
10175 return FindScalarElement(III->getOperand(0), EltNo);
10176 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
10177 unsigned InEl = getShuffleMask(SVI)[EltNo];
10178 if (InEl < Width)
10179 return FindScalarElement(SVI->getOperand(0), InEl);
10180 else if (InEl < Width*2)
10181 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10182 else
10183 return UndefValue::get(PTy->getElementType());
10184 }
10185
10186 // Otherwise, we don't know.
10187 return 0;
10188}
10189
10190Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
10191
10192 // If vector val is undef, replace extract with scalar undef.
10193 if (isa<UndefValue>(EI.getOperand(0)))
10194 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10195
10196 // If vector val is constant 0, replace extract with scalar 0.
10197 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10198 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10199
10200 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
10201 // If vector val is constant with uniform operands, replace EI
10202 // with that operand
10203 Constant *op0 = C->getOperand(0);
10204 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10205 if (C->getOperand(i) != op0) {
10206 op0 = 0;
10207 break;
10208 }
10209 if (op0)
10210 return ReplaceInstUsesWith(EI, op0);
10211 }
10212
10213 // If extracting a specified index from the vector, see if we can recursively
10214 // find a previously computed scalar that was inserted into the vector.
10215 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10216 unsigned IndexVal = IdxC->getZExtValue();
10217 unsigned VectorWidth =
10218 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10219
10220 // If this is extracting an invalid index, turn this into undef, to avoid
10221 // crashing the code below.
10222 if (IndexVal >= VectorWidth)
10223 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10224
10225 // This instruction only demands the single element from the input vector.
10226 // If the input vector has a single use, simplify it based on this use
10227 // property.
10228 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
10229 uint64_t UndefElts;
10230 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
10231 1 << IndexVal,
10232 UndefElts)) {
10233 EI.setOperand(0, V);
10234 return &EI;
10235 }
10236 }
10237
10238 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
10239 return ReplaceInstUsesWith(EI, Elt);
10240
10241 // If the this extractelement is directly using a bitcast from a vector of
10242 // the same number of elements, see if we can find the source element from
10243 // it. In this case, we will end up needing to bitcast the scalars.
10244 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10245 if (const VectorType *VT =
10246 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10247 if (VT->getNumElements() == VectorWidth)
10248 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10249 return new BitCastInst(Elt, EI.getType());
10250 }
10251 }
10252
10253 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
10254 if (I->hasOneUse()) {
10255 // Push extractelement into predecessor operation if legal and
10256 // profitable to do so
10257 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
10258 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10259 if (CheapToScalarize(BO, isConstantElt)) {
10260 ExtractElementInst *newEI0 =
10261 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10262 EI.getName()+".lhs");
10263 ExtractElementInst *newEI1 =
10264 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10265 EI.getName()+".rhs");
10266 InsertNewInstBefore(newEI0, EI);
10267 InsertNewInstBefore(newEI1, EI);
10268 return BinaryOperator::create(BO->getOpcode(), newEI0, newEI1);
10269 }
10270 } else if (isa<LoadInst>(I)) {
Christopher Lambbb2f2222007-12-17 01:12:55 +000010271 unsigned AS =
10272 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +000010273 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10274 PointerType::get(EI.getType(), AS),EI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010275 GetElementPtrInst *GEP =
10276 new GetElementPtrInst(Ptr, EI.getOperand(1), I->getName() + ".gep");
10277 InsertNewInstBefore(GEP, EI);
10278 return new LoadInst(GEP);
10279 }
10280 }
10281 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10282 // Extracting the inserted element?
10283 if (IE->getOperand(2) == EI.getOperand(1))
10284 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10285 // If the inserted and extracted elements are constants, they must not
10286 // be the same value, extract from the pre-inserted value instead.
10287 if (isa<Constant>(IE->getOperand(2)) &&
10288 isa<Constant>(EI.getOperand(1))) {
10289 AddUsesToWorkList(EI);
10290 EI.setOperand(0, IE->getOperand(0));
10291 return &EI;
10292 }
10293 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10294 // If this is extracting an element from a shufflevector, figure out where
10295 // it came from and extract from the appropriate input element instead.
10296 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10297 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
10298 Value *Src;
10299 if (SrcIdx < SVI->getType()->getNumElements())
10300 Src = SVI->getOperand(0);
10301 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10302 SrcIdx -= SVI->getType()->getNumElements();
10303 Src = SVI->getOperand(1);
10304 } else {
10305 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10306 }
10307 return new ExtractElementInst(Src, SrcIdx);
10308 }
10309 }
10310 }
10311 return 0;
10312}
10313
10314/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10315/// elements from either LHS or RHS, return the shuffle mask and true.
10316/// Otherwise, return false.
10317static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10318 std::vector<Constant*> &Mask) {
10319 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10320 "Invalid CollectSingleShuffleElements");
10321 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10322
10323 if (isa<UndefValue>(V)) {
10324 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10325 return true;
10326 } else if (V == LHS) {
10327 for (unsigned i = 0; i != NumElts; ++i)
10328 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10329 return true;
10330 } else if (V == RHS) {
10331 for (unsigned i = 0; i != NumElts; ++i)
10332 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
10333 return true;
10334 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10335 // If this is an insert of an extract from some other vector, include it.
10336 Value *VecOp = IEI->getOperand(0);
10337 Value *ScalarOp = IEI->getOperand(1);
10338 Value *IdxOp = IEI->getOperand(2);
10339
10340 if (!isa<ConstantInt>(IdxOp))
10341 return false;
10342 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10343
10344 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10345 // Okay, we can handle this if the vector we are insertinting into is
10346 // transitively ok.
10347 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10348 // If so, update the mask to reflect the inserted undef.
10349 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
10350 return true;
10351 }
10352 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10353 if (isa<ConstantInt>(EI->getOperand(1)) &&
10354 EI->getOperand(0)->getType() == V->getType()) {
10355 unsigned ExtractedIdx =
10356 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10357
10358 // This must be extracting from either LHS or RHS.
10359 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10360 // Okay, we can handle this if the vector we are insertinting into is
10361 // transitively ok.
10362 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10363 // If so, update the mask to reflect the inserted value.
10364 if (EI->getOperand(0) == LHS) {
10365 Mask[InsertedIdx & (NumElts-1)] =
10366 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10367 } else {
10368 assert(EI->getOperand(0) == RHS);
10369 Mask[InsertedIdx & (NumElts-1)] =
10370 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
10371
10372 }
10373 return true;
10374 }
10375 }
10376 }
10377 }
10378 }
10379 // TODO: Handle shufflevector here!
10380
10381 return false;
10382}
10383
10384/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10385/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10386/// that computes V and the LHS value of the shuffle.
10387static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
10388 Value *&RHS) {
10389 assert(isa<VectorType>(V->getType()) &&
10390 (RHS == 0 || V->getType() == RHS->getType()) &&
10391 "Invalid shuffle!");
10392 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10393
10394 if (isa<UndefValue>(V)) {
10395 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10396 return V;
10397 } else if (isa<ConstantAggregateZero>(V)) {
10398 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
10399 return V;
10400 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10401 // If this is an insert of an extract from some other vector, include it.
10402 Value *VecOp = IEI->getOperand(0);
10403 Value *ScalarOp = IEI->getOperand(1);
10404 Value *IdxOp = IEI->getOperand(2);
10405
10406 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10407 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10408 EI->getOperand(0)->getType() == V->getType()) {
10409 unsigned ExtractedIdx =
10410 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10411 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10412
10413 // Either the extracted from or inserted into vector must be RHSVec,
10414 // otherwise we'd end up with a shuffle of three inputs.
10415 if (EI->getOperand(0) == RHS || RHS == 0) {
10416 RHS = EI->getOperand(0);
10417 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
10418 Mask[InsertedIdx & (NumElts-1)] =
10419 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
10420 return V;
10421 }
10422
10423 if (VecOp == RHS) {
10424 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
10425 // Everything but the extracted element is replaced with the RHS.
10426 for (unsigned i = 0; i != NumElts; ++i) {
10427 if (i != InsertedIdx)
10428 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
10429 }
10430 return V;
10431 }
10432
10433 // If this insertelement is a chain that comes from exactly these two
10434 // vectors, return the vector and the effective shuffle.
10435 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
10436 return EI->getOperand(0);
10437
10438 }
10439 }
10440 }
10441 // TODO: Handle shufflevector here!
10442
10443 // Otherwise, can't do anything fancy. Return an identity vector.
10444 for (unsigned i = 0; i != NumElts; ++i)
10445 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10446 return V;
10447}
10448
10449Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
10450 Value *VecOp = IE.getOperand(0);
10451 Value *ScalarOp = IE.getOperand(1);
10452 Value *IdxOp = IE.getOperand(2);
10453
10454 // Inserting an undef or into an undefined place, remove this.
10455 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
10456 ReplaceInstUsesWith(IE, VecOp);
10457
10458 // If the inserted element was extracted from some other vector, and if the
10459 // indexes are constant, try to turn this into a shufflevector operation.
10460 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
10461 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
10462 EI->getOperand(0)->getType() == IE.getType()) {
10463 unsigned NumVectorElts = IE.getType()->getNumElements();
10464 unsigned ExtractedIdx =
10465 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10466 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10467
10468 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
10469 return ReplaceInstUsesWith(IE, VecOp);
10470
10471 if (InsertedIdx >= NumVectorElts) // Out of range insert.
10472 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
10473
10474 // If we are extracting a value from a vector, then inserting it right
10475 // back into the same place, just use the input vector.
10476 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
10477 return ReplaceInstUsesWith(IE, VecOp);
10478
10479 // We could theoretically do this for ANY input. However, doing so could
10480 // turn chains of insertelement instructions into a chain of shufflevector
10481 // instructions, and right now we do not merge shufflevectors. As such,
10482 // only do this in a situation where it is clear that there is benefit.
10483 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
10484 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
10485 // the values of VecOp, except then one read from EIOp0.
10486 // Build a new shuffle mask.
10487 std::vector<Constant*> Mask;
10488 if (isa<UndefValue>(VecOp))
10489 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
10490 else {
10491 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
10492 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
10493 NumVectorElts));
10494 }
10495 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10496 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
10497 ConstantVector::get(Mask));
10498 }
10499
10500 // If this insertelement isn't used by some other insertelement, turn it
10501 // (and any insertelements it points to), into one big shuffle.
10502 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
10503 std::vector<Constant*> Mask;
10504 Value *RHS = 0;
10505 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
10506 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
10507 // We now have a shuffle of LHS, RHS, Mask.
10508 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
10509 }
10510 }
10511 }
10512
10513 return 0;
10514}
10515
10516
10517Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
10518 Value *LHS = SVI.getOperand(0);
10519 Value *RHS = SVI.getOperand(1);
10520 std::vector<unsigned> Mask = getShuffleMask(&SVI);
10521
10522 bool MadeChange = false;
10523
10524 // Undefined shuffle mask -> undefined value.
10525 if (isa<UndefValue>(SVI.getOperand(2)))
10526 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
10527
10528 // If we have shuffle(x, undef, mask) and any elements of mask refer to
10529 // the undef, change them to undefs.
10530 if (isa<UndefValue>(SVI.getOperand(1))) {
10531 // Scan to see if there are any references to the RHS. If so, replace them
10532 // with undef element refs and set MadeChange to true.
10533 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10534 if (Mask[i] >= e && Mask[i] != 2*e) {
10535 Mask[i] = 2*e;
10536 MadeChange = true;
10537 }
10538 }
10539
10540 if (MadeChange) {
10541 // Remap any references to RHS to use LHS.
10542 std::vector<Constant*> Elts;
10543 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10544 if (Mask[i] == 2*e)
10545 Elts.push_back(UndefValue::get(Type::Int32Ty));
10546 else
10547 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10548 }
10549 SVI.setOperand(2, ConstantVector::get(Elts));
10550 }
10551 }
10552
10553 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
10554 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
10555 if (LHS == RHS || isa<UndefValue>(LHS)) {
10556 if (isa<UndefValue>(LHS) && LHS == RHS) {
10557 // shuffle(undef,undef,mask) -> undef.
10558 return ReplaceInstUsesWith(SVI, LHS);
10559 }
10560
10561 // Remap any references to RHS to use LHS.
10562 std::vector<Constant*> Elts;
10563 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10564 if (Mask[i] >= 2*e)
10565 Elts.push_back(UndefValue::get(Type::Int32Ty));
10566 else {
10567 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
10568 (Mask[i] < e && isa<UndefValue>(LHS)))
10569 Mask[i] = 2*e; // Turn into undef.
10570 else
10571 Mask[i] &= (e-1); // Force to LHS.
10572 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
10573 }
10574 }
10575 SVI.setOperand(0, SVI.getOperand(1));
10576 SVI.setOperand(1, UndefValue::get(RHS->getType()));
10577 SVI.setOperand(2, ConstantVector::get(Elts));
10578 LHS = SVI.getOperand(0);
10579 RHS = SVI.getOperand(1);
10580 MadeChange = true;
10581 }
10582
10583 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
10584 bool isLHSID = true, isRHSID = true;
10585
10586 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
10587 if (Mask[i] >= e*2) continue; // Ignore undef values.
10588 // Is this an identity shuffle of the LHS value?
10589 isLHSID &= (Mask[i] == i);
10590
10591 // Is this an identity shuffle of the RHS value?
10592 isRHSID &= (Mask[i]-e == i);
10593 }
10594
10595 // Eliminate identity shuffles.
10596 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
10597 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
10598
10599 // If the LHS is a shufflevector itself, see if we can combine it with this
10600 // one without producing an unusual shuffle. Here we are really conservative:
10601 // we are absolutely afraid of producing a shuffle mask not in the input
10602 // program, because the code gen may not be smart enough to turn a merged
10603 // shuffle into two specific shuffles: it may produce worse code. As such,
10604 // we only merge two shuffles if the result is one of the two input shuffle
10605 // masks. In this case, merging the shuffles just removes one instruction,
10606 // which we know is safe. This is good for things like turning:
10607 // (splat(splat)) -> splat.
10608 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
10609 if (isa<UndefValue>(RHS)) {
10610 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
10611
10612 std::vector<unsigned> NewMask;
10613 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
10614 if (Mask[i] >= 2*e)
10615 NewMask.push_back(2*e);
10616 else
10617 NewMask.push_back(LHSMask[Mask[i]]);
10618
10619 // If the result mask is equal to the src shuffle or this shuffle mask, do
10620 // the replacement.
10621 if (NewMask == LHSMask || NewMask == Mask) {
10622 std::vector<Constant*> Elts;
10623 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
10624 if (NewMask[i] >= e*2) {
10625 Elts.push_back(UndefValue::get(Type::Int32Ty));
10626 } else {
10627 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
10628 }
10629 }
10630 return new ShuffleVectorInst(LHSSVI->getOperand(0),
10631 LHSSVI->getOperand(1),
10632 ConstantVector::get(Elts));
10633 }
10634 }
10635 }
10636
10637 return MadeChange ? &SVI : 0;
10638}
10639
10640
10641
10642
10643/// TryToSinkInstruction - Try to move the specified instruction from its
10644/// current block into the beginning of DestBlock, which can only happen if it's
10645/// safe to move the instruction past all of the instructions between it and the
10646/// end of its block.
10647static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
10648 assert(I->hasOneUse() && "Invariants didn't hold!");
10649
10650 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
10651 if (isa<PHINode>(I) || I->mayWriteToMemory()) return false;
10652
10653 // Do not sink alloca instructions out of the entry block.
10654 if (isa<AllocaInst>(I) && I->getParent() ==
10655 &DestBlock->getParent()->getEntryBlock())
10656 return false;
10657
10658 // We can only sink load instructions if there is nothing between the load and
10659 // the end of block that could change the value.
10660 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10661 for (BasicBlock::iterator Scan = LI, E = LI->getParent()->end();
10662 Scan != E; ++Scan)
10663 if (Scan->mayWriteToMemory())
10664 return false;
10665 }
10666
10667 BasicBlock::iterator InsertPos = DestBlock->begin();
10668 while (isa<PHINode>(InsertPos)) ++InsertPos;
10669
10670 I->moveBefore(InsertPos);
10671 ++NumSunkInst;
10672 return true;
10673}
10674
10675
10676/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
10677/// all reachable code to the worklist.
10678///
10679/// This has a couple of tricks to make the code faster and more powerful. In
10680/// particular, we constant fold and DCE instructions as we go, to avoid adding
10681/// them to the worklist (this significantly speeds up instcombine on code where
10682/// many instructions are dead or constant). Additionally, if we find a branch
10683/// whose condition is a known constant, we only visit the reachable successors.
10684///
10685static void AddReachableCodeToWorklist(BasicBlock *BB,
10686 SmallPtrSet<BasicBlock*, 64> &Visited,
10687 InstCombiner &IC,
10688 const TargetData *TD) {
10689 std::vector<BasicBlock*> Worklist;
10690 Worklist.push_back(BB);
10691
10692 while (!Worklist.empty()) {
10693 BB = Worklist.back();
10694 Worklist.pop_back();
10695
10696 // We have now visited this block! If we've already been here, ignore it.
10697 if (!Visited.insert(BB)) continue;
10698
10699 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
10700 Instruction *Inst = BBI++;
10701
10702 // DCE instruction if trivially dead.
10703 if (isInstructionTriviallyDead(Inst)) {
10704 ++NumDeadInst;
10705 DOUT << "IC: DCE: " << *Inst;
10706 Inst->eraseFromParent();
10707 continue;
10708 }
10709
10710 // ConstantProp instruction if trivially constant.
10711 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
10712 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
10713 Inst->replaceAllUsesWith(C);
10714 ++NumConstProp;
10715 Inst->eraseFromParent();
10716 continue;
10717 }
Chris Lattnere0f462d2007-07-20 22:06:41 +000010718
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010719 IC.AddToWorkList(Inst);
10720 }
10721
10722 // Recursively visit successors. If this is a branch or switch on a
10723 // constant, only visit the reachable successor.
10724 TerminatorInst *TI = BB->getTerminator();
10725 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
10726 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
10727 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
10728 Worklist.push_back(BI->getSuccessor(!CondVal));
10729 continue;
10730 }
10731 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
10732 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
10733 // See if this is an explicit destination.
10734 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
10735 if (SI->getCaseValue(i) == Cond) {
10736 Worklist.push_back(SI->getSuccessor(i));
10737 continue;
10738 }
10739
10740 // Otherwise it is the default destination.
10741 Worklist.push_back(SI->getSuccessor(0));
10742 continue;
10743 }
10744 }
10745
10746 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
10747 Worklist.push_back(TI->getSuccessor(i));
10748 }
10749}
10750
10751bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
10752 bool Changed = false;
10753 TD = &getAnalysis<TargetData>();
10754
10755 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
10756 << F.getNameStr() << "\n");
10757
10758 {
10759 // Do a depth-first traversal of the function, populate the worklist with
10760 // the reachable instructions. Ignore blocks that are not reachable. Keep
10761 // track of which blocks we visit.
10762 SmallPtrSet<BasicBlock*, 64> Visited;
10763 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
10764
10765 // Do a quick scan over the function. If we find any blocks that are
10766 // unreachable, remove any instructions inside of them. This prevents
10767 // the instcombine code from having to deal with some bad special cases.
10768 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
10769 if (!Visited.count(BB)) {
10770 Instruction *Term = BB->getTerminator();
10771 while (Term != BB->begin()) { // Remove instrs bottom-up
10772 BasicBlock::iterator I = Term; --I;
10773
10774 DOUT << "IC: DCE: " << *I;
10775 ++NumDeadInst;
10776
10777 if (!I->use_empty())
10778 I->replaceAllUsesWith(UndefValue::get(I->getType()));
10779 I->eraseFromParent();
10780 }
10781 }
10782 }
10783
10784 while (!Worklist.empty()) {
10785 Instruction *I = RemoveOneFromWorkList();
10786 if (I == 0) continue; // skip null values.
10787
10788 // Check to see if we can DCE the instruction.
10789 if (isInstructionTriviallyDead(I)) {
10790 // Add operands to the worklist.
10791 if (I->getNumOperands() < 4)
10792 AddUsesToWorkList(*I);
10793 ++NumDeadInst;
10794
10795 DOUT << "IC: DCE: " << *I;
10796
10797 I->eraseFromParent();
10798 RemoveFromWorkList(I);
10799 continue;
10800 }
10801
10802 // Instruction isn't dead, see if we can constant propagate it.
10803 if (Constant *C = ConstantFoldInstruction(I, TD)) {
10804 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
10805
10806 // Add operands to the worklist.
10807 AddUsesToWorkList(*I);
10808 ReplaceInstUsesWith(*I, C);
10809
10810 ++NumConstProp;
10811 I->eraseFromParent();
10812 RemoveFromWorkList(I);
10813 continue;
10814 }
10815
10816 // See if we can trivially sink this instruction to a successor basic block.
10817 if (I->hasOneUse()) {
10818 BasicBlock *BB = I->getParent();
10819 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
10820 if (UserParent != BB) {
10821 bool UserIsSuccessor = false;
10822 // See if the user is one of our successors.
10823 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
10824 if (*SI == UserParent) {
10825 UserIsSuccessor = true;
10826 break;
10827 }
10828
10829 // If the user is one of our immediate successors, and if that successor
10830 // only has us as a predecessors (we'd have to split the critical edge
10831 // otherwise), we can keep going.
10832 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
10833 next(pred_begin(UserParent)) == pred_end(UserParent))
10834 // Okay, the CFG is simple enough, try to sink this instruction.
10835 Changed |= TryToSinkInstruction(I, UserParent);
10836 }
10837 }
10838
10839 // Now that we have an instruction, try combining it to simplify it...
10840#ifndef NDEBUG
10841 std::string OrigI;
10842#endif
10843 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
10844 if (Instruction *Result = visit(*I)) {
10845 ++NumCombined;
10846 // Should we replace the old instruction with a new one?
10847 if (Result != I) {
10848 DOUT << "IC: Old = " << *I
10849 << " New = " << *Result;
10850
10851 // Everything uses the new instruction now.
10852 I->replaceAllUsesWith(Result);
10853
10854 // Push the new instruction and any users onto the worklist.
10855 AddToWorkList(Result);
10856 AddUsersToWorkList(*Result);
10857
10858 // Move the name to the new instruction first.
10859 Result->takeName(I);
10860
10861 // Insert the new instruction into the basic block...
10862 BasicBlock *InstParent = I->getParent();
10863 BasicBlock::iterator InsertPos = I;
10864
10865 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
10866 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
10867 ++InsertPos;
10868
10869 InstParent->getInstList().insert(InsertPos, Result);
10870
10871 // Make sure that we reprocess all operands now that we reduced their
10872 // use counts.
10873 AddUsesToWorkList(*I);
10874
10875 // Instructions can end up on the worklist more than once. Make sure
10876 // we do not process an instruction that has been deleted.
10877 RemoveFromWorkList(I);
10878
10879 // Erase the old instruction.
10880 InstParent->getInstList().erase(I);
10881 } else {
10882#ifndef NDEBUG
10883 DOUT << "IC: Mod = " << OrigI
10884 << " New = " << *I;
10885#endif
10886
10887 // If the instruction was modified, it's possible that it is now dead.
10888 // if so, remove it.
10889 if (isInstructionTriviallyDead(I)) {
10890 // Make sure we process all operands now that we are reducing their
10891 // use counts.
10892 AddUsesToWorkList(*I);
10893
10894 // Instructions may end up in the worklist more than once. Erase all
10895 // occurrences of this instruction.
10896 RemoveFromWorkList(I);
10897 I->eraseFromParent();
10898 } else {
10899 AddToWorkList(I);
10900 AddUsersToWorkList(*I);
10901 }
10902 }
10903 Changed = true;
10904 }
10905 }
10906
10907 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnerb933ea62007-08-05 08:47:58 +000010908
10909 // Do an explicit clear, this shrinks the map if needed.
10910 WorklistMap.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010911 return Changed;
10912}
10913
10914
10915bool InstCombiner::runOnFunction(Function &F) {
10916 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
10917
10918 bool EverMadeChange = false;
10919
10920 // Iterate while there is work to do.
10921 unsigned Iteration = 0;
10922 while (DoOneIteration(F, Iteration++))
10923 EverMadeChange = true;
10924 return EverMadeChange;
10925}
10926
10927FunctionPass *llvm::createInstructionCombiningPass() {
10928 return new InstCombiner();
10929}
10930