blob: 3b341247688e5a3340daaa1ff10599025c891b04 [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
Dan Gohman089efff2008-05-13 00:00:25 +000011// instructions. This pass does not modify the CFG. This pass is where
12// algebraic simplification happens.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013//
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"
42#include "llvm/Analysis/ConstantFolding.h"
43#include "llvm/Target/TargetData.h"
44#include "llvm/Transforms/Utils/BasicBlockUtils.h"
45#include "llvm/Transforms/Utils/Local.h"
46#include "llvm/Support/CallSite.h"
Nick Lewycky0185bbf2008-02-03 16:33:09 +000047#include "llvm/Support/ConstantRange.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000048#include "llvm/Support/Debug.h"
49#include "llvm/Support/GetElementPtrTypeIterator.h"
50#include "llvm/Support/InstVisitor.h"
51#include "llvm/Support/MathExtras.h"
52#include "llvm/Support/PatternMatch.h"
53#include "llvm/Support/Compiler.h"
54#include "llvm/ADT/DenseMap.h"
55#include "llvm/ADT/SmallVector.h"
56#include "llvm/ADT/SmallPtrSet.h"
57#include "llvm/ADT/Statistic.h"
58#include "llvm/ADT/STLExtras.h"
59#include <algorithm>
Edwin Töröka0e6fce2008-04-20 08:33:11 +000060#include <climits>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000061#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);
Evan Chenge3779cf2008-03-24 00:21:34 +0000240 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
241 bool DoXform = true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000242
243 public:
244 // InsertNewInstBefore - insert an instruction New before instruction Old
245 // in the program. Add the new instruction to the worklist.
246 //
247 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
248 assert(New && New->getParent() == 0 &&
249 "New instruction already inserted into a basic block!");
250 BasicBlock *BB = Old.getParent();
251 BB->getInstList().insert(&Old, New); // Insert inst
252 AddToWorkList(New);
253 return New;
254 }
255
256 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
257 /// This also adds the cast to the worklist. Finally, this returns the
258 /// cast.
259 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
260 Instruction &Pos) {
261 if (V->getType() == Ty) return V;
262
263 if (Constant *CV = dyn_cast<Constant>(V))
264 return ConstantExpr::getCast(opc, CV, Ty);
265
Gabor Greifa645dd32008-05-16 19:29:10 +0000266 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000267 AddToWorkList(C);
268 return C;
269 }
Chris Lattner13c2d6e2008-01-13 22:23:22 +0000270
271 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
272 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
273 }
274
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000275
276 // ReplaceInstUsesWith - This method is to be used when an instruction is
277 // found to be dead, replacable with another preexisting expression. Here
278 // we add all uses of I to the worklist, replace all uses of I with the new
279 // value, then return I, so that the inst combiner will know that I was
280 // modified.
281 //
282 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
283 AddUsersToWorkList(I); // Add all modified instrs to worklist
284 if (&I != V) {
285 I.replaceAllUsesWith(V);
286 return &I;
287 } else {
288 // If we are replacing the instruction with itself, this must be in a
289 // segment of unreachable code, so just clobber the instruction.
290 I.replaceAllUsesWith(UndefValue::get(I.getType()));
291 return &I;
292 }
293 }
294
295 // UpdateValueUsesWith - This method is to be used when an value is
296 // found to be replacable with another preexisting expression or was
297 // updated. Here we add all uses of I to the worklist, replace all uses of
298 // I with the new value (unless the instruction was just updated), then
299 // return true, so that the inst combiner will know that I was modified.
300 //
301 bool UpdateValueUsesWith(Value *Old, Value *New) {
302 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
303 if (Old != New)
304 Old->replaceAllUsesWith(New);
305 if (Instruction *I = dyn_cast<Instruction>(Old))
306 AddToWorkList(I);
307 if (Instruction *I = dyn_cast<Instruction>(New))
308 AddToWorkList(I);
309 return true;
310 }
311
312 // EraseInstFromFunction - When dealing with an instruction that has side
313 // effects or produces a void value, we can't rely on DCE to delete the
314 // instruction. Instead, visit methods should return the value returned by
315 // this function.
316 Instruction *EraseInstFromFunction(Instruction &I) {
317 assert(I.use_empty() && "Cannot erase instruction that is used!");
318 AddUsesToWorkList(I);
319 RemoveFromWorkList(&I);
320 I.eraseFromParent();
321 return 0; // Don't do anything with FI
322 }
323
324 private:
325 /// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
326 /// InsertBefore instruction. This is specialized a bit to avoid inserting
327 /// casts that are known to not do anything...
328 ///
329 Value *InsertOperandCastBefore(Instruction::CastOps opcode,
330 Value *V, const Type *DestTy,
331 Instruction *InsertBefore);
332
333 /// SimplifyCommutative - This performs a few simplifications for
334 /// commutative operators.
335 bool SimplifyCommutative(BinaryOperator &I);
336
337 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
338 /// most-complex to least-complex order.
339 bool SimplifyCompare(CmpInst &I);
340
341 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
342 /// on the demanded bits.
343 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
344 APInt& KnownZero, APInt& KnownOne,
345 unsigned Depth = 0);
346
347 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
348 uint64_t &UndefElts, unsigned Depth = 0);
349
350 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
351 // PHI node as operand #0, see if we can fold the instruction into the PHI
352 // (which is only possible if all operands to the PHI are constants).
353 Instruction *FoldOpIntoPhi(Instruction &I);
354
355 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
356 // operator and they all are only used by the PHI, PHI together their
357 // inputs, and do the operation once, to the result of the PHI.
358 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
359 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
360
361
362 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
363 ConstantInt *AndRHS, BinaryOperator &TheAnd);
364
365 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
366 bool isSub, Instruction &I);
367 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
368 bool isSigned, bool Inside, Instruction &IB);
369 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
370 Instruction *MatchBSwap(BinaryOperator &I);
371 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000372 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +0000373 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000374
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000375
376 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000377
378 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt& KnownZero,
379 APInt& KnownOne, unsigned Depth = 0);
380 bool MaskedValueIsZero(Value *V, const APInt& Mask, unsigned Depth = 0);
381 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
382 unsigned CastOpc,
383 int &NumCastsRemoved);
384 unsigned GetOrEnforceKnownAlignment(Value *V,
385 unsigned PrefAlign = 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000386 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000387}
388
Dan Gohman089efff2008-05-13 00:00:25 +0000389char InstCombiner::ID = 0;
390static RegisterPass<InstCombiner>
391X("instcombine", "Combine redundant instructions");
392
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000393// getComplexity: Assign a complexity or rank value to LLVM Values...
394// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
395static unsigned getComplexity(Value *V) {
396 if (isa<Instruction>(V)) {
397 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
398 return 3;
399 return 4;
400 }
401 if (isa<Argument>(V)) return 3;
402 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
403}
404
405// isOnlyUse - Return true if this instruction will be deleted if we stop using
406// it.
407static bool isOnlyUse(Value *V) {
408 return V->hasOneUse() || isa<Constant>(V);
409}
410
411// getPromotedType - Return the specified type promoted as it would be to pass
412// though a va_arg area...
413static const Type *getPromotedType(const Type *Ty) {
414 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
415 if (ITy->getBitWidth() < 32)
416 return Type::Int32Ty;
417 }
418 return Ty;
419}
420
421/// getBitCastOperand - If the specified operand is a CastInst or a constant
422/// expression bitcast, return the operand value, otherwise return null.
423static Value *getBitCastOperand(Value *V) {
424 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
425 return I->getOperand(0);
426 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
427 if (CE->getOpcode() == Instruction::BitCast)
428 return CE->getOperand(0);
429 return 0;
430}
431
432/// This function is a wrapper around CastInst::isEliminableCastPair. It
433/// simply extracts arguments and returns what that function returns.
434static Instruction::CastOps
435isEliminableCastPair(
436 const CastInst *CI, ///< The first cast instruction
437 unsigned opcode, ///< The opcode of the second cast instruction
438 const Type *DstTy, ///< The target type for the second cast instruction
439 TargetData *TD ///< The target data for pointer size
440) {
441
442 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
443 const Type *MidTy = CI->getType(); // B from above
444
445 // Get the opcodes of the two Cast instructions
446 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
447 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
448
449 return Instruction::CastOps(
450 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
451 DstTy, TD->getIntPtrType()));
452}
453
454/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
455/// in any code being generated. It does not require codegen if V is simple
456/// enough or if the cast can be folded into other casts.
457static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
458 const Type *Ty, TargetData *TD) {
459 if (V->getType() == Ty || isa<Constant>(V)) return false;
460
461 // If this is another cast that can be eliminated, it isn't codegen either.
462 if (const CastInst *CI = dyn_cast<CastInst>(V))
463 if (isEliminableCastPair(CI, opcode, Ty, TD))
464 return false;
465 return true;
466}
467
468/// InsertOperandCastBefore - This inserts a cast of V to DestTy before the
469/// InsertBefore instruction. This is specialized a bit to avoid inserting
470/// casts that are known to not do anything...
471///
472Value *InstCombiner::InsertOperandCastBefore(Instruction::CastOps opcode,
473 Value *V, const Type *DestTy,
474 Instruction *InsertBefore) {
475 if (V->getType() == DestTy) return V;
476 if (Constant *C = dyn_cast<Constant>(V))
477 return ConstantExpr::getCast(opcode, C, DestTy);
478
479 return InsertCastBefore(opcode, V, DestTy, *InsertBefore);
480}
481
482// SimplifyCommutative - This performs a few simplifications for commutative
483// operators:
484//
485// 1. Order operands such that they are listed from right (least complex) to
486// left (most complex). This puts constants before unary operators before
487// binary operators.
488//
489// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
490// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
491//
492bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
493 bool Changed = false;
494 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
495 Changed = !I.swapOperands();
496
497 if (!I.isAssociative()) return Changed;
498 Instruction::BinaryOps Opcode = I.getOpcode();
499 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
500 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
501 if (isa<Constant>(I.getOperand(1))) {
502 Constant *Folded = ConstantExpr::get(I.getOpcode(),
503 cast<Constant>(I.getOperand(1)),
504 cast<Constant>(Op->getOperand(1)));
505 I.setOperand(0, Op->getOperand(0));
506 I.setOperand(1, Folded);
507 return true;
508 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
509 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
510 isOnlyUse(Op) && isOnlyUse(Op1)) {
511 Constant *C1 = cast<Constant>(Op->getOperand(1));
512 Constant *C2 = cast<Constant>(Op1->getOperand(1));
513
514 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
515 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +0000516 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000517 Op1->getOperand(0),
518 Op1->getName(), &I);
519 AddToWorkList(New);
520 I.setOperand(0, New);
521 I.setOperand(1, Folded);
522 return true;
523 }
524 }
525 return Changed;
526}
527
528/// SimplifyCompare - For a CmpInst this function just orders the operands
529/// so that theyare listed from right (least complex) to left (most complex).
530/// This puts constants before unary operators before binary operators.
531bool InstCombiner::SimplifyCompare(CmpInst &I) {
532 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
533 return false;
534 I.swapOperands();
535 // Compare instructions are not associative so there's nothing else we can do.
536 return true;
537}
538
539// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
540// if the LHS is a constant zero (which is the 'negate' form).
541//
542static inline Value *dyn_castNegVal(Value *V) {
543 if (BinaryOperator::isNeg(V))
544 return BinaryOperator::getNegArgument(V);
545
546 // Constants can be considered to be negated values if they can be folded.
547 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
548 return ConstantExpr::getNeg(C);
549 return 0;
550}
551
552static inline Value *dyn_castNotVal(Value *V) {
553 if (BinaryOperator::isNot(V))
554 return BinaryOperator::getNotArgument(V);
555
556 // Constants can be considered to be not'ed values...
557 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
558 return ConstantInt::get(~C->getValue());
559 return 0;
560}
561
562// dyn_castFoldableMul - If this value is a multiply that can be folded into
563// other computations (because it has a constant operand), return the
564// non-constant operand of the multiply, and set CST to point to the multiplier.
565// Otherwise, return null.
566//
567static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
568 if (V->hasOneUse() && V->getType()->isInteger())
569 if (Instruction *I = dyn_cast<Instruction>(V)) {
570 if (I->getOpcode() == Instruction::Mul)
571 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
572 return I->getOperand(0);
573 if (I->getOpcode() == Instruction::Shl)
574 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
575 // The multiplier is really 1 << CST.
576 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
577 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
578 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
579 return I->getOperand(0);
580 }
581 }
582 return 0;
583}
584
585/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
586/// expression, return it.
587static User *dyn_castGetElementPtr(Value *V) {
588 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
589 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
590 if (CE->getOpcode() == Instruction::GetElementPtr)
591 return cast<User>(V);
592 return false;
593}
594
Dan Gohman2d648bb2008-04-10 18:43:06 +0000595/// getOpcode - If this is an Instruction or a ConstantExpr, return the
596/// opcode value. Otherwise return UserOp1.
597static unsigned getOpcode(User *U) {
598 if (Instruction *I = dyn_cast<Instruction>(U))
599 return I->getOpcode();
600 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U))
601 return CE->getOpcode();
602 // Use UserOp1 to mean there's no opcode.
603 return Instruction::UserOp1;
604}
605
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000606/// AddOne - Add one to a ConstantInt
607static ConstantInt *AddOne(ConstantInt *C) {
608 APInt Val(C->getValue());
609 return ConstantInt::get(++Val);
610}
611/// SubOne - Subtract one from a ConstantInt
612static ConstantInt *SubOne(ConstantInt *C) {
613 APInt Val(C->getValue());
614 return ConstantInt::get(--Val);
615}
616/// Add - Add two ConstantInts together
617static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
618 return ConstantInt::get(C1->getValue() + C2->getValue());
619}
620/// And - Bitwise AND two ConstantInts together
621static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
622 return ConstantInt::get(C1->getValue() & C2->getValue());
623}
624/// Subtract - Subtract one ConstantInt from another
625static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
626 return ConstantInt::get(C1->getValue() - C2->getValue());
627}
628/// Multiply - Multiply two ConstantInts together
629static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
630 return ConstantInt::get(C1->getValue() * C2->getValue());
631}
Nick Lewycky9d798f92008-02-18 22:48:05 +0000632/// MultiplyOverflows - True if the multiply can not be expressed in an int
633/// this size.
634static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
635 uint32_t W = C1->getBitWidth();
636 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
637 if (sign) {
638 LHSExt.sext(W * 2);
639 RHSExt.sext(W * 2);
640 } else {
641 LHSExt.zext(W * 2);
642 RHSExt.zext(W * 2);
643 }
644
645 APInt MulExt = LHSExt * RHSExt;
646
647 if (sign) {
648 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
649 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
650 return MulExt.slt(Min) || MulExt.sgt(Max);
651 } else
652 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
653}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000654
655/// ComputeMaskedBits - Determine which of the bits specified in Mask are
656/// known to be either zero or one and return them in the KnownZero/KnownOne
657/// bit sets. This code only analyzes bits in Mask, in order to short-circuit
658/// processing.
659/// NOTE: we cannot consider 'undef' to be "IsZero" here. The problem is that
660/// we cannot optimize based on the assumption that it is zero without changing
661/// it to be an explicit zero. If we don't change it to zero, other code could
662/// optimized based on the contradictory assumption that it is non-zero.
663/// Because instcombine aggressively folds operations with undef args anyway,
664/// this won't lose us code quality.
Dan Gohman2d648bb2008-04-10 18:43:06 +0000665void InstCombiner::ComputeMaskedBits(Value *V, const APInt &Mask,
666 APInt& KnownZero, APInt& KnownOne,
667 unsigned Depth) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000668 assert(V && "No Value?");
669 assert(Depth <= 6 && "Limit Search Depth");
670 uint32_t BitWidth = Mask.getBitWidth();
Dan Gohman2d648bb2008-04-10 18:43:06 +0000671 assert((V->getType()->isInteger() || isa<PointerType>(V->getType())) &&
672 "Not integer or pointer type!");
673 assert((!TD || TD->getTypeSizeInBits(V->getType()) == BitWidth) &&
674 (!isa<IntegerType>(V->getType()) ||
675 V->getType()->getPrimitiveSizeInBits() == BitWidth) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000676 KnownZero.getBitWidth() == BitWidth &&
677 KnownOne.getBitWidth() == BitWidth &&
678 "V, Mask, KnownOne and KnownZero should have same BitWidth");
679 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
680 // We know all of the bits for a constant!
681 KnownOne = CI->getValue() & Mask;
682 KnownZero = ~KnownOne & Mask;
683 return;
684 }
Dan Gohman2d648bb2008-04-10 18:43:06 +0000685 // Null is all-zeros.
686 if (isa<ConstantPointerNull>(V)) {
687 KnownOne.clear();
688 KnownZero = Mask;
689 return;
690 }
691 // The address of an aligned GlobalValue has trailing zeros.
692 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
693 unsigned Align = GV->getAlignment();
694 if (Align == 0 && TD && GV->getType()->getElementType()->isSized())
695 Align = TD->getPrefTypeAlignment(GV->getType()->getElementType());
696 if (Align > 0)
697 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
698 CountTrailingZeros_32(Align));
699 else
700 KnownZero.clear();
701 KnownOne.clear();
702 return;
703 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000704
Dan Gohmanbec16052008-04-28 17:02:21 +0000705 KnownZero.clear(); KnownOne.clear(); // Start out not knowing anything.
706
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000707 if (Depth == 6 || Mask == 0)
708 return; // Limit search depth.
709
Dan Gohman2d648bb2008-04-10 18:43:06 +0000710 User *I = dyn_cast<User>(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000711 if (!I) return;
712
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000713 APInt KnownZero2(KnownZero), KnownOne2(KnownOne);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000714 switch (getOpcode(I)) {
715 default: break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000716 case Instruction::And: {
717 // If either the LHS or the RHS are Zero, the result is zero.
718 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
719 APInt Mask2(Mask & ~KnownZero);
720 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
721 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
722 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
723
724 // Output known-1 bits are only known if set in both the LHS & RHS.
725 KnownOne &= KnownOne2;
726 // Output known-0 are known to be clear if zero in either the LHS | RHS.
727 KnownZero |= KnownZero2;
728 return;
729 }
730 case Instruction::Or: {
731 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
732 APInt Mask2(Mask & ~KnownOne);
733 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
734 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
735 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
736
737 // Output known-0 bits are only known if clear in both the LHS & RHS.
738 KnownZero &= KnownZero2;
739 // Output known-1 are known to be set if set in either the LHS | RHS.
740 KnownOne |= KnownOne2;
741 return;
742 }
743 case Instruction::Xor: {
744 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
745 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
746 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
747 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
748
749 // Output known-0 bits are known if clear or set in both the LHS & RHS.
750 APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
751 // Output known-1 are known to be set if set in only one of the LHS, RHS.
752 KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
753 KnownZero = KnownZeroOut;
754 return;
755 }
Dan Gohman2d648bb2008-04-10 18:43:06 +0000756 case Instruction::Mul: {
757 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
758 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
759 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
760 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
761 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
762
763 // If low bits are zero in either operand, output low known-0 bits.
Dan Gohmanbec16052008-04-28 17:02:21 +0000764 // Also compute a conserative estimate for high known-0 bits.
Dan Gohman2d648bb2008-04-10 18:43:06 +0000765 // More trickiness is possible, but this is sufficient for the
766 // interesting case of alignment computation.
767 KnownOne.clear();
768 unsigned TrailZ = KnownZero.countTrailingOnes() +
769 KnownZero2.countTrailingOnes();
Dan Gohmanbec16052008-04-28 17:02:21 +0000770 unsigned LeadZ = std::max(KnownZero.countLeadingOnes() +
Dan Gohman4c451852008-05-07 00:35:55 +0000771 KnownZero2.countLeadingOnes(),
772 BitWidth) - BitWidth;
Dan Gohmanbec16052008-04-28 17:02:21 +0000773
Dan Gohman2d648bb2008-04-10 18:43:06 +0000774 TrailZ = std::min(TrailZ, BitWidth);
Dan Gohmanbec16052008-04-28 17:02:21 +0000775 LeadZ = std::min(LeadZ, BitWidth);
776 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
777 APInt::getHighBitsSet(BitWidth, LeadZ);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000778 KnownZero &= Mask;
779 return;
780 }
Dan Gohmanbec16052008-04-28 17:02:21 +0000781 case Instruction::UDiv: {
782 // For the purposes of computing leading zeros we can conservatively
783 // treat a udiv as a logical right shift by the power of 2 known to
Dan Gohman1b9fb1f2008-05-02 21:30:02 +0000784 // be less than the denominator.
Dan Gohmanbec16052008-04-28 17:02:21 +0000785 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
786 ComputeMaskedBits(I->getOperand(0),
787 AllOnes, KnownZero2, KnownOne2, Depth+1);
788 unsigned LeadZ = KnownZero2.countLeadingOnes();
789
790 KnownOne2.clear();
791 KnownZero2.clear();
792 ComputeMaskedBits(I->getOperand(1),
793 AllOnes, KnownZero2, KnownOne2, Depth+1);
Dan Gohman1b9fb1f2008-05-02 21:30:02 +0000794 unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
795 if (RHSUnknownLeadingOnes != BitWidth)
796 LeadZ = std::min(BitWidth,
797 LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
Dan Gohmanbec16052008-04-28 17:02:21 +0000798
799 KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
800 return;
801 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000802 case Instruction::Select:
803 ComputeMaskedBits(I->getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
804 ComputeMaskedBits(I->getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
805 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
806 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
807
808 // Only known if known in both the LHS and RHS.
809 KnownOne &= KnownOne2;
810 KnownZero &= KnownZero2;
811 return;
812 case Instruction::FPTrunc:
813 case Instruction::FPExt:
814 case Instruction::FPToUI:
815 case Instruction::FPToSI:
816 case Instruction::SIToFP:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000817 case Instruction::UIToFP:
Dan Gohman2d648bb2008-04-10 18:43:06 +0000818 return; // Can't work with floating point.
819 case Instruction::PtrToInt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000820 case Instruction::IntToPtr:
Dan Gohman2d648bb2008-04-10 18:43:06 +0000821 // We can't handle these if we don't know the pointer size.
822 if (!TD) return;
823 // Fall through and handle them the same as zext/trunc.
824 case Instruction::ZExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000825 case Instruction::Trunc: {
826 // All these have integer operands
Dan Gohman2d648bb2008-04-10 18:43:06 +0000827 const Type *SrcTy = I->getOperand(0)->getType();
828 uint32_t SrcBitWidth = TD ?
829 TD->getTypeSizeInBits(SrcTy) :
830 SrcTy->getPrimitiveSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000831 APInt MaskIn(Mask);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000832 MaskIn.zextOrTrunc(SrcBitWidth);
833 KnownZero.zextOrTrunc(SrcBitWidth);
834 KnownOne.zextOrTrunc(SrcBitWidth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000835 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000836 KnownZero.zextOrTrunc(BitWidth);
837 KnownOne.zextOrTrunc(BitWidth);
838 // Any top bits are known to be zero.
839 if (BitWidth > SrcBitWidth)
840 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000841 return;
842 }
843 case Instruction::BitCast: {
844 const Type *SrcTy = I->getOperand(0)->getType();
Dan Gohman2d648bb2008-04-10 18:43:06 +0000845 if (SrcTy->isInteger() || isa<PointerType>(SrcTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000846 ComputeMaskedBits(I->getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
847 return;
848 }
849 break;
850 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000851 case Instruction::SExt: {
852 // Compute the bits in the result that are not present in the input.
853 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
854 uint32_t SrcBitWidth = SrcTy->getBitWidth();
855
856 APInt MaskIn(Mask);
857 MaskIn.trunc(SrcBitWidth);
858 KnownZero.trunc(SrcBitWidth);
859 KnownOne.trunc(SrcBitWidth);
860 ComputeMaskedBits(I->getOperand(0), MaskIn, KnownZero, KnownOne, Depth+1);
861 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
862 KnownZero.zext(BitWidth);
863 KnownOne.zext(BitWidth);
864
865 // If the sign bit of the input is known set or clear, then we know the
866 // top bits of the result.
867 if (KnownZero[SrcBitWidth-1]) // Input sign bit known zero
868 KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
869 else if (KnownOne[SrcBitWidth-1]) // Input sign bit known set
870 KnownOne |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
871 return;
872 }
873 case Instruction::Shl:
874 // (shl X, C1) & C2 == 0 iff (X & C2 >>u C1) == 0
875 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
876 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
877 APInt Mask2(Mask.lshr(ShiftAmt));
878 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne, Depth+1);
879 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
880 KnownZero <<= ShiftAmt;
881 KnownOne <<= ShiftAmt;
882 KnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt); // low bits known 0
883 return;
884 }
885 break;
886 case Instruction::LShr:
887 // (ushr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
888 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
889 // Compute the new bits that are at the top now.
890 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
891
892 // Unsigned shift right.
893 APInt Mask2(Mask.shl(ShiftAmt));
894 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
895 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
896 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
897 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
898 // high bits known zero.
899 KnownZero |= APInt::getHighBitsSet(BitWidth, ShiftAmt);
900 return;
901 }
902 break;
903 case Instruction::AShr:
904 // (ashr X, C1) & C2 == 0 iff (-1 >> C1) & C2 == 0
905 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
906 // Compute the new bits that are at the top now.
907 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
908
909 // Signed shift right.
910 APInt Mask2(Mask.shl(ShiftAmt));
911 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero,KnownOne,Depth+1);
912 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
913 KnownZero = APIntOps::lshr(KnownZero, ShiftAmt);
914 KnownOne = APIntOps::lshr(KnownOne, ShiftAmt);
915
916 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
917 if (KnownZero[BitWidth-ShiftAmt-1]) // New bits are known zero.
918 KnownZero |= HighBits;
919 else if (KnownOne[BitWidth-ShiftAmt-1]) // New bits are known one.
920 KnownOne |= HighBits;
921 return;
922 }
923 break;
Dan Gohman2d648bb2008-04-10 18:43:06 +0000924 case Instruction::Sub: {
925 if (ConstantInt *CLHS = dyn_cast<ConstantInt>(I->getOperand(0))) {
926 // We know that the top bits of C-X are clear if X contains less bits
927 // than C (i.e. no wrap-around can happen). For example, 20-X is
928 // positive if we can prove that X is >= 0 and < 16.
929 if (!CLHS->getValue().isNegative()) {
930 unsigned NLZ = (CLHS->getValue()+1).countLeadingZeros();
931 // NLZ can't be BitWidth with no sign bit
932 APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
Dan Gohmanbec16052008-04-28 17:02:21 +0000933 ComputeMaskedBits(I->getOperand(1), MaskV, KnownZero2, KnownOne2,
934 Depth+1);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000935
Dan Gohmanbec16052008-04-28 17:02:21 +0000936 // If all of the MaskV bits are known to be zero, then we know the
937 // output top bits are zero, because we now know that the output is
938 // from [0-C].
939 if ((KnownZero2 & MaskV) == MaskV) {
Dan Gohman2d648bb2008-04-10 18:43:06 +0000940 unsigned NLZ2 = CLHS->getValue().countLeadingZeros();
941 // Top bits known zero.
942 KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
Dan Gohman2d648bb2008-04-10 18:43:06 +0000943 }
Dan Gohman2d648bb2008-04-10 18:43:06 +0000944 }
945 }
946 }
947 // fall through
Duncan Sandse71d4482008-03-21 08:32:17 +0000948 case Instruction::Add: {
Chris Lattner5ee84f82008-03-21 05:19:58 +0000949 // Output known-0 bits are known if clear or set in both the low clear bits
950 // common to both LHS & RHS. For example, 8+(X<<3) is known to have the
951 // low 3 bits clear.
Dan Gohmanbec16052008-04-28 17:02:21 +0000952 APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
953 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
954 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
955 unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
956
957 ComputeMaskedBits(I->getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
958 assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
959 KnownZeroOut = std::min(KnownZeroOut,
960 KnownZero2.countTrailingOnes());
961
962 KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
Chris Lattner5ee84f82008-03-21 05:19:58 +0000963 return;
Duncan Sandse71d4482008-03-21 08:32:17 +0000964 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +0000965 case Instruction::SRem:
966 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
967 APInt RA = Rem->getValue();
968 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman5a154a12008-05-06 00:51:48 +0000969 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1372c82008-03-06 06:48:30 +0000970 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
971 ComputeMaskedBits(I->getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
972
973 // The sign of a remainder is equal to the sign of the first
974 // operand (zero being positive).
975 if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
976 KnownZero2 |= ~LowBits;
977 else if (KnownOne2[BitWidth-1])
978 KnownOne2 |= ~LowBits;
979
980 KnownZero |= KnownZero2 & Mask;
981 KnownOne |= KnownOne2 & Mask;
982
983 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
984 }
985 }
986 break;
Dan Gohmanbec16052008-04-28 17:02:21 +0000987 case Instruction::URem: {
Nick Lewyckyc1372c82008-03-06 06:48:30 +0000988 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
989 APInt RA = Rem->getValue();
Dan Gohman5a154a12008-05-06 00:51:48 +0000990 if (RA.isPowerOf2()) {
991 APInt LowBits = (RA - 1);
Nick Lewyckyc1372c82008-03-06 06:48:30 +0000992 APInt Mask2 = LowBits & Mask;
993 KnownZero |= ~LowBits & Mask;
994 ComputeMaskedBits(I->getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
995 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohmanbec16052008-04-28 17:02:21 +0000996 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +0000997 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +0000998 }
Dan Gohmanbec16052008-04-28 17:02:21 +0000999
1000 // Since the result is less than or equal to either operand, any leading
1001 // zero bits in either operand must also exist in the result.
1002 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
1003 ComputeMaskedBits(I->getOperand(0), AllOnes, KnownZero, KnownOne,
1004 Depth+1);
1005 ComputeMaskedBits(I->getOperand(1), AllOnes, KnownZero2, KnownOne2,
1006 Depth+1);
1007
1008 uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
1009 KnownZero2.countLeadingOnes());
1010 KnownOne.clear();
1011 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001012 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001013 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00001014
1015 case Instruction::Alloca:
1016 case Instruction::Malloc: {
1017 AllocationInst *AI = cast<AllocationInst>(V);
1018 unsigned Align = AI->getAlignment();
1019 if (Align == 0 && TD) {
1020 if (isa<AllocaInst>(AI))
1021 Align = TD->getPrefTypeAlignment(AI->getType()->getElementType());
1022 else if (isa<MallocInst>(AI)) {
1023 // Malloc returns maximally aligned memory.
1024 Align = TD->getABITypeAlignment(AI->getType()->getElementType());
1025 Align =
1026 std::max(Align,
1027 (unsigned)TD->getABITypeAlignment(Type::DoubleTy));
1028 Align =
1029 std::max(Align,
1030 (unsigned)TD->getABITypeAlignment(Type::Int64Ty));
1031 }
1032 }
1033
1034 if (Align > 0)
1035 KnownZero = Mask & APInt::getLowBitsSet(BitWidth,
1036 CountTrailingZeros_32(Align));
1037 break;
1038 }
1039 case Instruction::GetElementPtr: {
1040 // Analyze all of the subscripts of this getelementptr instruction
1041 // to determine if we can prove known low zero bits.
1042 APInt LocalMask = APInt::getAllOnesValue(BitWidth);
1043 APInt LocalKnownZero(BitWidth, 0), LocalKnownOne(BitWidth, 0);
1044 ComputeMaskedBits(I->getOperand(0), LocalMask,
1045 LocalKnownZero, LocalKnownOne, Depth+1);
1046 unsigned TrailZ = LocalKnownZero.countTrailingOnes();
1047
1048 gep_type_iterator GTI = gep_type_begin(I);
1049 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i, ++GTI) {
1050 Value *Index = I->getOperand(i);
1051 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
1052 // Handle struct member offset arithmetic.
1053 if (!TD) return;
1054 const StructLayout *SL = TD->getStructLayout(STy);
1055 unsigned Idx = cast<ConstantInt>(Index)->getZExtValue();
1056 uint64_t Offset = SL->getElementOffset(Idx);
1057 TrailZ = std::min(TrailZ,
1058 CountTrailingZeros_64(Offset));
1059 } else {
1060 // Handle array index arithmetic.
1061 const Type *IndexedTy = GTI.getIndexedType();
1062 if (!IndexedTy->isSized()) return;
1063 unsigned GEPOpiBits = Index->getType()->getPrimitiveSizeInBits();
1064 uint64_t TypeSize = TD ? TD->getABITypeSize(IndexedTy) : 1;
1065 LocalMask = APInt::getAllOnesValue(GEPOpiBits);
1066 LocalKnownZero = LocalKnownOne = APInt(GEPOpiBits, 0);
1067 ComputeMaskedBits(Index, LocalMask,
1068 LocalKnownZero, LocalKnownOne, Depth+1);
1069 TrailZ = std::min(TrailZ,
1070 CountTrailingZeros_64(TypeSize) +
1071 LocalKnownZero.countTrailingOnes());
1072 }
1073 }
1074
1075 KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) & Mask;
1076 break;
1077 }
1078 case Instruction::PHI: {
1079 PHINode *P = cast<PHINode>(I);
1080 // Handle the case of a simple two-predecessor recurrence PHI.
1081 // There's a lot more that could theoretically be done here, but
1082 // this is sufficient to catch some interesting cases.
1083 if (P->getNumIncomingValues() == 2) {
1084 for (unsigned i = 0; i != 2; ++i) {
1085 Value *L = P->getIncomingValue(i);
1086 Value *R = P->getIncomingValue(!i);
1087 User *LU = dyn_cast<User>(L);
1088 unsigned Opcode = LU ? getOpcode(LU) : (unsigned)Instruction::UserOp1;
1089 // Check for operations that have the property that if
1090 // both their operands have low zero bits, the result
1091 // will have low zero bits.
1092 if (Opcode == Instruction::Add ||
1093 Opcode == Instruction::Sub ||
1094 Opcode == Instruction::And ||
1095 Opcode == Instruction::Or ||
1096 Opcode == Instruction::Mul) {
1097 Value *LL = LU->getOperand(0);
1098 Value *LR = LU->getOperand(1);
1099 // Find a recurrence.
1100 if (LL == I)
1101 L = LR;
1102 else if (LR == I)
1103 L = LL;
1104 else
1105 break;
1106 // Ok, we have a PHI of the form L op= R. Check for low
1107 // zero bits.
1108 APInt Mask2 = APInt::getAllOnesValue(BitWidth);
1109 ComputeMaskedBits(R, Mask2, KnownZero2, KnownOne2, Depth+1);
1110 Mask2 = APInt::getLowBitsSet(BitWidth,
1111 KnownZero2.countTrailingOnes());
1112 KnownOne2.clear();
1113 KnownZero2.clear();
1114 ComputeMaskedBits(L, Mask2, KnownZero2, KnownOne2, Depth+1);
1115 KnownZero = Mask &
1116 APInt::getLowBitsSet(BitWidth,
1117 KnownZero2.countTrailingOnes());
1118 break;
1119 }
1120 }
1121 }
1122 break;
1123 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001124 case Instruction::Call:
1125 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1126 switch (II->getIntrinsicID()) {
1127 default: break;
1128 case Intrinsic::ctpop:
1129 case Intrinsic::ctlz:
1130 case Intrinsic::cttz: {
1131 unsigned LowBits = Log2_32(BitWidth)+1;
1132 KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
1133 break;
1134 }
1135 }
1136 }
1137 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001138 }
1139}
1140
1141/// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
1142/// this predicate to simplify operations downstream. Mask is known to be zero
1143/// for bits that V cannot have.
Dan Gohman2d648bb2008-04-10 18:43:06 +00001144bool InstCombiner::MaskedValueIsZero(Value *V, const APInt& Mask,
1145 unsigned Depth) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001146 APInt KnownZero(Mask.getBitWidth(), 0), KnownOne(Mask.getBitWidth(), 0);
1147 ComputeMaskedBits(V, Mask, KnownZero, KnownOne, Depth);
1148 assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1149 return (KnownZero & Mask) == Mask;
1150}
1151
1152/// ShrinkDemandedConstant - Check to see if the specified operand of the
1153/// specified instruction is a constant integer. If so, check to see if there
1154/// are any bits set in the constant that are not demanded. If so, shrink the
1155/// constant and return true.
1156static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
1157 APInt Demanded) {
1158 assert(I && "No instruction?");
1159 assert(OpNo < I->getNumOperands() && "Operand index too large");
1160
1161 // If the operand is not a constant integer, nothing to do.
1162 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
1163 if (!OpC) return false;
1164
1165 // If there are no bits set that aren't demanded, nothing to do.
1166 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
1167 if ((~Demanded & OpC->getValue()) == 0)
1168 return false;
1169
1170 // This instruction is producing bits that are not demanded. Shrink the RHS.
1171 Demanded &= OpC->getValue();
1172 I->setOperand(OpNo, ConstantInt::get(Demanded));
1173 return true;
1174}
1175
1176// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
1177// set of known zero and one bits, compute the maximum and minimum values that
1178// could have the specified known zero and known one bits, returning them in
1179// min/max.
1180static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
1181 const APInt& KnownZero,
1182 const APInt& KnownOne,
1183 APInt& Min, APInt& Max) {
1184 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
1185 assert(KnownZero.getBitWidth() == BitWidth &&
1186 KnownOne.getBitWidth() == BitWidth &&
1187 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
1188 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
1189 APInt UnknownBits = ~(KnownZero|KnownOne);
1190
1191 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
1192 // bit if it is unknown.
1193 Min = KnownOne;
1194 Max = KnownOne|UnknownBits;
1195
1196 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
1197 Min.set(BitWidth-1);
1198 Max.clear(BitWidth-1);
1199 }
1200}
1201
1202// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
1203// a set of known zero and one bits, compute the maximum and minimum values that
1204// could have the specified known zero and known one bits, returning them in
1205// min/max.
1206static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnerb933ea62007-08-05 08:47:58 +00001207 const APInt &KnownZero,
1208 const APInt &KnownOne,
1209 APInt &Min, APInt &Max) {
1210 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001211 assert(KnownZero.getBitWidth() == BitWidth &&
1212 KnownOne.getBitWidth() == BitWidth &&
1213 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
1214 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
1215 APInt UnknownBits = ~(KnownZero|KnownOne);
1216
1217 // The minimum value is when the unknown bits are all zeros.
1218 Min = KnownOne;
1219 // The maximum value is when the unknown bits are all ones.
1220 Max = KnownOne|UnknownBits;
1221}
1222
1223/// SimplifyDemandedBits - This function attempts to replace V with a simpler
1224/// value based on the demanded bits. When this function is called, it is known
1225/// that only the bits set in DemandedMask of the result of V are ever used
1226/// downstream. Consequently, depending on the mask and V, it may be possible
1227/// to replace V with a constant or one of its operands. In such cases, this
1228/// function does the replacement and returns true. In all other cases, it
1229/// returns false after analyzing the expression and setting KnownOne and known
1230/// to be one in the expression. KnownZero contains all the bits that are known
1231/// to be zero in the expression. These are provided to potentially allow the
1232/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
1233/// the expression. KnownOne and KnownZero always follow the invariant that
1234/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
1235/// the bits in KnownOne and KnownZero may only be accurate for those bits set
1236/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
1237/// and KnownOne must all be the same.
1238bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
1239 APInt& KnownZero, APInt& KnownOne,
1240 unsigned Depth) {
1241 assert(V != 0 && "Null pointer of Value???");
1242 assert(Depth <= 6 && "Limit Search Depth");
1243 uint32_t BitWidth = DemandedMask.getBitWidth();
1244 const IntegerType *VTy = cast<IntegerType>(V->getType());
1245 assert(VTy->getBitWidth() == BitWidth &&
1246 KnownZero.getBitWidth() == BitWidth &&
1247 KnownOne.getBitWidth() == BitWidth &&
1248 "Value *V, DemandedMask, KnownZero and KnownOne \
1249 must have same BitWidth");
1250 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
1251 // We know all of the bits for a constant!
1252 KnownOne = CI->getValue() & DemandedMask;
1253 KnownZero = ~KnownOne & DemandedMask;
1254 return false;
1255 }
1256
1257 KnownZero.clear();
1258 KnownOne.clear();
1259 if (!V->hasOneUse()) { // Other users may use these bits.
1260 if (Depth != 0) { // Not at the root.
1261 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
1262 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
1263 return false;
1264 }
1265 // If this is the root being simplified, allow it to have multiple uses,
1266 // just set the DemandedMask to all bits.
1267 DemandedMask = APInt::getAllOnesValue(BitWidth);
1268 } else if (DemandedMask == 0) { // Not demanding any bits from V.
1269 if (V != UndefValue::get(VTy))
1270 return UpdateValueUsesWith(V, UndefValue::get(VTy));
1271 return false;
1272 } else if (Depth == 6) { // Limit search depth.
1273 return false;
1274 }
1275
1276 Instruction *I = dyn_cast<Instruction>(V);
1277 if (!I) return false; // Only analyze instructions.
1278
1279 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
1280 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
1281 switch (I->getOpcode()) {
Dan Gohmanbec16052008-04-28 17:02:21 +00001282 default:
1283 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
1284 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001285 case Instruction::And:
1286 // If either the LHS or the RHS are Zero, the result is zero.
1287 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1288 RHSKnownZero, RHSKnownOne, Depth+1))
1289 return true;
1290 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1291 "Bits known to be one AND zero?");
1292
1293 // If something is known zero on the RHS, the bits aren't demanded on the
1294 // LHS.
1295 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
1296 LHSKnownZero, LHSKnownOne, Depth+1))
1297 return true;
1298 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1299 "Bits known to be one AND zero?");
1300
1301 // If all of the demanded bits are known 1 on one side, return the other.
1302 // These bits cannot contribute to the result of the 'and'.
1303 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
1304 (DemandedMask & ~LHSKnownZero))
1305 return UpdateValueUsesWith(I, I->getOperand(0));
1306 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
1307 (DemandedMask & ~RHSKnownZero))
1308 return UpdateValueUsesWith(I, I->getOperand(1));
1309
1310 // If all of the demanded bits in the inputs are known zeros, return zero.
1311 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
1312 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
1313
1314 // If the RHS is a constant, see if we can simplify it.
1315 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
1316 return UpdateValueUsesWith(I, I);
1317
1318 // Output known-1 bits are only known if set in both the LHS & RHS.
1319 RHSKnownOne &= LHSKnownOne;
1320 // Output known-0 are known to be clear if zero in either the LHS | RHS.
1321 RHSKnownZero |= LHSKnownZero;
1322 break;
1323 case Instruction::Or:
1324 // If either the LHS or the RHS are One, the result is One.
1325 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1326 RHSKnownZero, RHSKnownOne, Depth+1))
1327 return true;
1328 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1329 "Bits known to be one AND zero?");
1330 // If something is known one on the RHS, the bits aren't demanded on the
1331 // LHS.
1332 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
1333 LHSKnownZero, LHSKnownOne, Depth+1))
1334 return true;
1335 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1336 "Bits known to be one AND zero?");
1337
1338 // If all of the demanded bits are known zero on one side, return the other.
1339 // These bits cannot contribute to the result of the 'or'.
1340 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
1341 (DemandedMask & ~LHSKnownOne))
1342 return UpdateValueUsesWith(I, I->getOperand(0));
1343 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
1344 (DemandedMask & ~RHSKnownOne))
1345 return UpdateValueUsesWith(I, I->getOperand(1));
1346
1347 // If all of the potentially set bits on one side are known to be set on
1348 // the other side, just use the 'other' side.
1349 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
1350 (DemandedMask & (~RHSKnownZero)))
1351 return UpdateValueUsesWith(I, I->getOperand(0));
1352 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
1353 (DemandedMask & (~LHSKnownZero)))
1354 return UpdateValueUsesWith(I, I->getOperand(1));
1355
1356 // If the RHS is a constant, see if we can simplify it.
1357 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1358 return UpdateValueUsesWith(I, I);
1359
1360 // Output known-0 bits are only known if clear in both the LHS & RHS.
1361 RHSKnownZero &= LHSKnownZero;
1362 // Output known-1 are known to be set if set in either the LHS | RHS.
1363 RHSKnownOne |= LHSKnownOne;
1364 break;
1365 case Instruction::Xor: {
1366 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1367 RHSKnownZero, RHSKnownOne, Depth+1))
1368 return true;
1369 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1370 "Bits known to be one AND zero?");
1371 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1372 LHSKnownZero, LHSKnownOne, Depth+1))
1373 return true;
1374 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1375 "Bits known to be one AND zero?");
1376
1377 // If all of the demanded bits are known zero on one side, return the other.
1378 // These bits cannot contribute to the result of the 'xor'.
1379 if ((DemandedMask & RHSKnownZero) == DemandedMask)
1380 return UpdateValueUsesWith(I, I->getOperand(0));
1381 if ((DemandedMask & LHSKnownZero) == DemandedMask)
1382 return UpdateValueUsesWith(I, I->getOperand(1));
1383
1384 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1385 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1386 (RHSKnownOne & LHSKnownOne);
1387 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1388 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1389 (RHSKnownOne & LHSKnownZero);
1390
1391 // If all of the demanded bits are known to be zero on one side or the
1392 // other, turn this into an *inclusive* or.
1393 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1394 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1395 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001396 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001397 I->getName());
1398 InsertNewInstBefore(Or, *I);
1399 return UpdateValueUsesWith(I, Or);
1400 }
1401
1402 // If all of the demanded bits on one side are known, and all of the set
1403 // bits on that side are also known to be set on the other side, turn this
1404 // into an AND, as we know the bits will be cleared.
1405 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1406 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1407 // all known
1408 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
1409 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
1410 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +00001411 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001412 InsertNewInstBefore(And, *I);
1413 return UpdateValueUsesWith(I, And);
1414 }
1415 }
1416
1417 // If the RHS is a constant, see if we can simplify it.
1418 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
1419 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1420 return UpdateValueUsesWith(I, I);
1421
1422 RHSKnownZero = KnownZeroOut;
1423 RHSKnownOne = KnownOneOut;
1424 break;
1425 }
1426 case Instruction::Select:
1427 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
1428 RHSKnownZero, RHSKnownOne, Depth+1))
1429 return true;
1430 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
1431 LHSKnownZero, LHSKnownOne, Depth+1))
1432 return true;
1433 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1434 "Bits known to be one AND zero?");
1435 assert((LHSKnownZero & LHSKnownOne) == 0 &&
1436 "Bits known to be one AND zero?");
1437
1438 // If the operands are constants, see if we can simplify them.
1439 if (ShrinkDemandedConstant(I, 1, DemandedMask))
1440 return UpdateValueUsesWith(I, I);
1441 if (ShrinkDemandedConstant(I, 2, DemandedMask))
1442 return UpdateValueUsesWith(I, I);
1443
1444 // Only known if known in both the LHS and RHS.
1445 RHSKnownOne &= LHSKnownOne;
1446 RHSKnownZero &= LHSKnownZero;
1447 break;
1448 case Instruction::Trunc: {
1449 uint32_t truncBf =
1450 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
1451 DemandedMask.zext(truncBf);
1452 RHSKnownZero.zext(truncBf);
1453 RHSKnownOne.zext(truncBf);
1454 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1455 RHSKnownZero, RHSKnownOne, Depth+1))
1456 return true;
1457 DemandedMask.trunc(BitWidth);
1458 RHSKnownZero.trunc(BitWidth);
1459 RHSKnownOne.trunc(BitWidth);
1460 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1461 "Bits known to be one AND zero?");
1462 break;
1463 }
1464 case Instruction::BitCast:
1465 if (!I->getOperand(0)->getType()->isInteger())
1466 return false;
1467
1468 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1469 RHSKnownZero, RHSKnownOne, Depth+1))
1470 return true;
1471 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1472 "Bits known to be one AND zero?");
1473 break;
1474 case Instruction::ZExt: {
1475 // Compute the bits in the result that are not present in the input.
1476 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1477 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1478
1479 DemandedMask.trunc(SrcBitWidth);
1480 RHSKnownZero.trunc(SrcBitWidth);
1481 RHSKnownOne.trunc(SrcBitWidth);
1482 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1483 RHSKnownZero, RHSKnownOne, Depth+1))
1484 return true;
1485 DemandedMask.zext(BitWidth);
1486 RHSKnownZero.zext(BitWidth);
1487 RHSKnownOne.zext(BitWidth);
1488 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1489 "Bits known to be one AND zero?");
1490 // The top bits are known to be zero.
1491 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1492 break;
1493 }
1494 case Instruction::SExt: {
1495 // Compute the bits in the result that are not present in the input.
1496 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1497 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1498
1499 APInt InputDemandedBits = DemandedMask &
1500 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1501
1502 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1503 // If any of the sign extended bits are demanded, we know that the sign
1504 // bit is demanded.
1505 if ((NewBits & DemandedMask) != 0)
1506 InputDemandedBits.set(SrcBitWidth-1);
1507
1508 InputDemandedBits.trunc(SrcBitWidth);
1509 RHSKnownZero.trunc(SrcBitWidth);
1510 RHSKnownOne.trunc(SrcBitWidth);
1511 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1512 RHSKnownZero, RHSKnownOne, Depth+1))
1513 return true;
1514 InputDemandedBits.zext(BitWidth);
1515 RHSKnownZero.zext(BitWidth);
1516 RHSKnownOne.zext(BitWidth);
1517 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1518 "Bits known to be one AND zero?");
1519
1520 // If the sign bit of the input is known set or clear, then we know the
1521 // top bits of the result.
1522
1523 // If the input sign bit is known zero, or if the NewBits are not demanded
1524 // convert this into a zero extension.
1525 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1526 {
1527 // Convert to ZExt cast
1528 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1529 return UpdateValueUsesWith(I, NewCast);
1530 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1531 RHSKnownOne |= NewBits;
1532 }
1533 break;
1534 }
1535 case Instruction::Add: {
1536 // Figure out what the input bits are. If the top bits of the and result
1537 // are not demanded, then the add doesn't demand them from its input
1538 // either.
1539 uint32_t NLZ = DemandedMask.countLeadingZeros();
1540
1541 // If there is a constant on the RHS, there are a variety of xformations
1542 // we can do.
1543 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1544 // If null, this should be simplified elsewhere. Some of the xforms here
1545 // won't work if the RHS is zero.
1546 if (RHS->isZero())
1547 break;
1548
1549 // If the top bit of the output is demanded, demand everything from the
1550 // input. Otherwise, we demand all the input bits except NLZ top bits.
1551 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1552
1553 // Find information about known zero/one bits in the input.
1554 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1555 LHSKnownZero, LHSKnownOne, Depth+1))
1556 return true;
1557
1558 // If the RHS of the add has bits set that can't affect the input, reduce
1559 // the constant.
1560 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1561 return UpdateValueUsesWith(I, I);
1562
1563 // Avoid excess work.
1564 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1565 break;
1566
1567 // Turn it into OR if input bits are zero.
1568 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1569 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001570 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001571 I->getName());
1572 InsertNewInstBefore(Or, *I);
1573 return UpdateValueUsesWith(I, Or);
1574 }
1575
1576 // We can say something about the output known-zero and known-one bits,
1577 // depending on potential carries from the input constant and the
1578 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1579 // bits set and the RHS constant is 0x01001, then we know we have a known
1580 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1581
1582 // To compute this, we first compute the potential carry bits. These are
1583 // the bits which may be modified. I'm not aware of a better way to do
1584 // this scan.
1585 const APInt& RHSVal = RHS->getValue();
1586 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1587
1588 // Now that we know which bits have carries, compute the known-1/0 sets.
1589
1590 // Bits are known one if they are known zero in one operand and one in the
1591 // other, and there is no input carry.
1592 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1593 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1594
1595 // Bits are known zero if they are known zero in both operands and there
1596 // is no input carry.
1597 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1598 } else {
1599 // If the high-bits of this ADD are not demanded, then it does not demand
1600 // the high bits of its LHS or RHS.
1601 if (DemandedMask[BitWidth-1] == 0) {
1602 // Right fill the mask of bits for this ADD to demand the most
1603 // significant bit and all those below it.
1604 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1605 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1606 LHSKnownZero, LHSKnownOne, Depth+1))
1607 return true;
1608 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1609 LHSKnownZero, LHSKnownOne, Depth+1))
1610 return true;
1611 }
1612 }
1613 break;
1614 }
1615 case Instruction::Sub:
1616 // If the high-bits of this SUB are not demanded, then it does not demand
1617 // the high bits of its LHS or RHS.
1618 if (DemandedMask[BitWidth-1] == 0) {
1619 // Right fill the mask of bits for this SUB to demand the most
1620 // significant bit and all those below it.
1621 uint32_t NLZ = DemandedMask.countLeadingZeros();
1622 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1623 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1624 LHSKnownZero, LHSKnownOne, Depth+1))
1625 return true;
1626 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1627 LHSKnownZero, LHSKnownOne, Depth+1))
1628 return true;
1629 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001630 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1631 // the known zeros and ones.
1632 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001633 break;
1634 case Instruction::Shl:
1635 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1636 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1637 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1638 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1639 RHSKnownZero, RHSKnownOne, Depth+1))
1640 return true;
1641 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1642 "Bits known to be one AND zero?");
1643 RHSKnownZero <<= ShiftAmt;
1644 RHSKnownOne <<= ShiftAmt;
1645 // low bits known zero.
1646 if (ShiftAmt)
1647 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1648 }
1649 break;
1650 case Instruction::LShr:
1651 // For a logical shift right
1652 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1653 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1654
1655 // Unsigned shift right.
1656 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1657 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1658 RHSKnownZero, RHSKnownOne, Depth+1))
1659 return true;
1660 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1661 "Bits known to be one AND zero?");
1662 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1663 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1664 if (ShiftAmt) {
1665 // Compute the new bits that are at the top now.
1666 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1667 RHSKnownZero |= HighBits; // high bits known zero.
1668 }
1669 }
1670 break;
1671 case Instruction::AShr:
1672 // If this is an arithmetic shift right and only the low-bit is set, we can
1673 // always convert this into a logical shr, even if the shift amount is
1674 // variable. The low bit of the shift cannot be an input sign bit unless
1675 // the shift amount is >= the size of the datatype, which is undefined.
1676 if (DemandedMask == 1) {
1677 // Perform the logical shift right.
Gabor Greifa645dd32008-05-16 19:29:10 +00001678 Value *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001679 I->getOperand(0), I->getOperand(1), I->getName());
1680 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1681 return UpdateValueUsesWith(I, NewVal);
1682 }
1683
1684 // If the sign bit is the only bit demanded by this ashr, then there is no
1685 // need to do it, the shift doesn't change the high bit.
1686 if (DemandedMask.isSignBit())
1687 return UpdateValueUsesWith(I, I->getOperand(0));
1688
1689 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1690 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1691
1692 // Signed shift right.
1693 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1694 // If any of the "high bits" are demanded, we should set the sign bit as
1695 // demanded.
1696 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1697 DemandedMaskIn.set(BitWidth-1);
1698 if (SimplifyDemandedBits(I->getOperand(0),
1699 DemandedMaskIn,
1700 RHSKnownZero, RHSKnownOne, Depth+1))
1701 return true;
1702 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1703 "Bits known to be one AND zero?");
1704 // Compute the new bits that are at the top now.
1705 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1706 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1707 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1708
1709 // Handle the sign bits.
1710 APInt SignBit(APInt::getSignBit(BitWidth));
1711 // Adjust to where it is now in the mask.
1712 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1713
1714 // If the input sign bit is known to be zero, or if none of the top bits
1715 // are demanded, turn this into an unsigned shift right.
1716 if (RHSKnownZero[BitWidth-ShiftAmt-1] ||
1717 (HighBits & ~DemandedMask) == HighBits) {
1718 // Perform the logical shift right.
Gabor Greifa645dd32008-05-16 19:29:10 +00001719 Value *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001720 I->getOperand(0), SA, I->getName());
1721 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1722 return UpdateValueUsesWith(I, NewVal);
1723 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1724 RHSKnownOne |= HighBits;
1725 }
1726 }
1727 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001728 case Instruction::SRem:
1729 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1730 APInt RA = Rem->getValue();
1731 if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
Dan Gohman5a154a12008-05-06 00:51:48 +00001732 APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001733 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1734 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1735 LHSKnownZero, LHSKnownOne, Depth+1))
1736 return true;
1737
1738 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1739 LHSKnownZero |= ~LowBits;
1740 else if (LHSKnownOne[BitWidth-1])
1741 LHSKnownOne |= ~LowBits;
1742
1743 KnownZero |= LHSKnownZero & DemandedMask;
1744 KnownOne |= LHSKnownOne & DemandedMask;
1745
1746 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1747 }
1748 }
1749 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001750 case Instruction::URem: {
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001751 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
1752 APInt RA = Rem->getValue();
Dan Gohman5a154a12008-05-06 00:51:48 +00001753 if (RA.isPowerOf2()) {
1754 APInt LowBits = (RA - 1);
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001755 APInt Mask2 = LowBits & DemandedMask;
1756 KnownZero |= ~LowBits & DemandedMask;
1757 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1758 KnownZero, KnownOne, Depth+1))
1759 return true;
1760
1761 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
Dan Gohmanbec16052008-04-28 17:02:21 +00001762 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001763 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001764 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001765
1766 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1767 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Dan Gohman23ea06d2008-05-01 19:13:24 +00001768 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1769 KnownZero2, KnownOne2, Depth+1))
1770 return true;
1771
Dan Gohmanbec16052008-04-28 17:02:21 +00001772 uint32_t Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23ea06d2008-05-01 19:13:24 +00001773 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
Dan Gohmanbec16052008-04-28 17:02:21 +00001774 KnownZero2, KnownOne2, Depth+1))
1775 return true;
1776
1777 Leaders = std::max(Leaders,
1778 KnownZero2.countLeadingOnes());
1779 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001780 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001781 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001782 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001783
1784 // If the client is only demanding bits that we know, return the known
1785 // constant.
1786 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1787 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1788 return false;
1789}
1790
1791
1792/// SimplifyDemandedVectorElts - The specified value producecs a vector with
1793/// 64 or fewer elements. DemandedElts contains the set of elements that are
1794/// actually used by the caller. This method analyzes which elements of the
1795/// operand are undef and returns that information in UndefElts.
1796///
1797/// If the information about demanded elements can be used to simplify the
1798/// operation, the operation is simplified, then the resultant value is
1799/// returned. This returns null if no change was made.
1800Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1801 uint64_t &UndefElts,
1802 unsigned Depth) {
1803 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1804 assert(VWidth <= 64 && "Vector too wide to analyze!");
1805 uint64_t EltMask = ~0ULL >> (64-VWidth);
1806 assert(DemandedElts != EltMask && (DemandedElts & ~EltMask) == 0 &&
1807 "Invalid DemandedElts!");
1808
1809 if (isa<UndefValue>(V)) {
1810 // If the entire vector is undefined, just return this info.
1811 UndefElts = EltMask;
1812 return 0;
1813 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1814 UndefElts = EltMask;
1815 return UndefValue::get(V->getType());
1816 }
1817
1818 UndefElts = 0;
1819 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1820 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1821 Constant *Undef = UndefValue::get(EltTy);
1822
1823 std::vector<Constant*> Elts;
1824 for (unsigned i = 0; i != VWidth; ++i)
1825 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1826 Elts.push_back(Undef);
1827 UndefElts |= (1ULL << i);
1828 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1829 Elts.push_back(Undef);
1830 UndefElts |= (1ULL << i);
1831 } else { // Otherwise, defined.
1832 Elts.push_back(CP->getOperand(i));
1833 }
1834
1835 // If we changed the constant, return it.
1836 Constant *NewCP = ConstantVector::get(Elts);
1837 return NewCP != CP ? NewCP : 0;
1838 } else if (isa<ConstantAggregateZero>(V)) {
1839 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1840 // set to undef.
1841 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1842 Constant *Zero = Constant::getNullValue(EltTy);
1843 Constant *Undef = UndefValue::get(EltTy);
1844 std::vector<Constant*> Elts;
1845 for (unsigned i = 0; i != VWidth; ++i)
1846 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1847 UndefElts = DemandedElts ^ EltMask;
1848 return ConstantVector::get(Elts);
1849 }
1850
1851 if (!V->hasOneUse()) { // Other users may use these bits.
1852 if (Depth != 0) { // Not at the root.
1853 // TODO: Just compute the UndefElts information recursively.
1854 return false;
1855 }
1856 return false;
1857 } else if (Depth == 10) { // Limit search depth.
1858 return false;
1859 }
1860
1861 Instruction *I = dyn_cast<Instruction>(V);
1862 if (!I) return false; // Only analyze instructions.
1863
1864 bool MadeChange = false;
1865 uint64_t UndefElts2;
1866 Value *TmpV;
1867 switch (I->getOpcode()) {
1868 default: break;
1869
1870 case Instruction::InsertElement: {
1871 // If this is a variable index, we don't know which element it overwrites.
1872 // demand exactly the same input as we produce.
1873 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1874 if (Idx == 0) {
1875 // Note that we can't propagate undef elt info, because we don't know
1876 // which elt is getting updated.
1877 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1878 UndefElts2, Depth+1);
1879 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1880 break;
1881 }
1882
1883 // If this is inserting an element that isn't demanded, remove this
1884 // insertelement.
1885 unsigned IdxNo = Idx->getZExtValue();
1886 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1887 return AddSoonDeadInstToWorklist(*I, 0);
1888
1889 // Otherwise, the element inserted overwrites whatever was there, so the
1890 // input demanded set is simpler than the output set.
1891 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1892 DemandedElts & ~(1ULL << IdxNo),
1893 UndefElts, Depth+1);
1894 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1895
1896 // The inserted element is defined.
1897 UndefElts |= 1ULL << IdxNo;
1898 break;
1899 }
1900 case Instruction::BitCast: {
1901 // Vector->vector casts only.
1902 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1903 if (!VTy) break;
1904 unsigned InVWidth = VTy->getNumElements();
1905 uint64_t InputDemandedElts = 0;
1906 unsigned Ratio;
1907
1908 if (VWidth == InVWidth) {
1909 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1910 // elements as are demanded of us.
1911 Ratio = 1;
1912 InputDemandedElts = DemandedElts;
1913 } else if (VWidth > InVWidth) {
1914 // Untested so far.
1915 break;
1916
1917 // If there are more elements in the result than there are in the source,
1918 // then an input element is live if any of the corresponding output
1919 // elements are live.
1920 Ratio = VWidth/InVWidth;
1921 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1922 if (DemandedElts & (1ULL << OutIdx))
1923 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1924 }
1925 } else {
1926 // Untested so far.
1927 break;
1928
1929 // If there are more elements in the source than there are in the result,
1930 // then an input element is live if the corresponding output element is
1931 // live.
1932 Ratio = InVWidth/VWidth;
1933 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1934 if (DemandedElts & (1ULL << InIdx/Ratio))
1935 InputDemandedElts |= 1ULL << InIdx;
1936 }
1937
1938 // div/rem demand all inputs, because they don't want divide by zero.
1939 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1940 UndefElts2, Depth+1);
1941 if (TmpV) {
1942 I->setOperand(0, TmpV);
1943 MadeChange = true;
1944 }
1945
1946 UndefElts = UndefElts2;
1947 if (VWidth > InVWidth) {
1948 assert(0 && "Unimp");
1949 // If there are more elements in the result than there are in the source,
1950 // then an output element is undef if the corresponding input element is
1951 // undef.
1952 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1953 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1954 UndefElts |= 1ULL << OutIdx;
1955 } else if (VWidth < InVWidth) {
1956 assert(0 && "Unimp");
1957 // If there are more elements in the source than there are in the result,
1958 // then a result element is undef if all of the corresponding input
1959 // elements are undef.
1960 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1961 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1962 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1963 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1964 }
1965 break;
1966 }
1967 case Instruction::And:
1968 case Instruction::Or:
1969 case Instruction::Xor:
1970 case Instruction::Add:
1971 case Instruction::Sub:
1972 case Instruction::Mul:
1973 // div/rem demand all inputs, because they don't want divide by zero.
1974 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1975 UndefElts, Depth+1);
1976 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1977 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1978 UndefElts2, Depth+1);
1979 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1980
1981 // Output elements are undefined if both are undefined. Consider things
1982 // like undef&0. The result is known zero, not undef.
1983 UndefElts &= UndefElts2;
1984 break;
1985
1986 case Instruction::Call: {
1987 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1988 if (!II) break;
1989 switch (II->getIntrinsicID()) {
1990 default: break;
1991
1992 // Binary vector operations that work column-wise. A dest element is a
1993 // function of the corresponding input elements from the two inputs.
1994 case Intrinsic::x86_sse_sub_ss:
1995 case Intrinsic::x86_sse_mul_ss:
1996 case Intrinsic::x86_sse_min_ss:
1997 case Intrinsic::x86_sse_max_ss:
1998 case Intrinsic::x86_sse2_sub_sd:
1999 case Intrinsic::x86_sse2_mul_sd:
2000 case Intrinsic::x86_sse2_min_sd:
2001 case Intrinsic::x86_sse2_max_sd:
2002 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
2003 UndefElts, Depth+1);
2004 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
2005 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
2006 UndefElts2, Depth+1);
2007 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
2008
2009 // If only the low elt is demanded and this is a scalarizable intrinsic,
2010 // scalarize it now.
2011 if (DemandedElts == 1) {
2012 switch (II->getIntrinsicID()) {
2013 default: break;
2014 case Intrinsic::x86_sse_sub_ss:
2015 case Intrinsic::x86_sse_mul_ss:
2016 case Intrinsic::x86_sse2_sub_sd:
2017 case Intrinsic::x86_sse2_mul_sd:
2018 // TODO: Lower MIN/MAX/ABS/etc
2019 Value *LHS = II->getOperand(1);
2020 Value *RHS = II->getOperand(2);
2021 // Extract the element as scalars.
2022 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
2023 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
2024
2025 switch (II->getIntrinsicID()) {
2026 default: assert(0 && "Case stmts out of sync!");
2027 case Intrinsic::x86_sse_sub_ss:
2028 case Intrinsic::x86_sse2_sub_sd:
Gabor Greifa645dd32008-05-16 19:29:10 +00002029 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002030 II->getName()), *II);
2031 break;
2032 case Intrinsic::x86_sse_mul_ss:
2033 case Intrinsic::x86_sse2_mul_sd:
Gabor Greifa645dd32008-05-16 19:29:10 +00002034 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002035 II->getName()), *II);
2036 break;
2037 }
2038
2039 Instruction *New =
Gabor Greifd6da1d02008-04-06 20:25:17 +00002040 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
2041 II->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002042 InsertNewInstBefore(New, *II);
2043 AddSoonDeadInstToWorklist(*II, 0);
2044 return New;
2045 }
2046 }
2047
2048 // Output elements are undefined if both are undefined. Consider things
2049 // like undef&0. The result is known zero, not undef.
2050 UndefElts &= UndefElts2;
2051 break;
2052 }
2053 break;
2054 }
2055 }
2056 return MadeChange ? I : 0;
2057}
2058
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002059/// AssociativeOpt - Perform an optimization on an associative operator. This
2060/// function is designed to check a chain of associative operators for a
2061/// potential to apply a certain optimization. Since the optimization may be
2062/// applicable if the expression was reassociated, this checks the chain, then
2063/// reassociates the expression as necessary to expose the optimization
2064/// opportunity. This makes use of a special Functor, which must define
2065/// 'shouldApply' and 'apply' methods.
2066///
2067template<typename Functor>
2068Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
2069 unsigned Opcode = Root.getOpcode();
2070 Value *LHS = Root.getOperand(0);
2071
2072 // Quick check, see if the immediate LHS matches...
2073 if (F.shouldApply(LHS))
2074 return F.apply(Root);
2075
2076 // Otherwise, if the LHS is not of the same opcode as the root, return.
2077 Instruction *LHSI = dyn_cast<Instruction>(LHS);
2078 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
2079 // Should we apply this transform to the RHS?
2080 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
2081
2082 // If not to the RHS, check to see if we should apply to the LHS...
2083 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
2084 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
2085 ShouldApply = true;
2086 }
2087
2088 // If the functor wants to apply the optimization to the RHS of LHSI,
2089 // reassociate the expression from ((? op A) op B) to (? op (A op B))
2090 if (ShouldApply) {
2091 BasicBlock *BB = Root.getParent();
2092
2093 // Now all of the instructions are in the current basic block, go ahead
2094 // and perform the reassociation.
2095 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
2096
2097 // First move the selected RHS to the LHS of the root...
2098 Root.setOperand(0, LHSI->getOperand(1));
2099
2100 // Make what used to be the LHS of the root be the user of the root...
2101 Value *ExtraOperand = TmpLHSI->getOperand(1);
2102 if (&Root == TmpLHSI) {
2103 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
2104 return 0;
2105 }
2106 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
2107 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
2108 TmpLHSI->getParent()->getInstList().remove(TmpLHSI);
2109 BasicBlock::iterator ARI = &Root; ++ARI;
2110 BB->getInstList().insert(ARI, TmpLHSI); // Move TmpLHSI to after Root
2111 ARI = Root;
2112
2113 // Now propagate the ExtraOperand down the chain of instructions until we
2114 // get to LHSI.
2115 while (TmpLHSI != LHSI) {
2116 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
2117 // Move the instruction to immediately before the chain we are
2118 // constructing to avoid breaking dominance properties.
2119 NextLHSI->getParent()->getInstList().remove(NextLHSI);
2120 BB->getInstList().insert(ARI, NextLHSI);
2121 ARI = NextLHSI;
2122
2123 Value *NextOp = NextLHSI->getOperand(1);
2124 NextLHSI->setOperand(1, ExtraOperand);
2125 TmpLHSI = NextLHSI;
2126 ExtraOperand = NextOp;
2127 }
2128
2129 // Now that the instructions are reassociated, have the functor perform
2130 // the transformation...
2131 return F.apply(Root);
2132 }
2133
2134 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
2135 }
2136 return 0;
2137}
2138
Dan Gohman089efff2008-05-13 00:00:25 +00002139namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002140
2141// AddRHS - Implements: X + X --> X << 1
2142struct AddRHS {
2143 Value *RHS;
2144 AddRHS(Value *rhs) : RHS(rhs) {}
2145 bool shouldApply(Value *LHS) const { return LHS == RHS; }
2146 Instruction *apply(BinaryOperator &Add) const {
Gabor Greifa645dd32008-05-16 19:29:10 +00002147 return BinaryOperator::CreateShl(Add.getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002148 ConstantInt::get(Add.getType(), 1));
2149 }
2150};
2151
2152// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
2153// iff C1&C2 == 0
2154struct AddMaskingAnd {
2155 Constant *C2;
2156 AddMaskingAnd(Constant *c) : C2(c) {}
2157 bool shouldApply(Value *LHS) const {
2158 ConstantInt *C1;
2159 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
2160 ConstantExpr::getAnd(C1, C2)->isNullValue();
2161 }
2162 Instruction *apply(BinaryOperator &Add) const {
Gabor Greifa645dd32008-05-16 19:29:10 +00002163 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002164 }
2165};
2166
Dan Gohman089efff2008-05-13 00:00:25 +00002167}
2168
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002169static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
2170 InstCombiner *IC) {
2171 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
2172 if (Constant *SOC = dyn_cast<Constant>(SO))
2173 return ConstantExpr::getCast(CI->getOpcode(), SOC, I.getType());
2174
Gabor Greifa645dd32008-05-16 19:29:10 +00002175 return IC->InsertNewInstBefore(CastInst::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002176 CI->getOpcode(), SO, I.getType(), SO->getName() + ".cast"), I);
2177 }
2178
2179 // Figure out if the constant is the left or the right argument.
2180 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
2181 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
2182
2183 if (Constant *SOC = dyn_cast<Constant>(SO)) {
2184 if (ConstIsRHS)
2185 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
2186 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
2187 }
2188
2189 Value *Op0 = SO, *Op1 = ConstOperand;
2190 if (!ConstIsRHS)
2191 std::swap(Op0, Op1);
2192 Instruction *New;
2193 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00002194 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002195 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00002196 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002197 SO->getName()+".cmp");
2198 else {
2199 assert(0 && "Unknown binary instruction type!");
2200 abort();
2201 }
2202 return IC->InsertNewInstBefore(New, I);
2203}
2204
2205// FoldOpIntoSelect - Given an instruction with a select as one operand and a
2206// constant as the other operand, try to fold the binary operator into the
2207// select arguments. This also works for Cast instructions, which obviously do
2208// not have a second operand.
2209static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
2210 InstCombiner *IC) {
2211 // Don't modify shared select instructions
2212 if (!SI->hasOneUse()) return 0;
2213 Value *TV = SI->getOperand(1);
2214 Value *FV = SI->getOperand(2);
2215
2216 if (isa<Constant>(TV) || isa<Constant>(FV)) {
2217 // Bool selects with constant operands can be folded to logical ops.
2218 if (SI->getType() == Type::Int1Ty) return 0;
2219
2220 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
2221 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
2222
Gabor Greifd6da1d02008-04-06 20:25:17 +00002223 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
2224 SelectFalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002225 }
2226 return 0;
2227}
2228
2229
2230/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
2231/// node as operand #0, see if we can fold the instruction into the PHI (which
2232/// is only possible if all operands to the PHI are constants).
2233Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
2234 PHINode *PN = cast<PHINode>(I.getOperand(0));
2235 unsigned NumPHIValues = PN->getNumIncomingValues();
2236 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
2237
2238 // Check to see if all of the operands of the PHI are constants. If there is
2239 // one non-constant value, remember the BB it is. If there is more than one
2240 // or if *it* is a PHI, bail out.
2241 BasicBlock *NonConstBB = 0;
2242 for (unsigned i = 0; i != NumPHIValues; ++i)
2243 if (!isa<Constant>(PN->getIncomingValue(i))) {
2244 if (NonConstBB) return 0; // More than one non-const value.
2245 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
2246 NonConstBB = PN->getIncomingBlock(i);
2247
2248 // If the incoming non-constant value is in I's block, we have an infinite
2249 // loop.
2250 if (NonConstBB == I.getParent())
2251 return 0;
2252 }
2253
2254 // If there is exactly one non-constant value, we can insert a copy of the
2255 // operation in that block. However, if this is a critical edge, we would be
2256 // inserting the computation one some other paths (e.g. inside a loop). Only
2257 // do this if the pred block is unconditionally branching into the phi block.
2258 if (NonConstBB) {
2259 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
2260 if (!BI || !BI->isUnconditional()) return 0;
2261 }
2262
2263 // Okay, we can do the transformation: create the new PHI node.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002264 PHINode *NewPN = PHINode::Create(I.getType(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002265 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
2266 InsertNewInstBefore(NewPN, *PN);
2267 NewPN->takeName(PN);
2268
2269 // Next, add all of the operands to the PHI.
2270 if (I.getNumOperands() == 2) {
2271 Constant *C = cast<Constant>(I.getOperand(1));
2272 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00002273 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002274 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2275 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
2276 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
2277 else
2278 InV = ConstantExpr::get(I.getOpcode(), InC, C);
2279 } else {
2280 assert(PN->getIncomingBlock(i) == NonConstBB);
2281 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00002282 InV = BinaryOperator::Create(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002283 PN->getIncomingValue(i), C, "phitmp",
2284 NonConstBB->getTerminator());
2285 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00002286 InV = CmpInst::Create(CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002287 CI->getPredicate(),
2288 PN->getIncomingValue(i), C, "phitmp",
2289 NonConstBB->getTerminator());
2290 else
2291 assert(0 && "Unknown binop!");
2292
2293 AddToWorkList(cast<Instruction>(InV));
2294 }
2295 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2296 }
2297 } else {
2298 CastInst *CI = cast<CastInst>(&I);
2299 const Type *RetTy = CI->getType();
2300 for (unsigned i = 0; i != NumPHIValues; ++i) {
2301 Value *InV;
2302 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2303 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
2304 } else {
2305 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greifa645dd32008-05-16 19:29:10 +00002306 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002307 I.getType(), "phitmp",
2308 NonConstBB->getTerminator());
2309 AddToWorkList(cast<Instruction>(InV));
2310 }
2311 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2312 }
2313 }
2314 return ReplaceInstUsesWith(I, NewPN);
2315}
2316
Chris Lattner55476162008-01-29 06:52:45 +00002317
2318/// CannotBeNegativeZero - Return true if we can prove that the specified FP
2319/// value is never equal to -0.0.
2320///
2321/// Note that this function will need to be revisited when we support nondefault
2322/// rounding modes!
2323///
2324static bool CannotBeNegativeZero(const Value *V) {
2325 if (const ConstantFP *CFP = dyn_cast<ConstantFP>(V))
2326 return !CFP->getValueAPF().isNegZero();
2327
2328 // (add x, 0.0) is guaranteed to return +0.0, not -0.0.
2329 if (const Instruction *I = dyn_cast<Instruction>(V)) {
2330 if (I->getOpcode() == Instruction::Add &&
2331 isa<ConstantFP>(I->getOperand(1)) &&
2332 cast<ConstantFP>(I->getOperand(1))->isNullValue())
2333 return true;
2334
2335 if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(I))
2336 if (II->getIntrinsicID() == Intrinsic::sqrt)
2337 return CannotBeNegativeZero(II->getOperand(1));
2338
2339 if (const CallInst *CI = dyn_cast<CallInst>(I))
2340 if (const Function *F = CI->getCalledFunction()) {
2341 if (F->isDeclaration()) {
2342 switch (F->getNameLen()) {
2343 case 3: // abs(x) != -0.0
2344 if (!strcmp(F->getNameStart(), "abs")) return true;
2345 break;
2346 case 4: // abs[lf](x) != -0.0
2347 if (!strcmp(F->getNameStart(), "absf")) return true;
2348 if (!strcmp(F->getNameStart(), "absl")) return true;
2349 break;
2350 }
2351 }
2352 }
2353 }
2354
2355 return false;
2356}
2357
2358
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002359Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2360 bool Changed = SimplifyCommutative(I);
2361 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2362
2363 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2364 // X + undef -> undef
2365 if (isa<UndefValue>(RHS))
2366 return ReplaceInstUsesWith(I, RHS);
2367
2368 // X + 0 --> X
2369 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
2370 if (RHSC->isNullValue())
2371 return ReplaceInstUsesWith(I, LHS);
2372 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen2fc20782007-09-14 22:26:36 +00002373 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
2374 (I.getType())->getValueAPF()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002375 return ReplaceInstUsesWith(I, LHS);
2376 }
2377
2378 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2379 // X + (signbit) --> X ^ signbit
2380 const APInt& Val = CI->getValue();
2381 uint32_t BitWidth = Val.getBitWidth();
2382 if (Val == APInt::getSignBit(BitWidth))
Gabor Greifa645dd32008-05-16 19:29:10 +00002383 return BinaryOperator::CreateXor(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002384
2385 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2386 // (X & 254)+1 -> (X&254)|1
2387 if (!isa<VectorType>(I.getType())) {
2388 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
2389 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
2390 KnownZero, KnownOne))
2391 return &I;
2392 }
2393 }
2394
2395 if (isa<PHINode>(LHS))
2396 if (Instruction *NV = FoldOpIntoPhi(I))
2397 return NV;
2398
2399 ConstantInt *XorRHS = 0;
2400 Value *XorLHS = 0;
2401 if (isa<ConstantInt>(RHSC) &&
2402 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2403 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2404 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2405
2406 uint32_t Size = TySizeBits / 2;
2407 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2408 APInt CFF80Val(-C0080Val);
2409 do {
2410 if (TySizeBits > Size) {
2411 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2412 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2413 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2414 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2415 // This is a sign extend if the top bits are known zero.
2416 if (!MaskedValueIsZero(XorLHS,
2417 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2418 Size = 0; // Not a sign ext, but can't be any others either.
2419 break;
2420 }
2421 }
2422 Size >>= 1;
2423 C0080Val = APIntOps::lshr(C0080Val, Size);
2424 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2425 } while (Size >= 1);
2426
2427 // FIXME: This shouldn't be necessary. When the backends can handle types
2428 // with funny bit widths then this whole cascade of if statements should
2429 // be removed. It is just here to get the size of the "middle" type back
2430 // up to something that the back ends can handle.
2431 const Type *MiddleType = 0;
2432 switch (Size) {
2433 default: break;
2434 case 32: MiddleType = Type::Int32Ty; break;
2435 case 16: MiddleType = Type::Int16Ty; break;
2436 case 8: MiddleType = Type::Int8Ty; break;
2437 }
2438 if (MiddleType) {
2439 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2440 InsertNewInstBefore(NewTrunc, I);
2441 return new SExtInst(NewTrunc, I.getType(), I.getName());
2442 }
2443 }
2444 }
2445
2446 // X + X --> X << 1
2447 if (I.getType()->isInteger() && I.getType() != Type::Int1Ty) {
2448 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2449
2450 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2451 if (RHSI->getOpcode() == Instruction::Sub)
2452 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2453 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2454 }
2455 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2456 if (LHSI->getOpcode() == Instruction::Sub)
2457 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2458 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2459 }
2460 }
2461
2462 // -A + B --> B - A
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002463 // -A + -B --> -(A + B)
2464 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattner322a9192008-02-18 17:50:16 +00002465 if (LHS->getType()->isIntOrIntVector()) {
2466 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002467 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattner322a9192008-02-18 17:50:16 +00002468 InsertNewInstBefore(NewAdd, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002469 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattner322a9192008-02-18 17:50:16 +00002470 }
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002471 }
2472
Gabor Greifa645dd32008-05-16 19:29:10 +00002473 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002474 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002475
2476 // A + -B --> A - B
2477 if (!isa<Constant>(RHS))
2478 if (Value *V = dyn_castNegVal(RHS))
Gabor Greifa645dd32008-05-16 19:29:10 +00002479 return BinaryOperator::CreateSub(LHS, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002480
2481
2482 ConstantInt *C2;
2483 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2484 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greifa645dd32008-05-16 19:29:10 +00002485 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002486
2487 // X*C1 + X*C2 --> X * (C1+C2)
2488 ConstantInt *C1;
2489 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002490 return BinaryOperator::CreateMul(X, Add(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002491 }
2492
2493 // X + X*C --> X * (C+1)
2494 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greifa645dd32008-05-16 19:29:10 +00002495 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002496
2497 // X + ~X --> -1 since ~X = -X-1
2498 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2499 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2500
2501
2502 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2503 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2504 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2505 return R;
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002506
2507 // A+B --> A|B iff A and B have no bits set in common.
2508 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2509 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2510 APInt LHSKnownOne(IT->getBitWidth(), 0);
2511 APInt LHSKnownZero(IT->getBitWidth(), 0);
2512 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2513 if (LHSKnownZero != 0) {
2514 APInt RHSKnownOne(IT->getBitWidth(), 0);
2515 APInt RHSKnownZero(IT->getBitWidth(), 0);
2516 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2517
2518 // No bits in common -> bitwise or.
2519 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue()) {
2520 cerr << "HACK\n" << *LHS << *RHS << "\n";
2521 return BinaryOperator::CreateOr(LHS, RHS);
2522 }
2523 }
2524 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002525
Nick Lewycky83598a72008-02-03 07:42:09 +00002526 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky5d03b512008-02-03 08:19:11 +00002527 if (I.getType()->isIntOrIntVector()) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002528 Value *W, *X, *Y, *Z;
2529 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2530 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2531 if (W != Y) {
2532 if (W == Z) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002533 std::swap(Y, Z);
Nick Lewycky83598a72008-02-03 07:42:09 +00002534 } else if (Y == X) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002535 std::swap(W, X);
2536 } else if (X == Z) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002537 std::swap(Y, Z);
2538 std::swap(W, X);
2539 }
2540 }
2541
2542 if (W == Y) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002543 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewycky83598a72008-02-03 07:42:09 +00002544 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002545 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewycky83598a72008-02-03 07:42:09 +00002546 }
2547 }
2548 }
2549
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002550 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2551 Value *X = 0;
2552 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greifa645dd32008-05-16 19:29:10 +00002553 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002554
2555 // (X & FF00) + xx00 -> (X+xx00) & FF00
2556 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2557 Constant *Anded = And(CRHS, C2);
2558 if (Anded == CRHS) {
2559 // See if all bits from the first bit set in the Add RHS up are included
2560 // in the mask. First, get the rightmost bit.
2561 const APInt& AddRHSV = CRHS->getValue();
2562
2563 // Form a mask of all bits from the lowest bit added through the top.
2564 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2565
2566 // See if the and mask includes all of these bits.
2567 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2568
2569 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2570 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greifa645dd32008-05-16 19:29:10 +00002571 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002572 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002573 return BinaryOperator::CreateAnd(NewAdd, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002574 }
2575 }
2576 }
2577
2578 // Try to fold constant add into select arguments.
2579 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2580 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2581 return R;
2582 }
2583
2584 // add (cast *A to intptrtype) B ->
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002585 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002586 {
2587 CastInst *CI = dyn_cast<CastInst>(LHS);
2588 Value *Other = RHS;
2589 if (!CI) {
2590 CI = dyn_cast<CastInst>(RHS);
2591 Other = LHS;
2592 }
2593 if (CI && CI->getType()->isSized() &&
2594 (CI->getType()->getPrimitiveSizeInBits() ==
2595 TD->getIntPtrType()->getPrimitiveSizeInBits())
2596 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00002597 unsigned AS =
2598 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +00002599 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2600 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greifd6da1d02008-04-06 20:25:17 +00002601 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002602 return new PtrToIntInst(I2, CI->getType());
2603 }
2604 }
Christopher Lamb244ec282007-12-18 09:34:41 +00002605
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002606 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb244ec282007-12-18 09:34:41 +00002607 {
2608 SelectInst *SI = dyn_cast<SelectInst>(LHS);
2609 Value *Other = RHS;
2610 if (!SI) {
2611 SI = dyn_cast<SelectInst>(RHS);
2612 Other = LHS;
2613 }
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002614 if (SI && SI->hasOneUse()) {
Christopher Lamb244ec282007-12-18 09:34:41 +00002615 Value *TV = SI->getTrueValue();
2616 Value *FV = SI->getFalseValue();
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002617 Value *A, *N;
Christopher Lamb244ec282007-12-18 09:34:41 +00002618
2619 // Can we fold the add into the argument of the select?
2620 // We check both true and false select arguments for a matching subtract.
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002621 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Value(A))) &&
2622 A == Other) // Fold the add into the true select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002623 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002624 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Value(A))) &&
2625 A == Other) // Fold the add into the false select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002626 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb244ec282007-12-18 09:34:41 +00002627 }
2628 }
Chris Lattner55476162008-01-29 06:52:45 +00002629
2630 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2631 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2632 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2633 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002634
2635 return Changed ? &I : 0;
2636}
2637
2638// isSignBit - Return true if the value represented by the constant only has the
2639// highest order bit set.
2640static bool isSignBit(ConstantInt *CI) {
2641 uint32_t NumBits = CI->getType()->getPrimitiveSizeInBits();
2642 return CI->getValue() == APInt::getSignBit(NumBits);
2643}
2644
2645Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2646 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2647
2648 if (Op0 == Op1) // sub X, X -> 0
2649 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2650
2651 // If this is a 'B = x-(-A)', change to B = x+A...
2652 if (Value *V = dyn_castNegVal(Op1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002653 return BinaryOperator::CreateAdd(Op0, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002654
2655 if (isa<UndefValue>(Op0))
2656 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2657 if (isa<UndefValue>(Op1))
2658 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2659
2660 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2661 // Replace (-1 - A) with (~A)...
2662 if (C->isAllOnesValue())
Gabor Greifa645dd32008-05-16 19:29:10 +00002663 return BinaryOperator::CreateNot(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002664
2665 // C - ~X == X + (1+C)
2666 Value *X = 0;
2667 if (match(Op1, m_Not(m_Value(X))))
Gabor Greifa645dd32008-05-16 19:29:10 +00002668 return BinaryOperator::CreateAdd(X, AddOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002669
2670 // -(X >>u 31) -> (X >>s 31)
2671 // -(X >>s 31) -> (X >>u 31)
2672 if (C->isZero()) {
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002673 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002674 if (SI->getOpcode() == Instruction::LShr) {
2675 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2676 // Check to see if we are shifting out everything but the sign bit.
2677 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2678 SI->getType()->getPrimitiveSizeInBits()-1) {
2679 // Ok, the transformation is safe. Insert AShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002680 return BinaryOperator::Create(Instruction::AShr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002681 SI->getOperand(0), CU, SI->getName());
2682 }
2683 }
2684 }
2685 else if (SI->getOpcode() == Instruction::AShr) {
2686 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2687 // Check to see if we are shifting out everything but the sign bit.
2688 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2689 SI->getType()->getPrimitiveSizeInBits()-1) {
2690 // Ok, the transformation is safe. Insert LShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002691 return BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002692 SI->getOperand(0), CU, SI->getName());
2693 }
2694 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002695 }
2696 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002697 }
2698
2699 // Try to fold constant sub into select arguments.
2700 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2701 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2702 return R;
2703
2704 if (isa<PHINode>(Op0))
2705 if (Instruction *NV = FoldOpIntoPhi(I))
2706 return NV;
2707 }
2708
2709 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2710 if (Op1I->getOpcode() == Instruction::Add &&
2711 !Op0->getType()->isFPOrFPVector()) {
2712 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002713 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002714 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002715 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002716 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2717 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2718 // C1-(X+C2) --> (C1-C2)-X
Gabor Greifa645dd32008-05-16 19:29:10 +00002719 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002720 Op1I->getOperand(0));
2721 }
2722 }
2723
2724 if (Op1I->hasOneUse()) {
2725 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2726 // is not used by anyone else...
2727 //
2728 if (Op1I->getOpcode() == Instruction::Sub &&
2729 !Op1I->getType()->isFPOrFPVector()) {
2730 // Swap the two operands of the subexpr...
2731 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2732 Op1I->setOperand(0, IIOp1);
2733 Op1I->setOperand(1, IIOp0);
2734
2735 // Create the new top level add instruction...
Gabor Greifa645dd32008-05-16 19:29:10 +00002736 return BinaryOperator::CreateAdd(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002737 }
2738
2739 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2740 //
2741 if (Op1I->getOpcode() == Instruction::And &&
2742 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2743 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2744
2745 Value *NewNot =
Gabor Greifa645dd32008-05-16 19:29:10 +00002746 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2747 return BinaryOperator::CreateAnd(Op0, NewNot);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002748 }
2749
2750 // 0 - (X sdiv C) -> (X sdiv -C)
2751 if (Op1I->getOpcode() == Instruction::SDiv)
2752 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2753 if (CSI->isZero())
2754 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002755 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002756 ConstantExpr::getNeg(DivRHS));
2757
2758 // X - X*C --> X * (1-C)
2759 ConstantInt *C2 = 0;
2760 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2761 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00002762 return BinaryOperator::CreateMul(Op0, CP1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002763 }
Dan Gohmanda338742007-09-17 17:31:57 +00002764
2765 // X - ((X / Y) * Y) --> X % Y
2766 if (Op1I->getOpcode() == Instruction::Mul)
2767 if (Instruction *I = dyn_cast<Instruction>(Op1I->getOperand(0)))
2768 if (Op0 == I->getOperand(0) &&
2769 Op1I->getOperand(1) == I->getOperand(1)) {
2770 if (I->getOpcode() == Instruction::SDiv)
Gabor Greifa645dd32008-05-16 19:29:10 +00002771 return BinaryOperator::CreateSRem(Op0, Op1I->getOperand(1));
Dan Gohmanda338742007-09-17 17:31:57 +00002772 if (I->getOpcode() == Instruction::UDiv)
Gabor Greifa645dd32008-05-16 19:29:10 +00002773 return BinaryOperator::CreateURem(Op0, Op1I->getOperand(1));
Dan Gohmanda338742007-09-17 17:31:57 +00002774 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002775 }
2776 }
2777
2778 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002779 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002780 if (Op0I->getOpcode() == Instruction::Add) {
2781 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2782 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2783 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2784 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2785 } else if (Op0I->getOpcode() == Instruction::Sub) {
2786 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002787 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002788 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002789 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002790
2791 ConstantInt *C1;
2792 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2793 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greifa645dd32008-05-16 19:29:10 +00002794 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002795
2796 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2797 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greifa645dd32008-05-16 19:29:10 +00002798 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002799 }
2800 return 0;
2801}
2802
2803/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2804/// comparison only checks the sign bit. If it only checks the sign bit, set
2805/// TrueIfSigned if the result of the comparison is true when the input value is
2806/// signed.
2807static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2808 bool &TrueIfSigned) {
2809 switch (pred) {
2810 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2811 TrueIfSigned = true;
2812 return RHS->isZero();
2813 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2814 TrueIfSigned = true;
2815 return RHS->isAllOnesValue();
2816 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2817 TrueIfSigned = false;
2818 return RHS->isAllOnesValue();
2819 case ICmpInst::ICMP_UGT:
2820 // True if LHS u> RHS and RHS == high-bit-mask - 1
2821 TrueIfSigned = true;
2822 return RHS->getValue() ==
2823 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2824 case ICmpInst::ICMP_UGE:
2825 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2826 TrueIfSigned = true;
2827 return RHS->getValue() ==
2828 APInt::getSignBit(RHS->getType()->getPrimitiveSizeInBits());
2829 default:
2830 return false;
2831 }
2832}
2833
2834Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2835 bool Changed = SimplifyCommutative(I);
2836 Value *Op0 = I.getOperand(0);
2837
2838 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2839 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2840
2841 // Simplify mul instructions with a constant RHS...
2842 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2843 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2844
2845 // ((X << C1)*C2) == (X * (C2 << C1))
2846 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2847 if (SI->getOpcode() == Instruction::Shl)
2848 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002849 return BinaryOperator::CreateMul(SI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002850 ConstantExpr::getShl(CI, ShOp));
2851
2852 if (CI->isZero())
2853 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2854 if (CI->equalsInt(1)) // X * 1 == X
2855 return ReplaceInstUsesWith(I, Op0);
2856 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greifa645dd32008-05-16 19:29:10 +00002857 return BinaryOperator::CreateNeg(Op0, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002858
2859 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2860 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greifa645dd32008-05-16 19:29:10 +00002861 return BinaryOperator::CreateShl(Op0,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002862 ConstantInt::get(Op0->getType(), Val.logBase2()));
2863 }
2864 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2865 if (Op1F->isNullValue())
2866 return ReplaceInstUsesWith(I, Op1);
2867
2868 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2869 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Dale Johannesen2fc20782007-09-14 22:26:36 +00002870 // We need a better interface for long double here.
2871 if (Op1->getType() == Type::FloatTy || Op1->getType() == Type::DoubleTy)
2872 if (Op1F->isExactlyValue(1.0))
2873 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002874 }
2875
2876 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2877 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner58194082008-05-18 04:11:26 +00002878 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002879 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greifa645dd32008-05-16 19:29:10 +00002880 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002881 Op1, "tmp");
2882 InsertNewInstBefore(Add, I);
2883 Value *C1C2 = ConstantExpr::getMul(Op1,
2884 cast<Constant>(Op0I->getOperand(1)));
Gabor Greifa645dd32008-05-16 19:29:10 +00002885 return BinaryOperator::CreateAdd(Add, C1C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002886
2887 }
2888
2889 // Try to fold constant mul into select arguments.
2890 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2891 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2892 return R;
2893
2894 if (isa<PHINode>(Op0))
2895 if (Instruction *NV = FoldOpIntoPhi(I))
2896 return NV;
2897 }
2898
2899 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2900 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002901 return BinaryOperator::CreateMul(Op0v, Op1v);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002902
2903 // If one of the operands of the multiply is a cast from a boolean value, then
2904 // we know the bool is either zero or one, so this is a 'masking' multiply.
2905 // See if we can simplify things based on how the boolean was originally
2906 // formed.
2907 CastInst *BoolCast = 0;
2908 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(0)))
2909 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2910 BoolCast = CI;
2911 if (!BoolCast)
2912 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2913 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2914 BoolCast = CI;
2915 if (BoolCast) {
2916 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2917 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2918 const Type *SCOpTy = SCIOp0->getType();
2919 bool TIS = false;
2920
2921 // If the icmp is true iff the sign bit of X is set, then convert this
2922 // multiply into a shift/and combination.
2923 if (isa<ConstantInt>(SCIOp1) &&
2924 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2925 TIS) {
2926 // Shift the X value right to turn it into "all signbits".
2927 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2928 SCOpTy->getPrimitiveSizeInBits()-1);
2929 Value *V =
2930 InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00002931 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002932 BoolCast->getOperand(0)->getName()+
2933 ".mask"), I);
2934
2935 // If the multiply type is not the same as the source type, sign extend
2936 // or truncate to the multiply type.
2937 if (I.getType() != V->getType()) {
2938 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2939 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2940 Instruction::CastOps opcode =
2941 (SrcBits == DstBits ? Instruction::BitCast :
2942 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2943 V = InsertCastBefore(opcode, V, I.getType(), I);
2944 }
2945
2946 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greifa645dd32008-05-16 19:29:10 +00002947 return BinaryOperator::CreateAnd(V, OtherOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002948 }
2949 }
2950 }
2951
2952 return Changed ? &I : 0;
2953}
2954
2955/// This function implements the transforms on div instructions that work
2956/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2957/// used by the visitors to those instructions.
2958/// @brief Transforms common to all three div instructions
2959Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2960 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2961
Chris Lattner653ef3c2008-02-19 06:12:18 +00002962 // undef / X -> 0 for integer.
2963 // undef / X -> undef for FP (the undef could be a snan).
2964 if (isa<UndefValue>(Op0)) {
2965 if (Op0->getType()->isFPOrFPVector())
2966 return ReplaceInstUsesWith(I, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002967 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00002968 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002969
2970 // X / undef -> undef
2971 if (isa<UndefValue>(Op1))
2972 return ReplaceInstUsesWith(I, Op1);
2973
Chris Lattner5be238b2008-01-28 00:58:18 +00002974 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2975 // This does not apply for fdiv.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002976 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
Chris Lattner5be238b2008-01-28 00:58:18 +00002977 // [su]div X, (Cond ? 0 : Y) -> div X, Y. If the div and the select are in
2978 // the same basic block, then we replace the select with Y, and the
2979 // condition of the select with false (if the cond value is in the same BB).
2980 // If the select has uses other than the div, this allows them to be
2981 // simplified also. Note that div X, Y is just as good as div X, 0 (undef)
2982 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(1)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002983 if (ST->isNullValue()) {
2984 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2985 if (CondI && CondI->getParent() == I.getParent())
2986 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
2987 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
2988 I.setOperand(1, SI->getOperand(2));
2989 else
2990 UpdateValueUsesWith(SI, SI->getOperand(2));
2991 return &I;
2992 }
2993
Chris Lattner5be238b2008-01-28 00:58:18 +00002994 // Likewise for: [su]div X, (Cond ? Y : 0) -> div X, Y
2995 if (ConstantInt *ST = dyn_cast<ConstantInt>(SI->getOperand(2)))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002996 if (ST->isNullValue()) {
2997 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
2998 if (CondI && CondI->getParent() == I.getParent())
2999 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
3000 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3001 I.setOperand(1, SI->getOperand(1));
3002 else
3003 UpdateValueUsesWith(SI, SI->getOperand(1));
3004 return &I;
3005 }
3006 }
3007
3008 return 0;
3009}
3010
3011/// This function implements the transforms common to both integer division
3012/// instructions (udiv and sdiv). It is called by the visitors to those integer
3013/// division instructions.
3014/// @brief Common integer divide transforms
3015Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
3016 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3017
Chris Lattnercefb36c2008-05-16 02:59:42 +00003018 // (sdiv X, X) --> 1 (udiv X, X) --> 1
3019 if (Op0 == Op1)
3020 return ReplaceInstUsesWith(I, ConstantInt::get(I.getType(), 1));
3021
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003022 if (Instruction *Common = commonDivTransforms(I))
3023 return Common;
3024
3025 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3026 // div X, 1 == X
3027 if (RHS->equalsInt(1))
3028 return ReplaceInstUsesWith(I, Op0);
3029
3030 // (X / C1) / C2 -> X / (C1*C2)
3031 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
3032 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
3033 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewycky9d798f92008-02-18 22:48:05 +00003034 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
3035 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3036 else
Gabor Greifa645dd32008-05-16 19:29:10 +00003037 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewycky9d798f92008-02-18 22:48:05 +00003038 Multiply(RHS, LHSRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003039 }
3040
3041 if (!RHS->isZero()) { // avoid X udiv 0
3042 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3043 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3044 return R;
3045 if (isa<PHINode>(Op0))
3046 if (Instruction *NV = FoldOpIntoPhi(I))
3047 return NV;
3048 }
3049 }
3050
3051 // 0 / X == 0, we don't need to preserve faults!
3052 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3053 if (LHS->equalsInt(0))
3054 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3055
3056 return 0;
3057}
3058
3059Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3060 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3061
3062 // Handle the integer div common cases
3063 if (Instruction *Common = commonIDivTransforms(I))
3064 return Common;
3065
3066 // X udiv C^2 -> X >> C
3067 // Check to see if this is an unsigned division with an exact power of 2,
3068 // if so, convert to a right shift.
3069 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
3070 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greifa645dd32008-05-16 19:29:10 +00003071 return BinaryOperator::CreateLShr(Op0,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003072 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
3073 }
3074
3075 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
3076 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3077 if (RHSI->getOpcode() == Instruction::Shl &&
3078 isa<ConstantInt>(RHSI->getOperand(0))) {
3079 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3080 if (C1.isPowerOf2()) {
3081 Value *N = RHSI->getOperand(1);
3082 const Type *NTy = N->getType();
3083 if (uint32_t C2 = C1.logBase2()) {
3084 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00003085 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003086 }
Gabor Greifa645dd32008-05-16 19:29:10 +00003087 return BinaryOperator::CreateLShr(Op0, N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003088 }
3089 }
3090 }
3091
3092 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3093 // where C1&C2 are powers of two.
3094 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3095 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3096 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3097 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3098 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3099 // Compute the shift amounts
3100 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3101 // Construct the "on true" case of the select
3102 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00003103 Instruction *TSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003104 Op0, TC, SI->getName()+".t");
3105 TSI = InsertNewInstBefore(TSI, I);
3106
3107 // Construct the "on false" case of the select
3108 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00003109 Instruction *FSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003110 Op0, FC, SI->getName()+".f");
3111 FSI = InsertNewInstBefore(FSI, I);
3112
3113 // construct the select instruction and return it.
Gabor Greifd6da1d02008-04-06 20:25:17 +00003114 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003115 }
3116 }
3117 return 0;
3118}
3119
3120Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3121 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3122
3123 // Handle the integer div common cases
3124 if (Instruction *Common = commonIDivTransforms(I))
3125 return Common;
3126
3127 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3128 // sdiv X, -1 == -X
3129 if (RHS->isAllOnesValue())
Gabor Greifa645dd32008-05-16 19:29:10 +00003130 return BinaryOperator::CreateNeg(Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003131
3132 // -X/C -> X/-C
3133 if (Value *LHSNeg = dyn_castNegVal(Op0))
Gabor Greifa645dd32008-05-16 19:29:10 +00003134 return BinaryOperator::CreateSDiv(LHSNeg, ConstantExpr::getNeg(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003135 }
3136
3137 // If the sign bits of both operands are zero (i.e. we can prove they are
3138 // unsigned inputs), turn this into a udiv.
3139 if (I.getType()->isInteger()) {
3140 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3141 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmandb3dd962007-11-05 23:16:33 +00003142 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00003143 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003144 }
3145 }
3146
3147 return 0;
3148}
3149
3150Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3151 return commonDivTransforms(I);
3152}
3153
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003154/// This function implements the transforms on rem instructions that work
3155/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3156/// is used by the visitors to those instructions.
3157/// @brief Transforms common to all three rem instructions
3158Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3159 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3160
Chris Lattner653ef3c2008-02-19 06:12:18 +00003161 // 0 % X == 0 for integer, we don't need to preserve faults!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003162 if (Constant *LHS = dyn_cast<Constant>(Op0))
3163 if (LHS->isNullValue())
3164 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3165
Chris Lattner653ef3c2008-02-19 06:12:18 +00003166 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3167 if (I.getType()->isFPOrFPVector())
3168 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003169 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00003170 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003171 if (isa<UndefValue>(Op1))
3172 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3173
3174 // Handle cases involving: rem X, (select Cond, Y, Z)
3175 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3176 // rem X, (Cond ? 0 : Y) -> rem X, Y. If the rem and the select are in
3177 // the same basic block, then we replace the select with Y, and the
3178 // condition of the select with false (if the cond value is in the same
3179 // BB). If the select has uses other than the div, this allows them to be
3180 // simplified also.
3181 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
3182 if (ST->isNullValue()) {
3183 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3184 if (CondI && CondI->getParent() == I.getParent())
3185 UpdateValueUsesWith(CondI, ConstantInt::getFalse());
3186 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3187 I.setOperand(1, SI->getOperand(2));
3188 else
3189 UpdateValueUsesWith(SI, SI->getOperand(2));
3190 return &I;
3191 }
3192 // Likewise for: rem X, (Cond ? Y : 0) -> rem X, Y
3193 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
3194 if (ST->isNullValue()) {
3195 Instruction *CondI = dyn_cast<Instruction>(SI->getOperand(0));
3196 if (CondI && CondI->getParent() == I.getParent())
3197 UpdateValueUsesWith(CondI, ConstantInt::getTrue());
3198 else if (I.getParent() != SI->getParent() || SI->hasOneUse())
3199 I.setOperand(1, SI->getOperand(1));
3200 else
3201 UpdateValueUsesWith(SI, SI->getOperand(1));
3202 return &I;
3203 }
3204 }
3205
3206 return 0;
3207}
3208
3209/// This function implements the transforms common to both integer remainder
3210/// instructions (urem and srem). It is called by the visitors to those integer
3211/// remainder instructions.
3212/// @brief Common integer remainder transforms
3213Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3214 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3215
3216 if (Instruction *common = commonRemTransforms(I))
3217 return common;
3218
3219 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3220 // X % 0 == undef, we don't need to preserve faults!
3221 if (RHS->equalsInt(0))
3222 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
3223
3224 if (RHS->equalsInt(1)) // X % 1 == 0
3225 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3226
3227 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3228 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3229 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3230 return R;
3231 } else if (isa<PHINode>(Op0I)) {
3232 if (Instruction *NV = FoldOpIntoPhi(I))
3233 return NV;
3234 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003235
3236 // See if we can fold away this rem instruction.
3237 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3238 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3239 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3240 KnownZero, KnownOne))
3241 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003242 }
3243 }
3244
3245 return 0;
3246}
3247
3248Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3249 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3250
3251 if (Instruction *common = commonIRemTransforms(I))
3252 return common;
3253
3254 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3255 // X urem C^2 -> X and C
3256 // Check to see if this is an unsigned remainder with an exact power of 2,
3257 // if so, convert to a bitwise and.
3258 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3259 if (C->getValue().isPowerOf2())
Gabor Greifa645dd32008-05-16 19:29:10 +00003260 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003261 }
3262
3263 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3264 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3265 if (RHSI->getOpcode() == Instruction::Shl &&
3266 isa<ConstantInt>(RHSI->getOperand(0))) {
3267 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3268 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00003269 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003270 "tmp"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003271 return BinaryOperator::CreateAnd(Op0, Add);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003272 }
3273 }
3274 }
3275
3276 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3277 // where C1&C2 are powers of two.
3278 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3279 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3280 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3281 // STO == 0 and SFO == 0 handled above.
3282 if ((STO->getValue().isPowerOf2()) &&
3283 (SFO->getValue().isPowerOf2())) {
3284 Value *TrueAnd = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003285 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003286 Value *FalseAnd = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003287 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greifd6da1d02008-04-06 20:25:17 +00003288 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003289 }
3290 }
3291 }
3292
3293 return 0;
3294}
3295
3296Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3297 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3298
Dan Gohmandb3dd962007-11-05 23:16:33 +00003299 // Handle the integer rem common cases
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003300 if (Instruction *common = commonIRemTransforms(I))
3301 return common;
3302
3303 if (Value *RHSNeg = dyn_castNegVal(Op1))
3304 if (!isa<ConstantInt>(RHSNeg) ||
3305 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive()) {
3306 // X % -Y -> X % Y
3307 AddUsesToWorkList(I);
3308 I.setOperand(1, RHSNeg);
3309 return &I;
3310 }
3311
Dan Gohmandb3dd962007-11-05 23:16:33 +00003312 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003313 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00003314 if (I.getType()->isInteger()) {
3315 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3316 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3317 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00003318 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmandb3dd962007-11-05 23:16:33 +00003319 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003320 }
3321
3322 return 0;
3323}
3324
3325Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3326 return commonRemTransforms(I);
3327}
3328
3329// isMaxValueMinusOne - return true if this is Max-1
3330static bool isMaxValueMinusOne(const ConstantInt *C, bool isSigned) {
3331 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3332 if (!isSigned)
3333 return C->getValue() == APInt::getAllOnesValue(TypeBits) - 1;
3334 return C->getValue() == APInt::getSignedMaxValue(TypeBits)-1;
3335}
3336
3337// isMinValuePlusOne - return true if this is Min+1
3338static bool isMinValuePlusOne(const ConstantInt *C, bool isSigned) {
3339 if (!isSigned)
3340 return C->getValue() == 1; // unsigned
3341
3342 // Calculate 1111111111000000000000
3343 uint32_t TypeBits = C->getType()->getPrimitiveSizeInBits();
3344 return C->getValue() == APInt::getSignedMinValue(TypeBits)+1;
3345}
3346
3347// isOneBitSet - Return true if there is exactly one bit set in the specified
3348// constant.
3349static bool isOneBitSet(const ConstantInt *CI) {
3350 return CI->getValue().isPowerOf2();
3351}
3352
3353// isHighOnes - Return true if the constant is of the form 1+0+.
3354// This is the same as lowones(~X).
3355static bool isHighOnes(const ConstantInt *CI) {
3356 return (~CI->getValue() + 1).isPowerOf2();
3357}
3358
3359/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3360/// are carefully arranged to allow folding of expressions such as:
3361///
3362/// (A < B) | (A > B) --> (A != B)
3363///
3364/// Note that this is only valid if the first and second predicates have the
3365/// same sign. Is illegal to do: (A u< B) | (A s> B)
3366///
3367/// Three bits are used to represent the condition, as follows:
3368/// 0 A > B
3369/// 1 A == B
3370/// 2 A < B
3371///
3372/// <=> Value Definition
3373/// 000 0 Always false
3374/// 001 1 A > B
3375/// 010 2 A == B
3376/// 011 3 A >= B
3377/// 100 4 A < B
3378/// 101 5 A != B
3379/// 110 6 A <= B
3380/// 111 7 Always true
3381///
3382static unsigned getICmpCode(const ICmpInst *ICI) {
3383 switch (ICI->getPredicate()) {
3384 // False -> 0
3385 case ICmpInst::ICMP_UGT: return 1; // 001
3386 case ICmpInst::ICMP_SGT: return 1; // 001
3387 case ICmpInst::ICMP_EQ: return 2; // 010
3388 case ICmpInst::ICMP_UGE: return 3; // 011
3389 case ICmpInst::ICMP_SGE: return 3; // 011
3390 case ICmpInst::ICMP_ULT: return 4; // 100
3391 case ICmpInst::ICMP_SLT: return 4; // 100
3392 case ICmpInst::ICMP_NE: return 5; // 101
3393 case ICmpInst::ICMP_ULE: return 6; // 110
3394 case ICmpInst::ICMP_SLE: return 6; // 110
3395 // True -> 7
3396 default:
3397 assert(0 && "Invalid ICmp predicate!");
3398 return 0;
3399 }
3400}
3401
3402/// getICmpValue - This is the complement of getICmpCode, which turns an
3403/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00003404/// new ICmp instruction. The sign is passed in to determine which kind
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003405/// of predicate to use in new icmp instructions.
3406static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3407 switch (code) {
3408 default: assert(0 && "Illegal ICmp code!");
3409 case 0: return ConstantInt::getFalse();
3410 case 1:
3411 if (sign)
3412 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3413 else
3414 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3415 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3416 case 3:
3417 if (sign)
3418 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3419 else
3420 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3421 case 4:
3422 if (sign)
3423 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3424 else
3425 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3426 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3427 case 6:
3428 if (sign)
3429 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3430 else
3431 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3432 case 7: return ConstantInt::getTrue();
3433 }
3434}
3435
3436static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3437 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
3438 (ICmpInst::isSignedPredicate(p1) &&
3439 (p2 == ICmpInst::ICMP_EQ || p2 == ICmpInst::ICMP_NE)) ||
3440 (ICmpInst::isSignedPredicate(p2) &&
3441 (p1 == ICmpInst::ICMP_EQ || p1 == ICmpInst::ICMP_NE));
3442}
3443
3444namespace {
3445// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3446struct FoldICmpLogical {
3447 InstCombiner &IC;
3448 Value *LHS, *RHS;
3449 ICmpInst::Predicate pred;
3450 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3451 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3452 pred(ICI->getPredicate()) {}
3453 bool shouldApply(Value *V) const {
3454 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3455 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003456 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3457 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003458 return false;
3459 }
3460 Instruction *apply(Instruction &Log) const {
3461 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3462 if (ICI->getOperand(0) != LHS) {
3463 assert(ICI->getOperand(1) == LHS);
3464 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3465 }
3466
3467 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3468 unsigned LHSCode = getICmpCode(ICI);
3469 unsigned RHSCode = getICmpCode(RHSICI);
3470 unsigned Code;
3471 switch (Log.getOpcode()) {
3472 case Instruction::And: Code = LHSCode & RHSCode; break;
3473 case Instruction::Or: Code = LHSCode | RHSCode; break;
3474 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3475 default: assert(0 && "Illegal logical opcode!"); return 0;
3476 }
3477
3478 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3479 ICmpInst::isSignedPredicate(ICI->getPredicate());
3480
3481 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3482 if (Instruction *I = dyn_cast<Instruction>(RV))
3483 return I;
3484 // Otherwise, it's a constant boolean value...
3485 return IC.ReplaceInstUsesWith(Log, RV);
3486 }
3487};
3488} // end anonymous namespace
3489
3490// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3491// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3492// guaranteed to be a binary operator.
3493Instruction *InstCombiner::OptAndOp(Instruction *Op,
3494 ConstantInt *OpRHS,
3495 ConstantInt *AndRHS,
3496 BinaryOperator &TheAnd) {
3497 Value *X = Op->getOperand(0);
3498 Constant *Together = 0;
3499 if (!Op->isShift())
3500 Together = And(AndRHS, OpRHS);
3501
3502 switch (Op->getOpcode()) {
3503 case Instruction::Xor:
3504 if (Op->hasOneUse()) {
3505 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greifa645dd32008-05-16 19:29:10 +00003506 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003507 InsertNewInstBefore(And, TheAnd);
3508 And->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003509 return BinaryOperator::CreateXor(And, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003510 }
3511 break;
3512 case Instruction::Or:
3513 if (Together == AndRHS) // (X | C) & C --> C
3514 return ReplaceInstUsesWith(TheAnd, AndRHS);
3515
3516 if (Op->hasOneUse() && Together != OpRHS) {
3517 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greifa645dd32008-05-16 19:29:10 +00003518 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003519 InsertNewInstBefore(Or, TheAnd);
3520 Or->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003521 return BinaryOperator::CreateAnd(Or, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003522 }
3523 break;
3524 case Instruction::Add:
3525 if (Op->hasOneUse()) {
3526 // Adding a one to a single bit bit-field should be turned into an XOR
3527 // of the bit. First thing to check is to see if this AND is with a
3528 // single bit constant.
3529 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3530
3531 // If there is only one bit set...
3532 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3533 // Ok, at this point, we know that we are masking the result of the
3534 // ADD down to exactly one bit. If the constant we are adding has
3535 // no bits set below this bit, then we can eliminate the ADD.
3536 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3537
3538 // Check to see if any bits below the one bit set in AndRHSV are set.
3539 if ((AddRHS & (AndRHSV-1)) == 0) {
3540 // If not, the only thing that can effect the output of the AND is
3541 // the bit specified by AndRHSV. If that bit is set, the effect of
3542 // the XOR is to toggle the bit. If it is clear, then the ADD has
3543 // no effect.
3544 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3545 TheAnd.setOperand(0, X);
3546 return &TheAnd;
3547 } else {
3548 // Pull the XOR out of the AND.
Gabor Greifa645dd32008-05-16 19:29:10 +00003549 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003550 InsertNewInstBefore(NewAnd, TheAnd);
3551 NewAnd->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003552 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003553 }
3554 }
3555 }
3556 }
3557 break;
3558
3559 case Instruction::Shl: {
3560 // We know that the AND will not produce any of the bits shifted in, so if
3561 // the anded constant includes them, clear them now!
3562 //
3563 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3564 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3565 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3566 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3567
3568 if (CI->getValue() == ShlMask) {
3569 // Masking out bits that the shift already masks
3570 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3571 } else if (CI != AndRHS) { // Reducing bits set in and.
3572 TheAnd.setOperand(1, CI);
3573 return &TheAnd;
3574 }
3575 break;
3576 }
3577 case Instruction::LShr:
3578 {
3579 // We know that the AND will not produce any of the bits shifted in, so if
3580 // the anded constant includes them, clear them now! This only applies to
3581 // unsigned shifts, because a signed shr may bring in set bits!
3582 //
3583 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3584 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3585 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3586 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3587
3588 if (CI->getValue() == ShrMask) {
3589 // Masking out bits that the shift already masks.
3590 return ReplaceInstUsesWith(TheAnd, Op);
3591 } else if (CI != AndRHS) {
3592 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3593 return &TheAnd;
3594 }
3595 break;
3596 }
3597 case Instruction::AShr:
3598 // Signed shr.
3599 // See if this is shifting in some sign extension, then masking it out
3600 // with an and.
3601 if (Op->hasOneUse()) {
3602 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3603 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3604 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3605 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3606 if (C == AndRHS) { // Masking out bits shifted in.
3607 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3608 // Make the argument unsigned.
3609 Value *ShVal = Op->getOperand(0);
3610 ShVal = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003611 BinaryOperator::CreateLShr(ShVal, OpRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003612 Op->getName()), TheAnd);
Gabor Greifa645dd32008-05-16 19:29:10 +00003613 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003614 }
3615 }
3616 break;
3617 }
3618 return 0;
3619}
3620
3621
3622/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3623/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3624/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3625/// whether to treat the V, Lo and HI as signed or not. IB is the location to
3626/// insert new instructions.
3627Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3628 bool isSigned, bool Inside,
3629 Instruction &IB) {
3630 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3631 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3632 "Lo is not <= Hi in range emission code!");
3633
3634 if (Inside) {
3635 if (Lo == Hi) // Trivially false.
3636 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3637
3638 // V >= Min && V < Hi --> V < Hi
3639 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3640 ICmpInst::Predicate pred = (isSigned ?
3641 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3642 return new ICmpInst(pred, V, Hi);
3643 }
3644
3645 // Emit V-Lo <u Hi-Lo
3646 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greifa645dd32008-05-16 19:29:10 +00003647 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003648 InsertNewInstBefore(Add, IB);
3649 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3650 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3651 }
3652
3653 if (Lo == Hi) // Trivially true.
3654 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3655
3656 // V < Min || V >= Hi -> V > Hi-1
3657 Hi = SubOne(cast<ConstantInt>(Hi));
3658 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3659 ICmpInst::Predicate pred = (isSigned ?
3660 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3661 return new ICmpInst(pred, V, Hi);
3662 }
3663
3664 // Emit V-Lo >u Hi-1-Lo
3665 // Note that Hi has already had one subtracted from it, above.
3666 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greifa645dd32008-05-16 19:29:10 +00003667 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003668 InsertNewInstBefore(Add, IB);
3669 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3670 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3671}
3672
3673// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3674// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3675// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3676// not, since all 1s are not contiguous.
3677static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3678 const APInt& V = Val->getValue();
3679 uint32_t BitWidth = Val->getType()->getBitWidth();
3680 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3681
3682 // look for the first zero bit after the run of ones
3683 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3684 // look for the first non-zero bit
3685 ME = V.getActiveBits();
3686 return true;
3687}
3688
3689/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3690/// where isSub determines whether the operator is a sub. If we can fold one of
3691/// the following xforms:
3692///
3693/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3694/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3695/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3696///
3697/// return (A +/- B).
3698///
3699Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3700 ConstantInt *Mask, bool isSub,
3701 Instruction &I) {
3702 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3703 if (!LHSI || LHSI->getNumOperands() != 2 ||
3704 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3705
3706 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3707
3708 switch (LHSI->getOpcode()) {
3709 default: return 0;
3710 case Instruction::And:
3711 if (And(N, Mask) == Mask) {
3712 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3713 if ((Mask->getValue().countLeadingZeros() +
3714 Mask->getValue().countPopulation()) ==
3715 Mask->getValue().getBitWidth())
3716 break;
3717
3718 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3719 // part, we don't need any explicit masks to take them out of A. If that
3720 // is all N is, ignore it.
3721 uint32_t MB = 0, ME = 0;
3722 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3723 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3724 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3725 if (MaskedValueIsZero(RHS, Mask))
3726 break;
3727 }
3728 }
3729 return 0;
3730 case Instruction::Or:
3731 case Instruction::Xor:
3732 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3733 if ((Mask->getValue().countLeadingZeros() +
3734 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3735 && And(N, Mask)->isZero())
3736 break;
3737 return 0;
3738 }
3739
3740 Instruction *New;
3741 if (isSub)
Gabor Greifa645dd32008-05-16 19:29:10 +00003742 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003743 else
Gabor Greifa645dd32008-05-16 19:29:10 +00003744 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003745 return InsertNewInstBefore(New, I);
3746}
3747
3748Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3749 bool Changed = SimplifyCommutative(I);
3750 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3751
3752 if (isa<UndefValue>(Op1)) // X & undef -> 0
3753 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3754
3755 // and X, X = X
3756 if (Op0 == Op1)
3757 return ReplaceInstUsesWith(I, Op1);
3758
3759 // See if we can simplify any instructions used by the instruction whose sole
3760 // purpose is to compute bits we don't care about.
3761 if (!isa<VectorType>(I.getType())) {
3762 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3763 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3764 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3765 KnownZero, KnownOne))
3766 return &I;
3767 } else {
3768 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3769 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
3770 return ReplaceInstUsesWith(I, I.getOperand(0));
3771 } else if (isa<ConstantAggregateZero>(Op1)) {
3772 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
3773 }
3774 }
3775
3776 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3777 const APInt& AndRHSMask = AndRHS->getValue();
3778 APInt NotAndRHS(~AndRHSMask);
3779
3780 // Optimize a variety of ((val OP C1) & C2) combinations...
3781 if (isa<BinaryOperator>(Op0)) {
3782 Instruction *Op0I = cast<Instruction>(Op0);
3783 Value *Op0LHS = Op0I->getOperand(0);
3784 Value *Op0RHS = Op0I->getOperand(1);
3785 switch (Op0I->getOpcode()) {
3786 case Instruction::Xor:
3787 case Instruction::Or:
3788 // If the mask is only needed on one incoming arm, push it up.
3789 if (Op0I->hasOneUse()) {
3790 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3791 // Not masking anything out for the LHS, move to RHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00003792 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003793 Op0RHS->getName()+".masked");
3794 InsertNewInstBefore(NewRHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003795 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003796 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3797 }
3798 if (!isa<Constant>(Op0RHS) &&
3799 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3800 // Not masking anything out for the RHS, move to LHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00003801 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003802 Op0LHS->getName()+".masked");
3803 InsertNewInstBefore(NewLHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003804 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003805 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3806 }
3807 }
3808
3809 break;
3810 case Instruction::Add:
3811 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3812 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3813 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3814 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003815 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003816 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003817 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003818 break;
3819
3820 case Instruction::Sub:
3821 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3822 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3823 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3824 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003825 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003826 break;
3827 }
3828
3829 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3830 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3831 return Res;
3832 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3833 // If this is an integer truncation or change from signed-to-unsigned, and
3834 // if the source is an and/or with immediate, transform it. This
3835 // frequently occurs for bitfield accesses.
3836 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3837 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3838 CastOp->getNumOperands() == 2)
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003839 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003840 if (CastOp->getOpcode() == Instruction::And) {
3841 // Change: and (cast (and X, C1) to T), C2
3842 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3843 // This will fold the two constants together, which may allow
3844 // other simplifications.
Gabor Greifa645dd32008-05-16 19:29:10 +00003845 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003846 CastOp->getOperand(0), I.getType(),
3847 CastOp->getName()+".shrunk");
3848 NewCast = InsertNewInstBefore(NewCast, I);
3849 // trunc_or_bitcast(C1)&C2
3850 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3851 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greifa645dd32008-05-16 19:29:10 +00003852 return BinaryOperator::CreateAnd(NewCast, C3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003853 } else if (CastOp->getOpcode() == Instruction::Or) {
3854 // Change: and (cast (or X, C1) to T), C2
3855 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3856 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3857 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3858 return ReplaceInstUsesWith(I, AndRHS);
3859 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003860 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003861 }
3862 }
3863
3864 // Try to fold constant and into select arguments.
3865 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3866 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3867 return R;
3868 if (isa<PHINode>(Op0))
3869 if (Instruction *NV = FoldOpIntoPhi(I))
3870 return NV;
3871 }
3872
3873 Value *Op0NotVal = dyn_castNotVal(Op0);
3874 Value *Op1NotVal = dyn_castNotVal(Op1);
3875
3876 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3877 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3878
3879 // (~A & ~B) == (~(A | B)) - De Morgan's Law
3880 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00003881 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003882 I.getName()+".demorgan");
3883 InsertNewInstBefore(Or, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003884 return BinaryOperator::CreateNot(Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003885 }
3886
3887 {
3888 Value *A = 0, *B = 0, *C = 0, *D = 0;
3889 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3890 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3891 return ReplaceInstUsesWith(I, Op1);
3892
3893 // (A|B) & ~(A&B) -> A^B
3894 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3895 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00003896 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003897 }
3898 }
3899
3900 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3901 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3902 return ReplaceInstUsesWith(I, Op0);
3903
3904 // ~(A&B) & (A|B) -> A^B
3905 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3906 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00003907 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003908 }
3909 }
3910
3911 if (Op0->hasOneUse() &&
3912 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3913 if (A == Op1) { // (A^B)&A -> A&(A^B)
3914 I.swapOperands(); // Simplify below
3915 std::swap(Op0, Op1);
3916 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3917 cast<BinaryOperator>(Op0)->swapOperands();
3918 I.swapOperands(); // Simplify below
3919 std::swap(Op0, Op1);
3920 }
3921 }
3922 if (Op1->hasOneUse() &&
3923 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3924 if (B == Op0) { // B&(A^B) -> B&(B^A)
3925 cast<BinaryOperator>(Op1)->swapOperands();
3926 std::swap(A, B);
3927 }
3928 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greifa645dd32008-05-16 19:29:10 +00003929 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003930 InsertNewInstBefore(NotB, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003931 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003932 }
3933 }
3934 }
3935
3936 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
3937 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3938 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
3939 return R;
3940
3941 Value *LHSVal, *RHSVal;
3942 ConstantInt *LHSCst, *RHSCst;
3943 ICmpInst::Predicate LHSCC, RHSCC;
3944 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
3945 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
3946 if (LHSVal == RHSVal && // Found (X icmp C1) & (X icmp C2)
3947 // ICMP_[GL]E X, CST is folded to ICMP_[GL]T elsewhere.
3948 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
3949 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
3950 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
Chris Lattner205ad1d2007-11-22 23:47:13 +00003951 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
3952
3953 // Don't try to fold ICMP_SLT + ICMP_ULT.
3954 (ICmpInst::isEquality(LHSCC) || ICmpInst::isEquality(RHSCC) ||
3955 ICmpInst::isSignedPredicate(LHSCC) ==
3956 ICmpInst::isSignedPredicate(RHSCC))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003957 // Ensure that the larger constant is on the RHS.
Chris Lattnerda628ca2008-01-13 20:59:02 +00003958 ICmpInst::Predicate GT;
3959 if (ICmpInst::isSignedPredicate(LHSCC) ||
3960 (ICmpInst::isEquality(LHSCC) &&
3961 ICmpInst::isSignedPredicate(RHSCC)))
3962 GT = ICmpInst::ICMP_SGT;
3963 else
3964 GT = ICmpInst::ICMP_UGT;
3965
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003966 Constant *Cmp = ConstantExpr::getICmp(GT, LHSCst, RHSCst);
3967 ICmpInst *LHS = cast<ICmpInst>(Op0);
3968 if (cast<ConstantInt>(Cmp)->getZExtValue()) {
3969 std::swap(LHS, RHS);
3970 std::swap(LHSCst, RHSCst);
3971 std::swap(LHSCC, RHSCC);
3972 }
3973
3974 // At this point, we know we have have two icmp instructions
3975 // comparing a value against two constants and and'ing the result
3976 // together. Because of the above check, we know that we only have
3977 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3978 // (from the FoldICmpLogical check above), that the two constants
3979 // are not equal and that the larger constant is on the RHS
3980 assert(LHSCst != RHSCst && "Compares not folded above?");
3981
3982 switch (LHSCC) {
3983 default: assert(0 && "Unknown integer condition code!");
3984 case ICmpInst::ICMP_EQ:
3985 switch (RHSCC) {
3986 default: assert(0 && "Unknown integer condition code!");
3987 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3988 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3989 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3990 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3991 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3992 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3993 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3994 return ReplaceInstUsesWith(I, LHS);
3995 }
3996 case ICmpInst::ICMP_NE:
3997 switch (RHSCC) {
3998 default: assert(0 && "Unknown integer condition code!");
3999 case ICmpInst::ICMP_ULT:
4000 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
4001 return new ICmpInst(ICmpInst::ICMP_ULT, LHSVal, LHSCst);
4002 break; // (X != 13 & X u< 15) -> no change
4003 case ICmpInst::ICMP_SLT:
4004 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
4005 return new ICmpInst(ICmpInst::ICMP_SLT, LHSVal, LHSCst);
4006 break; // (X != 13 & X s< 15) -> no change
4007 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
4008 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
4009 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
4010 return ReplaceInstUsesWith(I, RHS);
4011 case ICmpInst::ICMP_NE:
4012 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
4013 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greifa645dd32008-05-16 19:29:10 +00004014 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004015 LHSVal->getName()+".off");
4016 InsertNewInstBefore(Add, I);
4017 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
4018 ConstantInt::get(Add->getType(), 1));
4019 }
4020 break; // (X != 13 & X != 15) -> no change
4021 }
4022 break;
4023 case ICmpInst::ICMP_ULT:
4024 switch (RHSCC) {
4025 default: assert(0 && "Unknown integer condition code!");
4026 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
4027 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
4028 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4029 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
4030 break;
4031 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
4032 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
4033 return ReplaceInstUsesWith(I, LHS);
4034 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
4035 break;
4036 }
4037 break;
4038 case ICmpInst::ICMP_SLT:
4039 switch (RHSCC) {
4040 default: assert(0 && "Unknown integer condition code!");
4041 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
4042 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
4043 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4044 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
4045 break;
4046 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
4047 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
4048 return ReplaceInstUsesWith(I, LHS);
4049 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
4050 break;
4051 }
4052 break;
4053 case ICmpInst::ICMP_UGT:
4054 switch (RHSCC) {
4055 default: assert(0 && "Unknown integer condition code!");
4056 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X > 13
4057 return ReplaceInstUsesWith(I, LHS);
4058 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
4059 return ReplaceInstUsesWith(I, RHS);
4060 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
4061 break;
4062 case ICmpInst::ICMP_NE:
4063 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
4064 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4065 break; // (X u> 13 & X != 15) -> no change
4066 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) ->(X-14) <u 1
4067 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, false,
4068 true, I);
4069 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
4070 break;
4071 }
4072 break;
4073 case ICmpInst::ICMP_SGT:
4074 switch (RHSCC) {
4075 default: assert(0 && "Unknown integer condition code!");
Chris Lattnerab0fc252007-11-16 06:04:17 +00004076 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004077 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
4078 return ReplaceInstUsesWith(I, RHS);
4079 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
4080 break;
4081 case ICmpInst::ICMP_NE:
4082 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
4083 return new ICmpInst(LHSCC, LHSVal, RHSCst);
4084 break; // (X s> 13 & X != 15) -> no change
4085 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) ->(X-14) s< 1
4086 return InsertRangeTest(LHSVal, AddOne(LHSCst), RHSCst, true,
4087 true, I);
4088 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
4089 break;
4090 }
4091 break;
4092 }
4093 }
4094 }
4095
4096 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4097 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4098 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4099 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4100 const Type *SrcTy = Op0C->getOperand(0)->getType();
4101 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4102 // Only do this if the casts both really cause code to be generated.
4103 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4104 I.getType(), TD) &&
4105 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4106 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004107 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004108 Op1C->getOperand(0),
4109 I.getName());
4110 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004111 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004112 }
4113 }
4114
4115 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4116 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4117 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4118 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4119 SI0->getOperand(1) == SI1->getOperand(1) &&
4120 (SI0->hasOneUse() || SI1->hasOneUse())) {
4121 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004122 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004123 SI1->getOperand(0),
4124 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004125 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004126 SI1->getOperand(1));
4127 }
4128 }
4129
Chris Lattner91882432007-10-24 05:38:08 +00004130 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
4131 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4132 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4133 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
4134 RHS->getPredicate() == FCmpInst::FCMP_ORD)
4135 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4136 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4137 // If either of the constants are nans, then the whole thing returns
4138 // false.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00004139 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00004140 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4141 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4142 RHS->getOperand(0));
4143 }
4144 }
4145 }
4146
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004147 return Changed ? &I : 0;
4148}
4149
4150/// CollectBSwapParts - Look to see if the specified value defines a single byte
4151/// in the result. If it does, and if the specified byte hasn't been filled in
4152/// yet, fill it in and return false.
4153static bool CollectBSwapParts(Value *V, SmallVector<Value*, 8> &ByteValues) {
4154 Instruction *I = dyn_cast<Instruction>(V);
4155 if (I == 0) return true;
4156
4157 // If this is an or instruction, it is an inner node of the bswap.
4158 if (I->getOpcode() == Instruction::Or)
4159 return CollectBSwapParts(I->getOperand(0), ByteValues) ||
4160 CollectBSwapParts(I->getOperand(1), ByteValues);
4161
4162 uint32_t BitWidth = I->getType()->getPrimitiveSizeInBits();
4163 // If this is a shift by a constant int, and it is "24", then its operand
4164 // defines a byte. We only handle unsigned types here.
4165 if (I->isShift() && isa<ConstantInt>(I->getOperand(1))) {
4166 // Not shifting the entire input by N-1 bytes?
4167 if (cast<ConstantInt>(I->getOperand(1))->getLimitedValue(BitWidth) !=
4168 8*(ByteValues.size()-1))
4169 return true;
4170
4171 unsigned DestNo;
4172 if (I->getOpcode() == Instruction::Shl) {
4173 // X << 24 defines the top byte with the lowest of the input bytes.
4174 DestNo = ByteValues.size()-1;
4175 } else {
4176 // X >>u 24 defines the low byte with the highest of the input bytes.
4177 DestNo = 0;
4178 }
4179
4180 // If the destination byte value is already defined, the values are or'd
4181 // together, which isn't a bswap (unless it's an or of the same bits).
4182 if (ByteValues[DestNo] && ByteValues[DestNo] != I->getOperand(0))
4183 return true;
4184 ByteValues[DestNo] = I->getOperand(0);
4185 return false;
4186 }
4187
4188 // Otherwise, we can only handle and(shift X, imm), imm). Bail out of if we
4189 // don't have this.
4190 Value *Shift = 0, *ShiftLHS = 0;
4191 ConstantInt *AndAmt = 0, *ShiftAmt = 0;
4192 if (!match(I, m_And(m_Value(Shift), m_ConstantInt(AndAmt))) ||
4193 !match(Shift, m_Shift(m_Value(ShiftLHS), m_ConstantInt(ShiftAmt))))
4194 return true;
4195 Instruction *SI = cast<Instruction>(Shift);
4196
4197 // Make sure that the shift amount is by a multiple of 8 and isn't too big.
4198 if (ShiftAmt->getLimitedValue(BitWidth) & 7 ||
4199 ShiftAmt->getLimitedValue(BitWidth) > 8*ByteValues.size())
4200 return true;
4201
4202 // Turn 0xFF -> 0, 0xFF00 -> 1, 0xFF0000 -> 2, etc.
4203 unsigned DestByte;
4204 if (AndAmt->getValue().getActiveBits() > 64)
4205 return true;
4206 uint64_t AndAmtVal = AndAmt->getZExtValue();
4207 for (DestByte = 0; DestByte != ByteValues.size(); ++DestByte)
4208 if (AndAmtVal == uint64_t(0xFF) << 8*DestByte)
4209 break;
4210 // Unknown mask for bswap.
4211 if (DestByte == ByteValues.size()) return true;
4212
4213 unsigned ShiftBytes = ShiftAmt->getZExtValue()/8;
4214 unsigned SrcByte;
4215 if (SI->getOpcode() == Instruction::Shl)
4216 SrcByte = DestByte - ShiftBytes;
4217 else
4218 SrcByte = DestByte + ShiftBytes;
4219
4220 // If the SrcByte isn't a bswapped value from the DestByte, reject it.
4221 if (SrcByte != ByteValues.size()-DestByte-1)
4222 return true;
4223
4224 // If the destination byte value is already defined, the values are or'd
4225 // together, which isn't a bswap (unless it's an or of the same bits).
4226 if (ByteValues[DestByte] && ByteValues[DestByte] != SI->getOperand(0))
4227 return true;
4228 ByteValues[DestByte] = SI->getOperand(0);
4229 return false;
4230}
4231
4232/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4233/// If so, insert the new bswap intrinsic and return it.
4234Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4235 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
4236 if (!ITy || ITy->getBitWidth() % 16)
4237 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4238
4239 /// ByteValues - For each byte of the result, we keep track of which value
4240 /// defines each byte.
4241 SmallVector<Value*, 8> ByteValues;
4242 ByteValues.resize(ITy->getBitWidth()/8);
4243
4244 // Try to find all the pieces corresponding to the bswap.
4245 if (CollectBSwapParts(I.getOperand(0), ByteValues) ||
4246 CollectBSwapParts(I.getOperand(1), ByteValues))
4247 return 0;
4248
4249 // Check to see if all of the bytes come from the same value.
4250 Value *V = ByteValues[0];
4251 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4252
4253 // Check to make sure that all of the bytes come from the same value.
4254 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4255 if (ByteValues[i] != V)
4256 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00004257 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004258 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00004259 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00004260 return CallInst::Create(F, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004261}
4262
4263
4264Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4265 bool Changed = SimplifyCommutative(I);
4266 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4267
4268 if (isa<UndefValue>(Op1)) // X | undef -> -1
4269 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4270
4271 // or X, X = X
4272 if (Op0 == Op1)
4273 return ReplaceInstUsesWith(I, Op0);
4274
4275 // See if we can simplify any instructions used by the instruction whose sole
4276 // purpose is to compute bits we don't care about.
4277 if (!isa<VectorType>(I.getType())) {
4278 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4279 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4280 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4281 KnownZero, KnownOne))
4282 return &I;
4283 } else if (isa<ConstantAggregateZero>(Op1)) {
4284 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4285 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4286 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4287 return ReplaceInstUsesWith(I, I.getOperand(1));
4288 }
4289
4290
4291
4292 // or X, -1 == -1
4293 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4294 ConstantInt *C1 = 0; Value *X = 0;
4295 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4296 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004297 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004298 InsertNewInstBefore(Or, I);
4299 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004300 return BinaryOperator::CreateAnd(Or,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004301 ConstantInt::get(RHS->getValue() | C1->getValue()));
4302 }
4303
4304 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4305 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004306 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004307 InsertNewInstBefore(Or, I);
4308 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004309 return BinaryOperator::CreateXor(Or,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004310 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4311 }
4312
4313 // Try to fold constant and into select arguments.
4314 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4315 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4316 return R;
4317 if (isa<PHINode>(Op0))
4318 if (Instruction *NV = FoldOpIntoPhi(I))
4319 return NV;
4320 }
4321
4322 Value *A = 0, *B = 0;
4323 ConstantInt *C1 = 0, *C2 = 0;
4324
4325 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4326 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4327 return ReplaceInstUsesWith(I, Op1);
4328 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4329 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4330 return ReplaceInstUsesWith(I, Op0);
4331
4332 // (A | B) | C and A | (B | C) -> bswap if possible.
4333 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
4334 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4335 match(Op1, m_Or(m_Value(), m_Value())) ||
4336 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4337 match(Op1, m_Shift(m_Value(), m_Value())))) {
4338 if (Instruction *BSwap = MatchBSwap(I))
4339 return BSwap;
4340 }
4341
4342 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4343 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4344 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004345 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004346 InsertNewInstBefore(NOr, I);
4347 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004348 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004349 }
4350
4351 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4352 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4353 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004354 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004355 InsertNewInstBefore(NOr, I);
4356 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004357 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004358 }
4359
4360 // (A & C)|(B & D)
4361 Value *C = 0, *D = 0;
4362 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4363 match(Op1, m_And(m_Value(B), m_Value(D)))) {
4364 Value *V1 = 0, *V2 = 0, *V3 = 0;
4365 C1 = dyn_cast<ConstantInt>(C);
4366 C2 = dyn_cast<ConstantInt>(D);
4367 if (C1 && C2) { // (A & C1)|(B & C2)
4368 // If we have: ((V + N) & C1) | (V & C2)
4369 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4370 // replace with V+N.
4371 if (C1->getValue() == ~C2->getValue()) {
4372 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4373 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4374 // Add commutes, try both ways.
4375 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4376 return ReplaceInstUsesWith(I, A);
4377 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4378 return ReplaceInstUsesWith(I, A);
4379 }
4380 // Or commutes, try both ways.
4381 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4382 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4383 // Add commutes, try both ways.
4384 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4385 return ReplaceInstUsesWith(I, B);
4386 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4387 return ReplaceInstUsesWith(I, B);
4388 }
4389 }
4390 V1 = 0; V2 = 0; V3 = 0;
4391 }
4392
4393 // Check to see if we have any common things being and'ed. If so, find the
4394 // terms for V1 & (V2|V3).
4395 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4396 if (A == B) // (A & C)|(A & D) == A & (C|D)
4397 V1 = A, V2 = C, V3 = D;
4398 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4399 V1 = A, V2 = B, V3 = C;
4400 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4401 V1 = C, V2 = A, V3 = D;
4402 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4403 V1 = C, V2 = A, V3 = B;
4404
4405 if (V1) {
4406 Value *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00004407 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4408 return BinaryOperator::CreateAnd(V1, Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004409 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004410 }
4411 }
4412
4413 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4414 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4415 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4416 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4417 SI0->getOperand(1) == SI1->getOperand(1) &&
4418 (SI0->hasOneUse() || SI1->hasOneUse())) {
4419 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004420 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004421 SI1->getOperand(0),
4422 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004423 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004424 SI1->getOperand(1));
4425 }
4426 }
4427
4428 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4429 if (A == Op1) // ~A | A == -1
4430 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4431 } else {
4432 A = 0;
4433 }
4434 // Note, A is still live here!
4435 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4436 if (Op0 == B)
4437 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4438
4439 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4440 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004441 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004442 I.getName()+".demorgan"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004443 return BinaryOperator::CreateNot(And);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004444 }
4445 }
4446
4447 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4448 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4449 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4450 return R;
4451
4452 Value *LHSVal, *RHSVal;
4453 ConstantInt *LHSCst, *RHSCst;
4454 ICmpInst::Predicate LHSCC, RHSCC;
4455 if (match(Op0, m_ICmp(LHSCC, m_Value(LHSVal), m_ConstantInt(LHSCst))))
4456 if (match(RHS, m_ICmp(RHSCC, m_Value(RHSVal), m_ConstantInt(RHSCst))))
4457 if (LHSVal == RHSVal && // Found (X icmp C1) | (X icmp C2)
4458 // icmp [us][gl]e x, cst is folded to icmp [us][gl]t elsewhere.
4459 LHSCC != ICmpInst::ICMP_UGE && LHSCC != ICmpInst::ICMP_ULE &&
4460 RHSCC != ICmpInst::ICMP_UGE && RHSCC != ICmpInst::ICMP_ULE &&
4461 LHSCC != ICmpInst::ICMP_SGE && LHSCC != ICmpInst::ICMP_SLE &&
4462 RHSCC != ICmpInst::ICMP_SGE && RHSCC != ICmpInst::ICMP_SLE &&
4463 // We can't fold (ugt x, C) | (sgt x, C2).
4464 PredicatesFoldable(LHSCC, RHSCC)) {
4465 // Ensure that the larger constant is on the RHS.
4466 ICmpInst *LHS = cast<ICmpInst>(Op0);
4467 bool NeedsSwap;
4468 if (ICmpInst::isSignedPredicate(LHSCC))
4469 NeedsSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4470 else
4471 NeedsSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4472
4473 if (NeedsSwap) {
4474 std::swap(LHS, RHS);
4475 std::swap(LHSCst, RHSCst);
4476 std::swap(LHSCC, RHSCC);
4477 }
4478
4479 // At this point, we know we have have two icmp instructions
4480 // comparing a value against two constants and or'ing the result
4481 // together. Because of the above check, we know that we only have
4482 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4483 // FoldICmpLogical check above), that the two constants are not
4484 // equal.
4485 assert(LHSCst != RHSCst && "Compares not folded above?");
4486
4487 switch (LHSCC) {
4488 default: assert(0 && "Unknown integer condition code!");
4489 case ICmpInst::ICMP_EQ:
4490 switch (RHSCC) {
4491 default: assert(0 && "Unknown integer condition code!");
4492 case ICmpInst::ICMP_EQ:
4493 if (LHSCst == SubOne(RHSCst)) {// (X == 13 | X == 14) -> X-13 <u 2
4494 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
Gabor Greifa645dd32008-05-16 19:29:10 +00004495 Instruction *Add = BinaryOperator::CreateAdd(LHSVal, AddCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004496 LHSVal->getName()+".off");
4497 InsertNewInstBefore(Add, I);
4498 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4499 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4500 }
4501 break; // (X == 13 | X == 15) -> no change
4502 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4503 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4504 break;
4505 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4506 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4507 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4508 return ReplaceInstUsesWith(I, RHS);
4509 }
4510 break;
4511 case ICmpInst::ICMP_NE:
4512 switch (RHSCC) {
4513 default: assert(0 && "Unknown integer condition code!");
4514 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4515 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4516 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4517 return ReplaceInstUsesWith(I, LHS);
4518 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4519 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4520 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4521 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4522 }
4523 break;
4524 case ICmpInst::ICMP_ULT:
4525 switch (RHSCC) {
4526 default: assert(0 && "Unknown integer condition code!");
4527 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4528 break;
4529 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) ->(X-13) u> 2
Chris Lattner26376862007-11-01 02:18:41 +00004530 // If RHSCst is [us]MAXINT, it is always false. Not handling
4531 // this can cause overflow.
4532 if (RHSCst->isMaxValue(false))
4533 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004534 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), false,
4535 false, I);
4536 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4537 break;
4538 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4539 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4540 return ReplaceInstUsesWith(I, RHS);
4541 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4542 break;
4543 }
4544 break;
4545 case ICmpInst::ICMP_SLT:
4546 switch (RHSCC) {
4547 default: assert(0 && "Unknown integer condition code!");
4548 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4549 break;
4550 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) ->(X-13) s> 2
Chris Lattner26376862007-11-01 02:18:41 +00004551 // If RHSCst is [us]MAXINT, it is always false. Not handling
4552 // this can cause overflow.
4553 if (RHSCst->isMaxValue(true))
4554 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004555 return InsertRangeTest(LHSVal, LHSCst, AddOne(RHSCst), true,
4556 false, I);
4557 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4558 break;
4559 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4560 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4561 return ReplaceInstUsesWith(I, RHS);
4562 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4563 break;
4564 }
4565 break;
4566 case ICmpInst::ICMP_UGT:
4567 switch (RHSCC) {
4568 default: assert(0 && "Unknown integer condition code!");
4569 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4570 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4571 return ReplaceInstUsesWith(I, LHS);
4572 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4573 break;
4574 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4575 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4576 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4577 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4578 break;
4579 }
4580 break;
4581 case ICmpInst::ICMP_SGT:
4582 switch (RHSCC) {
4583 default: assert(0 && "Unknown integer condition code!");
4584 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4585 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4586 return ReplaceInstUsesWith(I, LHS);
4587 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4588 break;
4589 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4590 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4591 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4592 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4593 break;
4594 }
4595 break;
4596 }
4597 }
4598 }
4599
4600 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004601 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004602 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4603 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chenge3779cf2008-03-24 00:21:34 +00004604 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4605 !isa<ICmpInst>(Op1C->getOperand(0))) {
4606 const Type *SrcTy = Op0C->getOperand(0)->getType();
4607 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4608 // Only do this if the casts both really cause code to be
4609 // generated.
4610 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4611 I.getType(), TD) &&
4612 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4613 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004614 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chenge3779cf2008-03-24 00:21:34 +00004615 Op1C->getOperand(0),
4616 I.getName());
4617 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004618 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00004619 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004620 }
4621 }
Chris Lattner91882432007-10-24 05:38:08 +00004622 }
4623
4624
4625 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4626 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4627 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4628 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattnerbe9e63e2008-02-29 06:09:11 +00004629 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
4630 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType())
Chris Lattner91882432007-10-24 05:38:08 +00004631 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4632 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4633 // If either of the constants are nans, then the whole thing returns
4634 // true.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00004635 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00004636 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4637
4638 // Otherwise, no need to compare the two constants, compare the
4639 // rest.
4640 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4641 RHS->getOperand(0));
4642 }
4643 }
4644 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004645
4646 return Changed ? &I : 0;
4647}
4648
Dan Gohman089efff2008-05-13 00:00:25 +00004649namespace {
4650
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004651// XorSelf - Implements: X ^ X --> 0
4652struct XorSelf {
4653 Value *RHS;
4654 XorSelf(Value *rhs) : RHS(rhs) {}
4655 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4656 Instruction *apply(BinaryOperator &Xor) const {
4657 return &Xor;
4658 }
4659};
4660
Dan Gohman089efff2008-05-13 00:00:25 +00004661}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004662
4663Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4664 bool Changed = SimplifyCommutative(I);
4665 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4666
Evan Chenge5cd8032008-03-25 20:07:13 +00004667 if (isa<UndefValue>(Op1)) {
4668 if (isa<UndefValue>(Op0))
4669 // Handle undef ^ undef -> 0 special case. This is a common
4670 // idiom (misuse).
4671 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004672 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chenge5cd8032008-03-25 20:07:13 +00004673 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004674
4675 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4676 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00004677 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004678 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4679 }
4680
4681 // See if we can simplify any instructions used by the instruction whose sole
4682 // purpose is to compute bits we don't care about.
4683 if (!isa<VectorType>(I.getType())) {
4684 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4685 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4686 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4687 KnownZero, KnownOne))
4688 return &I;
4689 } else if (isa<ConstantAggregateZero>(Op1)) {
4690 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
4691 }
4692
4693 // Is this a ~ operation?
4694 if (Value *NotOp = dyn_castNotVal(&I)) {
4695 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4696 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4697 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4698 if (Op0I->getOpcode() == Instruction::And ||
4699 Op0I->getOpcode() == Instruction::Or) {
4700 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4701 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4702 Instruction *NotY =
Gabor Greifa645dd32008-05-16 19:29:10 +00004703 BinaryOperator::CreateNot(Op0I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004704 Op0I->getOperand(1)->getName()+".not");
4705 InsertNewInstBefore(NotY, I);
4706 if (Op0I->getOpcode() == Instruction::And)
Gabor Greifa645dd32008-05-16 19:29:10 +00004707 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004708 else
Gabor Greifa645dd32008-05-16 19:29:10 +00004709 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004710 }
4711 }
4712 }
4713 }
4714
4715
4716 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky1405e922007-08-06 20:04:16 +00004717 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
4718 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
4719 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004720 return new ICmpInst(ICI->getInversePredicate(),
4721 ICI->getOperand(0), ICI->getOperand(1));
4722
Nick Lewycky1405e922007-08-06 20:04:16 +00004723 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4724 return new FCmpInst(FCI->getInversePredicate(),
4725 FCI->getOperand(0), FCI->getOperand(1));
4726 }
4727
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004728 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4729 // ~(c-X) == X-c-1 == X+(-c-1)
4730 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4731 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4732 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4733 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4734 ConstantInt::get(I.getType(), 1));
Gabor Greifa645dd32008-05-16 19:29:10 +00004735 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004736 }
4737
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004738 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004739 if (Op0I->getOpcode() == Instruction::Add) {
4740 // ~(X-c) --> (-c-1)-X
4741 if (RHS->isAllOnesValue()) {
4742 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00004743 return BinaryOperator::CreateSub(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004744 ConstantExpr::getSub(NegOp0CI,
4745 ConstantInt::get(I.getType(), 1)),
4746 Op0I->getOperand(0));
4747 } else if (RHS->getValue().isSignBit()) {
4748 // (X + C) ^ signbit -> (X + C + signbit)
4749 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00004750 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004751
4752 }
4753 } else if (Op0I->getOpcode() == Instruction::Or) {
4754 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4755 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4756 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4757 // Anything in both C1 and C2 is known to be zero, remove it from
4758 // NewRHS.
4759 Constant *CommonBits = And(Op0CI, RHS);
4760 NewRHS = ConstantExpr::getAnd(NewRHS,
4761 ConstantExpr::getNot(CommonBits));
4762 AddToWorkList(Op0I);
4763 I.setOperand(0, Op0I->getOperand(0));
4764 I.setOperand(1, NewRHS);
4765 return &I;
4766 }
4767 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004768 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004769 }
4770
4771 // Try to fold constant and into select arguments.
4772 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4773 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4774 return R;
4775 if (isa<PHINode>(Op0))
4776 if (Instruction *NV = FoldOpIntoPhi(I))
4777 return NV;
4778 }
4779
4780 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
4781 if (X == Op1)
4782 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4783
4784 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
4785 if (X == Op0)
4786 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4787
4788
4789 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4790 if (Op1I) {
4791 Value *A, *B;
4792 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4793 if (A == Op0) { // B^(B|A) == (A|B)^B
4794 Op1I->swapOperands();
4795 I.swapOperands();
4796 std::swap(Op0, Op1);
4797 } else if (B == Op0) { // B^(A|B) == (A|B)^B
4798 I.swapOperands(); // Simplified below.
4799 std::swap(Op0, Op1);
4800 }
4801 } else if (match(Op1I, m_Xor(m_Value(A), m_Value(B)))) {
4802 if (Op0 == A) // A^(A^B) == B
4803 return ReplaceInstUsesWith(I, B);
4804 else if (Op0 == B) // A^(B^A) == B
4805 return ReplaceInstUsesWith(I, A);
4806 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4807 if (A == Op0) { // A^(A&B) -> A^(B&A)
4808 Op1I->swapOperands();
4809 std::swap(A, B);
4810 }
4811 if (B == Op0) { // A^(B&A) -> (B&A)^A
4812 I.swapOperands(); // Simplified below.
4813 std::swap(Op0, Op1);
4814 }
4815 }
4816 }
4817
4818 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4819 if (Op0I) {
4820 Value *A, *B;
4821 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4822 if (A == Op1) // (B|A)^B == (A|B)^B
4823 std::swap(A, B);
4824 if (B == Op1) { // (A|B)^B == A & ~B
4825 Instruction *NotB =
Gabor Greifa645dd32008-05-16 19:29:10 +00004826 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
4827 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004828 }
4829 } else if (match(Op0I, m_Xor(m_Value(A), m_Value(B)))) {
4830 if (Op1 == A) // (A^B)^A == B
4831 return ReplaceInstUsesWith(I, B);
4832 else if (Op1 == B) // (B^A)^A == B
4833 return ReplaceInstUsesWith(I, A);
4834 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
4835 if (A == Op1) // (A&B)^A -> (B&A)^A
4836 std::swap(A, B);
4837 if (B == Op1 && // (B&A)^A == ~B & A
4838 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
4839 Instruction *N =
Gabor Greifa645dd32008-05-16 19:29:10 +00004840 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
4841 return BinaryOperator::CreateAnd(N, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004842 }
4843 }
4844 }
4845
4846 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
4847 if (Op0I && Op1I && Op0I->isShift() &&
4848 Op0I->getOpcode() == Op1I->getOpcode() &&
4849 Op0I->getOperand(1) == Op1I->getOperand(1) &&
4850 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
4851 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004852 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004853 Op1I->getOperand(0),
4854 Op0I->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004855 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004856 Op1I->getOperand(1));
4857 }
4858
4859 if (Op0I && Op1I) {
4860 Value *A, *B, *C, *D;
4861 // (A & B)^(A | B) -> A ^ B
4862 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4863 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
4864 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004865 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004866 }
4867 // (A | B)^(A & B) -> A ^ B
4868 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
4869 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4870 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004871 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004872 }
4873
4874 // (A & B)^(C & D)
4875 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
4876 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
4877 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
4878 // (X & Y)^(X & Y) -> (Y^Z) & X
4879 Value *X = 0, *Y = 0, *Z = 0;
4880 if (A == C)
4881 X = A, Y = B, Z = D;
4882 else if (A == D)
4883 X = A, Y = B, Z = C;
4884 else if (B == C)
4885 X = B, Y = A, Z = D;
4886 else if (B == D)
4887 X = B, Y = A, Z = C;
4888
4889 if (X) {
4890 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004891 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
4892 return BinaryOperator::CreateAnd(NewOp, X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004893 }
4894 }
4895 }
4896
4897 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
4898 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
4899 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4900 return R;
4901
4902 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004903 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004904 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4905 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
4906 const Type *SrcTy = Op0C->getOperand(0)->getType();
4907 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4908 // Only do this if the casts both really cause code to be generated.
4909 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4910 I.getType(), TD) &&
4911 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4912 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004913 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004914 Op1C->getOperand(0),
4915 I.getName());
4916 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004917 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004918 }
4919 }
Chris Lattner91882432007-10-24 05:38:08 +00004920 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004921 return Changed ? &I : 0;
4922}
4923
4924/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
4925/// overflowed for this type.
4926static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
4927 ConstantInt *In2, bool IsSigned = false) {
4928 Result = cast<ConstantInt>(Add(In1, In2));
4929
4930 if (IsSigned)
4931 if (In2->getValue().isNegative())
4932 return Result->getValue().sgt(In1->getValue());
4933 else
4934 return Result->getValue().slt(In1->getValue());
4935 else
4936 return Result->getValue().ult(In1->getValue());
4937}
4938
4939/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
4940/// code necessary to compute the offset from the base pointer (without adding
4941/// in the base pointer). Return the result as a signed integer of intptr size.
4942static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
4943 TargetData &TD = IC.getTargetData();
4944 gep_type_iterator GTI = gep_type_begin(GEP);
4945 const Type *IntPtrTy = TD.getIntPtrType();
4946 Value *Result = Constant::getNullValue(IntPtrTy);
4947
4948 // Build a mask for high order bits.
Chris Lattnereba75862008-04-22 02:53:33 +00004949 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004950 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
4951
4952 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i, ++GTI) {
4953 Value *Op = GEP->getOperand(i);
Duncan Sandsf99fdc62007-11-01 20:53:16 +00004954 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType()) & PtrSizeMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004955 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
4956 if (OpC->isZero()) continue;
4957
4958 // Handle a struct index, which adds its field offset to the pointer.
4959 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
4960 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
4961
4962 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
4963 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
4964 else
4965 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00004966 BinaryOperator::CreateAdd(Result,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004967 ConstantInt::get(IntPtrTy, Size),
4968 GEP->getName()+".offs"), I);
4969 continue;
4970 }
4971
4972 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4973 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
4974 Scale = ConstantExpr::getMul(OC, Scale);
4975 if (Constant *RC = dyn_cast<Constant>(Result))
4976 Result = ConstantExpr::getAdd(RC, Scale);
4977 else {
4978 // Emit an add instruction.
4979 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00004980 BinaryOperator::CreateAdd(Result, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004981 GEP->getName()+".offs"), I);
4982 }
4983 continue;
4984 }
4985 // Convert to correct type.
4986 if (Op->getType() != IntPtrTy) {
4987 if (Constant *OpC = dyn_cast<Constant>(Op))
4988 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
4989 else
4990 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
4991 Op->getName()+".c"), I);
4992 }
4993 if (Size != 1) {
4994 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
4995 if (Constant *OpC = dyn_cast<Constant>(Op))
4996 Op = ConstantExpr::getMul(OpC, Scale);
4997 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greifa645dd32008-05-16 19:29:10 +00004998 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004999 GEP->getName()+".idx"), I);
5000 }
5001
5002 // Emit an add instruction.
5003 if (isa<Constant>(Op) && isa<Constant>(Result))
5004 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5005 cast<Constant>(Result));
5006 else
Gabor Greifa645dd32008-05-16 19:29:10 +00005007 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005008 GEP->getName()+".offs"), I);
5009 }
5010 return Result;
5011}
5012
Chris Lattnereba75862008-04-22 02:53:33 +00005013
5014/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5015/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5016/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5017/// complex, and scales are involved. The above expression would also be legal
5018/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5019/// later form is less amenable to optimization though, and we are allowed to
5020/// generate the first by knowing that pointer arithmetic doesn't overflow.
5021///
5022/// If we can't emit an optimized form for this expression, this returns null.
5023///
5024static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5025 InstCombiner &IC) {
Chris Lattnereba75862008-04-22 02:53:33 +00005026 TargetData &TD = IC.getTargetData();
5027 gep_type_iterator GTI = gep_type_begin(GEP);
5028
5029 // Check to see if this gep only has a single variable index. If so, and if
5030 // any constant indices are a multiple of its scale, then we can compute this
5031 // in terms of the scale of the variable index. For example, if the GEP
5032 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5033 // because the expression will cross zero at the same point.
5034 unsigned i, e = GEP->getNumOperands();
5035 int64_t Offset = 0;
5036 for (i = 1; i != e; ++i, ++GTI) {
5037 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5038 // Compute the aggregate offset of constant indices.
5039 if (CI->isZero()) continue;
5040
5041 // Handle a struct index, which adds its field offset to the pointer.
5042 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5043 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5044 } else {
5045 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5046 Offset += Size*CI->getSExtValue();
5047 }
5048 } else {
5049 // Found our variable index.
5050 break;
5051 }
5052 }
5053
5054 // If there are no variable indices, we must have a constant offset, just
5055 // evaluate it the general way.
5056 if (i == e) return 0;
5057
5058 Value *VariableIdx = GEP->getOperand(i);
5059 // Determine the scale factor of the variable element. For example, this is
5060 // 4 if the variable index is into an array of i32.
5061 uint64_t VariableScale = TD.getABITypeSize(GTI.getIndexedType());
5062
5063 // Verify that there are no other variable indices. If so, emit the hard way.
5064 for (++i, ++GTI; i != e; ++i, ++GTI) {
5065 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5066 if (!CI) return 0;
5067
5068 // Compute the aggregate offset of constant indices.
5069 if (CI->isZero()) continue;
5070
5071 // Handle a struct index, which adds its field offset to the pointer.
5072 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5073 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5074 } else {
5075 uint64_t Size = TD.getABITypeSize(GTI.getIndexedType());
5076 Offset += Size*CI->getSExtValue();
5077 }
5078 }
5079
5080 // Okay, we know we have a single variable index, which must be a
5081 // pointer/array/vector index. If there is no offset, life is simple, return
5082 // the index.
5083 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5084 if (Offset == 0) {
5085 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5086 // we don't need to bother extending: the extension won't affect where the
5087 // computation crosses zero.
5088 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5089 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5090 VariableIdx->getNameStart(), &I);
5091 return VariableIdx;
5092 }
5093
5094 // Otherwise, there is an index. The computation we will do will be modulo
5095 // the pointer size, so get it.
5096 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5097
5098 Offset &= PtrSizeMask;
5099 VariableScale &= PtrSizeMask;
5100
5101 // To do this transformation, any constant index must be a multiple of the
5102 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5103 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5104 // multiple of the variable scale.
5105 int64_t NewOffs = Offset / (int64_t)VariableScale;
5106 if (Offset != NewOffs*(int64_t)VariableScale)
5107 return 0;
5108
5109 // Okay, we can do this evaluation. Start by converting the index to intptr.
5110 const Type *IntPtrTy = TD.getIntPtrType();
5111 if (VariableIdx->getType() != IntPtrTy)
Gabor Greifa645dd32008-05-16 19:29:10 +00005112 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattnereba75862008-04-22 02:53:33 +00005113 true /*SExt*/,
5114 VariableIdx->getNameStart(), &I);
5115 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greifa645dd32008-05-16 19:29:10 +00005116 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattnereba75862008-04-22 02:53:33 +00005117}
5118
5119
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005120/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5121/// else. At this point we know that the GEP is on the LHS of the comparison.
5122Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5123 ICmpInst::Predicate Cond,
5124 Instruction &I) {
5125 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5126
Chris Lattnereba75862008-04-22 02:53:33 +00005127 // Look through bitcasts.
5128 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5129 RHS = BCI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005130
5131 Value *PtrBase = GEPLHS->getOperand(0);
5132 if (PtrBase == RHS) {
Chris Lattneraf97d022008-02-05 04:45:32 +00005133 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattnereba75862008-04-22 02:53:33 +00005134 // This transformation (ignoring the base and scales) is valid because we
5135 // know pointers can't overflow. See if we can output an optimized form.
5136 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5137
5138 // If not, synthesize the offset the hard way.
5139 if (Offset == 0)
5140 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattneraf97d022008-02-05 04:45:32 +00005141 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5142 Constant::getNullValue(Offset->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005143 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5144 // If the base pointers are different, but the indices are the same, just
5145 // compare the base pointer.
5146 if (PtrBase != GEPRHS->getOperand(0)) {
5147 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5148 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5149 GEPRHS->getOperand(0)->getType();
5150 if (IndicesTheSame)
5151 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5152 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5153 IndicesTheSame = false;
5154 break;
5155 }
5156
5157 // If all indices are the same, just compare the base pointers.
5158 if (IndicesTheSame)
5159 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5160 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5161
5162 // Otherwise, the base pointers are different and the indices are
5163 // different, bail out.
5164 return 0;
5165 }
5166
5167 // If one of the GEPs has all zero indices, recurse.
5168 bool AllZeros = true;
5169 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5170 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5171 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5172 AllZeros = false;
5173 break;
5174 }
5175 if (AllZeros)
5176 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5177 ICmpInst::getSwappedPredicate(Cond), I);
5178
5179 // If the other GEP has all zero indices, recurse.
5180 AllZeros = true;
5181 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5182 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5183 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5184 AllZeros = false;
5185 break;
5186 }
5187 if (AllZeros)
5188 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5189
5190 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5191 // If the GEPs only differ by one index, compare it.
5192 unsigned NumDifferences = 0; // Keep track of # differences.
5193 unsigned DiffOperand = 0; // The operand that differs.
5194 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5195 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5196 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5197 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5198 // Irreconcilable differences.
5199 NumDifferences = 2;
5200 break;
5201 } else {
5202 if (NumDifferences++) break;
5203 DiffOperand = i;
5204 }
5205 }
5206
5207 if (NumDifferences == 0) // SAME GEP?
5208 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky2de09a92007-09-06 02:40:25 +00005209 ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005210 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky2de09a92007-09-06 02:40:25 +00005211
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005212 else if (NumDifferences == 1) {
5213 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5214 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5215 // Make sure we do a signed comparison here.
5216 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5217 }
5218 }
5219
5220 // Only lower this if the icmp is the only user of the GEP or if we expect
5221 // the result to fold to a constant!
5222 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5223 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5224 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5225 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5226 Value *R = EmitGEPOffset(GEPRHS, I, *this);
5227 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5228 }
5229 }
5230 return 0;
5231}
5232
5233Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5234 bool Changed = SimplifyCompare(I);
5235 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5236
5237 // Fold trivial predicates.
5238 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
5239 return ReplaceInstUsesWith(I, Constant::getNullValue(Type::Int1Ty));
5240 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
5241 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5242
5243 // Simplify 'fcmp pred X, X'
5244 if (Op0 == Op1) {
5245 switch (I.getPredicate()) {
5246 default: assert(0 && "Unknown predicate!");
5247 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5248 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5249 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
5250 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 1));
5251 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5252 case FCmpInst::FCMP_OLT: // True if ordered and less than
5253 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
5254 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty, 0));
5255
5256 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5257 case FCmpInst::FCMP_ULT: // True if unordered or less than
5258 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5259 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5260 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5261 I.setPredicate(FCmpInst::FCMP_UNO);
5262 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5263 return &I;
5264
5265 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5266 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5267 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5268 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5269 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5270 I.setPredicate(FCmpInst::FCMP_ORD);
5271 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5272 return &I;
5273 }
5274 }
5275
5276 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
5277 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5278
5279 // Handle fcmp with constant RHS
5280 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5281 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5282 switch (LHSI->getOpcode()) {
5283 case Instruction::PHI:
5284 if (Instruction *NV = FoldOpIntoPhi(I))
5285 return NV;
5286 break;
5287 case Instruction::Select:
5288 // If either operand of the select is a constant, we can fold the
5289 // comparison into the select arms, which will cause one to be
5290 // constant folded and the select turned into a bitwise or.
5291 Value *Op1 = 0, *Op2 = 0;
5292 if (LHSI->hasOneUse()) {
5293 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5294 // Fold the known value into the constant operand.
5295 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5296 // Insert a new FCmp of the other select operand.
5297 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5298 LHSI->getOperand(2), RHSC,
5299 I.getName()), I);
5300 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5301 // Fold the known value into the constant operand.
5302 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5303 // Insert a new FCmp of the other select operand.
5304 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5305 LHSI->getOperand(1), RHSC,
5306 I.getName()), I);
5307 }
5308 }
5309
5310 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00005311 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005312 break;
5313 }
5314 }
5315
5316 return Changed ? &I : 0;
5317}
5318
5319Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5320 bool Changed = SimplifyCompare(I);
5321 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5322 const Type *Ty = Op0->getType();
5323
5324 // icmp X, X
5325 if (Op0 == Op1)
5326 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005327 I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005328
5329 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
5330 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lambf78cd322007-12-18 21:32:20 +00005331
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005332 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5333 // addresses never equal each other! We already know that Op0 != Op1.
5334 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5335 isa<ConstantPointerNull>(Op0)) &&
5336 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5337 isa<ConstantPointerNull>(Op1)))
5338 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005339 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005340
5341 // icmp's with boolean values can always be turned into bitwise operations
5342 if (Ty == Type::Int1Ty) {
5343 switch (I.getPredicate()) {
5344 default: assert(0 && "Invalid icmp instruction!");
5345 case ICmpInst::ICMP_EQ: { // icmp eq bool %A, %B -> ~(A^B)
Gabor Greifa645dd32008-05-16 19:29:10 +00005346 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005347 InsertNewInstBefore(Xor, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005348 return BinaryOperator::CreateNot(Xor);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005349 }
5350 case ICmpInst::ICMP_NE: // icmp eq bool %A, %B -> A^B
Gabor Greifa645dd32008-05-16 19:29:10 +00005351 return BinaryOperator::CreateXor(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005352
5353 case ICmpInst::ICMP_UGT:
5354 case ICmpInst::ICMP_SGT:
5355 std::swap(Op0, Op1); // Change icmp gt -> icmp lt
5356 // FALL THROUGH
5357 case ICmpInst::ICMP_ULT:
5358 case ICmpInst::ICMP_SLT: { // icmp lt bool A, B -> ~X & Y
Gabor Greifa645dd32008-05-16 19:29:10 +00005359 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005360 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005361 return BinaryOperator::CreateAnd(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005362 }
5363 case ICmpInst::ICMP_UGE:
5364 case ICmpInst::ICMP_SGE:
5365 std::swap(Op0, Op1); // Change icmp ge -> icmp le
5366 // FALL THROUGH
5367 case ICmpInst::ICMP_ULE:
5368 case ICmpInst::ICMP_SLE: { // icmp le bool %A, %B -> ~A | B
Gabor Greifa645dd32008-05-16 19:29:10 +00005369 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005370 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005371 return BinaryOperator::CreateOr(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005372 }
5373 }
5374 }
5375
5376 // See if we are doing a comparison between a constant and an instruction that
5377 // can be folded into the comparison.
5378 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Christopher Lambfa6b3102007-12-20 07:21:11 +00005379 Value *A, *B;
5380
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00005381 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5382 if (I.isEquality() && CI->isNullValue() &&
5383 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5384 // (icmp cond A B) if cond is equality
5385 return new ICmpInst(I.getPredicate(), A, B);
Owen Anderson42f61ed2007-12-28 07:42:12 +00005386 }
Christopher Lambfa6b3102007-12-20 07:21:11 +00005387
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005388 switch (I.getPredicate()) {
5389 default: break;
5390 case ICmpInst::ICMP_ULT: // A <u MIN -> FALSE
5391 if (CI->isMinValue(false))
5392 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5393 if (CI->isMaxValue(false)) // A <u MAX -> A != MAX
5394 return new ICmpInst(ICmpInst::ICMP_NE, Op0,Op1);
5395 if (isMinValuePlusOne(CI,false)) // A <u MIN+1 -> A == MIN
5396 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5397 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5398 if (CI->isMinValue(true))
5399 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5400 ConstantInt::getAllOnesValue(Op0->getType()));
5401
5402 break;
5403
5404 case ICmpInst::ICMP_SLT:
5405 if (CI->isMinValue(true)) // A <s MIN -> FALSE
5406 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5407 if (CI->isMaxValue(true)) // A <s MAX -> A != MAX
5408 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5409 if (isMinValuePlusOne(CI,true)) // A <s MIN+1 -> A == MIN
5410 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5411 break;
5412
5413 case ICmpInst::ICMP_UGT:
5414 if (CI->isMaxValue(false)) // A >u MAX -> FALSE
5415 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5416 if (CI->isMinValue(false)) // A >u MIN -> A != MIN
5417 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5418 if (isMaxValueMinusOne(CI, false)) // A >u MAX-1 -> A == MAX
5419 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5420
5421 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5422 if (CI->isMaxValue(true))
5423 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5424 ConstantInt::getNullValue(Op0->getType()));
5425 break;
5426
5427 case ICmpInst::ICMP_SGT:
5428 if (CI->isMaxValue(true)) // A >s MAX -> FALSE
5429 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5430 if (CI->isMinValue(true)) // A >s MIN -> A != MIN
5431 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5432 if (isMaxValueMinusOne(CI, true)) // A >s MAX-1 -> A == MAX
5433 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5434 break;
5435
5436 case ICmpInst::ICMP_ULE:
5437 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5438 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5439 if (CI->isMinValue(false)) // A <=u MIN -> A == MIN
5440 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5441 if (isMaxValueMinusOne(CI,false)) // A <=u MAX-1 -> A != MAX
5442 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5443 break;
5444
5445 case ICmpInst::ICMP_SLE:
5446 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5447 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5448 if (CI->isMinValue(true)) // A <=s MIN -> A == MIN
5449 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5450 if (isMaxValueMinusOne(CI,true)) // A <=s MAX-1 -> A != MAX
5451 return new ICmpInst(ICmpInst::ICMP_NE, Op0, AddOne(CI));
5452 break;
5453
5454 case ICmpInst::ICMP_UGE:
5455 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5456 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5457 if (CI->isMaxValue(false)) // A >=u MAX -> A == MAX
5458 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5459 if (isMinValuePlusOne(CI,false)) // A >=u MIN-1 -> A != MIN
5460 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5461 break;
5462
5463 case ICmpInst::ICMP_SGE:
5464 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5465 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5466 if (CI->isMaxValue(true)) // A >=s MAX -> A == MAX
5467 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
5468 if (isMinValuePlusOne(CI,true)) // A >=s MIN-1 -> A != MIN
5469 return new ICmpInst(ICmpInst::ICMP_NE, Op0, SubOne(CI));
5470 break;
5471 }
5472
5473 // If we still have a icmp le or icmp ge instruction, turn it into the
5474 // appropriate icmp lt or icmp gt instruction. Since the border cases have
5475 // already been handled above, this requires little checking.
5476 //
5477 switch (I.getPredicate()) {
5478 default: break;
5479 case ICmpInst::ICMP_ULE:
5480 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5481 case ICmpInst::ICMP_SLE:
5482 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5483 case ICmpInst::ICMP_UGE:
5484 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5485 case ICmpInst::ICMP_SGE:
5486 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5487 }
5488
5489 // See if we can fold the comparison based on bits known to be zero or one
5490 // in the input. If this comparison is a normal comparison, it demands all
5491 // bits, if it is a sign bit comparison, it only demands the sign bit.
5492
5493 bool UnusedBit;
5494 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5495
5496 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5497 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5498 if (SimplifyDemandedBits(Op0,
5499 isSignBit ? APInt::getSignBit(BitWidth)
5500 : APInt::getAllOnesValue(BitWidth),
5501 KnownZero, KnownOne, 0))
5502 return &I;
5503
5504 // Given the known and unknown bits, compute a range that the LHS could be
5505 // in.
5506 if ((KnownOne | KnownZero) != 0) {
5507 // Compute the Min, Max and RHS values based on the known bits. For the
5508 // EQ and NE we use unsigned values.
5509 APInt Min(BitWidth, 0), Max(BitWidth, 0);
5510 const APInt& RHSVal = CI->getValue();
5511 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
5512 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5513 Max);
5514 } else {
5515 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min,
5516 Max);
5517 }
5518 switch (I.getPredicate()) { // LE/GE have been folded already.
5519 default: assert(0 && "Unknown icmp opcode!");
5520 case ICmpInst::ICMP_EQ:
5521 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5522 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5523 break;
5524 case ICmpInst::ICMP_NE:
5525 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5526 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5527 break;
5528 case ICmpInst::ICMP_ULT:
5529 if (Max.ult(RHSVal))
5530 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5531 if (Min.uge(RHSVal))
5532 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5533 break;
5534 case ICmpInst::ICMP_UGT:
5535 if (Min.ugt(RHSVal))
5536 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5537 if (Max.ule(RHSVal))
5538 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5539 break;
5540 case ICmpInst::ICMP_SLT:
5541 if (Max.slt(RHSVal))
5542 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5543 if (Min.sgt(RHSVal))
5544 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5545 break;
5546 case ICmpInst::ICMP_SGT:
5547 if (Min.sgt(RHSVal))
5548 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5549 if (Max.sle(RHSVal))
5550 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5551 break;
5552 }
5553 }
5554
5555 // Since the RHS is a ConstantInt (CI), if the left hand side is an
5556 // instruction, see if that instruction also has constants so that the
5557 // instruction can be folded into the icmp
5558 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5559 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5560 return Res;
5561 }
5562
5563 // Handle icmp with constant (but not simple integer constant) RHS
5564 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5565 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5566 switch (LHSI->getOpcode()) {
5567 case Instruction::GetElementPtr:
5568 if (RHSC->isNullValue()) {
5569 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5570 bool isAllZeros = true;
5571 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5572 if (!isa<Constant>(LHSI->getOperand(i)) ||
5573 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5574 isAllZeros = false;
5575 break;
5576 }
5577 if (isAllZeros)
5578 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5579 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5580 }
5581 break;
5582
5583 case Instruction::PHI:
5584 if (Instruction *NV = FoldOpIntoPhi(I))
5585 return NV;
5586 break;
5587 case Instruction::Select: {
5588 // If either operand of the select is a constant, we can fold the
5589 // comparison into the select arms, which will cause one to be
5590 // constant folded and the select turned into a bitwise or.
5591 Value *Op1 = 0, *Op2 = 0;
5592 if (LHSI->hasOneUse()) {
5593 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5594 // Fold the known value into the constant operand.
5595 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5596 // Insert a new ICmp of the other select operand.
5597 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5598 LHSI->getOperand(2), RHSC,
5599 I.getName()), I);
5600 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5601 // Fold the known value into the constant operand.
5602 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5603 // Insert a new ICmp of the other select operand.
5604 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5605 LHSI->getOperand(1), RHSC,
5606 I.getName()), I);
5607 }
5608 }
5609
5610 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00005611 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005612 break;
5613 }
5614 case Instruction::Malloc:
5615 // If we have (malloc != null), and if the malloc has a single use, we
5616 // can assume it is successful and remove the malloc.
5617 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
5618 AddToWorkList(LHSI);
5619 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005620 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005621 }
5622 break;
5623 }
5624 }
5625
5626 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
5627 if (User *GEP = dyn_castGetElementPtr(Op0))
5628 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
5629 return NI;
5630 if (User *GEP = dyn_castGetElementPtr(Op1))
5631 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
5632 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
5633 return NI;
5634
5635 // Test to see if the operands of the icmp are casted versions of other
5636 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
5637 // now.
5638 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
5639 if (isa<PointerType>(Op0->getType()) &&
5640 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
5641 // We keep moving the cast from the left operand over to the right
5642 // operand, where it can often be eliminated completely.
5643 Op0 = CI->getOperand(0);
5644
5645 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
5646 // so eliminate it as well.
5647 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
5648 Op1 = CI2->getOperand(0);
5649
5650 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005651 if (Op0->getType() != Op1->getType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005652 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
5653 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
5654 } else {
5655 // Otherwise, cast the RHS right before the icmp
Chris Lattner13c2d6e2008-01-13 22:23:22 +00005656 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005657 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005658 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005659 return new ICmpInst(I.getPredicate(), Op0, Op1);
5660 }
5661 }
5662
5663 if (isa<CastInst>(Op0)) {
5664 // Handle the special case of: icmp (cast bool to X), <cst>
5665 // This comes up when you have code like
5666 // int X = A < B;
5667 // if (X) ...
5668 // For generality, we handle any zero-extension of any operand comparison
5669 // with a constant or another cast from the same type.
5670 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
5671 if (Instruction *R = visitICmpInstWithCastAndCast(I))
5672 return R;
5673 }
5674
Chris Lattnera4e1eef2008-05-09 05:19:28 +00005675 // ~x < ~y --> y < x
5676 { Value *A, *B;
5677 if (match(Op0, m_Not(m_Value(A))) &&
5678 match(Op1, m_Not(m_Value(B))))
5679 return new ICmpInst(I.getPredicate(), B, A);
5680 }
5681
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005682 if (I.isEquality()) {
5683 Value *A, *B, *C, *D;
Chris Lattnera4e1eef2008-05-09 05:19:28 +00005684
5685 // -x == -y --> x == y
5686 if (match(Op0, m_Neg(m_Value(A))) &&
5687 match(Op1, m_Neg(m_Value(B))))
5688 return new ICmpInst(I.getPredicate(), A, B);
5689
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005690 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
5691 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
5692 Value *OtherVal = A == Op1 ? B : A;
5693 return new ICmpInst(I.getPredicate(), OtherVal,
5694 Constant::getNullValue(A->getType()));
5695 }
5696
5697 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
5698 // A^c1 == C^c2 --> A == C^(c1^c2)
5699 if (ConstantInt *C1 = dyn_cast<ConstantInt>(B))
5700 if (ConstantInt *C2 = dyn_cast<ConstantInt>(D))
5701 if (Op1->hasOneUse()) {
5702 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00005703 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005704 return new ICmpInst(I.getPredicate(), A,
5705 InsertNewInstBefore(Xor, I));
5706 }
5707
5708 // A^B == A^D -> B == D
5709 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
5710 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
5711 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
5712 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
5713 }
5714 }
5715
5716 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
5717 (A == Op0 || B == Op0)) {
5718 // A == (A^B) -> B == 0
5719 Value *OtherVal = A == Op0 ? B : A;
5720 return new ICmpInst(I.getPredicate(), OtherVal,
5721 Constant::getNullValue(A->getType()));
5722 }
5723 if (match(Op0, m_Sub(m_Value(A), m_Value(B))) && A == Op1) {
5724 // (A-B) == A -> B == 0
5725 return new ICmpInst(I.getPredicate(), B,
5726 Constant::getNullValue(B->getType()));
5727 }
5728 if (match(Op1, m_Sub(m_Value(A), m_Value(B))) && A == Op0) {
5729 // A == (A-B) -> B == 0
5730 return new ICmpInst(I.getPredicate(), B,
5731 Constant::getNullValue(B->getType()));
5732 }
5733
5734 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
5735 if (Op0->hasOneUse() && Op1->hasOneUse() &&
5736 match(Op0, m_And(m_Value(A), m_Value(B))) &&
5737 match(Op1, m_And(m_Value(C), m_Value(D)))) {
5738 Value *X = 0, *Y = 0, *Z = 0;
5739
5740 if (A == C) {
5741 X = B; Y = D; Z = A;
5742 } else if (A == D) {
5743 X = B; Y = C; Z = A;
5744 } else if (B == C) {
5745 X = A; Y = D; Z = B;
5746 } else if (B == D) {
5747 X = A; Y = C; Z = B;
5748 }
5749
5750 if (X) { // Build (X^Y) & Z
Gabor Greifa645dd32008-05-16 19:29:10 +00005751 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
5752 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005753 I.setOperand(0, Op1);
5754 I.setOperand(1, Constant::getNullValue(Op1->getType()));
5755 return &I;
5756 }
5757 }
5758 }
5759 return Changed ? &I : 0;
5760}
5761
5762
5763/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
5764/// and CmpRHS are both known to be integer constants.
5765Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
5766 ConstantInt *DivRHS) {
5767 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
5768 const APInt &CmpRHSV = CmpRHS->getValue();
5769
5770 // FIXME: If the operand types don't match the type of the divide
5771 // then don't attempt this transform. The code below doesn't have the
5772 // logic to deal with a signed divide and an unsigned compare (and
5773 // vice versa). This is because (x /s C1) <s C2 produces different
5774 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
5775 // (x /u C1) <u C2. Simply casting the operands and result won't
5776 // work. :( The if statement below tests that condition and bails
5777 // if it finds it.
5778 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
5779 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
5780 return 0;
5781 if (DivRHS->isZero())
5782 return 0; // The ProdOV computation fails on divide by zero.
5783
5784 // Compute Prod = CI * DivRHS. We are essentially solving an equation
5785 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
5786 // C2 (CI). By solving for X we can turn this into a range check
5787 // instead of computing a divide.
5788 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
5789
5790 // Determine if the product overflows by seeing if the product is
5791 // not equal to the divide. Make sure we do the same kind of divide
5792 // as in the LHS instruction that we're folding.
5793 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
5794 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
5795
5796 // Get the ICmp opcode
5797 ICmpInst::Predicate Pred = ICI.getPredicate();
5798
5799 // Figure out the interval that is being checked. For example, a comparison
5800 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
5801 // Compute this interval based on the constants involved and the signedness of
5802 // the compare/divide. This computes a half-open interval, keeping track of
5803 // whether either value in the interval overflows. After analysis each
5804 // overflow variable is set to 0 if it's corresponding bound variable is valid
5805 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
5806 int LoOverflow = 0, HiOverflow = 0;
5807 ConstantInt *LoBound = 0, *HiBound = 0;
5808
5809
5810 if (!DivIsSigned) { // udiv
5811 // e.g. X/5 op 3 --> [15, 20)
5812 LoBound = Prod;
5813 HiOverflow = LoOverflow = ProdOV;
5814 if (!HiOverflow)
5815 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman5dceed12008-02-13 22:09:18 +00005816 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005817 if (CmpRHSV == 0) { // (X / pos) op 0
5818 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
5819 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
5820 HiBound = DivRHS;
Dan Gohman5dceed12008-02-13 22:09:18 +00005821 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005822 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
5823 HiOverflow = LoOverflow = ProdOV;
5824 if (!HiOverflow)
5825 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
5826 } else { // (X / pos) op neg
5827 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
5828 Constant *DivRHSH = ConstantExpr::getNeg(SubOne(DivRHS));
5829 LoOverflow = AddWithOverflow(LoBound, Prod,
5830 cast<ConstantInt>(DivRHSH), true) ? -1 : 0;
5831 HiBound = AddOne(Prod);
5832 HiOverflow = ProdOV ? -1 : 0;
5833 }
Dan Gohman5dceed12008-02-13 22:09:18 +00005834 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005835 if (CmpRHSV == 0) { // (X / neg) op 0
5836 // e.g. X/-5 op 0 --> [-4, 5)
5837 LoBound = AddOne(DivRHS);
5838 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
5839 if (HiBound == DivRHS) { // -INTMIN = INTMIN
5840 HiOverflow = 1; // [INTMIN+1, overflow)
5841 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
5842 }
Dan Gohman5dceed12008-02-13 22:09:18 +00005843 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005844 // e.g. X/-5 op 3 --> [-19, -14)
5845 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
5846 if (!LoOverflow)
5847 LoOverflow = AddWithOverflow(LoBound, Prod, AddOne(DivRHS), true) ?-1:0;
5848 HiBound = AddOne(Prod);
5849 } else { // (X / neg) op neg
5850 // e.g. X/-5 op -3 --> [15, 20)
5851 LoBound = Prod;
5852 LoOverflow = HiOverflow = ProdOV ? 1 : 0;
5853 HiBound = Subtract(Prod, DivRHS);
5854 }
5855
5856 // Dividing by a negative swaps the condition. LT <-> GT
5857 Pred = ICmpInst::getSwappedPredicate(Pred);
5858 }
5859
5860 Value *X = DivI->getOperand(0);
5861 switch (Pred) {
5862 default: assert(0 && "Unhandled icmp opcode!");
5863 case ICmpInst::ICMP_EQ:
5864 if (LoOverflow && HiOverflow)
5865 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5866 else if (HiOverflow)
5867 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5868 ICmpInst::ICMP_UGE, X, LoBound);
5869 else if (LoOverflow)
5870 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5871 ICmpInst::ICMP_ULT, X, HiBound);
5872 else
5873 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
5874 case ICmpInst::ICMP_NE:
5875 if (LoOverflow && HiOverflow)
5876 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5877 else if (HiOverflow)
5878 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
5879 ICmpInst::ICMP_ULT, X, LoBound);
5880 else if (LoOverflow)
5881 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
5882 ICmpInst::ICMP_UGE, X, HiBound);
5883 else
5884 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
5885 case ICmpInst::ICMP_ULT:
5886 case ICmpInst::ICMP_SLT:
5887 if (LoOverflow == +1) // Low bound is greater than input range.
5888 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5889 if (LoOverflow == -1) // Low bound is less than input range.
5890 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5891 return new ICmpInst(Pred, X, LoBound);
5892 case ICmpInst::ICMP_UGT:
5893 case ICmpInst::ICMP_SGT:
5894 if (HiOverflow == +1) // High bound greater than input range.
5895 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
5896 else if (HiOverflow == -1) // High bound less than input range.
5897 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
5898 if (Pred == ICmpInst::ICMP_UGT)
5899 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
5900 else
5901 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
5902 }
5903}
5904
5905
5906/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
5907///
5908Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
5909 Instruction *LHSI,
5910 ConstantInt *RHS) {
5911 const APInt &RHSV = RHS->getValue();
5912
5913 switch (LHSI->getOpcode()) {
5914 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
5915 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
5916 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
5917 // fold the xor.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005918 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
5919 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005920 Value *CompareVal = LHSI->getOperand(0);
5921
5922 // If the sign bit of the XorCST is not set, there is no change to
5923 // the operation, just stop using the Xor.
5924 if (!XorCST->getValue().isNegative()) {
5925 ICI.setOperand(0, CompareVal);
5926 AddToWorkList(LHSI);
5927 return &ICI;
5928 }
5929
5930 // Was the old condition true if the operand is positive?
5931 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
5932
5933 // If so, the new one isn't.
5934 isTrueIfPositive ^= true;
5935
5936 if (isTrueIfPositive)
5937 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
5938 else
5939 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
5940 }
5941 }
5942 break;
5943 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
5944 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
5945 LHSI->getOperand(0)->hasOneUse()) {
5946 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
5947
5948 // If the LHS is an AND of a truncating cast, we can widen the
5949 // and/compare to be the input width without changing the value
5950 // produced, eliminating a cast.
5951 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
5952 // We can do this transformation if either the AND constant does not
5953 // have its sign bit set or if it is an equality comparison.
5954 // Extending a relational comparison when we're checking the sign
5955 // bit would not work.
5956 if (Cast->hasOneUse() &&
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00005957 (ICI.isEquality() ||
5958 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005959 uint32_t BitWidth =
5960 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
5961 APInt NewCST = AndCST->getValue();
5962 NewCST.zext(BitWidth);
5963 APInt NewCI = RHSV;
5964 NewCI.zext(BitWidth);
5965 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00005966 BinaryOperator::CreateAnd(Cast->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005967 ConstantInt::get(NewCST),LHSI->getName());
5968 InsertNewInstBefore(NewAnd, ICI);
5969 return new ICmpInst(ICI.getPredicate(), NewAnd,
5970 ConstantInt::get(NewCI));
5971 }
5972 }
5973
5974 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
5975 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
5976 // happens a LOT in code produced by the C front-end, for bitfield
5977 // access.
5978 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
5979 if (Shift && !Shift->isShift())
5980 Shift = 0;
5981
5982 ConstantInt *ShAmt;
5983 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
5984 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
5985 const Type *AndTy = AndCST->getType(); // Type of the and.
5986
5987 // We can fold this as long as we can't shift unknown bits
5988 // into the mask. This can only happen with signed shift
5989 // rights, as they sign-extend.
5990 if (ShAmt) {
5991 bool CanFold = Shift->isLogicalShift();
5992 if (!CanFold) {
5993 // To test for the bad case of the signed shr, see if any
5994 // of the bits shifted in could be tested after the mask.
5995 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
5996 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
5997
5998 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
5999 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6000 AndCST->getValue()) == 0)
6001 CanFold = true;
6002 }
6003
6004 if (CanFold) {
6005 Constant *NewCst;
6006 if (Shift->getOpcode() == Instruction::Shl)
6007 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6008 else
6009 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6010
6011 // Check to see if we are shifting out any of the bits being
6012 // compared.
6013 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6014 // If we shifted bits out, the fold is not going to work out.
6015 // As a special case, check to see if this means that the
6016 // result is always true or false now.
6017 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6018 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6019 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6020 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6021 } else {
6022 ICI.setOperand(1, NewCst);
6023 Constant *NewAndCST;
6024 if (Shift->getOpcode() == Instruction::Shl)
6025 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6026 else
6027 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6028 LHSI->setOperand(1, NewAndCST);
6029 LHSI->setOperand(0, Shift->getOperand(0));
6030 AddToWorkList(Shift); // Shift is dead.
6031 AddUsesToWorkList(ICI);
6032 return &ICI;
6033 }
6034 }
6035 }
6036
6037 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6038 // preferable because it allows the C<<Y expression to be hoisted out
6039 // of a loop if Y is invariant and X is not.
6040 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6041 ICI.isEquality() && !Shift->isArithmeticShift() &&
6042 isa<Instruction>(Shift->getOperand(0))) {
6043 // Compute C << Y.
6044 Value *NS;
6045 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006046 NS = BinaryOperator::CreateShl(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006047 Shift->getOperand(1), "tmp");
6048 } else {
6049 // Insert a logical shift.
Gabor Greifa645dd32008-05-16 19:29:10 +00006050 NS = BinaryOperator::CreateLShr(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006051 Shift->getOperand(1), "tmp");
6052 }
6053 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6054
6055 // Compute X & (C << Y).
6056 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00006057 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006058 InsertNewInstBefore(NewAnd, ICI);
6059
6060 ICI.setOperand(0, NewAnd);
6061 return &ICI;
6062 }
6063 }
6064 break;
6065
6066 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6067 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6068 if (!ShAmt) break;
6069
6070 uint32_t TypeBits = RHSV.getBitWidth();
6071
6072 // Check that the shift amount is in range. If not, don't perform
6073 // undefined shifts. When the shift is visited it will be
6074 // simplified.
6075 if (ShAmt->uge(TypeBits))
6076 break;
6077
6078 if (ICI.isEquality()) {
6079 // If we are comparing against bits always shifted out, the
6080 // comparison cannot succeed.
6081 Constant *Comp =
6082 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6083 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6084 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6085 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6086 return ReplaceInstUsesWith(ICI, Cst);
6087 }
6088
6089 if (LHSI->hasOneUse()) {
6090 // Otherwise strength reduce the shift into an and.
6091 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6092 Constant *Mask =
6093 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6094
6095 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006096 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006097 Mask, LHSI->getName()+".mask");
6098 Value *And = InsertNewInstBefore(AndI, ICI);
6099 return new ICmpInst(ICI.getPredicate(), And,
6100 ConstantInt::get(RHSV.lshr(ShAmtVal)));
6101 }
6102 }
6103
6104 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6105 bool TrueIfSigned = false;
6106 if (LHSI->hasOneUse() &&
6107 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6108 // (X << 31) <s 0 --> (X&1) != 0
6109 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6110 (TypeBits-ShAmt->getZExtValue()-1));
6111 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006112 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006113 Mask, LHSI->getName()+".mask");
6114 Value *And = InsertNewInstBefore(AndI, ICI);
6115
6116 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6117 And, Constant::getNullValue(And->getType()));
6118 }
6119 break;
6120 }
6121
6122 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6123 case Instruction::AShr: {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006124 // Only handle equality comparisons of shift-by-constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006125 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner5ee84f82008-03-21 05:19:58 +00006126 if (!ShAmt || !ICI.isEquality()) break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006127
Chris Lattner5ee84f82008-03-21 05:19:58 +00006128 // Check that the shift amount is in range. If not, don't perform
6129 // undefined shifts. When the shift is visited it will be
6130 // simplified.
6131 uint32_t TypeBits = RHSV.getBitWidth();
6132 if (ShAmt->uge(TypeBits))
6133 break;
6134
6135 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006136
Chris Lattner5ee84f82008-03-21 05:19:58 +00006137 // If we are comparing against bits always shifted out, the
6138 // comparison cannot succeed.
6139 APInt Comp = RHSV << ShAmtVal;
6140 if (LHSI->getOpcode() == Instruction::LShr)
6141 Comp = Comp.lshr(ShAmtVal);
6142 else
6143 Comp = Comp.ashr(ShAmtVal);
6144
6145 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6146 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6147 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6148 return ReplaceInstUsesWith(ICI, Cst);
6149 }
6150
6151 // Otherwise, check to see if the bits shifted out are known to be zero.
6152 // If so, we can compare against the unshifted value:
6153 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengfb9292a2008-04-23 00:38:06 +00006154 if (LHSI->hasOneUse() &&
6155 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00006156 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6157 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6158 ConstantExpr::getShl(RHS, ShAmt));
6159 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006160
Evan Chengfb9292a2008-04-23 00:38:06 +00006161 if (LHSI->hasOneUse()) {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006162 // Otherwise strength reduce the shift into an and.
6163 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6164 Constant *Mask = ConstantInt::get(Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006165
Chris Lattner5ee84f82008-03-21 05:19:58 +00006166 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006167 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00006168 Mask, LHSI->getName()+".mask");
6169 Value *And = InsertNewInstBefore(AndI, ICI);
6170 return new ICmpInst(ICI.getPredicate(), And,
6171 ConstantExpr::getShl(RHS, ShAmt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006172 }
6173 break;
6174 }
6175
6176 case Instruction::SDiv:
6177 case Instruction::UDiv:
6178 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6179 // Fold this div into the comparison, producing a range check.
6180 // Determine, based on the divide type, what the range is being
6181 // checked. If there is an overflow on the low or high side, remember
6182 // it, otherwise compute the range [low, hi) bounding the new value.
6183 // See: InsertRangeTest above for the kinds of replacements possible.
6184 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6185 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6186 DivRHS))
6187 return R;
6188 break;
Nick Lewycky0185bbf2008-02-03 16:33:09 +00006189
6190 case Instruction::Add:
6191 // Fold: icmp pred (add, X, C1), C2
6192
6193 if (!ICI.isEquality()) {
6194 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6195 if (!LHSC) break;
6196 const APInt &LHSV = LHSC->getValue();
6197
6198 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6199 .subtract(LHSV);
6200
6201 if (ICI.isSignedPredicate()) {
6202 if (CR.getLower().isSignBit()) {
6203 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6204 ConstantInt::get(CR.getUpper()));
6205 } else if (CR.getUpper().isSignBit()) {
6206 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6207 ConstantInt::get(CR.getLower()));
6208 }
6209 } else {
6210 if (CR.getLower().isMinValue()) {
6211 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6212 ConstantInt::get(CR.getUpper()));
6213 } else if (CR.getUpper().isMinValue()) {
6214 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6215 ConstantInt::get(CR.getLower()));
6216 }
6217 }
6218 }
6219 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006220 }
6221
6222 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6223 if (ICI.isEquality()) {
6224 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6225
6226 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6227 // the second operand is a constant, simplify a bit.
6228 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6229 switch (BO->getOpcode()) {
6230 case Instruction::SRem:
6231 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6232 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6233 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6234 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6235 Instruction *NewRem =
Gabor Greifa645dd32008-05-16 19:29:10 +00006236 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006237 BO->getName());
6238 InsertNewInstBefore(NewRem, ICI);
6239 return new ICmpInst(ICI.getPredicate(), NewRem,
6240 Constant::getNullValue(BO->getType()));
6241 }
6242 }
6243 break;
6244 case Instruction::Add:
6245 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6246 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6247 if (BO->hasOneUse())
6248 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6249 Subtract(RHS, BOp1C));
6250 } else if (RHSV == 0) {
6251 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6252 // efficiently invertible, or if the add has just this one use.
6253 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6254
6255 if (Value *NegVal = dyn_castNegVal(BOp1))
6256 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6257 else if (Value *NegVal = dyn_castNegVal(BOp0))
6258 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6259 else if (BO->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006260 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006261 InsertNewInstBefore(Neg, ICI);
6262 Neg->takeName(BO);
6263 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6264 }
6265 }
6266 break;
6267 case Instruction::Xor:
6268 // For the xor case, we can xor two constants together, eliminating
6269 // the explicit xor.
6270 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6271 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6272 ConstantExpr::getXor(RHS, BOC));
6273
6274 // FALLTHROUGH
6275 case Instruction::Sub:
6276 // Replace (([sub|xor] A, B) != 0) with (A != B)
6277 if (RHSV == 0)
6278 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6279 BO->getOperand(1));
6280 break;
6281
6282 case Instruction::Or:
6283 // If bits are being or'd in that are not present in the constant we
6284 // are comparing against, then the comparison could never succeed!
6285 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6286 Constant *NotCI = ConstantExpr::getNot(RHS);
6287 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6288 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6289 isICMP_NE));
6290 }
6291 break;
6292
6293 case Instruction::And:
6294 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6295 // If bits are being compared against that are and'd out, then the
6296 // comparison can never succeed!
6297 if ((RHSV & ~BOC->getValue()) != 0)
6298 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6299 isICMP_NE));
6300
6301 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6302 if (RHS == BOC && RHSV.isPowerOf2())
6303 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6304 ICmpInst::ICMP_NE, LHSI,
6305 Constant::getNullValue(RHS->getType()));
6306
6307 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
6308 if (isSignBit(BOC)) {
6309 Value *X = BO->getOperand(0);
6310 Constant *Zero = Constant::getNullValue(X->getType());
6311 ICmpInst::Predicate pred = isICMP_NE ?
6312 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6313 return new ICmpInst(pred, X, Zero);
6314 }
6315
6316 // ((X & ~7) == 0) --> X < 8
6317 if (RHSV == 0 && isHighOnes(BOC)) {
6318 Value *X = BO->getOperand(0);
6319 Constant *NegX = ConstantExpr::getNeg(BOC);
6320 ICmpInst::Predicate pred = isICMP_NE ?
6321 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6322 return new ICmpInst(pred, X, NegX);
6323 }
6324 }
6325 default: break;
6326 }
6327 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6328 // Handle icmp {eq|ne} <intrinsic>, intcst.
6329 if (II->getIntrinsicID() == Intrinsic::bswap) {
6330 AddToWorkList(II);
6331 ICI.setOperand(0, II->getOperand(1));
6332 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6333 return &ICI;
6334 }
6335 }
6336 } else { // Not a ICMP_EQ/ICMP_NE
6337 // If the LHS is a cast from an integral value of the same size,
6338 // then since we know the RHS is a constant, try to simlify.
6339 if (CastInst *Cast = dyn_cast<CastInst>(LHSI)) {
6340 Value *CastOp = Cast->getOperand(0);
6341 const Type *SrcTy = CastOp->getType();
6342 uint32_t SrcTySize = SrcTy->getPrimitiveSizeInBits();
6343 if (SrcTy->isInteger() &&
6344 SrcTySize == Cast->getType()->getPrimitiveSizeInBits()) {
6345 // If this is an unsigned comparison, try to make the comparison use
6346 // smaller constant values.
6347 if (ICI.getPredicate() == ICmpInst::ICMP_ULT && RHSV.isSignBit()) {
6348 // X u< 128 => X s> -1
6349 return new ICmpInst(ICmpInst::ICMP_SGT, CastOp,
6350 ConstantInt::get(APInt::getAllOnesValue(SrcTySize)));
6351 } else if (ICI.getPredicate() == ICmpInst::ICMP_UGT &&
6352 RHSV == APInt::getSignedMaxValue(SrcTySize)) {
6353 // X u> 127 => X s< 0
6354 return new ICmpInst(ICmpInst::ICMP_SLT, CastOp,
6355 Constant::getNullValue(SrcTy));
6356 }
6357 }
6358 }
6359 }
6360 return 0;
6361}
6362
6363/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6364/// We only handle extending casts so far.
6365///
6366Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6367 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6368 Value *LHSCIOp = LHSCI->getOperand(0);
6369 const Type *SrcTy = LHSCIOp->getType();
6370 const Type *DestTy = LHSCI->getType();
6371 Value *RHSCIOp;
6372
6373 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6374 // integer type is the same size as the pointer type.
6375 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6376 getTargetData().getPointerSizeInBits() ==
6377 cast<IntegerType>(DestTy)->getBitWidth()) {
6378 Value *RHSOp = 0;
6379 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6380 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6381 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6382 RHSOp = RHSC->getOperand(0);
6383 // If the pointer types don't match, insert a bitcast.
6384 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner13c2d6e2008-01-13 22:23:22 +00006385 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006386 }
6387
6388 if (RHSOp)
6389 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6390 }
6391
6392 // The code below only handles extension cast instructions, so far.
6393 // Enforce this.
6394 if (LHSCI->getOpcode() != Instruction::ZExt &&
6395 LHSCI->getOpcode() != Instruction::SExt)
6396 return 0;
6397
6398 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6399 bool isSignedCmp = ICI.isSignedPredicate();
6400
6401 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6402 // Not an extension from the same type?
6403 RHSCIOp = CI->getOperand(0);
6404 if (RHSCIOp->getType() != LHSCIOp->getType())
6405 return 0;
6406
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00006407 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006408 // and the other is a zext), then we can't handle this.
6409 if (CI->getOpcode() != LHSCI->getOpcode())
6410 return 0;
6411
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00006412 // Deal with equality cases early.
6413 if (ICI.isEquality())
6414 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6415
6416 // A signed comparison of sign extended values simplifies into a
6417 // signed comparison.
6418 if (isSignedCmp && isSignedExt)
6419 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6420
6421 // The other three cases all fold into an unsigned comparison.
6422 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006423 }
6424
6425 // If we aren't dealing with a constant on the RHS, exit early
6426 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6427 if (!CI)
6428 return 0;
6429
6430 // Compute the constant that would happen if we truncated to SrcTy then
6431 // reextended to DestTy.
6432 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6433 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6434
6435 // If the re-extended constant didn't change...
6436 if (Res2 == CI) {
6437 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6438 // For example, we might have:
6439 // %A = sext short %X to uint
6440 // %B = icmp ugt uint %A, 1330
6441 // It is incorrect to transform this into
6442 // %B = icmp ugt short %X, 1330
6443 // because %A may have negative value.
6444 //
6445 // However, it is OK if SrcTy is bool (See cast-set.ll testcase)
6446 // OR operation is EQ/NE.
6447 if (isSignedExt == isSignedCmp || SrcTy == Type::Int1Ty || ICI.isEquality())
6448 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
6449 else
6450 return 0;
6451 }
6452
6453 // The re-extended constant changed so the constant cannot be represented
6454 // in the shorter type. Consequently, we cannot emit a simple comparison.
6455
6456 // First, handle some easy cases. We know the result cannot be equal at this
6457 // point so handle the ICI.isEquality() cases
6458 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6459 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6460 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6461 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6462
6463 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6464 // should have been folded away previously and not enter in here.
6465 Value *Result;
6466 if (isSignedCmp) {
6467 // We're performing a signed comparison.
6468 if (cast<ConstantInt>(CI)->getValue().isNegative())
6469 Result = ConstantInt::getFalse(); // X < (small) --> false
6470 else
6471 Result = ConstantInt::getTrue(); // X < (large) --> true
6472 } else {
6473 // We're performing an unsigned comparison.
6474 if (isSignedExt) {
6475 // We're performing an unsigned comp with a sign extended value.
6476 // This is true if the input is >= 0. [aka >s -1]
6477 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6478 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6479 NegOne, ICI.getName()), ICI);
6480 } else {
6481 // Unsigned extend & unsigned compare -> always true.
6482 Result = ConstantInt::getTrue();
6483 }
6484 }
6485
6486 // Finally, return the value computed.
6487 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
6488 ICI.getPredicate() == ICmpInst::ICMP_SLT) {
6489 return ReplaceInstUsesWith(ICI, Result);
6490 } else {
6491 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6492 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6493 "ICmp should be folded!");
6494 if (Constant *CI = dyn_cast<Constant>(Result))
6495 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6496 else
Gabor Greifa645dd32008-05-16 19:29:10 +00006497 return BinaryOperator::CreateNot(Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006498 }
6499}
6500
6501Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6502 return commonShiftTransforms(I);
6503}
6504
6505Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6506 return commonShiftTransforms(I);
6507}
6508
6509Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00006510 if (Instruction *R = commonShiftTransforms(I))
6511 return R;
6512
6513 Value *Op0 = I.getOperand(0);
6514
6515 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6516 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6517 if (CSI->isAllOnesValue())
6518 return ReplaceInstUsesWith(I, CSI);
6519
6520 // See if we can turn a signed shr into an unsigned shr.
6521 if (MaskedValueIsZero(Op0,
6522 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greifa645dd32008-05-16 19:29:10 +00006523 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattnere3c504f2007-12-06 01:59:46 +00006524
6525 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006526}
6527
6528Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6529 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6530 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6531
6532 // shl X, 0 == X and shr X, 0 == X
6533 // shl 0, X == 0 and shr 0, X == 0
6534 if (Op1 == Constant::getNullValue(Op1->getType()) ||
6535 Op0 == Constant::getNullValue(Op0->getType()))
6536 return ReplaceInstUsesWith(I, Op0);
6537
6538 if (isa<UndefValue>(Op0)) {
6539 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6540 return ReplaceInstUsesWith(I, Op0);
6541 else // undef << X -> 0, undef >>u X -> 0
6542 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6543 }
6544 if (isa<UndefValue>(Op1)) {
6545 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6546 return ReplaceInstUsesWith(I, Op0);
6547 else // X << undef, X >>u undef -> 0
6548 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6549 }
6550
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006551 // Try to fold constant and into select arguments.
6552 if (isa<Constant>(Op0))
6553 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6554 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6555 return R;
6556
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006557 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6558 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6559 return Res;
6560 return 0;
6561}
6562
6563Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6564 BinaryOperator &I) {
6565 bool isLeftShift = I.getOpcode() == Instruction::Shl;
6566
6567 // See if we can simplify any instructions used by the instruction whose sole
6568 // purpose is to compute bits we don't care about.
6569 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6570 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6571 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
6572 KnownZero, KnownOne))
6573 return &I;
6574
6575 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
6576 // of a signed value.
6577 //
6578 if (Op1->uge(TypeBits)) {
6579 if (I.getOpcode() != Instruction::AShr)
6580 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
6581 else {
6582 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
6583 return &I;
6584 }
6585 }
6586
6587 // ((X*C1) << C2) == (X * (C1 << C2))
6588 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
6589 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
6590 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00006591 return BinaryOperator::CreateMul(BO->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006592 ConstantExpr::getShl(BOOp, Op1));
6593
6594 // Try to fold constant and into select arguments.
6595 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
6596 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6597 return R;
6598 if (isa<PHINode>(Op0))
6599 if (Instruction *NV = FoldOpIntoPhi(I))
6600 return NV;
6601
Chris Lattnerc6d1f642007-12-22 09:07:47 +00006602 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
6603 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
6604 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
6605 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
6606 // place. Don't try to do this transformation in this case. Also, we
6607 // require that the input operand is a shift-by-constant so that we have
6608 // confidence that the shifts will get folded together. We could do this
6609 // xform in more cases, but it is unlikely to be profitable.
6610 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
6611 isa<ConstantInt>(TrOp->getOperand(1))) {
6612 // Okay, we'll do this xform. Make the shift of shift.
6613 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00006614 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattnerc6d1f642007-12-22 09:07:47 +00006615 I.getName());
6616 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
6617
6618 // For logical shifts, the truncation has the effect of making the high
6619 // part of the register be zeros. Emulate this by inserting an AND to
6620 // clear the top bits as needed. This 'and' will usually be zapped by
6621 // other xforms later if dead.
6622 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
6623 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
6624 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
6625
6626 // The mask we constructed says what the trunc would do if occurring
6627 // between the shifts. We want to know the effect *after* the second
6628 // shift. We know that it is a logical shift by a constant, so adjust the
6629 // mask as appropriate.
6630 if (I.getOpcode() == Instruction::Shl)
6631 MaskV <<= Op1->getZExtValue();
6632 else {
6633 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
6634 MaskV = MaskV.lshr(Op1->getZExtValue());
6635 }
6636
Gabor Greifa645dd32008-05-16 19:29:10 +00006637 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattnerc6d1f642007-12-22 09:07:47 +00006638 TI->getName());
6639 InsertNewInstBefore(And, I); // shift1 & 0x00FF
6640
6641 // Return the value truncated to the interesting size.
6642 return new TruncInst(And, I.getType());
6643 }
6644 }
6645
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006646 if (Op0->hasOneUse()) {
6647 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
6648 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6649 Value *V1, *V2;
6650 ConstantInt *CC;
6651 switch (Op0BO->getOpcode()) {
6652 default: break;
6653 case Instruction::Add:
6654 case Instruction::And:
6655 case Instruction::Or:
6656 case Instruction::Xor: {
6657 // These operators commute.
6658 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
6659 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
6660 match(Op0BO->getOperand(1),
6661 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006662 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006663 Op0BO->getOperand(0), Op1,
6664 Op0BO->getName());
6665 InsertNewInstBefore(YS, I); // (Y << C)
6666 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00006667 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006668 Op0BO->getOperand(1)->getName());
6669 InsertNewInstBefore(X, I); // (X + (Y << C))
6670 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greifa645dd32008-05-16 19:29:10 +00006671 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006672 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6673 }
6674
6675 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
6676 Value *Op0BOOp1 = Op0BO->getOperand(1);
6677 if (isLeftShift && Op0BOOp1->hasOneUse() &&
6678 match(Op0BOOp1,
6679 m_And(m_Shr(m_Value(V1), m_Value(V2)),m_ConstantInt(CC))) &&
6680 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse() &&
6681 V2 == Op1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006682 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006683 Op0BO->getOperand(0), Op1,
6684 Op0BO->getName());
6685 InsertNewInstBefore(YS, I); // (Y << C)
6686 Instruction *XM =
Gabor Greifa645dd32008-05-16 19:29:10 +00006687 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006688 V1->getName()+".mask");
6689 InsertNewInstBefore(XM, I); // X & (CC << C)
6690
Gabor Greifa645dd32008-05-16 19:29:10 +00006691 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006692 }
6693 }
6694
6695 // FALL THROUGH.
6696 case Instruction::Sub: {
6697 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
6698 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6699 match(Op0BO->getOperand(0),
6700 m_Shr(m_Value(V1), m_ConstantInt(CC))) && CC == Op1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006701 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006702 Op0BO->getOperand(1), Op1,
6703 Op0BO->getName());
6704 InsertNewInstBefore(YS, I); // (Y << C)
6705 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00006706 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006707 Op0BO->getOperand(0)->getName());
6708 InsertNewInstBefore(X, I); // (X + (Y << C))
6709 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greifa645dd32008-05-16 19:29:10 +00006710 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006711 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
6712 }
6713
6714 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
6715 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
6716 match(Op0BO->getOperand(0),
6717 m_And(m_Shr(m_Value(V1), m_Value(V2)),
6718 m_ConstantInt(CC))) && V2 == Op1 &&
6719 cast<BinaryOperator>(Op0BO->getOperand(0))
6720 ->getOperand(0)->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006721 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006722 Op0BO->getOperand(1), Op1,
6723 Op0BO->getName());
6724 InsertNewInstBefore(YS, I); // (Y << C)
6725 Instruction *XM =
Gabor Greifa645dd32008-05-16 19:29:10 +00006726 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006727 V1->getName()+".mask");
6728 InsertNewInstBefore(XM, I); // X & (CC << C)
6729
Gabor Greifa645dd32008-05-16 19:29:10 +00006730 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006731 }
6732
6733 break;
6734 }
6735 }
6736
6737
6738 // If the operand is an bitwise operator with a constant RHS, and the
6739 // shift is the only use, we can pull it out of the shift.
6740 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
6741 bool isValid = true; // Valid only for And, Or, Xor
6742 bool highBitSet = false; // Transform if high bit of constant set?
6743
6744 switch (Op0BO->getOpcode()) {
6745 default: isValid = false; break; // Do not perform transform!
6746 case Instruction::Add:
6747 isValid = isLeftShift;
6748 break;
6749 case Instruction::Or:
6750 case Instruction::Xor:
6751 highBitSet = false;
6752 break;
6753 case Instruction::And:
6754 highBitSet = true;
6755 break;
6756 }
6757
6758 // If this is a signed shift right, and the high bit is modified
6759 // by the logical operation, do not perform the transformation.
6760 // The highBitSet boolean indicates the value of the high bit of
6761 // the constant which would cause it to be modified for this
6762 // operation.
6763 //
Chris Lattner15b76e32007-12-06 06:25:04 +00006764 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006765 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006766
6767 if (isValid) {
6768 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
6769
6770 Instruction *NewShift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006771 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006772 InsertNewInstBefore(NewShift, I);
6773 NewShift->takeName(Op0BO);
6774
Gabor Greifa645dd32008-05-16 19:29:10 +00006775 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006776 NewRHS);
6777 }
6778 }
6779 }
6780 }
6781
6782 // Find out if this is a shift of a shift by a constant.
6783 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
6784 if (ShiftOp && !ShiftOp->isShift())
6785 ShiftOp = 0;
6786
6787 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
6788 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
6789 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
6790 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
6791 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
6792 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
6793 Value *X = ShiftOp->getOperand(0);
6794
6795 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
6796 if (AmtSum > TypeBits)
6797 AmtSum = TypeBits;
6798
6799 const IntegerType *Ty = cast<IntegerType>(I.getType());
6800
6801 // Check for (X << c1) << c2 and (X >> c1) >> c2
6802 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006803 return BinaryOperator::Create(I.getOpcode(), X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006804 ConstantInt::get(Ty, AmtSum));
6805 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
6806 I.getOpcode() == Instruction::AShr) {
6807 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greifa645dd32008-05-16 19:29:10 +00006808 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006809 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
6810 I.getOpcode() == Instruction::LShr) {
6811 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
6812 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006813 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006814 InsertNewInstBefore(Shift, I);
6815
6816 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00006817 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006818 }
6819
6820 // Okay, if we get here, one shift must be left, and the other shift must be
6821 // right. See if the amounts are equal.
6822 if (ShiftAmt1 == ShiftAmt2) {
6823 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
6824 if (I.getOpcode() == Instruction::Shl) {
6825 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greifa645dd32008-05-16 19:29:10 +00006826 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006827 }
6828 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
6829 if (I.getOpcode() == Instruction::LShr) {
6830 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greifa645dd32008-05-16 19:29:10 +00006831 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006832 }
6833 // We can simplify ((X << C) >>s C) into a trunc + sext.
6834 // NOTE: we could do this for any C, but that would make 'unusual' integer
6835 // types. For now, just stick to ones well-supported by the code
6836 // generators.
6837 const Type *SExtType = 0;
6838 switch (Ty->getBitWidth() - ShiftAmt1) {
6839 case 1 :
6840 case 8 :
6841 case 16 :
6842 case 32 :
6843 case 64 :
6844 case 128:
6845 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
6846 break;
6847 default: break;
6848 }
6849 if (SExtType) {
6850 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
6851 InsertNewInstBefore(NewTrunc, I);
6852 return new SExtInst(NewTrunc, Ty);
6853 }
6854 // Otherwise, we can't handle it yet.
6855 } else if (ShiftAmt1 < ShiftAmt2) {
6856 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
6857
6858 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
6859 if (I.getOpcode() == Instruction::Shl) {
6860 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6861 ShiftOp->getOpcode() == Instruction::AShr);
6862 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006863 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006864 InsertNewInstBefore(Shift, I);
6865
6866 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00006867 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006868 }
6869
6870 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
6871 if (I.getOpcode() == Instruction::LShr) {
6872 assert(ShiftOp->getOpcode() == Instruction::Shl);
6873 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006874 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006875 InsertNewInstBefore(Shift, I);
6876
6877 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00006878 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006879 }
6880
6881 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
6882 } else {
6883 assert(ShiftAmt2 < ShiftAmt1);
6884 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
6885
6886 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
6887 if (I.getOpcode() == Instruction::Shl) {
6888 assert(ShiftOp->getOpcode() == Instruction::LShr ||
6889 ShiftOp->getOpcode() == Instruction::AShr);
6890 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006891 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006892 ConstantInt::get(Ty, ShiftDiff));
6893 InsertNewInstBefore(Shift, I);
6894
6895 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00006896 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006897 }
6898
6899 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
6900 if (I.getOpcode() == Instruction::LShr) {
6901 assert(ShiftOp->getOpcode() == Instruction::Shl);
6902 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00006903 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006904 InsertNewInstBefore(Shift, I);
6905
6906 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00006907 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006908 }
6909
6910 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
6911 }
6912 }
6913 return 0;
6914}
6915
6916
6917/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
6918/// expression. If so, decompose it, returning some value X, such that Val is
6919/// X*Scale+Offset.
6920///
6921static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
6922 int &Offset) {
6923 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
6924 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
6925 Offset = CI->getZExtValue();
Chris Lattnerc59171a2007-10-12 05:30:59 +00006926 Scale = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006927 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattnerc59171a2007-10-12 05:30:59 +00006928 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
6929 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
6930 if (I->getOpcode() == Instruction::Shl) {
6931 // This is a value scaled by '1 << the shift amt'.
6932 Scale = 1U << RHS->getZExtValue();
6933 Offset = 0;
6934 return I->getOperand(0);
6935 } else if (I->getOpcode() == Instruction::Mul) {
6936 // This value is scaled by 'RHS'.
6937 Scale = RHS->getZExtValue();
6938 Offset = 0;
6939 return I->getOperand(0);
6940 } else if (I->getOpcode() == Instruction::Add) {
6941 // We have X+C. Check to see if we really have (X*C2)+C1,
6942 // where C1 is divisible by C2.
6943 unsigned SubScale;
6944 Value *SubVal =
6945 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
6946 Offset += RHS->getZExtValue();
6947 Scale = SubScale;
6948 return SubVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006949 }
6950 }
6951 }
6952
6953 // Otherwise, we can't look past this.
6954 Scale = 1;
6955 Offset = 0;
6956 return Val;
6957}
6958
6959
6960/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
6961/// try to eliminate the cast by moving the type information into the alloc.
6962Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
6963 AllocationInst &AI) {
6964 const PointerType *PTy = cast<PointerType>(CI.getType());
6965
6966 // Remove any uses of AI that are dead.
6967 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
6968
6969 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
6970 Instruction *User = cast<Instruction>(*UI++);
6971 if (isInstructionTriviallyDead(User)) {
6972 while (UI != E && *UI == User)
6973 ++UI; // If this instruction uses AI more than once, don't break UI.
6974
6975 ++NumDeadInst;
6976 DOUT << "IC: DCE: " << *User;
6977 EraseInstFromFunction(*User);
6978 }
6979 }
6980
6981 // Get the type really allocated and the type casted to.
6982 const Type *AllocElTy = AI.getAllocatedType();
6983 const Type *CastElTy = PTy->getElementType();
6984 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
6985
6986 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
6987 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
6988 if (CastElTyAlign < AllocElTyAlign) return 0;
6989
6990 // If the allocation has multiple uses, only promote it if we are strictly
6991 // increasing the alignment of the resultant allocation. If we keep it the
6992 // same, we open the door to infinite loops of various kinds.
6993 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
6994
Duncan Sandsf99fdc62007-11-01 20:53:16 +00006995 uint64_t AllocElTySize = TD->getABITypeSize(AllocElTy);
6996 uint64_t CastElTySize = TD->getABITypeSize(CastElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006997 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
6998
6999 // See if we can satisfy the modulus by pulling a scale out of the array
7000 // size argument.
7001 unsigned ArraySizeScale;
7002 int ArrayOffset;
7003 Value *NumElements = // See if the array size is a decomposable linear expr.
7004 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7005
7006 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7007 // do the xform.
7008 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7009 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7010
7011 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7012 Value *Amt = 0;
7013 if (Scale == 1) {
7014 Amt = NumElements;
7015 } else {
7016 // If the allocation size is constant, form a constant mul expression
7017 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7018 if (isa<ConstantInt>(NumElements))
7019 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
7020 // otherwise multiply the amount and the number of elements
7021 else if (Scale != 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007022 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007023 Amt = InsertNewInstBefore(Tmp, AI);
7024 }
7025 }
7026
7027 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7028 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greifa645dd32008-05-16 19:29:10 +00007029 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007030 Amt = InsertNewInstBefore(Tmp, AI);
7031 }
7032
7033 AllocationInst *New;
7034 if (isa<MallocInst>(AI))
7035 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7036 else
7037 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7038 InsertNewInstBefore(New, AI);
7039 New->takeName(&AI);
7040
7041 // If the allocation has multiple uses, insert a cast and change all things
7042 // that used it to use the new cast. This will also hack on CI, but it will
7043 // die soon.
7044 if (!AI.hasOneUse()) {
7045 AddUsesToWorkList(AI);
7046 // New is the allocation instruction, pointer typed. AI is the original
7047 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7048 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7049 InsertNewInstBefore(NewCast, AI);
7050 AI.replaceAllUsesWith(NewCast);
7051 }
7052 return ReplaceInstUsesWith(CI, New);
7053}
7054
7055/// CanEvaluateInDifferentType - Return true if we can take the specified value
7056/// and return it as type Ty without inserting any new casts and without
7057/// changing the computed value. This is used by code that tries to decide
7058/// whether promoting or shrinking integer operations to wider or smaller types
7059/// will allow us to eliminate a truncate or extend.
7060///
7061/// This is a truncation operation if Ty is smaller than V->getType(), or an
7062/// extension operation if Ty is larger.
Dan Gohman2d648bb2008-04-10 18:43:06 +00007063bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7064 unsigned CastOpc,
7065 int &NumCastsRemoved) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007066 // We can always evaluate constants in another type.
7067 if (isa<ConstantInt>(V))
7068 return true;
7069
7070 Instruction *I = dyn_cast<Instruction>(V);
7071 if (!I) return false;
7072
7073 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
7074
Chris Lattneref70bb82007-08-02 06:11:14 +00007075 // If this is an extension or truncate, we can often eliminate it.
7076 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7077 // If this is a cast from the destination type, we can trivially eliminate
7078 // it, and this will remove a cast overall.
7079 if (I->getOperand(0)->getType() == Ty) {
7080 // If the first operand is itself a cast, and is eliminable, do not count
7081 // this as an eliminable cast. We would prefer to eliminate those two
7082 // casts first.
7083 if (!isa<CastInst>(I->getOperand(0)))
7084 ++NumCastsRemoved;
7085 return true;
7086 }
7087 }
7088
7089 // We can't extend or shrink something that has multiple uses: doing so would
7090 // require duplicating the instruction in general, which isn't profitable.
7091 if (!I->hasOneUse()) return false;
7092
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007093 switch (I->getOpcode()) {
7094 case Instruction::Add:
7095 case Instruction::Sub:
7096 case Instruction::And:
7097 case Instruction::Or:
7098 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007099 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00007100 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7101 NumCastsRemoved) &&
7102 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7103 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007104
Nick Lewyckyc52646a2008-01-22 05:08:48 +00007105 case Instruction::Mul:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00007106 // A multiply can be truncated by truncating its operands.
7107 return Ty->getBitWidth() < OrigTy->getBitWidth() &&
7108 CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7109 NumCastsRemoved) &&
7110 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
7111 NumCastsRemoved);
7112
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007113 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007114 // If we are truncating the result of this SHL, and if it's a shift of a
7115 // constant amount, we can always perform a SHL in a smaller type.
7116 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7117 uint32_t BitWidth = Ty->getBitWidth();
7118 if (BitWidth < OrigTy->getBitWidth() &&
7119 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00007120 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7121 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007122 }
7123 break;
7124 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007125 // If this is a truncate of a logical shr, we can truncate it to a smaller
7126 // lshr iff we know that the bits we would otherwise be shifting in are
7127 // already zeros.
7128 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7129 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7130 uint32_t BitWidth = Ty->getBitWidth();
7131 if (BitWidth < OrigBitWidth &&
7132 MaskedValueIsZero(I->getOperand(0),
7133 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7134 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00007135 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
7136 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007137 }
7138 }
7139 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007140 case Instruction::ZExt:
7141 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00007142 case Instruction::Trunc:
7143 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00007144 // can safely replace it. Note that replacing it does not reduce the number
7145 // of casts in the input.
7146 if (I->getOpcode() == CastOpc)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007147 return true;
Chris Lattner2799b2f2007-09-10 23:46:29 +00007148
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007149 break;
7150 default:
7151 // TODO: Can handle more cases here.
7152 break;
7153 }
7154
7155 return false;
7156}
7157
7158/// EvaluateInDifferentType - Given an expression that
7159/// CanEvaluateInDifferentType returns true for, actually insert the code to
7160/// evaluate the expression.
7161Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
7162 bool isSigned) {
7163 if (Constant *C = dyn_cast<Constant>(V))
7164 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7165
7166 // Otherwise, it must be an instruction.
7167 Instruction *I = cast<Instruction>(V);
7168 Instruction *Res = 0;
7169 switch (I->getOpcode()) {
7170 case Instruction::Add:
7171 case Instruction::Sub:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00007172 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007173 case Instruction::And:
7174 case Instruction::Or:
7175 case Instruction::Xor:
7176 case Instruction::AShr:
7177 case Instruction::LShr:
7178 case Instruction::Shl: {
7179 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7180 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Gabor Greifa645dd32008-05-16 19:29:10 +00007181 Res = BinaryOperator::Create((Instruction::BinaryOps)I->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007182 LHS, RHS, I->getName());
7183 break;
7184 }
7185 case Instruction::Trunc:
7186 case Instruction::ZExt:
7187 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007188 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00007189 // just return the source. There's no need to insert it because it is not
7190 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007191 if (I->getOperand(0)->getType() == Ty)
7192 return I->getOperand(0);
7193
Chris Lattneref70bb82007-08-02 06:11:14 +00007194 // Otherwise, must be the same type of case, so just reinsert a new one.
Gabor Greifa645dd32008-05-16 19:29:10 +00007195 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattneref70bb82007-08-02 06:11:14 +00007196 Ty, I->getName());
7197 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007198 default:
7199 // TODO: Can handle more cases here.
7200 assert(0 && "Unreachable!");
7201 break;
7202 }
7203
7204 return InsertNewInstBefore(Res, *I);
7205}
7206
7207/// @brief Implement the transforms common to all CastInst visitors.
7208Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7209 Value *Src = CI.getOperand(0);
7210
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007211 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7212 // eliminate it now.
7213 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7214 if (Instruction::CastOps opc =
7215 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7216 // The first cast (CSrc) is eliminable so we need to fix up or replace
7217 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greifa645dd32008-05-16 19:29:10 +00007218 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007219 }
7220 }
7221
7222 // If we are casting a select then fold the cast into the select
7223 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7224 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7225 return NV;
7226
7227 // If we are casting a PHI then fold the cast into the PHI
7228 if (isa<PHINode>(Src))
7229 if (Instruction *NV = FoldOpIntoPhi(CI))
7230 return NV;
7231
7232 return 0;
7233}
7234
7235/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7236Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7237 Value *Src = CI.getOperand(0);
7238
7239 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7240 // If casting the result of a getelementptr instruction with no offset, turn
7241 // this into a cast of the original pointer!
7242 if (GEP->hasAllZeroIndices()) {
7243 // Changing the cast operand is usually not a good idea but it is safe
7244 // here because the pointer operand is being replaced with another
7245 // pointer operand so the opcode doesn't need to change.
7246 AddToWorkList(GEP);
7247 CI.setOperand(0, GEP->getOperand(0));
7248 return &CI;
7249 }
7250
7251 // If the GEP has a single use, and the base pointer is a bitcast, and the
7252 // GEP computes a constant offset, see if we can convert these three
7253 // instructions into fewer. This typically happens with unions and other
7254 // non-type-safe code.
7255 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7256 if (GEP->hasAllConstantIndices()) {
7257 // We are guaranteed to get a constant from EmitGEPOffset.
7258 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7259 int64_t Offset = OffsetV->getSExtValue();
7260
7261 // Get the base pointer input of the bitcast, and the type it points to.
7262 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7263 const Type *GEPIdxTy =
7264 cast<PointerType>(OrigBase->getType())->getElementType();
7265 if (GEPIdxTy->isSized()) {
7266 SmallVector<Value*, 8> NewIndices;
7267
7268 // Start with the index over the outer type. Note that the type size
7269 // might be zero (even if the offset isn't zero) if the indexed type
7270 // is something like [0 x {int, int}]
7271 const Type *IntPtrTy = TD->getIntPtrType();
7272 int64_t FirstIdx = 0;
Duncan Sandsf99fdc62007-11-01 20:53:16 +00007273 if (int64_t TySize = TD->getABITypeSize(GEPIdxTy)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007274 FirstIdx = Offset/TySize;
7275 Offset %= TySize;
7276
7277 // Handle silly modulus not returning values values [0..TySize).
7278 if (Offset < 0) {
7279 --FirstIdx;
7280 Offset += TySize;
7281 assert(Offset >= 0);
7282 }
7283 assert((uint64_t)Offset < (uint64_t)TySize &&"Out of range offset");
7284 }
7285
7286 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7287
7288 // Index into the types. If we fail, set OrigBase to null.
7289 while (Offset) {
7290 if (const StructType *STy = dyn_cast<StructType>(GEPIdxTy)) {
7291 const StructLayout *SL = TD->getStructLayout(STy);
7292 if (Offset < (int64_t)SL->getSizeInBytes()) {
7293 unsigned Elt = SL->getElementContainingOffset(Offset);
7294 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7295
7296 Offset -= SL->getElementOffset(Elt);
7297 GEPIdxTy = STy->getElementType(Elt);
7298 } else {
7299 // Otherwise, we can't index into this, bail out.
7300 Offset = 0;
7301 OrigBase = 0;
7302 }
7303 } else if (isa<ArrayType>(GEPIdxTy) || isa<VectorType>(GEPIdxTy)) {
7304 const SequentialType *STy = cast<SequentialType>(GEPIdxTy);
Duncan Sandsf99fdc62007-11-01 20:53:16 +00007305 if (uint64_t EltSize = TD->getABITypeSize(STy->getElementType())){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007306 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7307 Offset %= EltSize;
7308 } else {
7309 NewIndices.push_back(ConstantInt::get(IntPtrTy, 0));
7310 }
7311 GEPIdxTy = STy->getElementType();
7312 } else {
7313 // Otherwise, we can't index into this, bail out.
7314 Offset = 0;
7315 OrigBase = 0;
7316 }
7317 }
7318 if (OrigBase) {
7319 // If we were able to index down into an element, create the GEP
7320 // and bitcast the result. This eliminates one bitcast, potentially
7321 // two.
Gabor Greifd6da1d02008-04-06 20:25:17 +00007322 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7323 NewIndices.begin(),
7324 NewIndices.end(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007325 InsertNewInstBefore(NGEP, CI);
7326 NGEP->takeName(GEP);
7327
7328 if (isa<BitCastInst>(CI))
7329 return new BitCastInst(NGEP, CI.getType());
7330 assert(isa<PtrToIntInst>(CI));
7331 return new PtrToIntInst(NGEP, CI.getType());
7332 }
7333 }
7334 }
7335 }
7336 }
7337
7338 return commonCastTransforms(CI);
7339}
7340
7341
7342
7343/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7344/// integer types. This function implements the common transforms for all those
7345/// cases.
7346/// @brief Implement the transforms common to CastInst with integer operands
7347Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7348 if (Instruction *Result = commonCastTransforms(CI))
7349 return Result;
7350
7351 Value *Src = CI.getOperand(0);
7352 const Type *SrcTy = Src->getType();
7353 const Type *DestTy = CI.getType();
7354 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7355 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7356
7357 // See if we can simplify any instructions used by the LHS whose sole
7358 // purpose is to compute bits we don't care about.
7359 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7360 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7361 KnownZero, KnownOne))
7362 return &CI;
7363
7364 // If the source isn't an instruction or has more than one use then we
7365 // can't do anything more.
7366 Instruction *SrcI = dyn_cast<Instruction>(Src);
7367 if (!SrcI || !Src->hasOneUse())
7368 return 0;
7369
7370 // Attempt to propagate the cast into the instruction for int->int casts.
7371 int NumCastsRemoved = 0;
7372 if (!isa<BitCastInst>(CI) &&
7373 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Chris Lattneref70bb82007-08-02 06:11:14 +00007374 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007375 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00007376 // eliminates the cast, so it is always a win. If this is a zero-extension,
7377 // we need to do an AND to maintain the clear top-part of the computation,
7378 // so we require that the input have eliminated at least one cast. If this
7379 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007380 // require that two casts have been eliminated.
7381 bool DoXForm;
7382 switch (CI.getOpcode()) {
7383 default:
7384 // All the others use floating point so we shouldn't actually
7385 // get here because of the check above.
7386 assert(0 && "Unknown cast type");
7387 case Instruction::Trunc:
7388 DoXForm = true;
7389 break;
7390 case Instruction::ZExt:
7391 DoXForm = NumCastsRemoved >= 1;
7392 break;
7393 case Instruction::SExt:
7394 DoXForm = NumCastsRemoved >= 2;
7395 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007396 }
7397
7398 if (DoXForm) {
7399 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7400 CI.getOpcode() == Instruction::SExt);
7401 assert(Res->getType() == DestTy);
7402 switch (CI.getOpcode()) {
7403 default: assert(0 && "Unknown cast type!");
7404 case Instruction::Trunc:
7405 case Instruction::BitCast:
7406 // Just replace this cast with the result.
7407 return ReplaceInstUsesWith(CI, Res);
7408 case Instruction::ZExt: {
7409 // We need to emit an AND to clear the high bits.
7410 assert(SrcBitSize < DestBitSize && "Not a zext?");
7411 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7412 SrcBitSize));
Gabor Greifa645dd32008-05-16 19:29:10 +00007413 return BinaryOperator::CreateAnd(Res, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007414 }
7415 case Instruction::SExt:
7416 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greifa645dd32008-05-16 19:29:10 +00007417 return CastInst::Create(Instruction::SExt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007418 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7419 CI), DestTy);
7420 }
7421 }
7422 }
7423
7424 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7425 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7426
7427 switch (SrcI->getOpcode()) {
7428 case Instruction::Add:
7429 case Instruction::Mul:
7430 case Instruction::And:
7431 case Instruction::Or:
7432 case Instruction::Xor:
7433 // If we are discarding information, rewrite.
7434 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7435 // Don't insert two casts if they cannot be eliminated. We allow
7436 // two casts to be inserted if the sizes are the same. This could
7437 // only be converting signedness, which is a noop.
7438 if (DestBitSize == SrcBitSize ||
7439 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7440 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7441 Instruction::CastOps opcode = CI.getOpcode();
7442 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7443 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007444 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007445 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7446 }
7447 }
7448
7449 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7450 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7451 SrcI->getOpcode() == Instruction::Xor &&
7452 Op1 == ConstantInt::getTrue() &&
7453 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
7454 Value *New = InsertOperandCastBefore(Instruction::ZExt, Op0, DestTy, &CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007455 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007456 }
7457 break;
7458 case Instruction::SDiv:
7459 case Instruction::UDiv:
7460 case Instruction::SRem:
7461 case Instruction::URem:
7462 // If we are just changing the sign, rewrite.
7463 if (DestBitSize == SrcBitSize) {
7464 // Don't insert two casts if they cannot be eliminated. We allow
7465 // two casts to be inserted if the sizes are the same. This could
7466 // only be converting signedness, which is a noop.
7467 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7468 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7469 Value *Op0c = InsertOperandCastBefore(Instruction::BitCast,
7470 Op0, DestTy, SrcI);
7471 Value *Op1c = InsertOperandCastBefore(Instruction::BitCast,
7472 Op1, DestTy, SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007473 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007474 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7475 }
7476 }
7477 break;
7478
7479 case Instruction::Shl:
7480 // Allow changing the sign of the source operand. Do not allow
7481 // changing the size of the shift, UNLESS the shift amount is a
7482 // constant. We must not change variable sized shifts to a smaller
7483 // size, because it is undefined to shift more bits out than exist
7484 // in the value.
7485 if (DestBitSize == SrcBitSize ||
7486 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
7487 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
7488 Instruction::BitCast : Instruction::Trunc);
7489 Value *Op0c = InsertOperandCastBefore(opcode, Op0, DestTy, SrcI);
7490 Value *Op1c = InsertOperandCastBefore(opcode, Op1, DestTy, SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007491 return BinaryOperator::CreateShl(Op0c, Op1c);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007492 }
7493 break;
7494 case Instruction::AShr:
7495 // If this is a signed shr, and if all bits shifted in are about to be
7496 // truncated off, turn it into an unsigned shr to allow greater
7497 // simplifications.
7498 if (DestBitSize < SrcBitSize &&
7499 isa<ConstantInt>(Op1)) {
7500 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
7501 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
7502 // Insert the new logical shift right.
Gabor Greifa645dd32008-05-16 19:29:10 +00007503 return BinaryOperator::CreateLShr(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007504 }
7505 }
7506 break;
7507 }
7508 return 0;
7509}
7510
7511Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
7512 if (Instruction *Result = commonIntCastTransforms(CI))
7513 return Result;
7514
7515 Value *Src = CI.getOperand(0);
7516 const Type *Ty = CI.getType();
7517 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
7518 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
7519
7520 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
7521 switch (SrcI->getOpcode()) {
7522 default: break;
7523 case Instruction::LShr:
7524 // We can shrink lshr to something smaller if we know the bits shifted in
7525 // are already zeros.
7526 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
7527 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
7528
7529 // Get a mask for the bits shifting in.
7530 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
7531 Value* SrcIOp0 = SrcI->getOperand(0);
7532 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
7533 if (ShAmt >= DestBitWidth) // All zeros.
7534 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
7535
7536 // Okay, we can shrink this. Truncate the input, then return a new
7537 // shift.
7538 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
7539 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
7540 Ty, CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007541 return BinaryOperator::CreateLShr(V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007542 }
7543 } else { // This is a variable shr.
7544
7545 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
7546 // more LLVM instructions, but allows '1 << Y' to be hoisted if
7547 // loop-invariant and CSE'd.
7548 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
7549 Value *One = ConstantInt::get(SrcI->getType(), 1);
7550
7551 Value *V = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00007552 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007553 "tmp"), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007554 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007555 SrcI->getOperand(0),
7556 "tmp"), CI);
7557 Value *Zero = Constant::getNullValue(V->getType());
7558 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
7559 }
7560 }
7561 break;
7562 }
7563 }
7564
7565 return 0;
7566}
7567
Evan Chenge3779cf2008-03-24 00:21:34 +00007568/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
7569/// in order to eliminate the icmp.
7570Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
7571 bool DoXform) {
7572 // If we are just checking for a icmp eq of a single bit and zext'ing it
7573 // to an integer, then shift the bit to the appropriate place and then
7574 // cast to integer to avoid the comparison.
7575 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7576 const APInt &Op1CV = Op1C->getValue();
7577
7578 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
7579 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
7580 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7581 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
7582 if (!DoXform) return ICI;
7583
7584 Value *In = ICI->getOperand(0);
7585 Value *Sh = ConstantInt::get(In->getType(),
7586 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00007587 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chenge3779cf2008-03-24 00:21:34 +00007588 In->getName()+".lobit"),
7589 CI);
7590 if (In->getType() != CI.getType())
Gabor Greifa645dd32008-05-16 19:29:10 +00007591 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chenge3779cf2008-03-24 00:21:34 +00007592 false/*ZExt*/, "tmp", &CI);
7593
7594 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
7595 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00007596 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chenge3779cf2008-03-24 00:21:34 +00007597 In->getName()+".not"),
7598 CI);
7599 }
7600
7601 return ReplaceInstUsesWith(CI, In);
7602 }
7603
7604
7605
7606 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
7607 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7608 // zext (X == 1) to i32 --> X iff X has only the low bit set.
7609 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
7610 // zext (X != 0) to i32 --> X iff X has only the low bit set.
7611 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
7612 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
7613 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
7614 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
7615 // This only works for EQ and NE
7616 ICI->isEquality()) {
7617 // If Op1C some other power of two, convert:
7618 uint32_t BitWidth = Op1C->getType()->getBitWidth();
7619 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
7620 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
7621 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
7622
7623 APInt KnownZeroMask(~KnownZero);
7624 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
7625 if (!DoXform) return ICI;
7626
7627 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
7628 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
7629 // (X&4) == 2 --> false
7630 // (X&4) != 2 --> true
7631 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
7632 Res = ConstantExpr::getZExt(Res, CI.getType());
7633 return ReplaceInstUsesWith(CI, Res);
7634 }
7635
7636 uint32_t ShiftAmt = KnownZeroMask.logBase2();
7637 Value *In = ICI->getOperand(0);
7638 if (ShiftAmt) {
7639 // Perform a logical shr by shiftamt.
7640 // Insert the shift to put the result in the low bit.
Gabor Greifa645dd32008-05-16 19:29:10 +00007641 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chenge3779cf2008-03-24 00:21:34 +00007642 ConstantInt::get(In->getType(), ShiftAmt),
7643 In->getName()+".lobit"), CI);
7644 }
7645
7646 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
7647 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00007648 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00007649 InsertNewInstBefore(cast<Instruction>(In), CI);
7650 }
7651
7652 if (CI.getType() == In->getType())
7653 return ReplaceInstUsesWith(CI, In);
7654 else
Gabor Greifa645dd32008-05-16 19:29:10 +00007655 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chenge3779cf2008-03-24 00:21:34 +00007656 }
7657 }
7658 }
7659
7660 return 0;
7661}
7662
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007663Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
7664 // If one of the common conversion will work ..
7665 if (Instruction *Result = commonIntCastTransforms(CI))
7666 return Result;
7667
7668 Value *Src = CI.getOperand(0);
7669
7670 // If this is a cast of a cast
7671 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7672 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
7673 // types and if the sizes are just right we can convert this into a logical
7674 // 'and' which will be much cheaper than the pair of casts.
7675 if (isa<TruncInst>(CSrc)) {
7676 // Get the sizes of the types involved
7677 Value *A = CSrc->getOperand(0);
7678 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
7679 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
7680 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
7681 // If we're actually extending zero bits and the trunc is a no-op
7682 if (MidSize < DstSize && SrcSize == DstSize) {
7683 // Replace both of the casts with an And of the type mask.
7684 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
7685 Constant *AndConst = ConstantInt::get(AndValue);
7686 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +00007687 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007688 // Unfortunately, if the type changed, we need to cast it back.
7689 if (And->getType() != CI.getType()) {
7690 And->setName(CSrc->getName()+".mask");
7691 InsertNewInstBefore(And, CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007692 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007693 }
7694 return And;
7695 }
7696 }
7697 }
7698
Evan Chenge3779cf2008-03-24 00:21:34 +00007699 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
7700 return transformZExtICmp(ICI, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007701
Evan Chenge3779cf2008-03-24 00:21:34 +00007702 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
7703 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
7704 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
7705 // of the (zext icmp) will be transformed.
7706 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
7707 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
7708 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
7709 (transformZExtICmp(LHS, CI, false) ||
7710 transformZExtICmp(RHS, CI, false))) {
7711 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
7712 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007713 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007714 }
Evan Chenge3779cf2008-03-24 00:21:34 +00007715 }
7716
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007717 return 0;
7718}
7719
7720Instruction *InstCombiner::visitSExt(SExtInst &CI) {
7721 if (Instruction *I = commonIntCastTransforms(CI))
7722 return I;
7723
7724 Value *Src = CI.getOperand(0);
7725
7726 // sext (x <s 0) -> ashr x, 31 -> all ones if signed
7727 // sext (x >s -1) -> ashr x, 31 -> all ones if not signed
7728 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src)) {
7729 // If we are just checking for a icmp eq of a single bit and zext'ing it
7730 // to an integer, then shift the bit to the appropriate place and then
7731 // cast to integer to avoid the comparison.
7732 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
7733 const APInt &Op1CV = Op1C->getValue();
7734
7735 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
7736 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
7737 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
7738 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())){
7739 Value *In = ICI->getOperand(0);
7740 Value *Sh = ConstantInt::get(In->getType(),
7741 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00007742 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007743 In->getName()+".lobit"),
7744 CI);
7745 if (In->getType() != CI.getType())
Gabor Greifa645dd32008-05-16 19:29:10 +00007746 In = CastInst::CreateIntegerCast(In, CI.getType(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007747 true/*SExt*/, "tmp", &CI);
7748
7749 if (ICI->getPredicate() == ICmpInst::ICMP_SGT)
Gabor Greifa645dd32008-05-16 19:29:10 +00007750 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007751 In->getName()+".not"), CI);
7752
7753 return ReplaceInstUsesWith(CI, In);
7754 }
7755 }
7756 }
7757
7758 return 0;
7759}
7760
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007761/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
7762/// in the specified FP type without changing its value.
Chris Lattner5e0610f2008-04-20 00:41:09 +00007763static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007764 APFloat F = CFP->getValueAPF();
7765 if (F.convert(Sem, APFloat::rmNearestTiesToEven) == APFloat::opOK)
Chris Lattner5e0610f2008-04-20 00:41:09 +00007766 return ConstantFP::get(F);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007767 return 0;
7768}
7769
7770/// LookThroughFPExtensions - If this is an fp extension instruction, look
7771/// through it until we get the source value.
7772static Value *LookThroughFPExtensions(Value *V) {
7773 if (Instruction *I = dyn_cast<Instruction>(V))
7774 if (I->getOpcode() == Instruction::FPExt)
7775 return LookThroughFPExtensions(I->getOperand(0));
7776
7777 // If this value is a constant, return the constant in the smallest FP type
7778 // that can accurately represent it. This allows us to turn
7779 // (float)((double)X+2.0) into x+2.0f.
7780 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
7781 if (CFP->getType() == Type::PPC_FP128Ty)
7782 return V; // No constant folding of this.
7783 // See if the value can be truncated to float and then reextended.
Chris Lattner5e0610f2008-04-20 00:41:09 +00007784 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007785 return V;
7786 if (CFP->getType() == Type::DoubleTy)
7787 return V; // Won't shrink.
Chris Lattner5e0610f2008-04-20 00:41:09 +00007788 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007789 return V;
7790 // Don't try to shrink to various long double types.
7791 }
7792
7793 return V;
7794}
7795
7796Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
7797 if (Instruction *I = commonCastTransforms(CI))
7798 return I;
7799
7800 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
7801 // smaller than the destination type, we can eliminate the truncate by doing
7802 // the add as the smaller type. This applies to add/sub/mul/div as well as
7803 // many builtins (sqrt, etc).
7804 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
7805 if (OpI && OpI->hasOneUse()) {
7806 switch (OpI->getOpcode()) {
7807 default: break;
7808 case Instruction::Add:
7809 case Instruction::Sub:
7810 case Instruction::Mul:
7811 case Instruction::FDiv:
7812 case Instruction::FRem:
7813 const Type *SrcTy = OpI->getType();
7814 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
7815 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
7816 if (LHSTrunc->getType() != SrcTy &&
7817 RHSTrunc->getType() != SrcTy) {
7818 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
7819 // If the source types were both smaller than the destination type of
7820 // the cast, do this xform.
7821 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
7822 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
7823 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
7824 CI.getType(), CI);
7825 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
7826 CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007827 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00007828 }
7829 }
7830 break;
7831 }
7832 }
7833 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007834}
7835
7836Instruction *InstCombiner::visitFPExt(CastInst &CI) {
7837 return commonCastTransforms(CI);
7838}
7839
7840Instruction *InstCombiner::visitFPToUI(CastInst &CI) {
7841 return commonCastTransforms(CI);
7842}
7843
7844Instruction *InstCombiner::visitFPToSI(CastInst &CI) {
7845 return commonCastTransforms(CI);
7846}
7847
7848Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
7849 return commonCastTransforms(CI);
7850}
7851
7852Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
7853 return commonCastTransforms(CI);
7854}
7855
7856Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
7857 return commonPointerCastTransforms(CI);
7858}
7859
Chris Lattner7c1626482008-01-08 07:23:51 +00007860Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
7861 if (Instruction *I = commonCastTransforms(CI))
7862 return I;
7863
7864 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
7865 if (!DestPointee->isSized()) return 0;
7866
7867 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
7868 ConstantInt *Cst;
7869 Value *X;
7870 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
7871 m_ConstantInt(Cst)))) {
7872 // If the source and destination operands have the same type, see if this
7873 // is a single-index GEP.
7874 if (X->getType() == CI.getType()) {
7875 // Get the size of the pointee type.
Bill Wendling9594af02008-03-14 05:12:19 +00007876 uint64_t Size = TD->getABITypeSize(DestPointee);
Chris Lattner7c1626482008-01-08 07:23:51 +00007877
7878 // Convert the constant to intptr type.
7879 APInt Offset = Cst->getValue();
7880 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7881
7882 // If Offset is evenly divisible by Size, we can do this xform.
7883 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7884 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greifd6da1d02008-04-06 20:25:17 +00007885 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattner7c1626482008-01-08 07:23:51 +00007886 }
7887 }
7888 // TODO: Could handle other cases, e.g. where add is indexing into field of
7889 // struct etc.
7890 } else if (CI.getOperand(0)->hasOneUse() &&
7891 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
7892 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
7893 // "inttoptr+GEP" instead of "add+intptr".
7894
7895 // Get the size of the pointee type.
7896 uint64_t Size = TD->getABITypeSize(DestPointee);
7897
7898 // Convert the constant to intptr type.
7899 APInt Offset = Cst->getValue();
7900 Offset.sextOrTrunc(TD->getPointerSizeInBits());
7901
7902 // If Offset is evenly divisible by Size, we can do this xform.
7903 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
7904 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
7905
7906 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
7907 "tmp"), CI);
Gabor Greifd6da1d02008-04-06 20:25:17 +00007908 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattner7c1626482008-01-08 07:23:51 +00007909 }
7910 }
7911 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007912}
7913
7914Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
7915 // If the operands are integer typed then apply the integer transforms,
7916 // otherwise just apply the common ones.
7917 Value *Src = CI.getOperand(0);
7918 const Type *SrcTy = Src->getType();
7919 const Type *DestTy = CI.getType();
7920
7921 if (SrcTy->isInteger() && DestTy->isInteger()) {
7922 if (Instruction *Result = commonIntCastTransforms(CI))
7923 return Result;
7924 } else if (isa<PointerType>(SrcTy)) {
7925 if (Instruction *I = commonPointerCastTransforms(CI))
7926 return I;
7927 } else {
7928 if (Instruction *Result = commonCastTransforms(CI))
7929 return Result;
7930 }
7931
7932
7933 // Get rid of casts from one type to the same type. These are useless and can
7934 // be replaced by the operand.
7935 if (DestTy == Src->getType())
7936 return ReplaceInstUsesWith(CI, Src);
7937
7938 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
7939 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
7940 const Type *DstElTy = DstPTy->getElementType();
7941 const Type *SrcElTy = SrcPTy->getElementType();
7942
Nate Begemandf5b3612008-03-31 00:22:16 +00007943 // If the address spaces don't match, don't eliminate the bitcast, which is
7944 // required for changing types.
7945 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
7946 return 0;
7947
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007948 // If we are casting a malloc or alloca to a pointer to a type of the same
7949 // size, rewrite the allocation instruction to allocate the "right" type.
7950 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
7951 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
7952 return V;
7953
7954 // If the source and destination are pointers, and this cast is equivalent
7955 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
7956 // This can enhance SROA and other transforms that want type-safe pointers.
7957 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
7958 unsigned NumZeros = 0;
7959 while (SrcElTy != DstElTy &&
7960 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
7961 SrcElTy->getNumContainedTypes() /* not "{}" */) {
7962 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
7963 ++NumZeros;
7964 }
7965
7966 // If we found a path from the src to dest, create the getelementptr now.
7967 if (SrcElTy == DstElTy) {
7968 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greifd6da1d02008-04-06 20:25:17 +00007969 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
7970 ((Instruction*) NULL));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007971 }
7972 }
7973
7974 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
7975 if (SVI->hasOneUse()) {
7976 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
7977 // a bitconvert to a vector with the same # elts.
7978 if (isa<VectorType>(DestTy) &&
7979 cast<VectorType>(DestTy)->getNumElements() ==
7980 SVI->getType()->getNumElements()) {
7981 CastInst *Tmp;
7982 // If either of the operands is a cast from CI.getType(), then
7983 // evaluating the shuffle in the casted destination's type will allow
7984 // us to eliminate at least one cast.
7985 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
7986 Tmp->getOperand(0)->getType() == DestTy) ||
7987 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
7988 Tmp->getOperand(0)->getType() == DestTy)) {
7989 Value *LHS = InsertOperandCastBefore(Instruction::BitCast,
7990 SVI->getOperand(0), DestTy, &CI);
7991 Value *RHS = InsertOperandCastBefore(Instruction::BitCast,
7992 SVI->getOperand(1), DestTy, &CI);
7993 // Return a new shuffle vector. Use the same element ID's, as we
7994 // know the vector types match #elts.
7995 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
7996 }
7997 }
7998 }
7999 }
8000 return 0;
8001}
8002
8003/// GetSelectFoldableOperands - We want to turn code that looks like this:
8004/// %C = or %A, %B
8005/// %D = select %cond, %C, %A
8006/// into:
8007/// %C = select %cond, %B, 0
8008/// %D = or %A, %C
8009///
8010/// Assuming that the specified instruction is an operand to the select, return
8011/// a bitmask indicating which operands of this instruction are foldable if they
8012/// equal the other incoming value of the select.
8013///
8014static unsigned GetSelectFoldableOperands(Instruction *I) {
8015 switch (I->getOpcode()) {
8016 case Instruction::Add:
8017 case Instruction::Mul:
8018 case Instruction::And:
8019 case Instruction::Or:
8020 case Instruction::Xor:
8021 return 3; // Can fold through either operand.
8022 case Instruction::Sub: // Can only fold on the amount subtracted.
8023 case Instruction::Shl: // Can only fold on the shift amount.
8024 case Instruction::LShr:
8025 case Instruction::AShr:
8026 return 1;
8027 default:
8028 return 0; // Cannot fold
8029 }
8030}
8031
8032/// GetSelectFoldableConstant - For the same transformation as the previous
8033/// function, return the identity constant that goes into the select.
8034static Constant *GetSelectFoldableConstant(Instruction *I) {
8035 switch (I->getOpcode()) {
8036 default: assert(0 && "This cannot happen!"); abort();
8037 case Instruction::Add:
8038 case Instruction::Sub:
8039 case Instruction::Or:
8040 case Instruction::Xor:
8041 case Instruction::Shl:
8042 case Instruction::LShr:
8043 case Instruction::AShr:
8044 return Constant::getNullValue(I->getType());
8045 case Instruction::And:
8046 return Constant::getAllOnesValue(I->getType());
8047 case Instruction::Mul:
8048 return ConstantInt::get(I->getType(), 1);
8049 }
8050}
8051
8052/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8053/// have the same opcode and only one use each. Try to simplify this.
8054Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8055 Instruction *FI) {
8056 if (TI->getNumOperands() == 1) {
8057 // If this is a non-volatile load or a cast from the same type,
8058 // merge.
8059 if (TI->isCast()) {
8060 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8061 return 0;
8062 } else {
8063 return 0; // unknown unary op.
8064 }
8065
8066 // Fold this by inserting a select from the input values.
Gabor Greifd6da1d02008-04-06 20:25:17 +00008067 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8068 FI->getOperand(0), SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008069 InsertNewInstBefore(NewSI, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008070 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008071 TI->getType());
8072 }
8073
8074 // Only handle binary operators here.
8075 if (!isa<BinaryOperator>(TI))
8076 return 0;
8077
8078 // Figure out if the operations have any operands in common.
8079 Value *MatchOp, *OtherOpT, *OtherOpF;
8080 bool MatchIsOpZero;
8081 if (TI->getOperand(0) == FI->getOperand(0)) {
8082 MatchOp = TI->getOperand(0);
8083 OtherOpT = TI->getOperand(1);
8084 OtherOpF = FI->getOperand(1);
8085 MatchIsOpZero = true;
8086 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8087 MatchOp = TI->getOperand(1);
8088 OtherOpT = TI->getOperand(0);
8089 OtherOpF = FI->getOperand(0);
8090 MatchIsOpZero = false;
8091 } else if (!TI->isCommutative()) {
8092 return 0;
8093 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8094 MatchOp = TI->getOperand(0);
8095 OtherOpT = TI->getOperand(1);
8096 OtherOpF = FI->getOperand(0);
8097 MatchIsOpZero = true;
8098 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8099 MatchOp = TI->getOperand(1);
8100 OtherOpT = TI->getOperand(0);
8101 OtherOpF = FI->getOperand(1);
8102 MatchIsOpZero = true;
8103 } else {
8104 return 0;
8105 }
8106
8107 // If we reach here, they do have operations in common.
Gabor Greifd6da1d02008-04-06 20:25:17 +00008108 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8109 OtherOpF, SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008110 InsertNewInstBefore(NewSI, SI);
8111
8112 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8113 if (MatchIsOpZero)
Gabor Greifa645dd32008-05-16 19:29:10 +00008114 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008115 else
Gabor Greifa645dd32008-05-16 19:29:10 +00008116 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008117 }
8118 assert(0 && "Shouldn't get here");
8119 return 0;
8120}
8121
8122Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8123 Value *CondVal = SI.getCondition();
8124 Value *TrueVal = SI.getTrueValue();
8125 Value *FalseVal = SI.getFalseValue();
8126
8127 // select true, X, Y -> X
8128 // select false, X, Y -> Y
8129 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8130 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8131
8132 // select C, X, X -> X
8133 if (TrueVal == FalseVal)
8134 return ReplaceInstUsesWith(SI, TrueVal);
8135
8136 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8137 return ReplaceInstUsesWith(SI, FalseVal);
8138 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8139 return ReplaceInstUsesWith(SI, TrueVal);
8140 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8141 if (isa<Constant>(TrueVal))
8142 return ReplaceInstUsesWith(SI, TrueVal);
8143 else
8144 return ReplaceInstUsesWith(SI, FalseVal);
8145 }
8146
8147 if (SI.getType() == Type::Int1Ty) {
8148 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8149 if (C->getZExtValue()) {
8150 // Change: A = select B, true, C --> A = or B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00008151 return BinaryOperator::CreateOr(CondVal, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008152 } else {
8153 // Change: A = select B, false, C --> A = and !B, C
8154 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00008155 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008156 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008157 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008158 }
8159 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8160 if (C->getZExtValue() == false) {
8161 // Change: A = select B, C, false --> A = and B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00008162 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008163 } else {
8164 // Change: A = select B, C, true --> A = or !B, C
8165 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00008166 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008167 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008168 return BinaryOperator::CreateOr(NotCond, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008169 }
8170 }
Chris Lattner53f85a72007-11-25 21:27:53 +00008171
8172 // select a, b, a -> a&b
8173 // select a, a, b -> a|b
8174 if (CondVal == TrueVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00008175 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner53f85a72007-11-25 21:27:53 +00008176 else if (CondVal == FalseVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00008177 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008178 }
8179
8180 // Selecting between two integer constants?
8181 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8182 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8183 // select C, 1, 0 -> zext C to int
8184 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00008185 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008186 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8187 // select C, 0, 1 -> zext !C to int
8188 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00008189 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008190 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008191 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008192 }
8193
8194 // FIXME: Turn select 0/-1 and -1/0 into sext from condition!
8195
8196 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8197
8198 // (x <s 0) ? -1 : 0 -> ashr x, 31
8199 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8200 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8201 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8202 // The comparison constant and the result are not neccessarily the
8203 // same width. Make an all-ones value by inserting a AShr.
8204 Value *X = IC->getOperand(0);
8205 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8206 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008207 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008208 ShAmt, "ones");
8209 InsertNewInstBefore(SRA, SI);
8210
8211 // Finally, convert to the type of the select RHS. We figure out
8212 // if this requires a SExt, Trunc or BitCast based on the sizes.
8213 Instruction::CastOps opc = Instruction::BitCast;
8214 uint32_t SRASize = SRA->getType()->getPrimitiveSizeInBits();
8215 uint32_t SISize = SI.getType()->getPrimitiveSizeInBits();
8216 if (SRASize < SISize)
8217 opc = Instruction::SExt;
8218 else if (SRASize > SISize)
8219 opc = Instruction::Trunc;
Gabor Greifa645dd32008-05-16 19:29:10 +00008220 return CastInst::Create(opc, SRA, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008221 }
8222 }
8223
8224
8225 // If one of the constants is zero (we know they can't both be) and we
8226 // have an icmp instruction with zero, and we have an 'and' with the
8227 // non-constant value, eliminate this whole mess. This corresponds to
8228 // cases like this: ((X & 27) ? 27 : 0)
8229 if (TrueValC->isZero() || FalseValC->isZero())
8230 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8231 cast<Constant>(IC->getOperand(1))->isNullValue())
8232 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8233 if (ICA->getOpcode() == Instruction::And &&
8234 isa<ConstantInt>(ICA->getOperand(1)) &&
8235 (ICA->getOperand(1) == TrueValC ||
8236 ICA->getOperand(1) == FalseValC) &&
8237 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8238 // Okay, now we know that everything is set up, we just don't
8239 // know whether we have a icmp_ne or icmp_eq and whether the
8240 // true or false val is the zero.
8241 bool ShouldNotVal = !TrueValC->isZero();
8242 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8243 Value *V = ICA;
8244 if (ShouldNotVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00008245 V = InsertNewInstBefore(BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008246 Instruction::Xor, V, ICA->getOperand(1)), SI);
8247 return ReplaceInstUsesWith(SI, V);
8248 }
8249 }
8250 }
8251
8252 // See if we are selecting two values based on a comparison of the two values.
8253 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8254 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8255 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen2e1b7692007-10-03 17:45:27 +00008256 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8257 // This is not safe in general for floating point:
8258 // consider X== -0, Y== +0.
8259 // It becomes safe if either operand is a nonzero constant.
8260 ConstantFP *CFPt, *CFPf;
8261 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8262 !CFPt->getValueAPF().isZero()) ||
8263 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8264 !CFPf->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008265 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen2e1b7692007-10-03 17:45:27 +00008266 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008267 // Transform (X != Y) ? X : Y -> X
8268 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8269 return ReplaceInstUsesWith(SI, TrueVal);
8270 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8271
8272 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8273 // Transform (X == Y) ? Y : X -> X
Dale Johannesen2e1b7692007-10-03 17:45:27 +00008274 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8275 // This is not safe in general for floating point:
8276 // consider X== -0, Y== +0.
8277 // It becomes safe if either operand is a nonzero constant.
8278 ConstantFP *CFPt, *CFPf;
8279 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8280 !CFPt->getValueAPF().isZero()) ||
8281 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8282 !CFPf->getValueAPF().isZero()))
8283 return ReplaceInstUsesWith(SI, FalseVal);
8284 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008285 // Transform (X != Y) ? Y : X -> Y
8286 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8287 return ReplaceInstUsesWith(SI, TrueVal);
8288 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8289 }
8290 }
8291
8292 // See if we are selecting two values based on a comparison of the two values.
8293 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal)) {
8294 if (ICI->getOperand(0) == TrueVal && ICI->getOperand(1) == FalseVal) {
8295 // Transform (X == Y) ? X : Y -> Y
8296 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8297 return ReplaceInstUsesWith(SI, FalseVal);
8298 // Transform (X != Y) ? X : Y -> X
8299 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8300 return ReplaceInstUsesWith(SI, TrueVal);
8301 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8302
8303 } else if (ICI->getOperand(0) == FalseVal && ICI->getOperand(1) == TrueVal){
8304 // Transform (X == Y) ? Y : X -> X
8305 if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
8306 return ReplaceInstUsesWith(SI, FalseVal);
8307 // Transform (X != Y) ? Y : X -> Y
8308 if (ICI->getPredicate() == ICmpInst::ICMP_NE)
8309 return ReplaceInstUsesWith(SI, TrueVal);
8310 // NOTE: if we wanted to, this is where to detect MIN/MAX/ABS/etc.
8311 }
8312 }
8313
8314 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
8315 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
8316 if (TI->hasOneUse() && FI->hasOneUse()) {
8317 Instruction *AddOp = 0, *SubOp = 0;
8318
8319 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
8320 if (TI->getOpcode() == FI->getOpcode())
8321 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
8322 return IV;
8323
8324 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
8325 // even legal for FP.
8326 if (TI->getOpcode() == Instruction::Sub &&
8327 FI->getOpcode() == Instruction::Add) {
8328 AddOp = FI; SubOp = TI;
8329 } else if (FI->getOpcode() == Instruction::Sub &&
8330 TI->getOpcode() == Instruction::Add) {
8331 AddOp = TI; SubOp = FI;
8332 }
8333
8334 if (AddOp) {
8335 Value *OtherAddOp = 0;
8336 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
8337 OtherAddOp = AddOp->getOperand(1);
8338 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
8339 OtherAddOp = AddOp->getOperand(0);
8340 }
8341
8342 if (OtherAddOp) {
8343 // So at this point we know we have (Y -> OtherAddOp):
8344 // select C, (add X, Y), (sub X, Z)
8345 Value *NegVal; // Compute -Z
8346 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
8347 NegVal = ConstantExpr::getNeg(C);
8348 } else {
8349 NegVal = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00008350 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008351 }
8352
8353 Value *NewTrueOp = OtherAddOp;
8354 Value *NewFalseOp = NegVal;
8355 if (AddOp != TI)
8356 std::swap(NewTrueOp, NewFalseOp);
8357 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00008358 SelectInst::Create(CondVal, NewTrueOp,
8359 NewFalseOp, SI.getName() + ".p");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008360
8361 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008362 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008363 }
8364 }
8365 }
8366
8367 // See if we can fold the select into one of our operands.
8368 if (SI.getType()->isInteger()) {
8369 // See the comment above GetSelectFoldableOperands for a description of the
8370 // transformation we are doing here.
8371 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
8372 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
8373 !isa<Constant>(FalseVal))
8374 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
8375 unsigned OpToFold = 0;
8376 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
8377 OpToFold = 1;
8378 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
8379 OpToFold = 2;
8380 }
8381
8382 if (OpToFold) {
8383 Constant *C = GetSelectFoldableConstant(TVI);
8384 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00008385 SelectInst::Create(SI.getCondition(),
8386 TVI->getOperand(2-OpToFold), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008387 InsertNewInstBefore(NewSel, SI);
8388 NewSel->takeName(TVI);
8389 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greifa645dd32008-05-16 19:29:10 +00008390 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008391 else {
8392 assert(0 && "Unknown instruction!!");
8393 }
8394 }
8395 }
8396
8397 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
8398 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
8399 !isa<Constant>(TrueVal))
8400 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
8401 unsigned OpToFold = 0;
8402 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
8403 OpToFold = 1;
8404 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
8405 OpToFold = 2;
8406 }
8407
8408 if (OpToFold) {
8409 Constant *C = GetSelectFoldableConstant(FVI);
8410 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00008411 SelectInst::Create(SI.getCondition(), C,
8412 FVI->getOperand(2-OpToFold));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008413 InsertNewInstBefore(NewSel, SI);
8414 NewSel->takeName(FVI);
8415 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greifa645dd32008-05-16 19:29:10 +00008416 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008417 else
8418 assert(0 && "Unknown instruction!!");
8419 }
8420 }
8421 }
8422
8423 if (BinaryOperator::isNot(CondVal)) {
8424 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
8425 SI.setOperand(1, FalseVal);
8426 SI.setOperand(2, TrueVal);
8427 return &SI;
8428 }
8429
8430 return 0;
8431}
8432
Dan Gohman2d648bb2008-04-10 18:43:06 +00008433/// EnforceKnownAlignment - If the specified pointer points to an object that
8434/// we control, modify the object's alignment to PrefAlign. This isn't
8435/// often possible though. If alignment is important, a more reliable approach
8436/// is to simply align all global variables and allocation instructions to
8437/// their preferred alignment from the beginning.
8438///
8439static unsigned EnforceKnownAlignment(Value *V,
8440 unsigned Align, unsigned PrefAlign) {
Chris Lattner47cf3452007-08-09 19:05:49 +00008441
Dan Gohman2d648bb2008-04-10 18:43:06 +00008442 User *U = dyn_cast<User>(V);
8443 if (!U) return Align;
8444
8445 switch (getOpcode(U)) {
8446 default: break;
8447 case Instruction::BitCast:
8448 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
8449 case Instruction::GetElementPtr: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008450 // If all indexes are zero, it is just the alignment of the base pointer.
8451 bool AllZeroOperands = true;
Dan Gohman2d648bb2008-04-10 18:43:06 +00008452 for (unsigned i = 1, e = U->getNumOperands(); i != e; ++i)
8453 if (!isa<Constant>(U->getOperand(i)) ||
8454 !cast<Constant>(U->getOperand(i))->isNullValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008455 AllZeroOperands = false;
8456 break;
8457 }
Chris Lattner47cf3452007-08-09 19:05:49 +00008458
8459 if (AllZeroOperands) {
8460 // Treat this like a bitcast.
Dan Gohman2d648bb2008-04-10 18:43:06 +00008461 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattner47cf3452007-08-09 19:05:49 +00008462 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00008463 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008464 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00008465 }
8466
8467 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
8468 // If there is a large requested alignment and we can, bump up the alignment
8469 // of the global.
8470 if (!GV->isDeclaration()) {
8471 GV->setAlignment(PrefAlign);
8472 Align = PrefAlign;
8473 }
8474 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
8475 // If there is a requested alignment and if this is an alloca, round up. We
8476 // don't do this for malloc, because some systems can't respect the request.
8477 if (isa<AllocaInst>(AI)) {
8478 AI->setAlignment(PrefAlign);
8479 Align = PrefAlign;
8480 }
8481 }
8482
8483 return Align;
8484}
8485
8486/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
8487/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
8488/// and it is more than the alignment of the ultimate object, see if we can
8489/// increase the alignment of the ultimate object, making this check succeed.
8490unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
8491 unsigned PrefAlign) {
8492 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
8493 sizeof(PrefAlign) * CHAR_BIT;
8494 APInt Mask = APInt::getAllOnesValue(BitWidth);
8495 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8496 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
8497 unsigned TrailZ = KnownZero.countTrailingOnes();
8498 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
8499
8500 if (PrefAlign > Align)
8501 Align = EnforceKnownAlignment(V, Align, PrefAlign);
8502
8503 // We don't need to make any adjustment.
8504 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008505}
8506
Chris Lattner00ae5132008-01-13 23:50:23 +00008507Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00008508 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
8509 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattner00ae5132008-01-13 23:50:23 +00008510 unsigned MinAlign = std::min(DstAlign, SrcAlign);
8511 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
8512
8513 if (CopyAlign < MinAlign) {
8514 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
8515 return MI;
8516 }
8517
8518 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
8519 // load/store.
8520 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
8521 if (MemOpLength == 0) return 0;
8522
Chris Lattnerc669fb62008-01-14 00:28:35 +00008523 // Source and destination pointer types are always "i8*" for intrinsic. See
8524 // if the size is something we can handle with a single primitive load/store.
8525 // A single load+store correctly handles overlapping memory in the memmove
8526 // case.
Chris Lattner00ae5132008-01-13 23:50:23 +00008527 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner5af8a912008-04-30 06:39:11 +00008528 if (Size == 0) return MI; // Delete this mem transfer.
8529
8530 if (Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +00008531 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +00008532
Chris Lattnerc669fb62008-01-14 00:28:35 +00008533 // Use an integer load+store unless we can find something better.
Chris Lattner00ae5132008-01-13 23:50:23 +00008534 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattnerc669fb62008-01-14 00:28:35 +00008535
8536 // Memcpy forces the use of i8* for the source and destination. That means
8537 // that if you're using memcpy to move one double around, you'll get a cast
8538 // from double* to i8*. We'd much rather use a double load+store rather than
8539 // an i64 load+store, here because this improves the odds that the source or
8540 // dest address will be promotable. See if we can find a better type than the
8541 // integer datatype.
8542 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
8543 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
8544 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
8545 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
8546 // down through these levels if so.
8547 while (!SrcETy->isFirstClassType()) {
8548 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
8549 if (STy->getNumElements() == 1)
8550 SrcETy = STy->getElementType(0);
8551 else
8552 break;
8553 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
8554 if (ATy->getNumElements() == 1)
8555 SrcETy = ATy->getElementType();
8556 else
8557 break;
8558 } else
8559 break;
8560 }
8561
8562 if (SrcETy->isFirstClassType())
8563 NewPtrTy = PointerType::getUnqual(SrcETy);
8564 }
8565 }
8566
8567
Chris Lattner00ae5132008-01-13 23:50:23 +00008568 // If the memcpy/memmove provides better alignment info than we can
8569 // infer, use it.
8570 SrcAlign = std::max(SrcAlign, CopyAlign);
8571 DstAlign = std::max(DstAlign, CopyAlign);
8572
8573 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
8574 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattnerc669fb62008-01-14 00:28:35 +00008575 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
8576 InsertNewInstBefore(L, *MI);
8577 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
8578
8579 // Set the size of the copy to 0, it will be deleted on the next iteration.
8580 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
8581 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +00008582}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008583
Chris Lattner5af8a912008-04-30 06:39:11 +00008584Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
8585 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
8586 if (MI->getAlignment()->getZExtValue() < Alignment) {
8587 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
8588 return MI;
8589 }
8590
8591 // Extract the length and alignment and fill if they are constant.
8592 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
8593 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
8594 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
8595 return 0;
8596 uint64_t Len = LenC->getZExtValue();
8597 Alignment = MI->getAlignment()->getZExtValue();
8598
8599 // If the length is zero, this is a no-op
8600 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
8601
8602 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
8603 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
8604 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
8605
8606 Value *Dest = MI->getDest();
8607 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
8608
8609 // Alignment 0 is identity for alignment 1 for memset, but not store.
8610 if (Alignment == 0) Alignment = 1;
8611
8612 // Extract the fill value and store.
8613 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
8614 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
8615 Alignment), *MI);
8616
8617 // Set the size of the copy to 0, it will be deleted on the next iteration.
8618 MI->setLength(Constant::getNullValue(LenC->getType()));
8619 return MI;
8620 }
8621
8622 return 0;
8623}
8624
8625
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008626/// visitCallInst - CallInst simplification. This mostly only handles folding
8627/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
8628/// the heavy lifting.
8629///
8630Instruction *InstCombiner::visitCallInst(CallInst &CI) {
8631 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
8632 if (!II) return visitCallSite(&CI);
8633
8634 // Intrinsics cannot occur in an invoke, so handle them here instead of in
8635 // visitCallSite.
8636 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
8637 bool Changed = false;
8638
8639 // memmove/cpy/set of zero bytes is a noop.
8640 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
8641 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
8642
8643 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
8644 if (CI->getZExtValue() == 1) {
8645 // Replace the instruction with just byte operations. We would
8646 // transform other cases to loads/stores, but we don't know if
8647 // alignment is sufficient.
8648 }
8649 }
8650
8651 // If we have a memmove and the source operation is a constant global,
8652 // then the source and dest pointers can't alias, so we can change this
8653 // into a call to memcpy.
Chris Lattner00ae5132008-01-13 23:50:23 +00008654 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008655 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
8656 if (GVSrc->isConstant()) {
8657 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008658 Intrinsic::ID MemCpyID;
8659 if (CI.getOperand(3)->getType() == Type::Int32Ty)
8660 MemCpyID = Intrinsic::memcpy_i32;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008661 else
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008662 MemCpyID = Intrinsic::memcpy_i64;
8663 CI.setOperand(0, Intrinsic::getDeclaration(M, MemCpyID));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008664 Changed = true;
8665 }
8666 }
8667
8668 // If we can determine a pointer alignment that is bigger than currently
8669 // set, update the alignment.
8670 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +00008671 if (Instruction *I = SimplifyMemTransfer(MI))
8672 return I;
Chris Lattner5af8a912008-04-30 06:39:11 +00008673 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
8674 if (Instruction *I = SimplifyMemSet(MSI))
8675 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008676 }
8677
8678 if (Changed) return II;
8679 } else {
8680 switch (II->getIntrinsicID()) {
8681 default: break;
8682 case Intrinsic::ppc_altivec_lvx:
8683 case Intrinsic::ppc_altivec_lvxl:
8684 case Intrinsic::x86_sse_loadu_ps:
8685 case Intrinsic::x86_sse2_loadu_pd:
8686 case Intrinsic::x86_sse2_loadu_dq:
8687 // Turn PPC lvx -> load if the pointer is known aligned.
8688 // Turn X86 loadups -> load if the pointer is known aligned.
Dan Gohman2d648bb2008-04-10 18:43:06 +00008689 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008690 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
8691 PointerType::getUnqual(II->getType()),
8692 CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008693 return new LoadInst(Ptr);
8694 }
8695 break;
8696 case Intrinsic::ppc_altivec_stvx:
8697 case Intrinsic::ppc_altivec_stvxl:
8698 // Turn stvx -> store if the pointer is known aligned.
Dan Gohman2d648bb2008-04-10 18:43:06 +00008699 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00008700 const Type *OpPtrTy =
8701 PointerType::getUnqual(II->getOperand(1)->getType());
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008702 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008703 return new StoreInst(II->getOperand(1), Ptr);
8704 }
8705 break;
8706 case Intrinsic::x86_sse_storeu_ps:
8707 case Intrinsic::x86_sse2_storeu_pd:
8708 case Intrinsic::x86_sse2_storeu_dq:
8709 case Intrinsic::x86_sse2_storel_dq:
8710 // Turn X86 storeu -> store if the pointer is known aligned.
Dan Gohman2d648bb2008-04-10 18:43:06 +00008711 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00008712 const Type *OpPtrTy =
8713 PointerType::getUnqual(II->getOperand(2)->getType());
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008714 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008715 return new StoreInst(II->getOperand(2), Ptr);
8716 }
8717 break;
8718
8719 case Intrinsic::x86_sse_cvttss2si: {
8720 // These intrinsics only demands the 0th element of its input vector. If
8721 // we can simplify the input based on that, do so now.
8722 uint64_t UndefElts;
8723 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
8724 UndefElts)) {
8725 II->setOperand(1, V);
8726 return II;
8727 }
8728 break;
8729 }
8730
8731 case Intrinsic::ppc_altivec_vperm:
8732 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
8733 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
8734 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
8735
8736 // Check that all of the elements are integer constants or undefs.
8737 bool AllEltsOk = true;
8738 for (unsigned i = 0; i != 16; ++i) {
8739 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
8740 !isa<UndefValue>(Mask->getOperand(i))) {
8741 AllEltsOk = false;
8742 break;
8743 }
8744 }
8745
8746 if (AllEltsOk) {
8747 // Cast the input vectors to byte vectors.
Chris Lattner13c2d6e2008-01-13 22:23:22 +00008748 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
8749 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008750 Value *Result = UndefValue::get(Op0->getType());
8751
8752 // Only extract each element once.
8753 Value *ExtractedElts[32];
8754 memset(ExtractedElts, 0, sizeof(ExtractedElts));
8755
8756 for (unsigned i = 0; i != 16; ++i) {
8757 if (isa<UndefValue>(Mask->getOperand(i)))
8758 continue;
8759 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
8760 Idx &= 31; // Match the hardware behavior.
8761
8762 if (ExtractedElts[Idx] == 0) {
8763 Instruction *Elt =
8764 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
8765 InsertNewInstBefore(Elt, CI);
8766 ExtractedElts[Idx] = Elt;
8767 }
8768
8769 // Insert this value into the result vector.
Gabor Greifb91ea9d2008-05-15 10:04:30 +00008770 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
8771 i, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008772 InsertNewInstBefore(cast<Instruction>(Result), CI);
8773 }
Gabor Greifa645dd32008-05-16 19:29:10 +00008774 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008775 }
8776 }
8777 break;
8778
8779 case Intrinsic::stackrestore: {
8780 // If the save is right next to the restore, remove the restore. This can
8781 // happen when variable allocas are DCE'd.
8782 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
8783 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
8784 BasicBlock::iterator BI = SS;
8785 if (&*++BI == II)
8786 return EraseInstFromFunction(CI);
8787 }
8788 }
8789
Chris Lattner416d91c2008-02-18 06:12:38 +00008790 // Scan down this block to see if there is another stack restore in the
8791 // same block without an intervening call/alloca.
8792 BasicBlock::iterator BI = II;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008793 TerminatorInst *TI = II->getParent()->getTerminator();
Chris Lattner416d91c2008-02-18 06:12:38 +00008794 bool CannotRemove = false;
8795 for (++BI; &*BI != TI; ++BI) {
8796 if (isa<AllocaInst>(BI)) {
8797 CannotRemove = true;
8798 break;
8799 }
8800 if (isa<CallInst>(BI)) {
8801 if (!isa<IntrinsicInst>(BI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008802 CannotRemove = true;
8803 break;
8804 }
Chris Lattner416d91c2008-02-18 06:12:38 +00008805 // If there is a stackrestore below this one, remove this one.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008806 return EraseInstFromFunction(CI);
Chris Lattner416d91c2008-02-18 06:12:38 +00008807 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008808 }
Chris Lattner416d91c2008-02-18 06:12:38 +00008809
8810 // If the stack restore is in a return/unwind block and if there are no
8811 // allocas or calls between the restore and the return, nuke the restore.
8812 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
8813 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008814 break;
8815 }
8816 }
8817 }
8818
8819 return visitCallSite(II);
8820}
8821
8822// InvokeInst simplification
8823//
8824Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
8825 return visitCallSite(&II);
8826}
8827
Dale Johannesen96021832008-04-25 21:16:07 +00008828/// isSafeToEliminateVarargsCast - If this cast does not affect the value
8829/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen35615462008-04-23 18:34:37 +00008830static bool isSafeToEliminateVarargsCast(const CallSite CS,
8831 const CastInst * const CI,
8832 const TargetData * const TD,
8833 const int ix) {
8834 if (!CI->isLosslessCast())
8835 return false;
8836
8837 // The size of ByVal arguments is derived from the type, so we
8838 // can't change to a type with a different size. If the size were
8839 // passed explicitly we could avoid this check.
8840 if (!CS.paramHasAttr(ix, ParamAttr::ByVal))
8841 return true;
8842
8843 const Type* SrcTy =
8844 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
8845 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
8846 if (!SrcTy->isSized() || !DstTy->isSized())
8847 return false;
8848 if (TD->getABITypeSize(SrcTy) != TD->getABITypeSize(DstTy))
8849 return false;
8850 return true;
8851}
8852
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008853// visitCallSite - Improvements for call and invoke instructions.
8854//
8855Instruction *InstCombiner::visitCallSite(CallSite CS) {
8856 bool Changed = false;
8857
8858 // If the callee is a constexpr cast of a function, attempt to move the cast
8859 // to the arguments of the call/invoke.
8860 if (transformConstExprCastCall(CS)) return 0;
8861
8862 Value *Callee = CS.getCalledValue();
8863
8864 if (Function *CalleeF = dyn_cast<Function>(Callee))
8865 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
8866 Instruction *OldCall = CS.getInstruction();
8867 // If the call and callee calling conventions don't match, this call must
8868 // be unreachable, as the call is undefined.
8869 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00008870 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
8871 OldCall);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008872 if (!OldCall->use_empty())
8873 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
8874 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
8875 return EraseInstFromFunction(*OldCall);
8876 return 0;
8877 }
8878
8879 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
8880 // This instruction is not reachable, just remove it. We insert a store to
8881 // undef so that we know that this code is not reachable, despite the fact
8882 // that we can't modify the CFG here.
8883 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00008884 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008885 CS.getInstruction());
8886
8887 if (!CS.getInstruction()->use_empty())
8888 CS.getInstruction()->
8889 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
8890
8891 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
8892 // Don't break the CFG, insert a dummy cond branch.
Gabor Greifd6da1d02008-04-06 20:25:17 +00008893 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
8894 ConstantInt::getTrue(), II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008895 }
8896 return EraseInstFromFunction(*CS.getInstruction());
8897 }
8898
Duncan Sands74833f22007-09-17 10:26:40 +00008899 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
8900 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
8901 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
8902 return transformCallThroughTrampoline(CS);
8903
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008904 const PointerType *PTy = cast<PointerType>(Callee->getType());
8905 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
8906 if (FTy->isVarArg()) {
Dale Johannesen502336c2008-04-23 01:03:05 +00008907 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008908 // See if we can optimize any arguments passed through the varargs area of
8909 // the call.
8910 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen35615462008-04-23 18:34:37 +00008911 E = CS.arg_end(); I != E; ++I, ++ix) {
8912 CastInst *CI = dyn_cast<CastInst>(*I);
8913 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
8914 *I = CI->getOperand(0);
8915 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008916 }
Dale Johannesen35615462008-04-23 18:34:37 +00008917 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008918 }
8919
Duncan Sands2937e352007-12-19 21:13:37 +00008920 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +00008921 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +00008922 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +00008923 Changed = true;
8924 }
8925
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008926 return Changed ? CS.getInstruction() : 0;
8927}
8928
8929// transformConstExprCastCall - If the callee is a constexpr cast of a function,
8930// attempt to move the cast to the arguments of the call/invoke.
8931//
8932bool InstCombiner::transformConstExprCastCall(CallSite CS) {
8933 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
8934 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
8935 if (CE->getOpcode() != Instruction::BitCast ||
8936 !isa<Function>(CE->getOperand(0)))
8937 return false;
8938 Function *Callee = cast<Function>(CE->getOperand(0));
8939 Instruction *Caller = CS.getInstruction();
Chris Lattner1c8733e2008-03-12 17:45:29 +00008940 const PAListPtr &CallerPAL = CS.getParamAttrs();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008941
8942 // Okay, this is a cast from a function to a different type. Unless doing so
8943 // would cause a type conversion of one of our arguments, change this call to
8944 // be a direct call with arguments casted to the appropriate types.
8945 //
8946 const FunctionType *FT = Callee->getFunctionType();
8947 const Type *OldRetTy = Caller->getType();
8948
Devang Pateld091d322008-03-11 18:04:06 +00008949 if (isa<StructType>(FT->getReturnType()))
8950 return false; // TODO: Handle multiple return values.
8951
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008952 // Check to see if we are changing the return type...
8953 if (OldRetTy != FT->getReturnType()) {
Bill Wendlingd9644a42008-05-14 22:45:20 +00008954 if (Callee->isDeclaration() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008955 // Conversion is ok if changing from pointer to int of same size.
8956 !(isa<PointerType>(FT->getReturnType()) &&
8957 TD->getIntPtrType() == OldRetTy))
8958 return false; // Cannot transform this return value.
8959
Duncan Sands5c489582008-01-06 10:12:28 +00008960 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +00008961 // void -> non-void is handled specially
Duncan Sands4ced1f82008-01-13 08:02:44 +00008962 FT->getReturnType() != Type::VoidTy &&
8963 !CastInst::isCastable(FT->getReturnType(), OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +00008964 return false; // Cannot transform this return value.
8965
Chris Lattner1c8733e2008-03-12 17:45:29 +00008966 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
8967 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsdbe97dc2008-01-07 17:16:06 +00008968 if (RAttrs & ParamAttr::typeIncompatible(FT->getReturnType()))
8969 return false; // Attribute not compatible with transformed value.
8970 }
Duncan Sandsc849e662008-01-06 18:27:01 +00008971
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008972 // If the callsite is an invoke instruction, and the return value is used by
8973 // a PHI node in a successor, we cannot change the return type of the call
8974 // because there is no place to put the cast instruction (without breaking
8975 // the critical edge). Bail out in this case.
8976 if (!Caller->use_empty())
8977 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
8978 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
8979 UI != E; ++UI)
8980 if (PHINode *PN = dyn_cast<PHINode>(*UI))
8981 if (PN->getParent() == II->getNormalDest() ||
8982 PN->getParent() == II->getUnwindDest())
8983 return false;
8984 }
8985
8986 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
8987 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
8988
8989 CallSite::arg_iterator AI = CS.arg_begin();
8990 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
8991 const Type *ParamTy = FT->getParamType(i);
8992 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +00008993
8994 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +00008995 return false; // Cannot transform this parameter value.
8996
Chris Lattner1c8733e2008-03-12 17:45:29 +00008997 if (CallerPAL.getParamAttrs(i + 1) & ParamAttr::typeIncompatible(ParamTy))
8998 return false; // Attribute not compatible with transformed value.
Duncan Sands5c489582008-01-06 10:12:28 +00008999
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009000 ConstantInt *c = dyn_cast<ConstantInt>(*AI);
Duncan Sands5c489582008-01-06 10:12:28 +00009001 // Some conversions are safe even if we do not have a body.
9002 // Either we can cast directly, or we can upconvert the argument
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009003 bool isConvertible = ActTy == ParamTy ||
9004 (isa<PointerType>(ParamTy) && isa<PointerType>(ActTy)) ||
9005 (ParamTy->isInteger() && ActTy->isInteger() &&
9006 ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()) ||
9007 (c && ParamTy->getPrimitiveSizeInBits() >= ActTy->getPrimitiveSizeInBits()
9008 && c->getValue().isStrictlyPositive());
9009 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009010 }
9011
9012 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
9013 Callee->isDeclaration())
Chris Lattner1c8733e2008-03-12 17:45:29 +00009014 return false; // Do not delete arguments unless we have a function body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009015
Chris Lattner1c8733e2008-03-12 17:45:29 +00009016 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9017 !CallerPAL.isEmpty())
Duncan Sandsc849e662008-01-06 18:27:01 +00009018 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +00009019 // won't be dropping them. Check that these extra arguments have attributes
9020 // that are compatible with being a vararg call argument.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009021 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9022 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands4ced1f82008-01-13 08:02:44 +00009023 break;
Chris Lattner1c8733e2008-03-12 17:45:29 +00009024 ParameterAttributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Duncan Sands4ced1f82008-01-13 08:02:44 +00009025 if (PAttrs & ParamAttr::VarArgsIncompatible)
9026 return false;
9027 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009028
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009029 // Okay, we decided that this is a safe thing to do: go ahead and start
9030 // inserting cast instructions as necessary...
9031 std::vector<Value*> Args;
9032 Args.reserve(NumActualArgs);
Chris Lattner1c8733e2008-03-12 17:45:29 +00009033 SmallVector<ParamAttrsWithIndex, 8> attrVec;
Duncan Sandsc849e662008-01-06 18:27:01 +00009034 attrVec.reserve(NumCommonArgs);
9035
9036 // Get any return attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009037 ParameterAttributes RAttrs = CallerPAL.getParamAttrs(0);
Duncan Sandsc849e662008-01-06 18:27:01 +00009038
9039 // If the return value is not being used, the type may not be compatible
9040 // with the existing attributes. Wipe out any problematic attributes.
Duncan Sandsdbe97dc2008-01-07 17:16:06 +00009041 RAttrs &= ~ParamAttr::typeIncompatible(FT->getReturnType());
Duncan Sandsc849e662008-01-06 18:27:01 +00009042
9043 // Add the new return attributes.
9044 if (RAttrs)
9045 attrVec.push_back(ParamAttrsWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009046
9047 AI = CS.arg_begin();
9048 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9049 const Type *ParamTy = FT->getParamType(i);
9050 if ((*AI)->getType() == ParamTy) {
9051 Args.push_back(*AI);
9052 } else {
9053 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
9054 false, ParamTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00009055 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009056 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
9057 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009058
9059 // Add any parameter attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009060 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sandsc849e662008-01-06 18:27:01 +00009061 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009062 }
9063
9064 // If the function takes more arguments than the call was taking, add them
9065 // now...
9066 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9067 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9068
9069 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009070 if (FT->getNumParams() < NumActualArgs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009071 if (!FT->isVarArg()) {
9072 cerr << "WARNING: While resolving call to function '"
9073 << Callee->getName() << "' arguments were dropped!\n";
9074 } else {
9075 // Add all of the arguments in their promoted form to the arg list...
9076 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9077 const Type *PTy = getPromotedType((*AI)->getType());
9078 if (PTy != (*AI)->getType()) {
9079 // Must promote to pass through va_arg area!
9080 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9081 PTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00009082 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009083 InsertNewInstBefore(Cast, *Caller);
9084 Args.push_back(Cast);
9085 } else {
9086 Args.push_back(*AI);
9087 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009088
Duncan Sands4ced1f82008-01-13 08:02:44 +00009089 // Add any parameter attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009090 if (ParameterAttributes PAttrs = CallerPAL.getParamAttrs(i + 1))
Duncan Sands4ced1f82008-01-13 08:02:44 +00009091 attrVec.push_back(ParamAttrsWithIndex::get(i + 1, PAttrs));
9092 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009093 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009094 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009095
9096 if (FT->getReturnType() == Type::VoidTy)
9097 Caller->setName(""); // Void type should not have a name.
9098
Chris Lattner1c8733e2008-03-12 17:45:29 +00009099 const PAListPtr &NewCallerPAL = PAListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsc849e662008-01-06 18:27:01 +00009100
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009101 Instruction *NC;
9102 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009103 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009104 Args.begin(), Args.end(),
9105 Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +00009106 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Duncan Sandsc849e662008-01-06 18:27:01 +00009107 cast<InvokeInst>(NC)->setParamAttrs(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009108 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009109 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9110 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009111 CallInst *CI = cast<CallInst>(Caller);
9112 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009113 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009114 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Duncan Sandsc849e662008-01-06 18:27:01 +00009115 cast<CallInst>(NC)->setParamAttrs(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009116 }
9117
9118 // Insert a cast of the return type as necessary.
9119 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +00009120 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009121 if (NV->getType() != Type::VoidTy) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009122 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +00009123 OldRetTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00009124 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009125
9126 // If this is an invoke instruction, we should insert it after the first
9127 // non-phi, instruction in the normal successor block.
9128 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
9129 BasicBlock::iterator I = II->getNormalDest()->begin();
9130 while (isa<PHINode>(I)) ++I;
9131 InsertNewInstBefore(NC, *I);
9132 } else {
9133 // Otherwise, it's a call, just insert cast right after the call instr
9134 InsertNewInstBefore(NC, *Caller);
9135 }
9136 AddUsersToWorkList(*Caller);
9137 } else {
9138 NV = UndefValue::get(Caller->getType());
9139 }
9140 }
9141
9142 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9143 Caller->replaceAllUsesWith(NV);
9144 Caller->eraseFromParent();
9145 RemoveFromWorkList(Caller);
9146 return true;
9147}
9148
Duncan Sands74833f22007-09-17 10:26:40 +00009149// transformCallThroughTrampoline - Turn a call to a function created by the
9150// init_trampoline intrinsic into a direct call to the underlying function.
9151//
9152Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9153 Value *Callee = CS.getCalledValue();
9154 const PointerType *PTy = cast<PointerType>(Callee->getType());
9155 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Chris Lattner1c8733e2008-03-12 17:45:29 +00009156 const PAListPtr &Attrs = CS.getParamAttrs();
Duncan Sands48b81112008-01-14 19:52:09 +00009157
9158 // If the call already has the 'nest' attribute somewhere then give up -
9159 // otherwise 'nest' would occur twice after splicing in the chain.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009160 if (Attrs.hasAttrSomewhere(ParamAttr::Nest))
Duncan Sands48b81112008-01-14 19:52:09 +00009161 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +00009162
9163 IntrinsicInst *Tramp =
9164 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9165
Anton Korobeynikov48fc88f2008-05-07 22:54:15 +00009166 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sands74833f22007-09-17 10:26:40 +00009167 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9168 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9169
Chris Lattner1c8733e2008-03-12 17:45:29 +00009170 const PAListPtr &NestAttrs = NestF->getParamAttrs();
9171 if (!NestAttrs.isEmpty()) {
Duncan Sands74833f22007-09-17 10:26:40 +00009172 unsigned NestIdx = 1;
9173 const Type *NestTy = 0;
Dale Johannesenf4666f52008-02-19 21:38:47 +00009174 ParameterAttributes NestAttr = ParamAttr::None;
Duncan Sands74833f22007-09-17 10:26:40 +00009175
9176 // Look for a parameter marked with the 'nest' attribute.
9177 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9178 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Chris Lattner1c8733e2008-03-12 17:45:29 +00009179 if (NestAttrs.paramHasAttr(NestIdx, ParamAttr::Nest)) {
Duncan Sands74833f22007-09-17 10:26:40 +00009180 // Record the parameter type and any other attributes.
9181 NestTy = *I;
Chris Lattner1c8733e2008-03-12 17:45:29 +00009182 NestAttr = NestAttrs.getParamAttrs(NestIdx);
Duncan Sands74833f22007-09-17 10:26:40 +00009183 break;
9184 }
9185
9186 if (NestTy) {
9187 Instruction *Caller = CS.getInstruction();
9188 std::vector<Value*> NewArgs;
9189 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9190
Chris Lattner1c8733e2008-03-12 17:45:29 +00009191 SmallVector<ParamAttrsWithIndex, 8> NewAttrs;
9192 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sands48b81112008-01-14 19:52:09 +00009193
Duncan Sands74833f22007-09-17 10:26:40 +00009194 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +00009195 // mean appending it. Likewise for attributes.
9196
9197 // Add any function result attributes.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009198 if (ParameterAttributes Attr = Attrs.getParamAttrs(0))
9199 NewAttrs.push_back(ParamAttrsWithIndex::get(0, Attr));
Duncan Sands48b81112008-01-14 19:52:09 +00009200
Duncan Sands74833f22007-09-17 10:26:40 +00009201 {
9202 unsigned Idx = 1;
9203 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9204 do {
9205 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +00009206 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00009207 Value *NestVal = Tramp->getOperand(3);
9208 if (NestVal->getType() != NestTy)
9209 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9210 NewArgs.push_back(NestVal);
Duncan Sands48b81112008-01-14 19:52:09 +00009211 NewAttrs.push_back(ParamAttrsWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +00009212 }
9213
9214 if (I == E)
9215 break;
9216
Duncan Sands48b81112008-01-14 19:52:09 +00009217 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00009218 NewArgs.push_back(*I);
Chris Lattner1c8733e2008-03-12 17:45:29 +00009219 if (ParameterAttributes Attr = Attrs.getParamAttrs(Idx))
Duncan Sands48b81112008-01-14 19:52:09 +00009220 NewAttrs.push_back
9221 (ParamAttrsWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +00009222
9223 ++Idx, ++I;
9224 } while (1);
9225 }
9226
9227 // The trampoline may have been bitcast to a bogus type (FTy).
9228 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +00009229 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +00009230
Duncan Sands74833f22007-09-17 10:26:40 +00009231 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +00009232 NewTypes.reserve(FTy->getNumParams()+1);
9233
Duncan Sands74833f22007-09-17 10:26:40 +00009234 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +00009235 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +00009236 {
9237 unsigned Idx = 1;
9238 FunctionType::param_iterator I = FTy->param_begin(),
9239 E = FTy->param_end();
9240
9241 do {
Duncan Sands48b81112008-01-14 19:52:09 +00009242 if (Idx == NestIdx)
9243 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +00009244 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +00009245
9246 if (I == E)
9247 break;
9248
Duncan Sands48b81112008-01-14 19:52:09 +00009249 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +00009250 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +00009251
9252 ++Idx, ++I;
9253 } while (1);
9254 }
9255
9256 // Replace the trampoline call with a direct call. Let the generic
9257 // code sort out any function type mismatches.
9258 FunctionType *NewFTy =
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009259 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lambbb2f2222007-12-17 01:12:55 +00009260 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9261 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Chris Lattner1c8733e2008-03-12 17:45:29 +00009262 const PAListPtr &NewPAL = PAListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sands74833f22007-09-17 10:26:40 +00009263
9264 Instruction *NewCaller;
9265 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009266 NewCaller = InvokeInst::Create(NewCallee,
9267 II->getNormalDest(), II->getUnwindDest(),
9268 NewArgs.begin(), NewArgs.end(),
9269 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +00009270 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009271 cast<InvokeInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00009272 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009273 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9274 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +00009275 if (cast<CallInst>(Caller)->isTailCall())
9276 cast<CallInst>(NewCaller)->setTailCall();
9277 cast<CallInst>(NewCaller)->
9278 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009279 cast<CallInst>(NewCaller)->setParamAttrs(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00009280 }
9281 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9282 Caller->replaceAllUsesWith(NewCaller);
9283 Caller->eraseFromParent();
9284 RemoveFromWorkList(Caller);
9285 return 0;
9286 }
9287 }
9288
9289 // Replace the trampoline call with a direct call. Since there is no 'nest'
9290 // parameter, there is no need to adjust the argument list. Let the generic
9291 // code sort out any function type mismatches.
9292 Constant *NewCallee =
9293 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
9294 CS.setCalledFunction(NewCallee);
9295 return CS.getInstruction();
9296}
9297
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009298/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
9299/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
9300/// and a single binop.
9301Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
9302 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9303 assert(isa<BinaryOperator>(FirstInst) || isa<GetElementPtrInst>(FirstInst) ||
9304 isa<CmpInst>(FirstInst));
9305 unsigned Opc = FirstInst->getOpcode();
9306 Value *LHSVal = FirstInst->getOperand(0);
9307 Value *RHSVal = FirstInst->getOperand(1);
9308
9309 const Type *LHSType = LHSVal->getType();
9310 const Type *RHSType = RHSVal->getType();
9311
9312 // Scan to see if all operands are the same opcode, all have one use, and all
9313 // kill their operands (i.e. the operands have one use).
9314 for (unsigned i = 0; i != PN.getNumIncomingValues(); ++i) {
9315 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
9316 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
9317 // Verify type of the LHS matches so we don't fold cmp's of different
9318 // types or GEP's with different index types.
9319 I->getOperand(0)->getType() != LHSType ||
9320 I->getOperand(1)->getType() != RHSType)
9321 return 0;
9322
9323 // If they are CmpInst instructions, check their predicates
9324 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
9325 if (cast<CmpInst>(I)->getPredicate() !=
9326 cast<CmpInst>(FirstInst)->getPredicate())
9327 return 0;
9328
9329 // Keep track of which operand needs a phi node.
9330 if (I->getOperand(0) != LHSVal) LHSVal = 0;
9331 if (I->getOperand(1) != RHSVal) RHSVal = 0;
9332 }
9333
9334 // Otherwise, this is safe to transform, determine if it is profitable.
9335
9336 // If this is a GEP, and if the index (not the pointer) needs a PHI, bail out.
9337 // Indexes are often folded into load/store instructions, so we don't want to
9338 // hide them behind a phi.
9339 if (isa<GetElementPtrInst>(FirstInst) && RHSVal == 0)
9340 return 0;
9341
9342 Value *InLHS = FirstInst->getOperand(0);
9343 Value *InRHS = FirstInst->getOperand(1);
9344 PHINode *NewLHS = 0, *NewRHS = 0;
9345 if (LHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009346 NewLHS = PHINode::Create(LHSType,
9347 FirstInst->getOperand(0)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009348 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
9349 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
9350 InsertNewInstBefore(NewLHS, PN);
9351 LHSVal = NewLHS;
9352 }
9353
9354 if (RHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009355 NewRHS = PHINode::Create(RHSType,
9356 FirstInst->getOperand(1)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009357 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
9358 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
9359 InsertNewInstBefore(NewRHS, PN);
9360 RHSVal = NewRHS;
9361 }
9362
9363 // Add all operands to the new PHIs.
9364 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9365 if (NewLHS) {
9366 Value *NewInLHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9367 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
9368 }
9369 if (NewRHS) {
9370 Value *NewInRHS =cast<Instruction>(PN.getIncomingValue(i))->getOperand(1);
9371 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
9372 }
9373 }
9374
9375 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009376 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009377 else if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009378 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009379 RHSVal);
9380 else {
9381 assert(isa<GetElementPtrInst>(FirstInst));
Gabor Greifd6da1d02008-04-06 20:25:17 +00009382 return GetElementPtrInst::Create(LHSVal, RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009383 }
9384}
9385
9386/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
9387/// of the block that defines it. This means that it must be obvious the value
9388/// of the load is not changed from the point of the load to the end of the
9389/// block it is in.
9390///
9391/// Finally, it is safe, but not profitable, to sink a load targetting a
9392/// non-address-taken alloca. Doing so will cause us to not promote the alloca
9393/// to a register.
9394static bool isSafeToSinkLoad(LoadInst *L) {
9395 BasicBlock::iterator BBI = L, E = L->getParent()->end();
9396
9397 for (++BBI; BBI != E; ++BBI)
9398 if (BBI->mayWriteToMemory())
9399 return false;
9400
9401 // Check for non-address taken alloca. If not address-taken already, it isn't
9402 // profitable to do this xform.
9403 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
9404 bool isAddressTaken = false;
9405 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
9406 UI != E; ++UI) {
9407 if (isa<LoadInst>(UI)) continue;
9408 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
9409 // If storing TO the alloca, then the address isn't taken.
9410 if (SI->getOperand(1) == AI) continue;
9411 }
9412 isAddressTaken = true;
9413 break;
9414 }
9415
9416 if (!isAddressTaken)
9417 return false;
9418 }
9419
9420 return true;
9421}
9422
9423
9424// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
9425// operator and they all are only used by the PHI, PHI together their
9426// inputs, and do the operation once, to the result of the PHI.
9427Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
9428 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
9429
9430 // Scan the instruction, looking for input operations that can be folded away.
9431 // If all input operands to the phi are the same instruction (e.g. a cast from
9432 // the same type or "+42") we can pull the operation through the PHI, reducing
9433 // code size and simplifying code.
9434 Constant *ConstantOp = 0;
9435 const Type *CastSrcTy = 0;
9436 bool isVolatile = false;
9437 if (isa<CastInst>(FirstInst)) {
9438 CastSrcTy = FirstInst->getOperand(0)->getType();
9439 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
9440 // Can fold binop, compare or shift here if the RHS is a constant,
9441 // otherwise call FoldPHIArgBinOpIntoPHI.
9442 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
9443 if (ConstantOp == 0)
9444 return FoldPHIArgBinOpIntoPHI(PN);
9445 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
9446 isVolatile = LI->isVolatile();
9447 // We can't sink the load if the loaded value could be modified between the
9448 // load and the PHI.
9449 if (LI->getParent() != PN.getIncomingBlock(0) ||
9450 !isSafeToSinkLoad(LI))
9451 return 0;
9452 } else if (isa<GetElementPtrInst>(FirstInst)) {
9453 if (FirstInst->getNumOperands() == 2)
9454 return FoldPHIArgBinOpIntoPHI(PN);
9455 // Can't handle general GEPs yet.
9456 return 0;
9457 } else {
9458 return 0; // Cannot fold this operation.
9459 }
9460
9461 // Check to see if all arguments are the same operation.
9462 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9463 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
9464 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
9465 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
9466 return 0;
9467 if (CastSrcTy) {
9468 if (I->getOperand(0)->getType() != CastSrcTy)
9469 return 0; // Cast operation must match.
9470 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
9471 // We can't sink the load if the loaded value could be modified between
9472 // the load and the PHI.
9473 if (LI->isVolatile() != isVolatile ||
9474 LI->getParent() != PN.getIncomingBlock(i) ||
9475 !isSafeToSinkLoad(LI))
9476 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +00009477
9478 // If the PHI is volatile and its block has multiple successors, sinking
9479 // it would remove a load of the volatile value from the path through the
9480 // other successor.
9481 if (isVolatile &&
9482 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
9483 return 0;
9484
9485
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009486 } else if (I->getOperand(1) != ConstantOp) {
9487 return 0;
9488 }
9489 }
9490
9491 // Okay, they are all the same operation. Create a new PHI node of the
9492 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009493 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
9494 PN.getName()+".in");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009495 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
9496
9497 Value *InVal = FirstInst->getOperand(0);
9498 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
9499
9500 // Add all operands to the new PHI.
9501 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
9502 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
9503 if (NewInVal != InVal)
9504 InVal = 0;
9505 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
9506 }
9507
9508 Value *PhiVal;
9509 if (InVal) {
9510 // The new PHI unions all of the same values together. This is really
9511 // common, so we handle it intelligently here for compile-time speed.
9512 PhiVal = InVal;
9513 delete NewPN;
9514 } else {
9515 InsertNewInstBefore(NewPN, PN);
9516 PhiVal = NewPN;
9517 }
9518
9519 // Insert and return the new operation.
9520 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009521 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnerfc984e92008-04-29 17:13:43 +00009522 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009523 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +00009524 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +00009525 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009526 PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +00009527 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
9528
9529 // If this was a volatile load that we are merging, make sure to loop through
9530 // and mark all the input loads as non-volatile. If we don't do this, we will
9531 // insert a new volatile load and the old ones will not be deletable.
9532 if (isVolatile)
9533 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
9534 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
9535
9536 return new LoadInst(PhiVal, "", isVolatile);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009537}
9538
9539/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
9540/// that is dead.
9541static bool DeadPHICycle(PHINode *PN,
9542 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
9543 if (PN->use_empty()) return true;
9544 if (!PN->hasOneUse()) return false;
9545
9546 // Remember this node, and if we find the cycle, return.
9547 if (!PotentiallyDeadPHIs.insert(PN))
9548 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +00009549
9550 // Don't scan crazily complex things.
9551 if (PotentiallyDeadPHIs.size() == 16)
9552 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009553
9554 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
9555 return DeadPHICycle(PU, PotentiallyDeadPHIs);
9556
9557 return false;
9558}
9559
Chris Lattner27b695d2007-11-06 21:52:06 +00009560/// PHIsEqualValue - Return true if this phi node is always equal to
9561/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
9562/// z = some value; x = phi (y, z); y = phi (x, z)
9563static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
9564 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
9565 // See if we already saw this PHI node.
9566 if (!ValueEqualPHIs.insert(PN))
9567 return true;
9568
9569 // Don't scan crazily complex things.
9570 if (ValueEqualPHIs.size() == 16)
9571 return false;
9572
9573 // Scan the operands to see if they are either phi nodes or are equal to
9574 // the value.
9575 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
9576 Value *Op = PN->getIncomingValue(i);
9577 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
9578 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
9579 return false;
9580 } else if (Op != NonPhiInVal)
9581 return false;
9582 }
9583
9584 return true;
9585}
9586
9587
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009588// PHINode simplification
9589//
9590Instruction *InstCombiner::visitPHINode(PHINode &PN) {
9591 // If LCSSA is around, don't mess with Phi nodes
9592 if (MustPreserveLCSSA) return 0;
9593
9594 if (Value *V = PN.hasConstantValue())
9595 return ReplaceInstUsesWith(PN, V);
9596
9597 // If all PHI operands are the same operation, pull them through the PHI,
9598 // reducing code size.
9599 if (isa<Instruction>(PN.getIncomingValue(0)) &&
9600 PN.getIncomingValue(0)->hasOneUse())
9601 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
9602 return Result;
9603
9604 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
9605 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
9606 // PHI)... break the cycle.
9607 if (PN.hasOneUse()) {
9608 Instruction *PHIUser = cast<Instruction>(PN.use_back());
9609 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
9610 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
9611 PotentiallyDeadPHIs.insert(&PN);
9612 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
9613 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9614 }
9615
9616 // If this phi has a single use, and if that use just computes a value for
9617 // the next iteration of a loop, delete the phi. This occurs with unused
9618 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
9619 // common case here is good because the only other things that catch this
9620 // are induction variable analysis (sometimes) and ADCE, which is only run
9621 // late.
9622 if (PHIUser->hasOneUse() &&
9623 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
9624 PHIUser->use_back() == &PN) {
9625 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
9626 }
9627 }
9628
Chris Lattner27b695d2007-11-06 21:52:06 +00009629 // We sometimes end up with phi cycles that non-obviously end up being the
9630 // same value, for example:
9631 // z = some value; x = phi (y, z); y = phi (x, z)
9632 // where the phi nodes don't necessarily need to be in the same block. Do a
9633 // quick check to see if the PHI node only contains a single non-phi value, if
9634 // so, scan to see if the phi cycle is actually equal to that value.
9635 {
9636 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
9637 // Scan for the first non-phi operand.
9638 while (InValNo != NumOperandVals &&
9639 isa<PHINode>(PN.getIncomingValue(InValNo)))
9640 ++InValNo;
9641
9642 if (InValNo != NumOperandVals) {
9643 Value *NonPhiInVal = PN.getOperand(InValNo);
9644
9645 // Scan the rest of the operands to see if there are any conflicts, if so
9646 // there is no need to recursively scan other phis.
9647 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
9648 Value *OpVal = PN.getIncomingValue(InValNo);
9649 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
9650 break;
9651 }
9652
9653 // If we scanned over all operands, then we have one unique value plus
9654 // phi values. Scan PHI nodes to see if they all merge in each other or
9655 // the value.
9656 if (InValNo == NumOperandVals) {
9657 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
9658 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
9659 return ReplaceInstUsesWith(PN, NonPhiInVal);
9660 }
9661 }
9662 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009663 return 0;
9664}
9665
9666static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
9667 Instruction *InsertPoint,
9668 InstCombiner *IC) {
9669 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
9670 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
9671 // We must cast correctly to the pointer type. Ensure that we
9672 // sign extend the integer value if it is smaller as this is
9673 // used for address computation.
9674 Instruction::CastOps opcode =
9675 (VTySize < PtrSize ? Instruction::SExt :
9676 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
9677 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
9678}
9679
9680
9681Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
9682 Value *PtrOp = GEP.getOperand(0);
9683 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
9684 // If so, eliminate the noop.
9685 if (GEP.getNumOperands() == 1)
9686 return ReplaceInstUsesWith(GEP, PtrOp);
9687
9688 if (isa<UndefValue>(GEP.getOperand(0)))
9689 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
9690
9691 bool HasZeroPointerIndex = false;
9692 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
9693 HasZeroPointerIndex = C->isNullValue();
9694
9695 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
9696 return ReplaceInstUsesWith(GEP, PtrOp);
9697
9698 // Eliminate unneeded casts for indices.
9699 bool MadeChange = false;
9700
9701 gep_type_iterator GTI = gep_type_begin(GEP);
9702 for (unsigned i = 1, e = GEP.getNumOperands(); i != e; ++i, ++GTI) {
9703 if (isa<SequentialType>(*GTI)) {
9704 if (CastInst *CI = dyn_cast<CastInst>(GEP.getOperand(i))) {
9705 if (CI->getOpcode() == Instruction::ZExt ||
9706 CI->getOpcode() == Instruction::SExt) {
9707 const Type *SrcTy = CI->getOperand(0)->getType();
9708 // We can eliminate a cast from i32 to i64 iff the target
9709 // is a 32-bit pointer target.
9710 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
9711 MadeChange = true;
9712 GEP.setOperand(i, CI->getOperand(0));
9713 }
9714 }
9715 }
9716 // If we are using a wider index than needed for this platform, shrink it
9717 // to what we need. If the incoming value needs a cast instruction,
9718 // insert it. This explicit cast can make subsequent optimizations more
9719 // obvious.
9720 Value *Op = GEP.getOperand(i);
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009721 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009722 if (Constant *C = dyn_cast<Constant>(Op)) {
9723 GEP.setOperand(i, ConstantExpr::getTrunc(C, TD->getIntPtrType()));
9724 MadeChange = true;
9725 } else {
9726 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
9727 GEP);
9728 GEP.setOperand(i, Op);
9729 MadeChange = true;
9730 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009731 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009732 }
9733 }
9734 if (MadeChange) return &GEP;
9735
9736 // If this GEP instruction doesn't move the pointer, and if the input operand
9737 // is a bitcast of another pointer, just replace the GEP with a bitcast of the
9738 // real input to the dest type.
Chris Lattnerc59171a2007-10-12 05:30:59 +00009739 if (GEP.hasAllZeroIndices()) {
9740 if (BitCastInst *BCI = dyn_cast<BitCastInst>(GEP.getOperand(0))) {
9741 // If the bitcast is of an allocation, and the allocation will be
9742 // converted to match the type of the cast, don't touch this.
9743 if (isa<AllocationInst>(BCI->getOperand(0))) {
9744 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
Chris Lattner551a5872007-10-12 18:05:47 +00009745 if (Instruction *I = visitBitCast(*BCI)) {
9746 if (I != BCI) {
9747 I->takeName(BCI);
9748 BCI->getParent()->getInstList().insert(BCI, I);
9749 ReplaceInstUsesWith(*BCI, I);
9750 }
Chris Lattnerc59171a2007-10-12 05:30:59 +00009751 return &GEP;
Chris Lattner551a5872007-10-12 18:05:47 +00009752 }
Chris Lattnerc59171a2007-10-12 05:30:59 +00009753 }
9754 return new BitCastInst(BCI->getOperand(0), GEP.getType());
9755 }
9756 }
9757
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009758 // Combine Indices - If the source pointer to this getelementptr instruction
9759 // is a getelementptr instruction, combine the indices of the two
9760 // getelementptr instructions into a single instruction.
9761 //
9762 SmallVector<Value*, 8> SrcGEPOperands;
9763 if (User *Src = dyn_castGetElementPtr(PtrOp))
9764 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
9765
9766 if (!SrcGEPOperands.empty()) {
9767 // Note that if our source is a gep chain itself that we wait for that
9768 // chain to be resolved before we perform this transformation. This
9769 // avoids us creating a TON of code in some cases.
9770 //
9771 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
9772 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
9773 return 0; // Wait until our source is folded to completion.
9774
9775 SmallVector<Value*, 8> Indices;
9776
9777 // Find out whether the last index in the source GEP is a sequential idx.
9778 bool EndsWithSequential = false;
9779 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
9780 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
9781 EndsWithSequential = !isa<StructType>(*I);
9782
9783 // Can we combine the two pointer arithmetics offsets?
9784 if (EndsWithSequential) {
9785 // Replace: gep (gep %P, long B), long A, ...
9786 // With: T = long A+B; gep %P, T, ...
9787 //
9788 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
9789 if (SO1 == Constant::getNullValue(SO1->getType())) {
9790 Sum = GO1;
9791 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
9792 Sum = SO1;
9793 } else {
9794 // If they aren't the same type, convert both to an integer of the
9795 // target's pointer size.
9796 if (SO1->getType() != GO1->getType()) {
9797 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
9798 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
9799 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
9800 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
9801 } else {
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009802 unsigned PS = TD->getPointerSizeInBits();
9803 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009804 // Convert GO1 to SO1's type.
9805 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
9806
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009807 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009808 // Convert SO1 to GO1's type.
9809 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
9810 } else {
9811 const Type *PT = TD->getIntPtrType();
9812 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
9813 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
9814 }
9815 }
9816 }
9817 if (isa<Constant>(SO1) && isa<Constant>(GO1))
9818 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
9819 else {
Gabor Greifa645dd32008-05-16 19:29:10 +00009820 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009821 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
9822 }
9823 }
9824
9825 // Recycle the GEP we already have if possible.
9826 if (SrcGEPOperands.size() == 2) {
9827 GEP.setOperand(0, SrcGEPOperands[0]);
9828 GEP.setOperand(1, Sum);
9829 return &GEP;
9830 } else {
9831 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9832 SrcGEPOperands.end()-1);
9833 Indices.push_back(Sum);
9834 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
9835 }
9836 } else if (isa<Constant>(*GEP.idx_begin()) &&
9837 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
9838 SrcGEPOperands.size() != 1) {
9839 // Otherwise we can do the fold if the first index of the GEP is a zero
9840 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
9841 SrcGEPOperands.end());
9842 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
9843 }
9844
9845 if (!Indices.empty())
Gabor Greifd6da1d02008-04-06 20:25:17 +00009846 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
9847 Indices.end(), GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009848
9849 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
9850 // GEP of global variable. If all of the indices for this GEP are
9851 // constants, we can promote this to a constexpr instead of an instruction.
9852
9853 // Scan for nonconstants...
9854 SmallVector<Constant*, 8> Indices;
9855 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
9856 for (; I != E && isa<Constant>(*I); ++I)
9857 Indices.push_back(cast<Constant>(*I));
9858
9859 if (I == E) { // If they are all constants...
9860 Constant *CE = ConstantExpr::getGetElementPtr(GV,
9861 &Indices[0],Indices.size());
9862
9863 // Replace all uses of the GEP with the new constexpr...
9864 return ReplaceInstUsesWith(GEP, CE);
9865 }
9866 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
9867 if (!isa<PointerType>(X->getType())) {
9868 // Not interesting. Source pointer must be a cast from pointer.
9869 } else if (HasZeroPointerIndex) {
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009870 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
9871 // into : GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009872 //
9873 // This occurs when the program declares an array extern like "int X[];"
9874 //
9875 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
9876 const PointerType *XTy = cast<PointerType>(X->getType());
9877 if (const ArrayType *XATy =
9878 dyn_cast<ArrayType>(XTy->getElementType()))
9879 if (const ArrayType *CATy =
9880 dyn_cast<ArrayType>(CPTy->getElementType()))
9881 if (CATy->getElementType() == XATy->getElementType()) {
9882 // At this point, we know that the cast source type is a pointer
9883 // to an array of the same type as the destination pointer
9884 // array. Because the array type is never stepped over (there
9885 // is a leading zero) we can fold the cast into this GEP.
9886 GEP.setOperand(0, X);
9887 return &GEP;
9888 }
9889 } else if (GEP.getNumOperands() == 2) {
9890 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009891 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
9892 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009893 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
9894 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
9895 if (isa<ArrayType>(SrcElTy) &&
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009896 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
9897 TD->getABITypeSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +00009898 Value *Idx[2];
9899 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9900 Idx[1] = GEP.getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009901 Value *V = InsertNewInstBefore(
Gabor Greifd6da1d02008-04-06 20:25:17 +00009902 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009903 // V and GEP are both pointer types --> BitCast
9904 return new BitCastInst(V, GEP.getType());
9905 }
9906
9907 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009908 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009909 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009910 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009911
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009912 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009913 uint64_t ArrayEltSize =
Duncan Sandsf99fdc62007-11-01 20:53:16 +00009914 TD->getABITypeSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009915
9916 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
9917 // allow either a mul, shift, or constant here.
9918 Value *NewIdx = 0;
9919 ConstantInt *Scale = 0;
9920 if (ArrayEltSize == 1) {
9921 NewIdx = GEP.getOperand(1);
9922 Scale = ConstantInt::get(NewIdx->getType(), 1);
9923 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
9924 NewIdx = ConstantInt::get(CI->getType(), 1);
9925 Scale = CI;
9926 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
9927 if (Inst->getOpcode() == Instruction::Shl &&
9928 isa<ConstantInt>(Inst->getOperand(1))) {
9929 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
9930 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
9931 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
9932 NewIdx = Inst->getOperand(0);
9933 } else if (Inst->getOpcode() == Instruction::Mul &&
9934 isa<ConstantInt>(Inst->getOperand(1))) {
9935 Scale = cast<ConstantInt>(Inst->getOperand(1));
9936 NewIdx = Inst->getOperand(0);
9937 }
9938 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009939
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009940 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009941 // out, perform the transformation. Note, we don't know whether Scale is
9942 // signed or not. We'll use unsigned version of division/modulo
9943 // operation after making sure Scale doesn't have the sign bit set.
9944 if (Scale && Scale->getSExtValue() >= 0LL &&
9945 Scale->getZExtValue() % ArrayEltSize == 0) {
9946 Scale = ConstantInt::get(Scale->getType(),
9947 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009948 if (Scale->getZExtValue() != 1) {
9949 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +00009950 false /*ZExt*/);
Gabor Greifa645dd32008-05-16 19:29:10 +00009951 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009952 NewIdx = InsertNewInstBefore(Sc, GEP);
9953 }
9954
9955 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +00009956 Value *Idx[2];
9957 Idx[0] = Constant::getNullValue(Type::Int32Ty);
9958 Idx[1] = NewIdx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009959 Instruction *NewGEP =
Gabor Greifd6da1d02008-04-06 20:25:17 +00009960 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009961 NewGEP = InsertNewInstBefore(NewGEP, GEP);
9962 // The NewGEP must be pointer typed, so must the old one -> BitCast
9963 return new BitCastInst(NewGEP, GEP.getType());
9964 }
9965 }
9966 }
9967 }
9968
9969 return 0;
9970}
9971
9972Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
9973 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009974 if (AI.isArrayAllocation()) { // Check C != 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009975 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
9976 const Type *NewTy =
9977 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
9978 AllocationInst *New = 0;
9979
9980 // Create and insert the replacement instruction...
9981 if (isa<MallocInst>(AI))
9982 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
9983 else {
9984 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
9985 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
9986 }
9987
9988 InsertNewInstBefore(New, AI);
9989
9990 // Scan to the end of the allocation instructions, to skip over a block of
9991 // allocas if possible...
9992 //
9993 BasicBlock::iterator It = New;
9994 while (isa<AllocationInst>(*It)) ++It;
9995
9996 // Now that I is pointing to the first non-allocation-inst in the block,
9997 // insert our getelementptr instruction...
9998 //
9999 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greene393be882007-09-04 15:46:09 +000010000 Value *Idx[2];
10001 Idx[0] = NullIdx;
10002 Idx[1] = NullIdx;
Gabor Greifd6da1d02008-04-06 20:25:17 +000010003 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10004 New->getName()+".sub", It);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010005
10006 // Now make everything use the getelementptr instead of the original
10007 // allocation.
10008 return ReplaceInstUsesWith(AI, V);
10009 } else if (isa<UndefValue>(AI.getArraySize())) {
10010 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10011 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010012 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010013
10014 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10015 // Note that we only do this for alloca's, because malloc should allocate and
10016 // return a unique pointer, even for a zero byte allocation.
10017 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized() &&
Duncan Sandsf99fdc62007-11-01 20:53:16 +000010018 TD->getABITypeSize(AI.getAllocatedType()) == 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010019 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10020
10021 return 0;
10022}
10023
10024Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10025 Value *Op = FI.getOperand(0);
10026
10027 // free undef -> unreachable.
10028 if (isa<UndefValue>(Op)) {
10029 // Insert a new store to null because we cannot modify the CFG here.
10030 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +000010031 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010032 return EraseInstFromFunction(FI);
10033 }
10034
10035 // If we have 'free null' delete the instruction. This can happen in stl code
10036 // when lots of inlining happens.
10037 if (isa<ConstantPointerNull>(Op))
10038 return EraseInstFromFunction(FI);
10039
10040 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10041 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10042 FI.setOperand(0, CI->getOperand(0));
10043 return &FI;
10044 }
10045
10046 // Change free (gep X, 0,0,0,0) into free(X)
10047 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10048 if (GEPI->hasAllZeroIndices()) {
10049 AddToWorkList(GEPI);
10050 FI.setOperand(0, GEPI->getOperand(0));
10051 return &FI;
10052 }
10053 }
10054
10055 // Change free(malloc) into nothing, if the malloc has a single use.
10056 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10057 if (MI->hasOneUse()) {
10058 EraseInstFromFunction(FI);
10059 return EraseInstFromFunction(*MI);
10060 }
10061
10062 return 0;
10063}
10064
10065
10066/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patela0f8ea82007-10-18 19:52:32 +000010067static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling44a36ea2008-02-26 10:53:30 +000010068 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010069 User *CI = cast<User>(LI.getOperand(0));
10070 Value *CastOp = CI->getOperand(0);
10071
Devang Patela0f8ea82007-10-18 19:52:32 +000010072 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10073 // Instead of loading constant c string, use corresponding integer value
10074 // directly if string length is small enough.
10075 const std::string &Str = CE->getOperand(0)->getStringValue();
10076 if (!Str.empty()) {
10077 unsigned len = Str.length();
10078 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10079 unsigned numBits = Ty->getPrimitiveSizeInBits();
10080 // Replace LI with immediate integer store.
10081 if ((numBits >> 3) == len + 1) {
Bill Wendling44a36ea2008-02-26 10:53:30 +000010082 APInt StrVal(numBits, 0);
10083 APInt SingleChar(numBits, 0);
10084 if (TD->isLittleEndian()) {
10085 for (signed i = len-1; i >= 0; i--) {
10086 SingleChar = (uint64_t) Str[i];
10087 StrVal = (StrVal << 8) | SingleChar;
10088 }
10089 } else {
10090 for (unsigned i = 0; i < len; i++) {
10091 SingleChar = (uint64_t) Str[i];
10092 StrVal = (StrVal << 8) | SingleChar;
10093 }
10094 // Append NULL at the end.
10095 SingleChar = 0;
10096 StrVal = (StrVal << 8) | SingleChar;
10097 }
10098 Value *NL = ConstantInt::get(StrVal);
10099 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patela0f8ea82007-10-18 19:52:32 +000010100 }
10101 }
10102 }
10103
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010104 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10105 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10106 const Type *SrcPTy = SrcTy->getElementType();
10107
10108 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
10109 isa<VectorType>(DestPTy)) {
10110 // If the source is an array, the code below will not succeed. Check to
10111 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10112 // constants.
10113 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10114 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10115 if (ASrcTy->getNumElements() != 0) {
10116 Value *Idxs[2];
10117 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10118 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10119 SrcTy = cast<PointerType>(CastOp->getType());
10120 SrcPTy = SrcTy->getElementType();
10121 }
10122
10123 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
10124 isa<VectorType>(SrcPTy)) &&
10125 // Do not allow turning this into a load of an integer, which is then
10126 // casted to a pointer, this pessimizes pointer analysis a lot.
10127 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
10128 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10129 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10130
10131 // Okay, we are casting from one integer or pointer type to another of
10132 // the same size. Instead of casting the pointer before the load, cast
10133 // the result of the loaded value.
10134 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10135 CI->getName(),
10136 LI.isVolatile()),LI);
10137 // Now cast the result of the load.
10138 return new BitCastInst(NewLoad, LI.getType());
10139 }
10140 }
10141 }
10142 return 0;
10143}
10144
10145/// isSafeToLoadUnconditionally - Return true if we know that executing a load
10146/// from this value cannot trap. If it is not obviously safe to load from the
10147/// specified pointer, we do a quick local scan of the basic block containing
10148/// ScanFrom, to determine if the address is already accessed.
10149static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands9b27dbe2007-09-19 10:10:31 +000010150 // If it is an alloca it is always safe to load from.
10151 if (isa<AllocaInst>(V)) return true;
10152
Duncan Sandse40a94a2007-09-19 10:25:38 +000010153 // If it is a global variable it is mostly safe to load from.
Duncan Sands9b27dbe2007-09-19 10:10:31 +000010154 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sandse40a94a2007-09-19 10:25:38 +000010155 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands9b27dbe2007-09-19 10:10:31 +000010156 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010157
10158 // Otherwise, be a little bit agressive by scanning the local block where we
10159 // want to check to see if the pointer is already being loaded or stored
10160 // from/to. If so, the previous load or store would have already trapped,
10161 // so there is no harm doing an extra load (also, CSE will later eliminate
10162 // the load entirely).
10163 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10164
10165 while (BBI != E) {
10166 --BBI;
10167
10168 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10169 if (LI->getOperand(0) == V) return true;
10170 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10171 if (SI->getOperand(1) == V) return true;
10172
10173 }
10174 return false;
10175}
10176
Chris Lattner0270a112007-08-11 18:48:48 +000010177/// GetUnderlyingObject - Trace through a series of getelementptrs and bitcasts
10178/// until we find the underlying object a pointer is referring to or something
10179/// we don't understand. Note that the returned pointer may be offset from the
10180/// input, because we ignore GEP indices.
10181static Value *GetUnderlyingObject(Value *Ptr) {
10182 while (1) {
10183 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
10184 if (CE->getOpcode() == Instruction::BitCast ||
10185 CE->getOpcode() == Instruction::GetElementPtr)
10186 Ptr = CE->getOperand(0);
10187 else
10188 return Ptr;
10189 } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(Ptr)) {
10190 Ptr = BCI->getOperand(0);
10191 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
10192 Ptr = GEP->getOperand(0);
10193 } else {
10194 return Ptr;
10195 }
10196 }
10197}
10198
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010199Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
10200 Value *Op = LI.getOperand(0);
10201
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010202 // Attempt to improve the alignment.
Dan Gohman2d648bb2008-04-10 18:43:06 +000010203 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
10204 if (KnownAlign >
10205 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
10206 LI.getAlignment()))
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010207 LI.setAlignment(KnownAlign);
10208
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010209 // load (cast X) --> cast (load X) iff safe
10210 if (isa<CastInst>(Op))
Devang Patela0f8ea82007-10-18 19:52:32 +000010211 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010212 return Res;
10213
10214 // None of the following transforms are legal for volatile loads.
10215 if (LI.isVolatile()) return 0;
10216
10217 if (&LI.getParent()->front() != &LI) {
10218 BasicBlock::iterator BBI = &LI; --BBI;
10219 // If the instruction immediately before this is a store to the same
10220 // address, do a simple form of store->load forwarding.
10221 if (StoreInst *SI = dyn_cast<StoreInst>(BBI))
10222 if (SI->getOperand(1) == LI.getOperand(0))
10223 return ReplaceInstUsesWith(LI, SI->getOperand(0));
10224 if (LoadInst *LIB = dyn_cast<LoadInst>(BBI))
10225 if (LIB->getOperand(0) == LI.getOperand(0))
10226 return ReplaceInstUsesWith(LI, LIB);
10227 }
10228
Christopher Lamb2c175392007-12-29 07:56:53 +000010229 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10230 const Value *GEPI0 = GEPI->getOperand(0);
10231 // TODO: Consider a target hook for valid address spaces for this xform.
10232 if (isa<ConstantPointerNull>(GEPI0) &&
10233 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010234 // Insert a new store to null instruction before the load to indicate
10235 // that this code is not reachable. We do this instead of inserting
10236 // an unreachable instruction directly because we cannot modify the
10237 // CFG.
10238 new StoreInst(UndefValue::get(LI.getType()),
10239 Constant::getNullValue(Op->getType()), &LI);
10240 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10241 }
Christopher Lamb2c175392007-12-29 07:56:53 +000010242 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010243
10244 if (Constant *C = dyn_cast<Constant>(Op)) {
10245 // load null/undef -> undef
Christopher Lamb2c175392007-12-29 07:56:53 +000010246 // TODO: Consider a target hook for valid address spaces for this xform.
10247 if (isa<UndefValue>(C) || (C->isNullValue() &&
10248 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010249 // Insert a new store to null instruction before the load to indicate that
10250 // this code is not reachable. We do this instead of inserting an
10251 // unreachable instruction directly because we cannot modify the CFG.
10252 new StoreInst(UndefValue::get(LI.getType()),
10253 Constant::getNullValue(Op->getType()), &LI);
10254 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10255 }
10256
10257 // Instcombine load (constant global) into the value loaded.
10258 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
10259 if (GV->isConstant() && !GV->isDeclaration())
10260 return ReplaceInstUsesWith(LI, GV->getInitializer());
10261
10262 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010263 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010264 if (CE->getOpcode() == Instruction::GetElementPtr) {
10265 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
10266 if (GV->isConstant() && !GV->isDeclaration())
10267 if (Constant *V =
10268 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
10269 return ReplaceInstUsesWith(LI, V);
10270 if (CE->getOperand(0)->isNullValue()) {
10271 // Insert a new store to null instruction before the load to indicate
10272 // that this code is not reachable. We do this instead of inserting
10273 // an unreachable instruction directly because we cannot modify the
10274 // CFG.
10275 new StoreInst(UndefValue::get(LI.getType()),
10276 Constant::getNullValue(Op->getType()), &LI);
10277 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10278 }
10279
10280 } else if (CE->isCast()) {
Devang Patela0f8ea82007-10-18 19:52:32 +000010281 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010282 return Res;
10283 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010284 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010285 }
Chris Lattner0270a112007-08-11 18:48:48 +000010286
10287 // If this load comes from anywhere in a constant global, and if the global
10288 // is all undef or zero, we know what it loads.
10289 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GetUnderlyingObject(Op))) {
10290 if (GV->isConstant() && GV->hasInitializer()) {
10291 if (GV->getInitializer()->isNullValue())
10292 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
10293 else if (isa<UndefValue>(GV->getInitializer()))
10294 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
10295 }
10296 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010297
10298 if (Op->hasOneUse()) {
10299 // Change select and PHI nodes to select values instead of addresses: this
10300 // helps alias analysis out a lot, allows many others simplifications, and
10301 // exposes redundancy in the code.
10302 //
10303 // Note that we cannot do the transformation unless we know that the
10304 // introduced loads cannot trap! Something like this is valid as long as
10305 // the condition is always false: load (select bool %C, int* null, int* %G),
10306 // but it would not be valid if we transformed it to load from null
10307 // unconditionally.
10308 //
10309 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
10310 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
10311 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
10312 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
10313 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
10314 SI->getOperand(1)->getName()+".val"), LI);
10315 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
10316 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greifd6da1d02008-04-06 20:25:17 +000010317 return SelectInst::Create(SI->getCondition(), V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010318 }
10319
10320 // load (select (cond, null, P)) -> load P
10321 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
10322 if (C->isNullValue()) {
10323 LI.setOperand(0, SI->getOperand(2));
10324 return &LI;
10325 }
10326
10327 // load (select (cond, P, null)) -> load P
10328 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
10329 if (C->isNullValue()) {
10330 LI.setOperand(0, SI->getOperand(1));
10331 return &LI;
10332 }
10333 }
10334 }
10335 return 0;
10336}
10337
10338/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
10339/// when possible.
10340static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
10341 User *CI = cast<User>(SI.getOperand(1));
10342 Value *CastOp = CI->getOperand(0);
10343
10344 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10345 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10346 const Type *SrcPTy = SrcTy->getElementType();
10347
10348 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
10349 // If the source is an array, the code below will not succeed. Check to
10350 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10351 // constants.
10352 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10353 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10354 if (ASrcTy->getNumElements() != 0) {
10355 Value* Idxs[2];
10356 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10357 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10358 SrcTy = cast<PointerType>(CastOp->getType());
10359 SrcPTy = SrcTy->getElementType();
10360 }
10361
10362 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
10363 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10364 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10365
10366 // Okay, we are casting from one integer or pointer type to another of
10367 // the same size. Instead of casting the pointer before
10368 // the store, cast the value to be stored.
10369 Value *NewCast;
10370 Value *SIOp0 = SI.getOperand(0);
10371 Instruction::CastOps opcode = Instruction::BitCast;
10372 const Type* CastSrcTy = SIOp0->getType();
10373 const Type* CastDstTy = SrcPTy;
10374 if (isa<PointerType>(CastDstTy)) {
10375 if (CastSrcTy->isInteger())
10376 opcode = Instruction::IntToPtr;
10377 } else if (isa<IntegerType>(CastDstTy)) {
10378 if (isa<PointerType>(SIOp0->getType()))
10379 opcode = Instruction::PtrToInt;
10380 }
10381 if (Constant *C = dyn_cast<Constant>(SIOp0))
10382 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
10383 else
10384 NewCast = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +000010385 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010386 SI);
10387 return new StoreInst(NewCast, CastOp);
10388 }
10389 }
10390 }
10391 return 0;
10392}
10393
10394Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
10395 Value *Val = SI.getOperand(0);
10396 Value *Ptr = SI.getOperand(1);
10397
10398 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
10399 EraseInstFromFunction(SI);
10400 ++NumCombined;
10401 return 0;
10402 }
10403
10404 // If the RHS is an alloca with a single use, zapify the store, making the
10405 // alloca dead.
Chris Lattnera02bacc2008-04-29 04:58:38 +000010406 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010407 if (isa<AllocaInst>(Ptr)) {
10408 EraseInstFromFunction(SI);
10409 ++NumCombined;
10410 return 0;
10411 }
10412
10413 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
10414 if (isa<AllocaInst>(GEP->getOperand(0)) &&
10415 GEP->getOperand(0)->hasOneUse()) {
10416 EraseInstFromFunction(SI);
10417 ++NumCombined;
10418 return 0;
10419 }
10420 }
10421
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010422 // Attempt to improve the alignment.
Dan Gohman2d648bb2008-04-10 18:43:06 +000010423 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
10424 if (KnownAlign >
10425 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
10426 SI.getAlignment()))
Dan Gohman5c4d0e12007-07-20 16:34:21 +000010427 SI.setAlignment(KnownAlign);
10428
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010429 // Do really simple DSE, to catch cases where there are several consequtive
10430 // stores to the same location, separated by a few arithmetic operations. This
10431 // situation often occurs with bitfield accesses.
10432 BasicBlock::iterator BBI = &SI;
10433 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
10434 --ScanInsts) {
10435 --BBI;
10436
10437 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
10438 // Prev store isn't volatile, and stores to the same location?
10439 if (!PrevSI->isVolatile() && PrevSI->getOperand(1) == SI.getOperand(1)) {
10440 ++NumDeadStore;
10441 ++BBI;
10442 EraseInstFromFunction(*PrevSI);
10443 continue;
10444 }
10445 break;
10446 }
10447
10448 // If this is a load, we have to stop. However, if the loaded value is from
10449 // the pointer we're loading and is producing the pointer we're storing,
10450 // then *this* store is dead (X = load P; store X -> P).
10451 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Chris Lattner24905f72007-09-07 05:33:03 +000010452 if (LI == Val && LI->getOperand(0) == Ptr && !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010453 EraseInstFromFunction(SI);
10454 ++NumCombined;
10455 return 0;
10456 }
10457 // Otherwise, this is a load from some other location. Stores before it
10458 // may not be dead.
10459 break;
10460 }
10461
10462 // Don't skip over loads or things that can modify memory.
Chris Lattner84504282008-05-08 17:20:30 +000010463 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010464 break;
10465 }
10466
10467
10468 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
10469
10470 // store X, null -> turns into 'unreachable' in SimplifyCFG
10471 if (isa<ConstantPointerNull>(Ptr)) {
10472 if (!isa<UndefValue>(Val)) {
10473 SI.setOperand(0, UndefValue::get(Val->getType()));
10474 if (Instruction *U = dyn_cast<Instruction>(Val))
10475 AddToWorkList(U); // Dropped a use.
10476 ++NumCombined;
10477 }
10478 return 0; // Do not modify these!
10479 }
10480
10481 // store undef, Ptr -> noop
10482 if (isa<UndefValue>(Val)) {
10483 EraseInstFromFunction(SI);
10484 ++NumCombined;
10485 return 0;
10486 }
10487
10488 // If the pointer destination is a cast, see if we can fold the cast into the
10489 // source instead.
10490 if (isa<CastInst>(Ptr))
10491 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10492 return Res;
10493 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
10494 if (CE->isCast())
10495 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
10496 return Res;
10497
10498
10499 // If this store is the last instruction in the basic block, and if the block
10500 // ends with an unconditional branch, try to move it to the successor block.
10501 BBI = &SI; ++BBI;
10502 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
10503 if (BI->isUnconditional())
10504 if (SimplifyStoreAtEndOfBlock(SI))
10505 return 0; // xform done!
10506
10507 return 0;
10508}
10509
10510/// SimplifyStoreAtEndOfBlock - Turn things like:
10511/// if () { *P = v1; } else { *P = v2 }
10512/// into a phi node with a store in the successor.
10513///
10514/// Simplify things like:
10515/// *P = v1; if () { *P = v2; }
10516/// into a phi node with a store in the successor.
10517///
10518bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
10519 BasicBlock *StoreBB = SI.getParent();
10520
10521 // Check to see if the successor block has exactly two incoming edges. If
10522 // so, see if the other predecessor contains a store to the same location.
10523 // if so, insert a PHI node (if needed) and move the stores down.
10524 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
10525
10526 // Determine whether Dest has exactly two predecessors and, if so, compute
10527 // the other predecessor.
10528 pred_iterator PI = pred_begin(DestBB);
10529 BasicBlock *OtherBB = 0;
10530 if (*PI != StoreBB)
10531 OtherBB = *PI;
10532 ++PI;
10533 if (PI == pred_end(DestBB))
10534 return false;
10535
10536 if (*PI != StoreBB) {
10537 if (OtherBB)
10538 return false;
10539 OtherBB = *PI;
10540 }
10541 if (++PI != pred_end(DestBB))
10542 return false;
10543
10544
10545 // Verify that the other block ends in a branch and is not otherwise empty.
10546 BasicBlock::iterator BBI = OtherBB->getTerminator();
10547 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
10548 if (!OtherBr || BBI == OtherBB->begin())
10549 return false;
10550
10551 // If the other block ends in an unconditional branch, check for the 'if then
10552 // else' case. there is an instruction before the branch.
10553 StoreInst *OtherStore = 0;
10554 if (OtherBr->isUnconditional()) {
10555 // If this isn't a store, or isn't a store to the same location, bail out.
10556 --BBI;
10557 OtherStore = dyn_cast<StoreInst>(BBI);
10558 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
10559 return false;
10560 } else {
10561 // Otherwise, the other block ended with a conditional branch. If one of the
10562 // destinations is StoreBB, then we have the if/then case.
10563 if (OtherBr->getSuccessor(0) != StoreBB &&
10564 OtherBr->getSuccessor(1) != StoreBB)
10565 return false;
10566
10567 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
10568 // if/then triangle. See if there is a store to the same ptr as SI that
10569 // lives in OtherBB.
10570 for (;; --BBI) {
10571 // Check to see if we find the matching store.
10572 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
10573 if (OtherStore->getOperand(1) != SI.getOperand(1))
10574 return false;
10575 break;
10576 }
10577 // If we find something that may be using the stored value, or if we run
10578 // out of instructions, we can't do the xform.
10579 if (isa<LoadInst>(BBI) || BBI->mayWriteToMemory() ||
10580 BBI == OtherBB->begin())
10581 return false;
10582 }
10583
10584 // In order to eliminate the store in OtherBr, we have to
10585 // make sure nothing reads the stored value in StoreBB.
10586 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
10587 // FIXME: This should really be AA driven.
10588 if (isa<LoadInst>(I) || I->mayWriteToMemory())
10589 return false;
10590 }
10591 }
10592
10593 // Insert a PHI node now if we need it.
10594 Value *MergedVal = OtherStore->getOperand(0);
10595 if (MergedVal != SI.getOperand(0)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010596 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010597 PN->reserveOperandSpace(2);
10598 PN->addIncoming(SI.getOperand(0), SI.getParent());
10599 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
10600 MergedVal = InsertNewInstBefore(PN, DestBB->front());
10601 }
10602
10603 // Advance to a place where it is safe to insert the new store and
10604 // insert it.
10605 BBI = DestBB->begin();
10606 while (isa<PHINode>(BBI)) ++BBI;
10607 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
10608 OtherStore->isVolatile()), *BBI);
10609
10610 // Nuke the old stores.
10611 EraseInstFromFunction(SI);
10612 EraseInstFromFunction(*OtherStore);
10613 ++NumCombined;
10614 return true;
10615}
10616
10617
10618Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
10619 // Change br (not X), label True, label False to: br X, label False, True
10620 Value *X = 0;
10621 BasicBlock *TrueDest;
10622 BasicBlock *FalseDest;
10623 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
10624 !isa<Constant>(X)) {
10625 // Swap Destinations and condition...
10626 BI.setCondition(X);
10627 BI.setSuccessor(0, FalseDest);
10628 BI.setSuccessor(1, TrueDest);
10629 return &BI;
10630 }
10631
10632 // Cannonicalize fcmp_one -> fcmp_oeq
10633 FCmpInst::Predicate FPred; Value *Y;
10634 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
10635 TrueDest, FalseDest)))
10636 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
10637 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
10638 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
10639 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
10640 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
10641 NewSCC->takeName(I);
10642 // Swap Destinations and condition...
10643 BI.setCondition(NewSCC);
10644 BI.setSuccessor(0, FalseDest);
10645 BI.setSuccessor(1, TrueDest);
10646 RemoveFromWorkList(I);
10647 I->eraseFromParent();
10648 AddToWorkList(NewSCC);
10649 return &BI;
10650 }
10651
10652 // Cannonicalize icmp_ne -> icmp_eq
10653 ICmpInst::Predicate IPred;
10654 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
10655 TrueDest, FalseDest)))
10656 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
10657 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
10658 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
10659 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
10660 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
10661 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
10662 NewSCC->takeName(I);
10663 // Swap Destinations and condition...
10664 BI.setCondition(NewSCC);
10665 BI.setSuccessor(0, FalseDest);
10666 BI.setSuccessor(1, TrueDest);
10667 RemoveFromWorkList(I);
10668 I->eraseFromParent();;
10669 AddToWorkList(NewSCC);
10670 return &BI;
10671 }
10672
10673 return 0;
10674}
10675
10676Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
10677 Value *Cond = SI.getCondition();
10678 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
10679 if (I->getOpcode() == Instruction::Add)
10680 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
10681 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
10682 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
10683 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
10684 AddRHS));
10685 SI.setOperand(0, I->getOperand(0));
10686 AddToWorkList(I);
10687 return &SI;
10688 }
10689 }
10690 return 0;
10691}
10692
10693/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
10694/// is to leave as a vector operation.
10695static bool CheapToScalarize(Value *V, bool isConstant) {
10696 if (isa<ConstantAggregateZero>(V))
10697 return true;
10698 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
10699 if (isConstant) return true;
10700 // If all elts are the same, we can extract.
10701 Constant *Op0 = C->getOperand(0);
10702 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10703 if (C->getOperand(i) != Op0)
10704 return false;
10705 return true;
10706 }
10707 Instruction *I = dyn_cast<Instruction>(V);
10708 if (!I) return false;
10709
10710 // Insert element gets simplified to the inserted element or is deleted if
10711 // this is constant idx extract element and its a constant idx insertelt.
10712 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
10713 isa<ConstantInt>(I->getOperand(2)))
10714 return true;
10715 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
10716 return true;
10717 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
10718 if (BO->hasOneUse() &&
10719 (CheapToScalarize(BO->getOperand(0), isConstant) ||
10720 CheapToScalarize(BO->getOperand(1), isConstant)))
10721 return true;
10722 if (CmpInst *CI = dyn_cast<CmpInst>(I))
10723 if (CI->hasOneUse() &&
10724 (CheapToScalarize(CI->getOperand(0), isConstant) ||
10725 CheapToScalarize(CI->getOperand(1), isConstant)))
10726 return true;
10727
10728 return false;
10729}
10730
10731/// Read and decode a shufflevector mask.
10732///
10733/// It turns undef elements into values that are larger than the number of
10734/// elements in the input.
10735static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
10736 unsigned NElts = SVI->getType()->getNumElements();
10737 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
10738 return std::vector<unsigned>(NElts, 0);
10739 if (isa<UndefValue>(SVI->getOperand(2)))
10740 return std::vector<unsigned>(NElts, 2*NElts);
10741
10742 std::vector<unsigned> Result;
10743 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
10744 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
10745 if (isa<UndefValue>(CP->getOperand(i)))
10746 Result.push_back(NElts*2); // undef -> 8
10747 else
10748 Result.push_back(cast<ConstantInt>(CP->getOperand(i))->getZExtValue());
10749 return Result;
10750}
10751
10752/// FindScalarElement - Given a vector and an element number, see if the scalar
10753/// value is already around as a register, for example if it were inserted then
10754/// extracted from the vector.
10755static Value *FindScalarElement(Value *V, unsigned EltNo) {
10756 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
10757 const VectorType *PTy = cast<VectorType>(V->getType());
10758 unsigned Width = PTy->getNumElements();
10759 if (EltNo >= Width) // Out of range access.
10760 return UndefValue::get(PTy->getElementType());
10761
10762 if (isa<UndefValue>(V))
10763 return UndefValue::get(PTy->getElementType());
10764 else if (isa<ConstantAggregateZero>(V))
10765 return Constant::getNullValue(PTy->getElementType());
10766 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
10767 return CP->getOperand(EltNo);
10768 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
10769 // If this is an insert to a variable element, we don't know what it is.
10770 if (!isa<ConstantInt>(III->getOperand(2)))
10771 return 0;
10772 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
10773
10774 // If this is an insert to the element we are looking for, return the
10775 // inserted value.
10776 if (EltNo == IIElt)
10777 return III->getOperand(1);
10778
10779 // Otherwise, the insertelement doesn't modify the value, recurse on its
10780 // vector input.
10781 return FindScalarElement(III->getOperand(0), EltNo);
10782 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
10783 unsigned InEl = getShuffleMask(SVI)[EltNo];
10784 if (InEl < Width)
10785 return FindScalarElement(SVI->getOperand(0), InEl);
10786 else if (InEl < Width*2)
10787 return FindScalarElement(SVI->getOperand(1), InEl - Width);
10788 else
10789 return UndefValue::get(PTy->getElementType());
10790 }
10791
10792 // Otherwise, we don't know.
10793 return 0;
10794}
10795
10796Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
10797
10798 // If vector val is undef, replace extract with scalar undef.
10799 if (isa<UndefValue>(EI.getOperand(0)))
10800 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10801
10802 // If vector val is constant 0, replace extract with scalar 0.
10803 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
10804 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
10805
10806 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
10807 // If vector val is constant with uniform operands, replace EI
10808 // with that operand
10809 Constant *op0 = C->getOperand(0);
10810 for (unsigned i = 1; i < C->getNumOperands(); ++i)
10811 if (C->getOperand(i) != op0) {
10812 op0 = 0;
10813 break;
10814 }
10815 if (op0)
10816 return ReplaceInstUsesWith(EI, op0);
10817 }
10818
10819 // If extracting a specified index from the vector, see if we can recursively
10820 // find a previously computed scalar that was inserted into the vector.
10821 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10822 unsigned IndexVal = IdxC->getZExtValue();
10823 unsigned VectorWidth =
10824 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
10825
10826 // If this is extracting an invalid index, turn this into undef, to avoid
10827 // crashing the code below.
10828 if (IndexVal >= VectorWidth)
10829 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10830
10831 // This instruction only demands the single element from the input vector.
10832 // If the input vector has a single use, simplify it based on this use
10833 // property.
10834 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
10835 uint64_t UndefElts;
10836 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
10837 1 << IndexVal,
10838 UndefElts)) {
10839 EI.setOperand(0, V);
10840 return &EI;
10841 }
10842 }
10843
10844 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
10845 return ReplaceInstUsesWith(EI, Elt);
10846
10847 // If the this extractelement is directly using a bitcast from a vector of
10848 // the same number of elements, see if we can find the source element from
10849 // it. In this case, we will end up needing to bitcast the scalars.
10850 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
10851 if (const VectorType *VT =
10852 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
10853 if (VT->getNumElements() == VectorWidth)
10854 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
10855 return new BitCastInst(Elt, EI.getType());
10856 }
10857 }
10858
10859 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
10860 if (I->hasOneUse()) {
10861 // Push extractelement into predecessor operation if legal and
10862 // profitable to do so
10863 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
10864 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
10865 if (CheapToScalarize(BO, isConstantElt)) {
10866 ExtractElementInst *newEI0 =
10867 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
10868 EI.getName()+".lhs");
10869 ExtractElementInst *newEI1 =
10870 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
10871 EI.getName()+".rhs");
10872 InsertNewInstBefore(newEI0, EI);
10873 InsertNewInstBefore(newEI1, EI);
Gabor Greifa645dd32008-05-16 19:29:10 +000010874 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010875 }
10876 } else if (isa<LoadInst>(I)) {
Christopher Lambbb2f2222007-12-17 01:12:55 +000010877 unsigned AS =
10878 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +000010879 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
10880 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010881 GetElementPtrInst *GEP =
10882 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010883 InsertNewInstBefore(GEP, EI);
10884 return new LoadInst(GEP);
10885 }
10886 }
10887 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
10888 // Extracting the inserted element?
10889 if (IE->getOperand(2) == EI.getOperand(1))
10890 return ReplaceInstUsesWith(EI, IE->getOperand(1));
10891 // If the inserted and extracted elements are constants, they must not
10892 // be the same value, extract from the pre-inserted value instead.
10893 if (isa<Constant>(IE->getOperand(2)) &&
10894 isa<Constant>(EI.getOperand(1))) {
10895 AddUsesToWorkList(EI);
10896 EI.setOperand(0, IE->getOperand(0));
10897 return &EI;
10898 }
10899 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
10900 // If this is extracting an element from a shufflevector, figure out where
10901 // it came from and extract from the appropriate input element instead.
10902 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
10903 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
10904 Value *Src;
10905 if (SrcIdx < SVI->getType()->getNumElements())
10906 Src = SVI->getOperand(0);
10907 else if (SrcIdx < SVI->getType()->getNumElements()*2) {
10908 SrcIdx -= SVI->getType()->getNumElements();
10909 Src = SVI->getOperand(1);
10910 } else {
10911 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
10912 }
10913 return new ExtractElementInst(Src, SrcIdx);
10914 }
10915 }
10916 }
10917 return 0;
10918}
10919
10920/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
10921/// elements from either LHS or RHS, return the shuffle mask and true.
10922/// Otherwise, return false.
10923static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
10924 std::vector<Constant*> &Mask) {
10925 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
10926 "Invalid CollectSingleShuffleElements");
10927 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10928
10929 if (isa<UndefValue>(V)) {
10930 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
10931 return true;
10932 } else if (V == LHS) {
10933 for (unsigned i = 0; i != NumElts; ++i)
10934 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
10935 return true;
10936 } else if (V == RHS) {
10937 for (unsigned i = 0; i != NumElts; ++i)
10938 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
10939 return true;
10940 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
10941 // If this is an insert of an extract from some other vector, include it.
10942 Value *VecOp = IEI->getOperand(0);
10943 Value *ScalarOp = IEI->getOperand(1);
10944 Value *IdxOp = IEI->getOperand(2);
10945
10946 if (!isa<ConstantInt>(IdxOp))
10947 return false;
10948 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
10949
10950 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
10951 // Okay, we can handle this if the vector we are insertinting into is
10952 // transitively ok.
10953 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10954 // If so, update the mask to reflect the inserted undef.
10955 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
10956 return true;
10957 }
10958 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
10959 if (isa<ConstantInt>(EI->getOperand(1)) &&
10960 EI->getOperand(0)->getType() == V->getType()) {
10961 unsigned ExtractedIdx =
10962 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
10963
10964 // This must be extracting from either LHS or RHS.
10965 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
10966 // Okay, we can handle this if the vector we are insertinting into is
10967 // transitively ok.
10968 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
10969 // If so, update the mask to reflect the inserted value.
10970 if (EI->getOperand(0) == LHS) {
10971 Mask[InsertedIdx & (NumElts-1)] =
10972 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
10973 } else {
10974 assert(EI->getOperand(0) == RHS);
10975 Mask[InsertedIdx & (NumElts-1)] =
10976 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
10977
10978 }
10979 return true;
10980 }
10981 }
10982 }
10983 }
10984 }
10985 // TODO: Handle shufflevector here!
10986
10987 return false;
10988}
10989
10990/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
10991/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
10992/// that computes V and the LHS value of the shuffle.
10993static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
10994 Value *&RHS) {
10995 assert(isa<VectorType>(V->getType()) &&
10996 (RHS == 0 || V->getType() == RHS->getType()) &&
10997 "Invalid shuffle!");
10998 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
10999
11000 if (isa<UndefValue>(V)) {
11001 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11002 return V;
11003 } else if (isa<ConstantAggregateZero>(V)) {
11004 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
11005 return V;
11006 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11007 // If this is an insert of an extract from some other vector, include it.
11008 Value *VecOp = IEI->getOperand(0);
11009 Value *ScalarOp = IEI->getOperand(1);
11010 Value *IdxOp = IEI->getOperand(2);
11011
11012 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11013 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11014 EI->getOperand(0)->getType() == V->getType()) {
11015 unsigned ExtractedIdx =
11016 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11017 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11018
11019 // Either the extracted from or inserted into vector must be RHSVec,
11020 // otherwise we'd end up with a shuffle of three inputs.
11021 if (EI->getOperand(0) == RHS || RHS == 0) {
11022 RHS = EI->getOperand(0);
11023 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
11024 Mask[InsertedIdx & (NumElts-1)] =
11025 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
11026 return V;
11027 }
11028
11029 if (VecOp == RHS) {
11030 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
11031 // Everything but the extracted element is replaced with the RHS.
11032 for (unsigned i = 0; i != NumElts; ++i) {
11033 if (i != InsertedIdx)
11034 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
11035 }
11036 return V;
11037 }
11038
11039 // If this insertelement is a chain that comes from exactly these two
11040 // vectors, return the vector and the effective shuffle.
11041 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11042 return EI->getOperand(0);
11043
11044 }
11045 }
11046 }
11047 // TODO: Handle shufflevector here!
11048
11049 // Otherwise, can't do anything fancy. Return an identity vector.
11050 for (unsigned i = 0; i != NumElts; ++i)
11051 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11052 return V;
11053}
11054
11055Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11056 Value *VecOp = IE.getOperand(0);
11057 Value *ScalarOp = IE.getOperand(1);
11058 Value *IdxOp = IE.getOperand(2);
11059
11060 // Inserting an undef or into an undefined place, remove this.
11061 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11062 ReplaceInstUsesWith(IE, VecOp);
11063
11064 // If the inserted element was extracted from some other vector, and if the
11065 // indexes are constant, try to turn this into a shufflevector operation.
11066 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11067 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11068 EI->getOperand(0)->getType() == IE.getType()) {
11069 unsigned NumVectorElts = IE.getType()->getNumElements();
11070 unsigned ExtractedIdx =
11071 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11072 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11073
11074 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11075 return ReplaceInstUsesWith(IE, VecOp);
11076
11077 if (InsertedIdx >= NumVectorElts) // Out of range insert.
11078 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
11079
11080 // If we are extracting a value from a vector, then inserting it right
11081 // back into the same place, just use the input vector.
11082 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
11083 return ReplaceInstUsesWith(IE, VecOp);
11084
11085 // We could theoretically do this for ANY input. However, doing so could
11086 // turn chains of insertelement instructions into a chain of shufflevector
11087 // instructions, and right now we do not merge shufflevectors. As such,
11088 // only do this in a situation where it is clear that there is benefit.
11089 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
11090 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
11091 // the values of VecOp, except then one read from EIOp0.
11092 // Build a new shuffle mask.
11093 std::vector<Constant*> Mask;
11094 if (isa<UndefValue>(VecOp))
11095 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
11096 else {
11097 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
11098 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
11099 NumVectorElts));
11100 }
11101 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11102 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
11103 ConstantVector::get(Mask));
11104 }
11105
11106 // If this insertelement isn't used by some other insertelement, turn it
11107 // (and any insertelements it points to), into one big shuffle.
11108 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
11109 std::vector<Constant*> Mask;
11110 Value *RHS = 0;
11111 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
11112 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
11113 // We now have a shuffle of LHS, RHS, Mask.
11114 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
11115 }
11116 }
11117 }
11118
11119 return 0;
11120}
11121
11122
11123Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
11124 Value *LHS = SVI.getOperand(0);
11125 Value *RHS = SVI.getOperand(1);
11126 std::vector<unsigned> Mask = getShuffleMask(&SVI);
11127
11128 bool MadeChange = false;
11129
11130 // Undefined shuffle mask -> undefined value.
11131 if (isa<UndefValue>(SVI.getOperand(2)))
11132 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
11133
11134 // If we have shuffle(x, undef, mask) and any elements of mask refer to
11135 // the undef, change them to undefs.
11136 if (isa<UndefValue>(SVI.getOperand(1))) {
11137 // Scan to see if there are any references to the RHS. If so, replace them
11138 // with undef element refs and set MadeChange to true.
11139 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11140 if (Mask[i] >= e && Mask[i] != 2*e) {
11141 Mask[i] = 2*e;
11142 MadeChange = true;
11143 }
11144 }
11145
11146 if (MadeChange) {
11147 // Remap any references to RHS to use LHS.
11148 std::vector<Constant*> Elts;
11149 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11150 if (Mask[i] == 2*e)
11151 Elts.push_back(UndefValue::get(Type::Int32Ty));
11152 else
11153 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11154 }
11155 SVI.setOperand(2, ConstantVector::get(Elts));
11156 }
11157 }
11158
11159 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
11160 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
11161 if (LHS == RHS || isa<UndefValue>(LHS)) {
11162 if (isa<UndefValue>(LHS) && LHS == RHS) {
11163 // shuffle(undef,undef,mask) -> undef.
11164 return ReplaceInstUsesWith(SVI, LHS);
11165 }
11166
11167 // Remap any references to RHS to use LHS.
11168 std::vector<Constant*> Elts;
11169 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11170 if (Mask[i] >= 2*e)
11171 Elts.push_back(UndefValue::get(Type::Int32Ty));
11172 else {
11173 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
11174 (Mask[i] < e && isa<UndefValue>(LHS)))
11175 Mask[i] = 2*e; // Turn into undef.
11176 else
11177 Mask[i] &= (e-1); // Force to LHS.
11178 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
11179 }
11180 }
11181 SVI.setOperand(0, SVI.getOperand(1));
11182 SVI.setOperand(1, UndefValue::get(RHS->getType()));
11183 SVI.setOperand(2, ConstantVector::get(Elts));
11184 LHS = SVI.getOperand(0);
11185 RHS = SVI.getOperand(1);
11186 MadeChange = true;
11187 }
11188
11189 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
11190 bool isLHSID = true, isRHSID = true;
11191
11192 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
11193 if (Mask[i] >= e*2) continue; // Ignore undef values.
11194 // Is this an identity shuffle of the LHS value?
11195 isLHSID &= (Mask[i] == i);
11196
11197 // Is this an identity shuffle of the RHS value?
11198 isRHSID &= (Mask[i]-e == i);
11199 }
11200
11201 // Eliminate identity shuffles.
11202 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
11203 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
11204
11205 // If the LHS is a shufflevector itself, see if we can combine it with this
11206 // one without producing an unusual shuffle. Here we are really conservative:
11207 // we are absolutely afraid of producing a shuffle mask not in the input
11208 // program, because the code gen may not be smart enough to turn a merged
11209 // shuffle into two specific shuffles: it may produce worse code. As such,
11210 // we only merge two shuffles if the result is one of the two input shuffle
11211 // masks. In this case, merging the shuffles just removes one instruction,
11212 // which we know is safe. This is good for things like turning:
11213 // (splat(splat)) -> splat.
11214 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
11215 if (isa<UndefValue>(RHS)) {
11216 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
11217
11218 std::vector<unsigned> NewMask;
11219 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
11220 if (Mask[i] >= 2*e)
11221 NewMask.push_back(2*e);
11222 else
11223 NewMask.push_back(LHSMask[Mask[i]]);
11224
11225 // If the result mask is equal to the src shuffle or this shuffle mask, do
11226 // the replacement.
11227 if (NewMask == LHSMask || NewMask == Mask) {
11228 std::vector<Constant*> Elts;
11229 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
11230 if (NewMask[i] >= e*2) {
11231 Elts.push_back(UndefValue::get(Type::Int32Ty));
11232 } else {
11233 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
11234 }
11235 }
11236 return new ShuffleVectorInst(LHSSVI->getOperand(0),
11237 LHSSVI->getOperand(1),
11238 ConstantVector::get(Elts));
11239 }
11240 }
11241 }
11242
11243 return MadeChange ? &SVI : 0;
11244}
11245
11246
11247
11248
11249/// TryToSinkInstruction - Try to move the specified instruction from its
11250/// current block into the beginning of DestBlock, which can only happen if it's
11251/// safe to move the instruction past all of the instructions between it and the
11252/// end of its block.
11253static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
11254 assert(I->hasOneUse() && "Invariants didn't hold!");
11255
11256 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnercb19a1c2008-05-09 15:07:33 +000011257 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
11258 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011259
11260 // Do not sink alloca instructions out of the entry block.
11261 if (isa<AllocaInst>(I) && I->getParent() ==
11262 &DestBlock->getParent()->getEntryBlock())
11263 return false;
11264
11265 // We can only sink load instructions if there is nothing between the load and
11266 // the end of block that could change the value.
Chris Lattner0db40a62008-05-08 17:37:37 +000011267 if (I->mayReadFromMemory()) {
11268 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011269 Scan != E; ++Scan)
11270 if (Scan->mayWriteToMemory())
11271 return false;
11272 }
11273
11274 BasicBlock::iterator InsertPos = DestBlock->begin();
11275 while (isa<PHINode>(InsertPos)) ++InsertPos;
11276
11277 I->moveBefore(InsertPos);
11278 ++NumSunkInst;
11279 return true;
11280}
11281
11282
11283/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
11284/// all reachable code to the worklist.
11285///
11286/// This has a couple of tricks to make the code faster and more powerful. In
11287/// particular, we constant fold and DCE instructions as we go, to avoid adding
11288/// them to the worklist (this significantly speeds up instcombine on code where
11289/// many instructions are dead or constant). Additionally, if we find a branch
11290/// whose condition is a known constant, we only visit the reachable successors.
11291///
11292static void AddReachableCodeToWorklist(BasicBlock *BB,
11293 SmallPtrSet<BasicBlock*, 64> &Visited,
11294 InstCombiner &IC,
11295 const TargetData *TD) {
11296 std::vector<BasicBlock*> Worklist;
11297 Worklist.push_back(BB);
11298
11299 while (!Worklist.empty()) {
11300 BB = Worklist.back();
11301 Worklist.pop_back();
11302
11303 // We have now visited this block! If we've already been here, ignore it.
11304 if (!Visited.insert(BB)) continue;
11305
11306 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
11307 Instruction *Inst = BBI++;
11308
11309 // DCE instruction if trivially dead.
11310 if (isInstructionTriviallyDead(Inst)) {
11311 ++NumDeadInst;
11312 DOUT << "IC: DCE: " << *Inst;
11313 Inst->eraseFromParent();
11314 continue;
11315 }
11316
11317 // ConstantProp instruction if trivially constant.
11318 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
11319 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
11320 Inst->replaceAllUsesWith(C);
11321 ++NumConstProp;
11322 Inst->eraseFromParent();
11323 continue;
11324 }
Chris Lattnere0f462d2007-07-20 22:06:41 +000011325
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011326 IC.AddToWorkList(Inst);
11327 }
11328
11329 // Recursively visit successors. If this is a branch or switch on a
11330 // constant, only visit the reachable successor.
11331 TerminatorInst *TI = BB->getTerminator();
11332 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
11333 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
11334 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewyckyd551cf12008-03-09 08:50:23 +000011335 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000011336 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011337 continue;
11338 }
11339 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
11340 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
11341 // See if this is an explicit destination.
11342 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
11343 if (SI->getCaseValue(i) == Cond) {
Nick Lewyckyd551cf12008-03-09 08:50:23 +000011344 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000011345 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011346 continue;
11347 }
11348
11349 // Otherwise it is the default destination.
11350 Worklist.push_back(SI->getSuccessor(0));
11351 continue;
11352 }
11353 }
11354
11355 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
11356 Worklist.push_back(TI->getSuccessor(i));
11357 }
11358}
11359
11360bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
11361 bool Changed = false;
11362 TD = &getAnalysis<TargetData>();
11363
11364 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
11365 << F.getNameStr() << "\n");
11366
11367 {
11368 // Do a depth-first traversal of the function, populate the worklist with
11369 // the reachable instructions. Ignore blocks that are not reachable. Keep
11370 // track of which blocks we visit.
11371 SmallPtrSet<BasicBlock*, 64> Visited;
11372 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
11373
11374 // Do a quick scan over the function. If we find any blocks that are
11375 // unreachable, remove any instructions inside of them. This prevents
11376 // the instcombine code from having to deal with some bad special cases.
11377 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
11378 if (!Visited.count(BB)) {
11379 Instruction *Term = BB->getTerminator();
11380 while (Term != BB->begin()) { // Remove instrs bottom-up
11381 BasicBlock::iterator I = Term; --I;
11382
11383 DOUT << "IC: DCE: " << *I;
11384 ++NumDeadInst;
11385
11386 if (!I->use_empty())
11387 I->replaceAllUsesWith(UndefValue::get(I->getType()));
11388 I->eraseFromParent();
11389 }
11390 }
11391 }
11392
11393 while (!Worklist.empty()) {
11394 Instruction *I = RemoveOneFromWorkList();
11395 if (I == 0) continue; // skip null values.
11396
11397 // Check to see if we can DCE the instruction.
11398 if (isInstructionTriviallyDead(I)) {
11399 // Add operands to the worklist.
11400 if (I->getNumOperands() < 4)
11401 AddUsesToWorkList(*I);
11402 ++NumDeadInst;
11403
11404 DOUT << "IC: DCE: " << *I;
11405
11406 I->eraseFromParent();
11407 RemoveFromWorkList(I);
11408 continue;
11409 }
11410
11411 // Instruction isn't dead, see if we can constant propagate it.
11412 if (Constant *C = ConstantFoldInstruction(I, TD)) {
11413 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
11414
11415 // Add operands to the worklist.
11416 AddUsesToWorkList(*I);
11417 ReplaceInstUsesWith(*I, C);
11418
11419 ++NumConstProp;
11420 I->eraseFromParent();
11421 RemoveFromWorkList(I);
11422 continue;
11423 }
11424
11425 // See if we can trivially sink this instruction to a successor basic block.
Chris Lattner0db40a62008-05-08 17:37:37 +000011426 // FIXME: Remove GetResultInst test when first class support for aggregates
11427 // is implemented.
Devang Patela0a6cae2008-05-03 00:36:30 +000011428 if (I->hasOneUse() && !isa<GetResultInst>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011429 BasicBlock *BB = I->getParent();
11430 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
11431 if (UserParent != BB) {
11432 bool UserIsSuccessor = false;
11433 // See if the user is one of our successors.
11434 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
11435 if (*SI == UserParent) {
11436 UserIsSuccessor = true;
11437 break;
11438 }
11439
11440 // If the user is one of our immediate successors, and if that successor
11441 // only has us as a predecessors (we'd have to split the critical edge
11442 // otherwise), we can keep going.
11443 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
11444 next(pred_begin(UserParent)) == pred_end(UserParent))
11445 // Okay, the CFG is simple enough, try to sink this instruction.
11446 Changed |= TryToSinkInstruction(I, UserParent);
11447 }
11448 }
11449
11450 // Now that we have an instruction, try combining it to simplify it...
11451#ifndef NDEBUG
11452 std::string OrigI;
11453#endif
11454 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
11455 if (Instruction *Result = visit(*I)) {
11456 ++NumCombined;
11457 // Should we replace the old instruction with a new one?
11458 if (Result != I) {
11459 DOUT << "IC: Old = " << *I
11460 << " New = " << *Result;
11461
11462 // Everything uses the new instruction now.
11463 I->replaceAllUsesWith(Result);
11464
11465 // Push the new instruction and any users onto the worklist.
11466 AddToWorkList(Result);
11467 AddUsersToWorkList(*Result);
11468
11469 // Move the name to the new instruction first.
11470 Result->takeName(I);
11471
11472 // Insert the new instruction into the basic block...
11473 BasicBlock *InstParent = I->getParent();
11474 BasicBlock::iterator InsertPos = I;
11475
11476 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
11477 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
11478 ++InsertPos;
11479
11480 InstParent->getInstList().insert(InsertPos, Result);
11481
11482 // Make sure that we reprocess all operands now that we reduced their
11483 // use counts.
11484 AddUsesToWorkList(*I);
11485
11486 // Instructions can end up on the worklist more than once. Make sure
11487 // we do not process an instruction that has been deleted.
11488 RemoveFromWorkList(I);
11489
11490 // Erase the old instruction.
11491 InstParent->getInstList().erase(I);
11492 } else {
11493#ifndef NDEBUG
11494 DOUT << "IC: Mod = " << OrigI
11495 << " New = " << *I;
11496#endif
11497
11498 // If the instruction was modified, it's possible that it is now dead.
11499 // if so, remove it.
11500 if (isInstructionTriviallyDead(I)) {
11501 // Make sure we process all operands now that we are reducing their
11502 // use counts.
11503 AddUsesToWorkList(*I);
11504
11505 // Instructions may end up in the worklist more than once. Erase all
11506 // occurrences of this instruction.
11507 RemoveFromWorkList(I);
11508 I->eraseFromParent();
11509 } else {
11510 AddToWorkList(I);
11511 AddUsersToWorkList(*I);
11512 }
11513 }
11514 Changed = true;
11515 }
11516 }
11517
11518 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnerb933ea62007-08-05 08:47:58 +000011519
11520 // Do an explicit clear, this shrinks the map if needed.
11521 WorklistMap.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011522 return Changed;
11523}
11524
11525
11526bool InstCombiner::runOnFunction(Function &F) {
11527 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
11528
11529 bool EverMadeChange = false;
11530
11531 // Iterate while there is work to do.
11532 unsigned Iteration = 0;
Bill Wendlingd9644a42008-05-14 22:45:20 +000011533 while (DoOneIteration(F, Iteration++))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011534 EverMadeChange = true;
11535 return EverMadeChange;
11536}
11537
11538FunctionPass *llvm::createInstructionCombiningPass() {
11539 return new InstCombiner();
11540}
11541