blob: 36a2ad5e455d406042b0bb391a6b688043d75db2 [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"
Chris Lattnera432bc72008-06-02 01:18:21 +000043#include "llvm/Analysis/ValueTracking.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000044#include "llvm/Target/TargetData.h"
45#include "llvm/Transforms/Utils/BasicBlockUtils.h"
46#include "llvm/Transforms/Utils/Local.h"
47#include "llvm/Support/CallSite.h"
Nick Lewycky0185bbf2008-02-03 16:33:09 +000048#include "llvm/Support/ConstantRange.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000049#include "llvm/Support/Debug.h"
50#include "llvm/Support/GetElementPtrTypeIterator.h"
51#include "llvm/Support/InstVisitor.h"
52#include "llvm/Support/MathExtras.h"
53#include "llvm/Support/PatternMatch.h"
54#include "llvm/Support/Compiler.h"
55#include "llvm/ADT/DenseMap.h"
56#include "llvm/ADT/SmallVector.h"
57#include "llvm/ADT/SmallPtrSet.h"
58#include "llvm/ADT/Statistic.h"
59#include "llvm/ADT/STLExtras.h"
60#include <algorithm>
Edwin Töröka0e6fce2008-04-20 08:33:11 +000061#include <climits>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000062#include <sstream>
63using namespace llvm;
64using namespace llvm::PatternMatch;
65
66STATISTIC(NumCombined , "Number of insts combined");
67STATISTIC(NumConstProp, "Number of constant folds");
68STATISTIC(NumDeadInst , "Number of dead inst eliminated");
69STATISTIC(NumDeadStore, "Number of dead stores eliminated");
70STATISTIC(NumSunkInst , "Number of instructions sunk");
71
72namespace {
73 class VISIBILITY_HIDDEN InstCombiner
74 : public FunctionPass,
75 public InstVisitor<InstCombiner, Instruction*> {
76 // Worklist of all of the instructions that need to be simplified.
Chris Lattnera06291a2008-08-15 04:03:01 +000077 SmallVector<Instruction*, 256> Worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000078 DenseMap<Instruction*, unsigned> WorklistMap;
79 TargetData *TD;
80 bool MustPreserveLCSSA;
81 public:
82 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +000083 InstCombiner() : FunctionPass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000084
85 /// AddToWorkList - Add the specified instruction to the worklist if it
86 /// isn't already in it.
87 void AddToWorkList(Instruction *I) {
Dan Gohman55d19662008-07-07 17:46:23 +000088 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000089 Worklist.push_back(I);
90 }
91
92 // RemoveFromWorkList - remove I from the worklist if it exists.
93 void RemoveFromWorkList(Instruction *I) {
94 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
95 if (It == WorklistMap.end()) return; // Not in worklist.
96
97 // Don't bother moving everything down, just null out the slot.
98 Worklist[It->second] = 0;
99
100 WorklistMap.erase(It);
101 }
102
103 Instruction *RemoveOneFromWorkList() {
104 Instruction *I = Worklist.back();
105 Worklist.pop_back();
106 WorklistMap.erase(I);
107 return I;
108 }
109
110
111 /// AddUsersToWorkList - When an instruction is simplified, add all users of
112 /// the instruction to the work lists because they might get more simplified
113 /// now.
114 ///
115 void AddUsersToWorkList(Value &I) {
116 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
117 UI != UE; ++UI)
118 AddToWorkList(cast<Instruction>(*UI));
119 }
120
121 /// AddUsesToWorkList - When an instruction is simplified, add operands to
122 /// the work lists because they might get more simplified now.
123 ///
124 void AddUsesToWorkList(Instruction &I) {
Gabor Greif17396002008-06-12 21:37:33 +0000125 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
126 if (Instruction *Op = dyn_cast<Instruction>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000127 AddToWorkList(Op);
128 }
129
130 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
131 /// dead. Add all of its operands to the worklist, turning them into
132 /// undef's to reduce the number of uses of those instructions.
133 ///
134 /// Return the specified operand before it is turned into an undef.
135 ///
136 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
137 Value *R = I.getOperand(op);
138
Gabor Greif17396002008-06-12 21:37:33 +0000139 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
140 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000141 AddToWorkList(Op);
142 // Set the operand to undef to drop the use.
Gabor Greif17396002008-06-12 21:37:33 +0000143 *i = UndefValue::get(Op->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000144 }
145
146 return R;
147 }
148
149 public:
150 virtual bool runOnFunction(Function &F);
151
152 bool DoOneIteration(Function &F, unsigned ItNum);
153
154 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
155 AU.addRequired<TargetData>();
156 AU.addPreservedID(LCSSAID);
157 AU.setPreservesCFG();
158 }
159
160 TargetData &getTargetData() const { return *TD; }
161
162 // Visitation implementation - Implement instruction combining for different
163 // instruction types. The semantics are as follows:
164 // Return Value:
165 // null - No change was made
166 // I - Change was made, I is still valid, I may be dead though
167 // otherwise - Change was made, replace I with returned instruction
168 //
169 Instruction *visitAdd(BinaryOperator &I);
170 Instruction *visitSub(BinaryOperator &I);
171 Instruction *visitMul(BinaryOperator &I);
172 Instruction *visitURem(BinaryOperator &I);
173 Instruction *visitSRem(BinaryOperator &I);
174 Instruction *visitFRem(BinaryOperator &I);
Chris Lattner76972db2008-07-14 00:15:52 +0000175 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000176 Instruction *commonRemTransforms(BinaryOperator &I);
177 Instruction *commonIRemTransforms(BinaryOperator &I);
178 Instruction *commonDivTransforms(BinaryOperator &I);
179 Instruction *commonIDivTransforms(BinaryOperator &I);
180 Instruction *visitUDiv(BinaryOperator &I);
181 Instruction *visitSDiv(BinaryOperator &I);
182 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner0631ea72008-11-16 05:06:21 +0000183 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000184 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner0c678e52008-11-16 05:20:07 +0000185 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Bill Wendling9912f712008-12-01 08:32:40 +0000186 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +0000187 Value *A, Value *B, Value *C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000188 Instruction *visitOr (BinaryOperator &I);
189 Instruction *visitXor(BinaryOperator &I);
190 Instruction *visitShl(BinaryOperator &I);
191 Instruction *visitAShr(BinaryOperator &I);
192 Instruction *visitLShr(BinaryOperator &I);
193 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnere6b62d92008-05-19 20:18:56 +0000194 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
195 Constant *RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000196 Instruction *visitFCmpInst(FCmpInst &I);
197 Instruction *visitICmpInst(ICmpInst &I);
198 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
199 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
200 Instruction *LHS,
201 ConstantInt *RHS);
202 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
203 ConstantInt *DivRHS);
204
205 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
206 ICmpInst::Predicate Cond, Instruction &I);
207 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
208 BinaryOperator &I);
209 Instruction *commonCastTransforms(CastInst &CI);
210 Instruction *commonIntCastTransforms(CastInst &CI);
211 Instruction *commonPointerCastTransforms(CastInst &CI);
212 Instruction *visitTrunc(TruncInst &CI);
213 Instruction *visitZExt(ZExtInst &CI);
214 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerdf7e8402008-01-27 05:29:54 +0000215 Instruction *visitFPTrunc(FPTruncInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000216 Instruction *visitFPExt(CastInst &CI);
Chris Lattnerdeef1a72008-05-19 20:25:04 +0000217 Instruction *visitFPToUI(FPToUIInst &FI);
218 Instruction *visitFPToSI(FPToSIInst &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000219 Instruction *visitUIToFP(CastInst &CI);
220 Instruction *visitSIToFP(CastInst &CI);
221 Instruction *visitPtrToInt(CastInst &CI);
Chris Lattner7c1626482008-01-08 07:23:51 +0000222 Instruction *visitIntToPtr(IntToPtrInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000223 Instruction *visitBitCast(BitCastInst &CI);
224 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
225 Instruction *FI);
Dan Gohman58c09632008-09-16 18:46:06 +0000226 Instruction *visitSelectInst(SelectInst &SI);
227 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000228 Instruction *visitCallInst(CallInst &CI);
229 Instruction *visitInvokeInst(InvokeInst &II);
230 Instruction *visitPHINode(PHINode &PN);
231 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
232 Instruction *visitAllocationInst(AllocationInst &AI);
233 Instruction *visitFreeInst(FreeInst &FI);
234 Instruction *visitLoadInst(LoadInst &LI);
235 Instruction *visitStoreInst(StoreInst &SI);
236 Instruction *visitBranchInst(BranchInst &BI);
237 Instruction *visitSwitchInst(SwitchInst &SI);
238 Instruction *visitInsertElementInst(InsertElementInst &IE);
239 Instruction *visitExtractElementInst(ExtractElementInst &EI);
240 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000241 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000242
243 // visitInstruction - Specify what to return for unhandled instructions...
244 Instruction *visitInstruction(Instruction &I) { return 0; }
245
246 private:
247 Instruction *visitCallSite(CallSite CS);
248 bool transformConstExprCastCall(CallSite CS);
Duncan Sands74833f22007-09-17 10:26:40 +0000249 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chenge3779cf2008-03-24 00:21:34 +0000250 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
251 bool DoXform = true);
Chris Lattner3554f972008-05-20 05:46:13 +0000252 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000253
254 public:
255 // InsertNewInstBefore - insert an instruction New before instruction Old
256 // in the program. Add the new instruction to the worklist.
257 //
258 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
259 assert(New && New->getParent() == 0 &&
260 "New instruction already inserted into a basic block!");
261 BasicBlock *BB = Old.getParent();
262 BB->getInstList().insert(&Old, New); // Insert inst
263 AddToWorkList(New);
264 return New;
265 }
266
267 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
268 /// This also adds the cast to the worklist. Finally, this returns the
269 /// cast.
270 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
271 Instruction &Pos) {
272 if (V->getType() == Ty) return V;
273
274 if (Constant *CV = dyn_cast<Constant>(V))
275 return ConstantExpr::getCast(opc, CV, Ty);
276
Gabor Greifa645dd32008-05-16 19:29:10 +0000277 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000278 AddToWorkList(C);
279 return C;
280 }
Chris Lattner13c2d6e2008-01-13 22:23:22 +0000281
282 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
283 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
284 }
285
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000286
287 // ReplaceInstUsesWith - This method is to be used when an instruction is
288 // found to be dead, replacable with another preexisting expression. Here
289 // we add all uses of I to the worklist, replace all uses of I with the new
290 // value, then return I, so that the inst combiner will know that I was
291 // modified.
292 //
293 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
294 AddUsersToWorkList(I); // Add all modified instrs to worklist
295 if (&I != V) {
296 I.replaceAllUsesWith(V);
297 return &I;
298 } else {
299 // If we are replacing the instruction with itself, this must be in a
300 // segment of unreachable code, so just clobber the instruction.
301 I.replaceAllUsesWith(UndefValue::get(I.getType()));
302 return &I;
303 }
304 }
305
306 // UpdateValueUsesWith - This method is to be used when an value is
307 // found to be replacable with another preexisting expression or was
308 // updated. Here we add all uses of I to the worklist, replace all uses of
309 // I with the new value (unless the instruction was just updated), then
310 // return true, so that the inst combiner will know that I was modified.
311 //
312 bool UpdateValueUsesWith(Value *Old, Value *New) {
313 AddUsersToWorkList(*Old); // Add all modified instrs to worklist
314 if (Old != New)
315 Old->replaceAllUsesWith(New);
316 if (Instruction *I = dyn_cast<Instruction>(Old))
317 AddToWorkList(I);
318 if (Instruction *I = dyn_cast<Instruction>(New))
319 AddToWorkList(I);
320 return true;
321 }
322
323 // EraseInstFromFunction - When dealing with an instruction that has side
324 // effects or produces a void value, we can't rely on DCE to delete the
325 // instruction. Instead, visit methods should return the value returned by
326 // this function.
327 Instruction *EraseInstFromFunction(Instruction &I) {
328 assert(I.use_empty() && "Cannot erase instruction that is used!");
329 AddUsesToWorkList(I);
330 RemoveFromWorkList(&I);
331 I.eraseFromParent();
332 return 0; // Don't do anything with FI
333 }
Chris Lattnera432bc72008-06-02 01:18:21 +0000334
335 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
336 APInt &KnownOne, unsigned Depth = 0) const {
337 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
338 }
339
340 bool MaskedValueIsZero(Value *V, const APInt &Mask,
341 unsigned Depth = 0) const {
342 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
343 }
344 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
345 return llvm::ComputeNumSignBits(Op, TD, Depth);
346 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000347
348 private:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000349
350 /// SimplifyCommutative - This performs a few simplifications for
351 /// commutative operators.
352 bool SimplifyCommutative(BinaryOperator &I);
353
354 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
355 /// most-complex to least-complex order.
356 bool SimplifyCompare(CmpInst &I);
357
358 /// SimplifyDemandedBits - Attempts to replace V with a simpler value based
359 /// on the demanded bits.
360 bool SimplifyDemandedBits(Value *V, APInt DemandedMask,
361 APInt& KnownZero, APInt& KnownOne,
362 unsigned Depth = 0);
363
364 Value *SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
365 uint64_t &UndefElts, unsigned Depth = 0);
366
367 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
368 // PHI node as operand #0, see if we can fold the instruction into the PHI
369 // (which is only possible if all operands to the PHI are constants).
370 Instruction *FoldOpIntoPhi(Instruction &I);
371
372 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
373 // operator and they all are only used by the PHI, PHI together their
374 // inputs, and do the operation once, to the result of the PHI.
375 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
376 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner9e1916e2008-12-01 02:34:36 +0000377 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
378
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000379
380 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
381 ConstantInt *AndRHS, BinaryOperator &TheAnd);
382
383 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
384 bool isSub, Instruction &I);
385 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
386 bool isSigned, bool Inside, Instruction &IB);
387 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
388 Instruction *MatchBSwap(BinaryOperator &I);
389 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000390 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +0000391 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000392
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000393
394 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000395
Dan Gohman2d648bb2008-04-10 18:43:06 +0000396 bool CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +0000397 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000398 unsigned GetOrEnforceKnownAlignment(Value *V,
399 unsigned PrefAlign = 0);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000400
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000401 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000402}
403
Dan Gohman089efff2008-05-13 00:00:25 +0000404char InstCombiner::ID = 0;
405static RegisterPass<InstCombiner>
406X("instcombine", "Combine redundant instructions");
407
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000408// getComplexity: Assign a complexity or rank value to LLVM Values...
409// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
410static unsigned getComplexity(Value *V) {
411 if (isa<Instruction>(V)) {
412 if (BinaryOperator::isNeg(V) || BinaryOperator::isNot(V))
413 return 3;
414 return 4;
415 }
416 if (isa<Argument>(V)) return 3;
417 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
418}
419
420// isOnlyUse - Return true if this instruction will be deleted if we stop using
421// it.
422static bool isOnlyUse(Value *V) {
423 return V->hasOneUse() || isa<Constant>(V);
424}
425
426// getPromotedType - Return the specified type promoted as it would be to pass
427// though a va_arg area...
428static const Type *getPromotedType(const Type *Ty) {
429 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
430 if (ITy->getBitWidth() < 32)
431 return Type::Int32Ty;
432 }
433 return Ty;
434}
435
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000436/// getBitCastOperand - If the specified operand is a CastInst, a constant
437/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
438/// operand value, otherwise return null.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000439static Value *getBitCastOperand(Value *V) {
440 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000441 // BitCastInst?
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000442 return I->getOperand(0);
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000443 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
444 // GetElementPtrInst?
445 if (GEP->hasAllZeroIndices())
446 return GEP->getOperand(0);
447 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000448 if (CE->getOpcode() == Instruction::BitCast)
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000449 // BitCast ConstantExp?
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000450 return CE->getOperand(0);
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000451 else if (CE->getOpcode() == Instruction::GetElementPtr) {
452 // GetElementPtr ConstantExp?
453 for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
454 I != E; ++I) {
455 ConstantInt *CI = dyn_cast<ConstantInt>(I);
456 if (!CI || !CI->isZero())
457 // Any non-zero indices? Not cast-like.
458 return 0;
459 }
460 // All-zero indices? This is just like casting.
461 return CE->getOperand(0);
462 }
463 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000464 return 0;
465}
466
467/// This function is a wrapper around CastInst::isEliminableCastPair. It
468/// simply extracts arguments and returns what that function returns.
469static Instruction::CastOps
470isEliminableCastPair(
471 const CastInst *CI, ///< The first cast instruction
472 unsigned opcode, ///< The opcode of the second cast instruction
473 const Type *DstTy, ///< The target type for the second cast instruction
474 TargetData *TD ///< The target data for pointer size
475) {
476
477 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
478 const Type *MidTy = CI->getType(); // B from above
479
480 // Get the opcodes of the two Cast instructions
481 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
482 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
483
484 return Instruction::CastOps(
485 CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
486 DstTy, TD->getIntPtrType()));
487}
488
489/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
490/// in any code being generated. It does not require codegen if V is simple
491/// enough or if the cast can be folded into other casts.
492static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
493 const Type *Ty, TargetData *TD) {
494 if (V->getType() == Ty || isa<Constant>(V)) return false;
495
496 // If this is another cast that can be eliminated, it isn't codegen either.
497 if (const CastInst *CI = dyn_cast<CastInst>(V))
498 if (isEliminableCastPair(CI, opcode, Ty, TD))
499 return false;
500 return true;
501}
502
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000503// SimplifyCommutative - This performs a few simplifications for commutative
504// operators:
505//
506// 1. Order operands such that they are listed from right (least complex) to
507// left (most complex). This puts constants before unary operators before
508// binary operators.
509//
510// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
511// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
512//
513bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
514 bool Changed = false;
515 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
516 Changed = !I.swapOperands();
517
518 if (!I.isAssociative()) return Changed;
519 Instruction::BinaryOps Opcode = I.getOpcode();
520 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
521 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
522 if (isa<Constant>(I.getOperand(1))) {
523 Constant *Folded = ConstantExpr::get(I.getOpcode(),
524 cast<Constant>(I.getOperand(1)),
525 cast<Constant>(Op->getOperand(1)));
526 I.setOperand(0, Op->getOperand(0));
527 I.setOperand(1, Folded);
528 return true;
529 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
530 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
531 isOnlyUse(Op) && isOnlyUse(Op1)) {
532 Constant *C1 = cast<Constant>(Op->getOperand(1));
533 Constant *C2 = cast<Constant>(Op1->getOperand(1));
534
535 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
536 Constant *Folded = ConstantExpr::get(I.getOpcode(), C1, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +0000537 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000538 Op1->getOperand(0),
539 Op1->getName(), &I);
540 AddToWorkList(New);
541 I.setOperand(0, New);
542 I.setOperand(1, Folded);
543 return true;
544 }
545 }
546 return Changed;
547}
548
549/// SimplifyCompare - For a CmpInst this function just orders the operands
550/// so that theyare listed from right (least complex) to left (most complex).
551/// This puts constants before unary operators before binary operators.
552bool InstCombiner::SimplifyCompare(CmpInst &I) {
553 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
554 return false;
555 I.swapOperands();
556 // Compare instructions are not associative so there's nothing else we can do.
557 return true;
558}
559
560// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
561// if the LHS is a constant zero (which is the 'negate' form).
562//
563static inline Value *dyn_castNegVal(Value *V) {
564 if (BinaryOperator::isNeg(V))
565 return BinaryOperator::getNegArgument(V);
566
567 // Constants can be considered to be negated values if they can be folded.
568 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
569 return ConstantExpr::getNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000570
571 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
572 if (C->getType()->getElementType()->isInteger())
573 return ConstantExpr::getNeg(C);
574
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000575 return 0;
576}
577
578static inline Value *dyn_castNotVal(Value *V) {
579 if (BinaryOperator::isNot(V))
580 return BinaryOperator::getNotArgument(V);
581
582 // Constants can be considered to be not'ed values...
583 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
584 return ConstantInt::get(~C->getValue());
585 return 0;
586}
587
588// dyn_castFoldableMul - If this value is a multiply that can be folded into
589// other computations (because it has a constant operand), return the
590// non-constant operand of the multiply, and set CST to point to the multiplier.
591// Otherwise, return null.
592//
593static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST) {
594 if (V->hasOneUse() && V->getType()->isInteger())
595 if (Instruction *I = dyn_cast<Instruction>(V)) {
596 if (I->getOpcode() == Instruction::Mul)
597 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
598 return I->getOperand(0);
599 if (I->getOpcode() == Instruction::Shl)
600 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
601 // The multiplier is really 1 << CST.
602 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
603 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
604 CST = ConstantInt::get(APInt(BitWidth, 1).shl(CSTVal));
605 return I->getOperand(0);
606 }
607 }
608 return 0;
609}
610
611/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
612/// expression, return it.
613static User *dyn_castGetElementPtr(Value *V) {
614 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
615 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
616 if (CE->getOpcode() == Instruction::GetElementPtr)
617 return cast<User>(V);
618 return false;
619}
620
Dan Gohman2d648bb2008-04-10 18:43:06 +0000621/// getOpcode - If this is an Instruction or a ConstantExpr, return the
622/// opcode value. Otherwise return UserOp1.
Dan Gohman8c397862008-05-29 19:53:46 +0000623static unsigned getOpcode(const Value *V) {
624 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohman2d648bb2008-04-10 18:43:06 +0000625 return I->getOpcode();
Dan Gohman8c397862008-05-29 19:53:46 +0000626 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohman2d648bb2008-04-10 18:43:06 +0000627 return CE->getOpcode();
628 // Use UserOp1 to mean there's no opcode.
629 return Instruction::UserOp1;
630}
631
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000632/// AddOne - Add one to a ConstantInt
633static ConstantInt *AddOne(ConstantInt *C) {
634 APInt Val(C->getValue());
635 return ConstantInt::get(++Val);
636}
637/// SubOne - Subtract one from a ConstantInt
638static ConstantInt *SubOne(ConstantInt *C) {
639 APInt Val(C->getValue());
640 return ConstantInt::get(--Val);
641}
642/// Add - Add two ConstantInts together
643static ConstantInt *Add(ConstantInt *C1, ConstantInt *C2) {
644 return ConstantInt::get(C1->getValue() + C2->getValue());
645}
646/// And - Bitwise AND two ConstantInts together
647static ConstantInt *And(ConstantInt *C1, ConstantInt *C2) {
648 return ConstantInt::get(C1->getValue() & C2->getValue());
649}
650/// Subtract - Subtract one ConstantInt from another
651static ConstantInt *Subtract(ConstantInt *C1, ConstantInt *C2) {
652 return ConstantInt::get(C1->getValue() - C2->getValue());
653}
654/// Multiply - Multiply two ConstantInts together
655static ConstantInt *Multiply(ConstantInt *C1, ConstantInt *C2) {
656 return ConstantInt::get(C1->getValue() * C2->getValue());
657}
Nick Lewycky9d798f92008-02-18 22:48:05 +0000658/// MultiplyOverflows - True if the multiply can not be expressed in an int
659/// this size.
660static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign) {
661 uint32_t W = C1->getBitWidth();
662 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
663 if (sign) {
664 LHSExt.sext(W * 2);
665 RHSExt.sext(W * 2);
666 } else {
667 LHSExt.zext(W * 2);
668 RHSExt.zext(W * 2);
669 }
670
671 APInt MulExt = LHSExt * RHSExt;
672
673 if (sign) {
674 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
675 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
676 return MulExt.slt(Min) || MulExt.sgt(Max);
677 } else
678 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
679}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000680
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000681
682/// ShrinkDemandedConstant - Check to see if the specified operand of the
683/// specified instruction is a constant integer. If so, check to see if there
684/// are any bits set in the constant that are not demanded. If so, shrink the
685/// constant and return true.
686static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
687 APInt Demanded) {
688 assert(I && "No instruction?");
689 assert(OpNo < I->getNumOperands() && "Operand index too large");
690
691 // If the operand is not a constant integer, nothing to do.
692 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
693 if (!OpC) return false;
694
695 // If there are no bits set that aren't demanded, nothing to do.
696 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
697 if ((~Demanded & OpC->getValue()) == 0)
698 return false;
699
700 // This instruction is producing bits that are not demanded. Shrink the RHS.
701 Demanded &= OpC->getValue();
702 I->setOperand(OpNo, ConstantInt::get(Demanded));
703 return true;
704}
705
706// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
707// set of known zero and one bits, compute the maximum and minimum values that
708// could have the specified known zero and known one bits, returning them in
709// min/max.
710static void ComputeSignedMinMaxValuesFromKnownBits(const Type *Ty,
711 const APInt& KnownZero,
712 const APInt& KnownOne,
713 APInt& Min, APInt& Max) {
714 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
715 assert(KnownZero.getBitWidth() == BitWidth &&
716 KnownOne.getBitWidth() == BitWidth &&
717 Min.getBitWidth() == BitWidth && Max.getBitWidth() == BitWidth &&
718 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
719 APInt UnknownBits = ~(KnownZero|KnownOne);
720
721 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
722 // bit if it is unknown.
723 Min = KnownOne;
724 Max = KnownOne|UnknownBits;
725
726 if (UnknownBits[BitWidth-1]) { // Sign bit is unknown
727 Min.set(BitWidth-1);
728 Max.clear(BitWidth-1);
729 }
730}
731
732// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
733// a set of known zero and one bits, compute the maximum and minimum values that
734// could have the specified known zero and known one bits, returning them in
735// min/max.
736static void ComputeUnsignedMinMaxValuesFromKnownBits(const Type *Ty,
Chris Lattnerb933ea62007-08-05 08:47:58 +0000737 const APInt &KnownZero,
738 const APInt &KnownOne,
739 APInt &Min, APInt &Max) {
740 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth(); BitWidth = BitWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000741 assert(KnownZero.getBitWidth() == BitWidth &&
742 KnownOne.getBitWidth() == BitWidth &&
743 Min.getBitWidth() == BitWidth && Max.getBitWidth() &&
744 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
745 APInt UnknownBits = ~(KnownZero|KnownOne);
746
747 // The minimum value is when the unknown bits are all zeros.
748 Min = KnownOne;
749 // The maximum value is when the unknown bits are all ones.
750 Max = KnownOne|UnknownBits;
751}
752
753/// SimplifyDemandedBits - This function attempts to replace V with a simpler
754/// value based on the demanded bits. When this function is called, it is known
755/// that only the bits set in DemandedMask of the result of V are ever used
756/// downstream. Consequently, depending on the mask and V, it may be possible
757/// to replace V with a constant or one of its operands. In such cases, this
758/// function does the replacement and returns true. In all other cases, it
759/// returns false after analyzing the expression and setting KnownOne and known
760/// to be one in the expression. KnownZero contains all the bits that are known
761/// to be zero in the expression. These are provided to potentially allow the
762/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
763/// the expression. KnownOne and KnownZero always follow the invariant that
764/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
765/// the bits in KnownOne and KnownZero may only be accurate for those bits set
766/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
767/// and KnownOne must all be the same.
768bool InstCombiner::SimplifyDemandedBits(Value *V, APInt DemandedMask,
769 APInt& KnownZero, APInt& KnownOne,
770 unsigned Depth) {
771 assert(V != 0 && "Null pointer of Value???");
772 assert(Depth <= 6 && "Limit Search Depth");
773 uint32_t BitWidth = DemandedMask.getBitWidth();
774 const IntegerType *VTy = cast<IntegerType>(V->getType());
775 assert(VTy->getBitWidth() == BitWidth &&
776 KnownZero.getBitWidth() == BitWidth &&
777 KnownOne.getBitWidth() == BitWidth &&
778 "Value *V, DemandedMask, KnownZero and KnownOne \
779 must have same BitWidth");
780 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
781 // We know all of the bits for a constant!
782 KnownOne = CI->getValue() & DemandedMask;
783 KnownZero = ~KnownOne & DemandedMask;
784 return false;
785 }
786
787 KnownZero.clear();
788 KnownOne.clear();
789 if (!V->hasOneUse()) { // Other users may use these bits.
790 if (Depth != 0) { // Not at the root.
791 // Just compute the KnownZero/KnownOne bits to simplify things downstream.
792 ComputeMaskedBits(V, DemandedMask, KnownZero, KnownOne, Depth);
793 return false;
794 }
795 // If this is the root being simplified, allow it to have multiple uses,
796 // just set the DemandedMask to all bits.
797 DemandedMask = APInt::getAllOnesValue(BitWidth);
798 } else if (DemandedMask == 0) { // Not demanding any bits from V.
799 if (V != UndefValue::get(VTy))
800 return UpdateValueUsesWith(V, UndefValue::get(VTy));
801 return false;
802 } else if (Depth == 6) { // Limit search depth.
803 return false;
804 }
805
806 Instruction *I = dyn_cast<Instruction>(V);
807 if (!I) return false; // Only analyze instructions.
808
809 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
810 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
811 switch (I->getOpcode()) {
Dan Gohmanbec16052008-04-28 17:02:21 +0000812 default:
813 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
814 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000815 case Instruction::And:
816 // If either the LHS or the RHS are Zero, the result is zero.
817 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
818 RHSKnownZero, RHSKnownOne, Depth+1))
819 return true;
820 assert((RHSKnownZero & RHSKnownOne) == 0 &&
821 "Bits known to be one AND zero?");
822
823 // If something is known zero on the RHS, the bits aren't demanded on the
824 // LHS.
825 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
826 LHSKnownZero, LHSKnownOne, Depth+1))
827 return true;
828 assert((LHSKnownZero & LHSKnownOne) == 0 &&
829 "Bits known to be one AND zero?");
830
831 // If all of the demanded bits are known 1 on one side, return the other.
832 // These bits cannot contribute to the result of the 'and'.
833 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
834 (DemandedMask & ~LHSKnownZero))
835 return UpdateValueUsesWith(I, I->getOperand(0));
836 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
837 (DemandedMask & ~RHSKnownZero))
838 return UpdateValueUsesWith(I, I->getOperand(1));
839
840 // If all of the demanded bits in the inputs are known zeros, return zero.
841 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
842 return UpdateValueUsesWith(I, Constant::getNullValue(VTy));
843
844 // If the RHS is a constant, see if we can simplify it.
845 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero))
846 return UpdateValueUsesWith(I, I);
847
848 // Output known-1 bits are only known if set in both the LHS & RHS.
849 RHSKnownOne &= LHSKnownOne;
850 // Output known-0 are known to be clear if zero in either the LHS | RHS.
851 RHSKnownZero |= LHSKnownZero;
852 break;
853 case Instruction::Or:
854 // If either the LHS or the RHS are One, the result is One.
855 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
856 RHSKnownZero, RHSKnownOne, Depth+1))
857 return true;
858 assert((RHSKnownZero & RHSKnownOne) == 0 &&
859 "Bits known to be one AND zero?");
860 // If something is known one on the RHS, the bits aren't demanded on the
861 // LHS.
862 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
863 LHSKnownZero, LHSKnownOne, Depth+1))
864 return true;
865 assert((LHSKnownZero & LHSKnownOne) == 0 &&
866 "Bits known to be one AND zero?");
867
868 // If all of the demanded bits are known zero on one side, return the other.
869 // These bits cannot contribute to the result of the 'or'.
870 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
871 (DemandedMask & ~LHSKnownOne))
872 return UpdateValueUsesWith(I, I->getOperand(0));
873 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
874 (DemandedMask & ~RHSKnownOne))
875 return UpdateValueUsesWith(I, I->getOperand(1));
876
877 // If all of the potentially set bits on one side are known to be set on
878 // the other side, just use the 'other' side.
879 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
880 (DemandedMask & (~RHSKnownZero)))
881 return UpdateValueUsesWith(I, I->getOperand(0));
882 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
883 (DemandedMask & (~LHSKnownZero)))
884 return UpdateValueUsesWith(I, I->getOperand(1));
885
886 // If the RHS is a constant, see if we can simplify it.
887 if (ShrinkDemandedConstant(I, 1, DemandedMask))
888 return UpdateValueUsesWith(I, I);
889
890 // Output known-0 bits are only known if clear in both the LHS & RHS.
891 RHSKnownZero &= LHSKnownZero;
892 // Output known-1 are known to be set if set in either the LHS | RHS.
893 RHSKnownOne |= LHSKnownOne;
894 break;
895 case Instruction::Xor: {
896 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
897 RHSKnownZero, RHSKnownOne, Depth+1))
898 return true;
899 assert((RHSKnownZero & RHSKnownOne) == 0 &&
900 "Bits known to be one AND zero?");
901 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
902 LHSKnownZero, LHSKnownOne, Depth+1))
903 return true;
904 assert((LHSKnownZero & LHSKnownOne) == 0 &&
905 "Bits known to be one AND zero?");
906
907 // If all of the demanded bits are known zero on one side, return the other.
908 // These bits cannot contribute to the result of the 'xor'.
909 if ((DemandedMask & RHSKnownZero) == DemandedMask)
910 return UpdateValueUsesWith(I, I->getOperand(0));
911 if ((DemandedMask & LHSKnownZero) == DemandedMask)
912 return UpdateValueUsesWith(I, I->getOperand(1));
913
914 // Output known-0 bits are known if clear or set in both the LHS & RHS.
915 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
916 (RHSKnownOne & LHSKnownOne);
917 // Output known-1 are known to be set if set in only one of the LHS, RHS.
918 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
919 (RHSKnownOne & LHSKnownZero);
920
921 // If all of the demanded bits are known to be zero on one side or the
922 // other, turn this into an *inclusive* or.
923 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
924 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
925 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +0000926 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000927 I->getName());
928 InsertNewInstBefore(Or, *I);
929 return UpdateValueUsesWith(I, Or);
930 }
931
932 // If all of the demanded bits on one side are known, and all of the set
933 // bits on that side are also known to be set on the other side, turn this
934 // into an AND, as we know the bits will be cleared.
935 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
936 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
937 // all known
938 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
939 Constant *AndC = ConstantInt::get(~RHSKnownOne & DemandedMask);
940 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +0000941 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000942 InsertNewInstBefore(And, *I);
943 return UpdateValueUsesWith(I, And);
944 }
945 }
946
947 // If the RHS is a constant, see if we can simplify it.
948 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
949 if (ShrinkDemandedConstant(I, 1, DemandedMask))
950 return UpdateValueUsesWith(I, I);
951
952 RHSKnownZero = KnownZeroOut;
953 RHSKnownOne = KnownOneOut;
954 break;
955 }
956 case Instruction::Select:
957 if (SimplifyDemandedBits(I->getOperand(2), DemandedMask,
958 RHSKnownZero, RHSKnownOne, Depth+1))
959 return true;
960 if (SimplifyDemandedBits(I->getOperand(1), DemandedMask,
961 LHSKnownZero, LHSKnownOne, Depth+1))
962 return true;
963 assert((RHSKnownZero & RHSKnownOne) == 0 &&
964 "Bits known to be one AND zero?");
965 assert((LHSKnownZero & LHSKnownOne) == 0 &&
966 "Bits known to be one AND zero?");
967
968 // If the operands are constants, see if we can simplify them.
969 if (ShrinkDemandedConstant(I, 1, DemandedMask))
970 return UpdateValueUsesWith(I, I);
971 if (ShrinkDemandedConstant(I, 2, DemandedMask))
972 return UpdateValueUsesWith(I, I);
973
974 // Only known if known in both the LHS and RHS.
975 RHSKnownOne &= LHSKnownOne;
976 RHSKnownZero &= LHSKnownZero;
977 break;
978 case Instruction::Trunc: {
979 uint32_t truncBf =
980 cast<IntegerType>(I->getOperand(0)->getType())->getBitWidth();
981 DemandedMask.zext(truncBf);
982 RHSKnownZero.zext(truncBf);
983 RHSKnownOne.zext(truncBf);
984 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
985 RHSKnownZero, RHSKnownOne, Depth+1))
986 return true;
987 DemandedMask.trunc(BitWidth);
988 RHSKnownZero.trunc(BitWidth);
989 RHSKnownOne.trunc(BitWidth);
990 assert((RHSKnownZero & RHSKnownOne) == 0 &&
991 "Bits known to be one AND zero?");
992 break;
993 }
994 case Instruction::BitCast:
995 if (!I->getOperand(0)->getType()->isInteger())
996 return false;
997
998 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
999 RHSKnownZero, RHSKnownOne, Depth+1))
1000 return true;
1001 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1002 "Bits known to be one AND zero?");
1003 break;
1004 case Instruction::ZExt: {
1005 // Compute the bits in the result that are not present in the input.
1006 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1007 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1008
1009 DemandedMask.trunc(SrcBitWidth);
1010 RHSKnownZero.trunc(SrcBitWidth);
1011 RHSKnownOne.trunc(SrcBitWidth);
1012 if (SimplifyDemandedBits(I->getOperand(0), DemandedMask,
1013 RHSKnownZero, RHSKnownOne, Depth+1))
1014 return true;
1015 DemandedMask.zext(BitWidth);
1016 RHSKnownZero.zext(BitWidth);
1017 RHSKnownOne.zext(BitWidth);
1018 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1019 "Bits known to be one AND zero?");
1020 // The top bits are known to be zero.
1021 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1022 break;
1023 }
1024 case Instruction::SExt: {
1025 // Compute the bits in the result that are not present in the input.
1026 const IntegerType *SrcTy = cast<IntegerType>(I->getOperand(0)->getType());
1027 uint32_t SrcBitWidth = SrcTy->getBitWidth();
1028
1029 APInt InputDemandedBits = DemandedMask &
1030 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1031
1032 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1033 // If any of the sign extended bits are demanded, we know that the sign
1034 // bit is demanded.
1035 if ((NewBits & DemandedMask) != 0)
1036 InputDemandedBits.set(SrcBitWidth-1);
1037
1038 InputDemandedBits.trunc(SrcBitWidth);
1039 RHSKnownZero.trunc(SrcBitWidth);
1040 RHSKnownOne.trunc(SrcBitWidth);
1041 if (SimplifyDemandedBits(I->getOperand(0), InputDemandedBits,
1042 RHSKnownZero, RHSKnownOne, Depth+1))
1043 return true;
1044 InputDemandedBits.zext(BitWidth);
1045 RHSKnownZero.zext(BitWidth);
1046 RHSKnownOne.zext(BitWidth);
1047 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1048 "Bits known to be one AND zero?");
1049
1050 // If the sign bit of the input is known set or clear, then we know the
1051 // top bits of the result.
1052
1053 // If the input sign bit is known zero, or if the NewBits are not demanded
1054 // convert this into a zero extension.
1055 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits)
1056 {
1057 // Convert to ZExt cast
1058 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName(), I);
1059 return UpdateValueUsesWith(I, NewCast);
1060 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1061 RHSKnownOne |= NewBits;
1062 }
1063 break;
1064 }
1065 case Instruction::Add: {
1066 // Figure out what the input bits are. If the top bits of the and result
1067 // are not demanded, then the add doesn't demand them from its input
1068 // either.
1069 uint32_t NLZ = DemandedMask.countLeadingZeros();
1070
1071 // If there is a constant on the RHS, there are a variety of xformations
1072 // we can do.
1073 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1074 // If null, this should be simplified elsewhere. Some of the xforms here
1075 // won't work if the RHS is zero.
1076 if (RHS->isZero())
1077 break;
1078
1079 // If the top bit of the output is demanded, demand everything from the
1080 // input. Otherwise, we demand all the input bits except NLZ top bits.
1081 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1082
1083 // Find information about known zero/one bits in the input.
1084 if (SimplifyDemandedBits(I->getOperand(0), InDemandedBits,
1085 LHSKnownZero, LHSKnownOne, Depth+1))
1086 return true;
1087
1088 // If the RHS of the add has bits set that can't affect the input, reduce
1089 // the constant.
1090 if (ShrinkDemandedConstant(I, 1, InDemandedBits))
1091 return UpdateValueUsesWith(I, I);
1092
1093 // Avoid excess work.
1094 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1095 break;
1096
1097 // Turn it into OR if input bits are zero.
1098 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1099 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001100 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001101 I->getName());
1102 InsertNewInstBefore(Or, *I);
1103 return UpdateValueUsesWith(I, Or);
1104 }
1105
1106 // We can say something about the output known-zero and known-one bits,
1107 // depending on potential carries from the input constant and the
1108 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1109 // bits set and the RHS constant is 0x01001, then we know we have a known
1110 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1111
1112 // To compute this, we first compute the potential carry bits. These are
1113 // the bits which may be modified. I'm not aware of a better way to do
1114 // this scan.
1115 const APInt& RHSVal = RHS->getValue();
1116 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1117
1118 // Now that we know which bits have carries, compute the known-1/0 sets.
1119
1120 // Bits are known one if they are known zero in one operand and one in the
1121 // other, and there is no input carry.
1122 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1123 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1124
1125 // Bits are known zero if they are known zero in both operands and there
1126 // is no input carry.
1127 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1128 } else {
1129 // If the high-bits of this ADD are not demanded, then it does not demand
1130 // the high bits of its LHS or RHS.
1131 if (DemandedMask[BitWidth-1] == 0) {
1132 // Right fill the mask of bits for this ADD to demand the most
1133 // significant bit and all those below it.
1134 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1135 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1136 LHSKnownZero, LHSKnownOne, Depth+1))
1137 return true;
1138 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1139 LHSKnownZero, LHSKnownOne, Depth+1))
1140 return true;
1141 }
1142 }
1143 break;
1144 }
1145 case Instruction::Sub:
1146 // If the high-bits of this SUB are not demanded, then it does not demand
1147 // the high bits of its LHS or RHS.
1148 if (DemandedMask[BitWidth-1] == 0) {
1149 // Right fill the mask of bits for this SUB to demand the most
1150 // significant bit and all those below it.
1151 uint32_t NLZ = DemandedMask.countLeadingZeros();
1152 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
1153 if (SimplifyDemandedBits(I->getOperand(0), DemandedFromOps,
1154 LHSKnownZero, LHSKnownOne, Depth+1))
1155 return true;
1156 if (SimplifyDemandedBits(I->getOperand(1), DemandedFromOps,
1157 LHSKnownZero, LHSKnownOne, Depth+1))
1158 return true;
1159 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001160 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1161 // the known zeros and ones.
1162 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001163 break;
1164 case Instruction::Shl:
1165 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1166 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1167 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
1168 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1169 RHSKnownZero, RHSKnownOne, Depth+1))
1170 return true;
1171 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1172 "Bits known to be one AND zero?");
1173 RHSKnownZero <<= ShiftAmt;
1174 RHSKnownOne <<= ShiftAmt;
1175 // low bits known zero.
1176 if (ShiftAmt)
1177 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1178 }
1179 break;
1180 case Instruction::LShr:
1181 // For a logical shift right
1182 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1183 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1184
1185 // Unsigned shift right.
1186 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1187 if (SimplifyDemandedBits(I->getOperand(0), DemandedMaskIn,
1188 RHSKnownZero, RHSKnownOne, Depth+1))
1189 return true;
1190 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1191 "Bits known to be one AND zero?");
1192 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1193 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1194 if (ShiftAmt) {
1195 // Compute the new bits that are at the top now.
1196 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1197 RHSKnownZero |= HighBits; // high bits known zero.
1198 }
1199 }
1200 break;
1201 case Instruction::AShr:
1202 // If this is an arithmetic shift right and only the low-bit is set, we can
1203 // always convert this into a logical shr, even if the shift amount is
1204 // variable. The low bit of the shift cannot be an input sign bit unless
1205 // the shift amount is >= the size of the datatype, which is undefined.
1206 if (DemandedMask == 1) {
1207 // Perform the logical shift right.
Gabor Greifa645dd32008-05-16 19:29:10 +00001208 Value *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001209 I->getOperand(0), I->getOperand(1), I->getName());
1210 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1211 return UpdateValueUsesWith(I, NewVal);
1212 }
1213
1214 // If the sign bit is the only bit demanded by this ashr, then there is no
1215 // need to do it, the shift doesn't change the high bit.
1216 if (DemandedMask.isSignBit())
1217 return UpdateValueUsesWith(I, I->getOperand(0));
1218
1219 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1220 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1221
1222 // Signed shift right.
1223 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1224 // If any of the "high bits" are demanded, we should set the sign bit as
1225 // demanded.
1226 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1227 DemandedMaskIn.set(BitWidth-1);
1228 if (SimplifyDemandedBits(I->getOperand(0),
1229 DemandedMaskIn,
1230 RHSKnownZero, RHSKnownOne, Depth+1))
1231 return true;
1232 assert((RHSKnownZero & RHSKnownOne) == 0 &&
1233 "Bits known to be one AND zero?");
1234 // Compute the new bits that are at the top now.
1235 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1236 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1237 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1238
1239 // Handle the sign bits.
1240 APInt SignBit(APInt::getSignBit(BitWidth));
1241 // Adjust to where it is now in the mask.
1242 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1243
1244 // If the input sign bit is known to be zero, or if none of the top bits
1245 // are demanded, turn this into an unsigned shift right.
Zhou Sheng533604e2008-06-06 08:32:05 +00001246 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001247 (HighBits & ~DemandedMask) == HighBits) {
1248 // Perform the logical shift right.
Gabor Greifa645dd32008-05-16 19:29:10 +00001249 Value *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001250 I->getOperand(0), SA, I->getName());
1251 InsertNewInstBefore(cast<Instruction>(NewVal), *I);
1252 return UpdateValueUsesWith(I, NewVal);
1253 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1254 RHSKnownOne |= HighBits;
1255 }
1256 }
1257 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001258 case Instruction::SRem:
1259 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001260 APInt RA = Rem->getValue().abs();
1261 if (RA.isPowerOf2()) {
Nick Lewycky245de422008-07-12 05:04:38 +00001262 if (DemandedMask.ule(RA)) // srem won't affect demanded bits
1263 return UpdateValueUsesWith(I, I->getOperand(0));
1264
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001265 APInt LowBits = RA - 1;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001266 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1267 if (SimplifyDemandedBits(I->getOperand(0), Mask2,
1268 LHSKnownZero, LHSKnownOne, Depth+1))
1269 return true;
1270
1271 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1272 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001273
1274 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001275
1276 assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
1277 }
1278 }
1279 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001280 case Instruction::URem: {
Dan Gohmanbec16052008-04-28 17:02:21 +00001281 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1282 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Dan Gohman23ea06d2008-05-01 19:13:24 +00001283 if (SimplifyDemandedBits(I->getOperand(0), AllOnes,
1284 KnownZero2, KnownOne2, Depth+1))
1285 return true;
1286
Dan Gohmanbec16052008-04-28 17:02:21 +00001287 uint32_t Leaders = KnownZero2.countLeadingOnes();
Dan Gohman23ea06d2008-05-01 19:13:24 +00001288 if (SimplifyDemandedBits(I->getOperand(1), AllOnes,
Dan Gohmanbec16052008-04-28 17:02:21 +00001289 KnownZero2, KnownOne2, Depth+1))
1290 return true;
1291
1292 Leaders = std::max(Leaders,
1293 KnownZero2.countLeadingOnes());
1294 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001295 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001296 }
Chris Lattner989ba312008-06-18 04:33:20 +00001297 case Instruction::Call:
1298 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1299 switch (II->getIntrinsicID()) {
1300 default: break;
1301 case Intrinsic::bswap: {
1302 // If the only bits demanded come from one byte of the bswap result,
1303 // just shift the input byte into position to eliminate the bswap.
1304 unsigned NLZ = DemandedMask.countLeadingZeros();
1305 unsigned NTZ = DemandedMask.countTrailingZeros();
1306
1307 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1308 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1309 // have 14 leading zeros, round to 8.
1310 NLZ &= ~7;
1311 NTZ &= ~7;
1312 // If we need exactly one byte, we can do this transformation.
1313 if (BitWidth-NLZ-NTZ == 8) {
1314 unsigned ResultBit = NTZ;
1315 unsigned InputBit = BitWidth-NTZ-8;
1316
1317 // Replace this with either a left or right shift to get the byte into
1318 // the right place.
1319 Instruction *NewVal;
1320 if (InputBit > ResultBit)
1321 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
1322 ConstantInt::get(I->getType(), InputBit-ResultBit));
1323 else
1324 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
1325 ConstantInt::get(I->getType(), ResultBit-InputBit));
1326 NewVal->takeName(I);
1327 InsertNewInstBefore(NewVal, *I);
1328 return UpdateValueUsesWith(I, NewVal);
1329 }
1330
1331 // TODO: Could compute known zero/one bits based on the input.
1332 break;
1333 }
1334 }
1335 }
Chris Lattner4946e222008-06-18 18:11:55 +00001336 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner989ba312008-06-18 04:33:20 +00001337 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001338 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001339
1340 // If the client is only demanding bits that we know, return the known
1341 // constant.
1342 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask)
1343 return UpdateValueUsesWith(I, ConstantInt::get(RHSKnownOne));
1344 return false;
1345}
1346
1347
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001348/// SimplifyDemandedVectorElts - The specified value produces a vector with
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001349/// 64 or fewer elements. DemandedElts contains the set of elements that are
1350/// actually used by the caller. This method analyzes which elements of the
1351/// operand are undef and returns that information in UndefElts.
1352///
1353/// If the information about demanded elements can be used to simplify the
1354/// operation, the operation is simplified, then the resultant value is
1355/// returned. This returns null if no change was made.
1356Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, uint64_t DemandedElts,
1357 uint64_t &UndefElts,
1358 unsigned Depth) {
1359 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
1360 assert(VWidth <= 64 && "Vector too wide to analyze!");
1361 uint64_t EltMask = ~0ULL >> (64-VWidth);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001362 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001363
1364 if (isa<UndefValue>(V)) {
1365 // If the entire vector is undefined, just return this info.
1366 UndefElts = EltMask;
1367 return 0;
1368 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1369 UndefElts = EltMask;
1370 return UndefValue::get(V->getType());
1371 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001372
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001373 UndefElts = 0;
1374 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1375 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1376 Constant *Undef = UndefValue::get(EltTy);
1377
1378 std::vector<Constant*> Elts;
1379 for (unsigned i = 0; i != VWidth; ++i)
1380 if (!(DemandedElts & (1ULL << i))) { // If not demanded, set to undef.
1381 Elts.push_back(Undef);
1382 UndefElts |= (1ULL << i);
1383 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1384 Elts.push_back(Undef);
1385 UndefElts |= (1ULL << i);
1386 } else { // Otherwise, defined.
1387 Elts.push_back(CP->getOperand(i));
1388 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001389
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001390 // If we changed the constant, return it.
1391 Constant *NewCP = ConstantVector::get(Elts);
1392 return NewCP != CP ? NewCP : 0;
1393 } else if (isa<ConstantAggregateZero>(V)) {
1394 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1395 // set to undef.
Mon P Wang927daf52008-11-06 22:52:21 +00001396
1397 // Check if this is identity. If so, return 0 since we are not simplifying
1398 // anything.
1399 if (DemandedElts == ((1ULL << VWidth) -1))
1400 return 0;
1401
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001402 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
1403 Constant *Zero = Constant::getNullValue(EltTy);
1404 Constant *Undef = UndefValue::get(EltTy);
1405 std::vector<Constant*> Elts;
1406 for (unsigned i = 0; i != VWidth; ++i)
1407 Elts.push_back((DemandedElts & (1ULL << i)) ? Zero : Undef);
1408 UndefElts = DemandedElts ^ EltMask;
1409 return ConstantVector::get(Elts);
1410 }
1411
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001412 // Limit search depth.
1413 if (Depth == 10)
1414 return false;
1415
1416 // If multiple users are using the root value, procede with
1417 // simplification conservatively assuming that all elements
1418 // are needed.
1419 if (!V->hasOneUse()) {
1420 // Quit if we find multiple users of a non-root value though.
1421 // They'll be handled when it's their turn to be visited by
1422 // the main instcombine process.
1423 if (Depth != 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001424 // TODO: Just compute the UndefElts information recursively.
1425 return false;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001426
1427 // Conservatively assume that all elements are needed.
1428 DemandedElts = EltMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001429 }
1430
1431 Instruction *I = dyn_cast<Instruction>(V);
1432 if (!I) return false; // Only analyze instructions.
1433
1434 bool MadeChange = false;
1435 uint64_t UndefElts2;
1436 Value *TmpV;
1437 switch (I->getOpcode()) {
1438 default: break;
1439
1440 case Instruction::InsertElement: {
1441 // If this is a variable index, we don't know which element it overwrites.
1442 // demand exactly the same input as we produce.
1443 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1444 if (Idx == 0) {
1445 // Note that we can't propagate undef elt info, because we don't know
1446 // which elt is getting updated.
1447 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1448 UndefElts2, Depth+1);
1449 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1450 break;
1451 }
1452
1453 // If this is inserting an element that isn't demanded, remove this
1454 // insertelement.
1455 unsigned IdxNo = Idx->getZExtValue();
1456 if (IdxNo >= VWidth || (DemandedElts & (1ULL << IdxNo)) == 0)
1457 return AddSoonDeadInstToWorklist(*I, 0);
1458
1459 // Otherwise, the element inserted overwrites whatever was there, so the
1460 // input demanded set is simpler than the output set.
1461 TmpV = SimplifyDemandedVectorElts(I->getOperand(0),
1462 DemandedElts & ~(1ULL << IdxNo),
1463 UndefElts, Depth+1);
1464 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1465
1466 // The inserted element is defined.
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001467 UndefElts &= ~(1ULL << IdxNo);
1468 break;
1469 }
1470 case Instruction::ShuffleVector: {
1471 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001472 uint64_t LHSVWidth =
1473 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001474 uint64_t LeftDemanded = 0, RightDemanded = 0;
1475 for (unsigned i = 0; i < VWidth; i++) {
1476 if (DemandedElts & (1ULL << i)) {
1477 unsigned MaskVal = Shuffle->getMaskValue(i);
1478 if (MaskVal != -1u) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001479 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001480 "shufflevector mask index out of range!");
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001481 if (MaskVal < LHSVWidth)
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001482 LeftDemanded |= 1ULL << MaskVal;
1483 else
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001484 RightDemanded |= 1ULL << (MaskVal - LHSVWidth);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001485 }
1486 }
1487 }
1488
1489 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
1490 UndefElts2, Depth+1);
1491 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1492
1493 uint64_t UndefElts3;
1494 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1495 UndefElts3, Depth+1);
1496 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1497
1498 bool NewUndefElts = false;
1499 for (unsigned i = 0; i < VWidth; i++) {
1500 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohman24f6ee22008-09-10 01:09:32 +00001501 if (MaskVal == -1u) {
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001502 uint64_t NewBit = 1ULL << i;
1503 UndefElts |= NewBit;
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001504 } else if (MaskVal < LHSVWidth) {
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001505 uint64_t NewBit = ((UndefElts2 >> MaskVal) & 1) << i;
1506 NewUndefElts |= NewBit;
1507 UndefElts |= NewBit;
1508 } else {
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001509 uint64_t NewBit = ((UndefElts3 >> (MaskVal - LHSVWidth)) & 1) << i;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001510 NewUndefElts |= NewBit;
1511 UndefElts |= NewBit;
1512 }
1513 }
1514
1515 if (NewUndefElts) {
1516 // Add additional discovered undefs.
1517 std::vector<Constant*> Elts;
1518 for (unsigned i = 0; i < VWidth; ++i) {
1519 if (UndefElts & (1ULL << i))
1520 Elts.push_back(UndefValue::get(Type::Int32Ty));
1521 else
1522 Elts.push_back(ConstantInt::get(Type::Int32Ty,
1523 Shuffle->getMaskValue(i)));
1524 }
1525 I->setOperand(2, ConstantVector::get(Elts));
1526 MadeChange = true;
1527 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001528 break;
1529 }
1530 case Instruction::BitCast: {
1531 // Vector->vector casts only.
1532 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1533 if (!VTy) break;
1534 unsigned InVWidth = VTy->getNumElements();
1535 uint64_t InputDemandedElts = 0;
1536 unsigned Ratio;
1537
1538 if (VWidth == InVWidth) {
1539 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1540 // elements as are demanded of us.
1541 Ratio = 1;
1542 InputDemandedElts = DemandedElts;
1543 } else if (VWidth > InVWidth) {
1544 // Untested so far.
1545 break;
1546
1547 // If there are more elements in the result than there are in the source,
1548 // then an input element is live if any of the corresponding output
1549 // elements are live.
1550 Ratio = VWidth/InVWidth;
1551 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
1552 if (DemandedElts & (1ULL << OutIdx))
1553 InputDemandedElts |= 1ULL << (OutIdx/Ratio);
1554 }
1555 } else {
1556 // Untested so far.
1557 break;
1558
1559 // If there are more elements in the source than there are in the result,
1560 // then an input element is live if the corresponding output element is
1561 // live.
1562 Ratio = InVWidth/VWidth;
1563 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1564 if (DemandedElts & (1ULL << InIdx/Ratio))
1565 InputDemandedElts |= 1ULL << InIdx;
1566 }
1567
1568 // div/rem demand all inputs, because they don't want divide by zero.
1569 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1570 UndefElts2, Depth+1);
1571 if (TmpV) {
1572 I->setOperand(0, TmpV);
1573 MadeChange = true;
1574 }
1575
1576 UndefElts = UndefElts2;
1577 if (VWidth > InVWidth) {
1578 assert(0 && "Unimp");
1579 // If there are more elements in the result than there are in the source,
1580 // then an output element is undef if the corresponding input element is
1581 // undef.
1582 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
1583 if (UndefElts2 & (1ULL << (OutIdx/Ratio)))
1584 UndefElts |= 1ULL << OutIdx;
1585 } else if (VWidth < InVWidth) {
1586 assert(0 && "Unimp");
1587 // If there are more elements in the source than there are in the result,
1588 // then a result element is undef if all of the corresponding input
1589 // elements are undef.
1590 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1591 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
1592 if ((UndefElts2 & (1ULL << InIdx)) == 0) // Not undef?
1593 UndefElts &= ~(1ULL << (InIdx/Ratio)); // Clear undef bit.
1594 }
1595 break;
1596 }
1597 case Instruction::And:
1598 case Instruction::Or:
1599 case Instruction::Xor:
1600 case Instruction::Add:
1601 case Instruction::Sub:
1602 case Instruction::Mul:
1603 // div/rem demand all inputs, because they don't want divide by zero.
1604 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1605 UndefElts, Depth+1);
1606 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1607 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1608 UndefElts2, Depth+1);
1609 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1610
1611 // Output elements are undefined if both are undefined. Consider things
1612 // like undef&0. The result is known zero, not undef.
1613 UndefElts &= UndefElts2;
1614 break;
1615
1616 case Instruction::Call: {
1617 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1618 if (!II) break;
1619 switch (II->getIntrinsicID()) {
1620 default: break;
1621
1622 // Binary vector operations that work column-wise. A dest element is a
1623 // function of the corresponding input elements from the two inputs.
1624 case Intrinsic::x86_sse_sub_ss:
1625 case Intrinsic::x86_sse_mul_ss:
1626 case Intrinsic::x86_sse_min_ss:
1627 case Intrinsic::x86_sse_max_ss:
1628 case Intrinsic::x86_sse2_sub_sd:
1629 case Intrinsic::x86_sse2_mul_sd:
1630 case Intrinsic::x86_sse2_min_sd:
1631 case Intrinsic::x86_sse2_max_sd:
1632 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1633 UndefElts, Depth+1);
1634 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1635 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1636 UndefElts2, Depth+1);
1637 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1638
1639 // If only the low elt is demanded and this is a scalarizable intrinsic,
1640 // scalarize it now.
1641 if (DemandedElts == 1) {
1642 switch (II->getIntrinsicID()) {
1643 default: break;
1644 case Intrinsic::x86_sse_sub_ss:
1645 case Intrinsic::x86_sse_mul_ss:
1646 case Intrinsic::x86_sse2_sub_sd:
1647 case Intrinsic::x86_sse2_mul_sd:
1648 // TODO: Lower MIN/MAX/ABS/etc
1649 Value *LHS = II->getOperand(1);
1650 Value *RHS = II->getOperand(2);
1651 // Extract the element as scalars.
1652 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1653 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1654
1655 switch (II->getIntrinsicID()) {
1656 default: assert(0 && "Case stmts out of sync!");
1657 case Intrinsic::x86_sse_sub_ss:
1658 case Intrinsic::x86_sse2_sub_sd:
Gabor Greifa645dd32008-05-16 19:29:10 +00001659 TmpV = InsertNewInstBefore(BinaryOperator::CreateSub(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001660 II->getName()), *II);
1661 break;
1662 case Intrinsic::x86_sse_mul_ss:
1663 case Intrinsic::x86_sse2_mul_sd:
Gabor Greifa645dd32008-05-16 19:29:10 +00001664 TmpV = InsertNewInstBefore(BinaryOperator::CreateMul(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001665 II->getName()), *II);
1666 break;
1667 }
1668
1669 Instruction *New =
Gabor Greifd6da1d02008-04-06 20:25:17 +00001670 InsertElementInst::Create(UndefValue::get(II->getType()), TmpV, 0U,
1671 II->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001672 InsertNewInstBefore(New, *II);
1673 AddSoonDeadInstToWorklist(*II, 0);
1674 return New;
1675 }
1676 }
1677
1678 // Output elements are undefined if both are undefined. Consider things
1679 // like undef&0. The result is known zero, not undef.
1680 UndefElts &= UndefElts2;
1681 break;
1682 }
1683 break;
1684 }
1685 }
1686 return MadeChange ? I : 0;
1687}
1688
Dan Gohman5d56fd42008-05-19 22:14:15 +00001689
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001690/// AssociativeOpt - Perform an optimization on an associative operator. This
1691/// function is designed to check a chain of associative operators for a
1692/// potential to apply a certain optimization. Since the optimization may be
1693/// applicable if the expression was reassociated, this checks the chain, then
1694/// reassociates the expression as necessary to expose the optimization
1695/// opportunity. This makes use of a special Functor, which must define
1696/// 'shouldApply' and 'apply' methods.
1697///
1698template<typename Functor>
Dan Gohmand8bcf5b2008-05-20 01:14:05 +00001699static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001700 unsigned Opcode = Root.getOpcode();
1701 Value *LHS = Root.getOperand(0);
1702
1703 // Quick check, see if the immediate LHS matches...
1704 if (F.shouldApply(LHS))
1705 return F.apply(Root);
1706
1707 // Otherwise, if the LHS is not of the same opcode as the root, return.
1708 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1709 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1710 // Should we apply this transform to the RHS?
1711 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1712
1713 // If not to the RHS, check to see if we should apply to the LHS...
1714 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1715 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1716 ShouldApply = true;
1717 }
1718
1719 // If the functor wants to apply the optimization to the RHS of LHSI,
1720 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1721 if (ShouldApply) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001722 // Now all of the instructions are in the current basic block, go ahead
1723 // and perform the reassociation.
1724 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1725
1726 // First move the selected RHS to the LHS of the root...
1727 Root.setOperand(0, LHSI->getOperand(1));
1728
1729 // Make what used to be the LHS of the root be the user of the root...
1730 Value *ExtraOperand = TmpLHSI->getOperand(1);
1731 if (&Root == TmpLHSI) {
1732 Root.replaceAllUsesWith(Constant::getNullValue(TmpLHSI->getType()));
1733 return 0;
1734 }
1735 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1736 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001737 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001738 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001739 ARI = Root;
1740
1741 // Now propagate the ExtraOperand down the chain of instructions until we
1742 // get to LHSI.
1743 while (TmpLHSI != LHSI) {
1744 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1745 // Move the instruction to immediately before the chain we are
1746 // constructing to avoid breaking dominance properties.
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001747 NextLHSI->moveBefore(ARI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001748 ARI = NextLHSI;
1749
1750 Value *NextOp = NextLHSI->getOperand(1);
1751 NextLHSI->setOperand(1, ExtraOperand);
1752 TmpLHSI = NextLHSI;
1753 ExtraOperand = NextOp;
1754 }
1755
1756 // Now that the instructions are reassociated, have the functor perform
1757 // the transformation...
1758 return F.apply(Root);
1759 }
1760
1761 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1762 }
1763 return 0;
1764}
1765
Dan Gohman089efff2008-05-13 00:00:25 +00001766namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001767
Nick Lewycky27f6c132008-05-23 04:34:58 +00001768// AddRHS - Implements: X + X --> X << 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001769struct AddRHS {
1770 Value *RHS;
1771 AddRHS(Value *rhs) : RHS(rhs) {}
1772 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1773 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky27f6c132008-05-23 04:34:58 +00001774 return BinaryOperator::CreateShl(Add.getOperand(0),
1775 ConstantInt::get(Add.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001776 }
1777};
1778
1779// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1780// iff C1&C2 == 0
1781struct AddMaskingAnd {
1782 Constant *C2;
1783 AddMaskingAnd(Constant *c) : C2(c) {}
1784 bool shouldApply(Value *LHS) const {
1785 ConstantInt *C1;
1786 return match(LHS, m_And(m_Value(), m_ConstantInt(C1))) &&
1787 ConstantExpr::getAnd(C1, C2)->isNullValue();
1788 }
1789 Instruction *apply(BinaryOperator &Add) const {
Gabor Greifa645dd32008-05-16 19:29:10 +00001790 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001791 }
1792};
1793
Dan Gohman089efff2008-05-13 00:00:25 +00001794}
1795
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001796static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1797 InstCombiner *IC) {
1798 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedman722b4792008-11-30 21:09:11 +00001799 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001800 }
1801
1802 // Figure out if the constant is the left or the right argument.
1803 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1804 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1805
1806 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1807 if (ConstIsRHS)
1808 return ConstantExpr::get(I.getOpcode(), SOC, ConstOperand);
1809 return ConstantExpr::get(I.getOpcode(), ConstOperand, SOC);
1810 }
1811
1812 Value *Op0 = SO, *Op1 = ConstOperand;
1813 if (!ConstIsRHS)
1814 std::swap(Op0, Op1);
1815 Instruction *New;
1816 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001817 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001818 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001819 New = CmpInst::Create(CI->getOpcode(), CI->getPredicate(), Op0, Op1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001820 SO->getName()+".cmp");
1821 else {
1822 assert(0 && "Unknown binary instruction type!");
1823 abort();
1824 }
1825 return IC->InsertNewInstBefore(New, I);
1826}
1827
1828// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1829// constant as the other operand, try to fold the binary operator into the
1830// select arguments. This also works for Cast instructions, which obviously do
1831// not have a second operand.
1832static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1833 InstCombiner *IC) {
1834 // Don't modify shared select instructions
1835 if (!SI->hasOneUse()) return 0;
1836 Value *TV = SI->getOperand(1);
1837 Value *FV = SI->getOperand(2);
1838
1839 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1840 // Bool selects with constant operands can be folded to logical ops.
1841 if (SI->getType() == Type::Int1Ty) return 0;
1842
1843 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1844 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1845
Gabor Greifd6da1d02008-04-06 20:25:17 +00001846 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1847 SelectFalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001848 }
1849 return 0;
1850}
1851
1852
1853/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1854/// node as operand #0, see if we can fold the instruction into the PHI (which
1855/// is only possible if all operands to the PHI are constants).
1856Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1857 PHINode *PN = cast<PHINode>(I.getOperand(0));
1858 unsigned NumPHIValues = PN->getNumIncomingValues();
1859 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1860
1861 // Check to see if all of the operands of the PHI are constants. If there is
1862 // one non-constant value, remember the BB it is. If there is more than one
1863 // or if *it* is a PHI, bail out.
1864 BasicBlock *NonConstBB = 0;
1865 for (unsigned i = 0; i != NumPHIValues; ++i)
1866 if (!isa<Constant>(PN->getIncomingValue(i))) {
1867 if (NonConstBB) return 0; // More than one non-const value.
1868 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1869 NonConstBB = PN->getIncomingBlock(i);
1870
1871 // If the incoming non-constant value is in I's block, we have an infinite
1872 // loop.
1873 if (NonConstBB == I.getParent())
1874 return 0;
1875 }
1876
1877 // If there is exactly one non-constant value, we can insert a copy of the
1878 // operation in that block. However, if this is a critical edge, we would be
1879 // inserting the computation one some other paths (e.g. inside a loop). Only
1880 // do this if the pred block is unconditionally branching into the phi block.
1881 if (NonConstBB) {
1882 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1883 if (!BI || !BI->isUnconditional()) return 0;
1884 }
1885
1886 // Okay, we can do the transformation: create the new PHI node.
Gabor Greifd6da1d02008-04-06 20:25:17 +00001887 PHINode *NewPN = PHINode::Create(I.getType(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001888 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1889 InsertNewInstBefore(NewPN, *PN);
1890 NewPN->takeName(PN);
1891
1892 // Next, add all of the operands to the PHI.
1893 if (I.getNumOperands() == 2) {
1894 Constant *C = cast<Constant>(I.getOperand(1));
1895 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00001896 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001897 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1898 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
1899 InV = ConstantExpr::getCompare(CI->getPredicate(), InC, C);
1900 else
1901 InV = ConstantExpr::get(I.getOpcode(), InC, C);
1902 } else {
1903 assert(PN->getIncomingBlock(i) == NonConstBB);
1904 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001905 InV = BinaryOperator::Create(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001906 PN->getIncomingValue(i), C, "phitmp",
1907 NonConstBB->getTerminator());
1908 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001909 InV = CmpInst::Create(CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001910 CI->getPredicate(),
1911 PN->getIncomingValue(i), C, "phitmp",
1912 NonConstBB->getTerminator());
1913 else
1914 assert(0 && "Unknown binop!");
1915
1916 AddToWorkList(cast<Instruction>(InV));
1917 }
1918 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1919 }
1920 } else {
1921 CastInst *CI = cast<CastInst>(&I);
1922 const Type *RetTy = CI->getType();
1923 for (unsigned i = 0; i != NumPHIValues; ++i) {
1924 Value *InV;
1925 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
1926 InV = ConstantExpr::getCast(CI->getOpcode(), InC, RetTy);
1927 } else {
1928 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greifa645dd32008-05-16 19:29:10 +00001929 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001930 I.getType(), "phitmp",
1931 NonConstBB->getTerminator());
1932 AddToWorkList(cast<Instruction>(InV));
1933 }
1934 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
1935 }
1936 }
1937 return ReplaceInstUsesWith(I, NewPN);
1938}
1939
Chris Lattner55476162008-01-29 06:52:45 +00001940
Chris Lattner3554f972008-05-20 05:46:13 +00001941/// WillNotOverflowSignedAdd - Return true if we can prove that:
1942/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
1943/// This basically requires proving that the add in the original type would not
1944/// overflow to change the sign bit or have a carry out.
1945bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
1946 // There are different heuristics we can use for this. Here are some simple
1947 // ones.
1948
1949 // Add has the property that adding any two 2's complement numbers can only
1950 // have one carry bit which can change a sign. As such, if LHS and RHS each
1951 // have at least two sign bits, we know that the addition of the two values will
1952 // sign extend fine.
1953 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
1954 return true;
1955
1956
1957 // If one of the operands only has one non-zero bit, and if the other operand
1958 // has a known-zero bit in a more significant place than it (not including the
1959 // sign bit) the ripple may go up to and fill the zero, but won't change the
1960 // sign. For example, (X & ~4) + 1.
1961
1962 // TODO: Implement.
1963
1964 return false;
1965}
1966
Chris Lattner55476162008-01-29 06:52:45 +00001967
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001968Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
1969 bool Changed = SimplifyCommutative(I);
1970 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
1971
1972 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
1973 // X + undef -> undef
1974 if (isa<UndefValue>(RHS))
1975 return ReplaceInstUsesWith(I, RHS);
1976
1977 // X + 0 --> X
1978 if (!I.getType()->isFPOrFPVector()) { // NOTE: -0 + +0 = +0.
1979 if (RHSC->isNullValue())
1980 return ReplaceInstUsesWith(I, LHS);
1981 } else if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Dale Johannesen2fc20782007-09-14 22:26:36 +00001982 if (CFP->isExactlyValue(ConstantFP::getNegativeZero
1983 (I.getType())->getValueAPF()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001984 return ReplaceInstUsesWith(I, LHS);
1985 }
1986
1987 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
1988 // X + (signbit) --> X ^ signbit
1989 const APInt& Val = CI->getValue();
1990 uint32_t BitWidth = Val.getBitWidth();
1991 if (Val == APInt::getSignBit(BitWidth))
Gabor Greifa645dd32008-05-16 19:29:10 +00001992 return BinaryOperator::CreateXor(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001993
1994 // See if SimplifyDemandedBits can simplify this. This handles stuff like
1995 // (X & 254)+1 -> (X&254)|1
1996 if (!isa<VectorType>(I.getType())) {
1997 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
1998 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
1999 KnownZero, KnownOne))
2000 return &I;
2001 }
Dan Gohman35b76162008-10-30 20:40:10 +00002002
2003 // zext(i1) - 1 -> select i1, 0, -1
2004 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2005 if (CI->isAllOnesValue() &&
2006 ZI->getOperand(0)->getType() == Type::Int1Ty)
2007 return SelectInst::Create(ZI->getOperand(0),
2008 Constant::getNullValue(I.getType()),
2009 ConstantInt::getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002010 }
2011
2012 if (isa<PHINode>(LHS))
2013 if (Instruction *NV = FoldOpIntoPhi(I))
2014 return NV;
2015
2016 ConstantInt *XorRHS = 0;
2017 Value *XorLHS = 0;
2018 if (isa<ConstantInt>(RHSC) &&
2019 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)))) {
2020 uint32_t TySizeBits = I.getType()->getPrimitiveSizeInBits();
2021 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2022
2023 uint32_t Size = TySizeBits / 2;
2024 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2025 APInt CFF80Val(-C0080Val);
2026 do {
2027 if (TySizeBits > Size) {
2028 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2029 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2030 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2031 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2032 // This is a sign extend if the top bits are known zero.
2033 if (!MaskedValueIsZero(XorLHS,
2034 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2035 Size = 0; // Not a sign ext, but can't be any others either.
2036 break;
2037 }
2038 }
2039 Size >>= 1;
2040 C0080Val = APIntOps::lshr(C0080Val, Size);
2041 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2042 } while (Size >= 1);
2043
2044 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattnerdeef1a72008-05-19 20:25:04 +00002045 // with funny bit widths then this switch statement should be removed. It
2046 // is just here to get the size of the "middle" type back up to something
2047 // that the back ends can handle.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002048 const Type *MiddleType = 0;
2049 switch (Size) {
2050 default: break;
2051 case 32: MiddleType = Type::Int32Ty; break;
2052 case 16: MiddleType = Type::Int16Ty; break;
2053 case 8: MiddleType = Type::Int8Ty; break;
2054 }
2055 if (MiddleType) {
2056 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2057 InsertNewInstBefore(NewTrunc, I);
2058 return new SExtInst(NewTrunc, I.getType(), I.getName());
2059 }
2060 }
2061 }
2062
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002063 if (I.getType() == Type::Int1Ty)
2064 return BinaryOperator::CreateXor(LHS, RHS);
2065
Nick Lewycky4d474cd2008-05-23 04:39:38 +00002066 // X + X --> X << 1
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002067 if (I.getType()->isInteger()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002068 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS))) return Result;
2069
2070 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2071 if (RHSI->getOpcode() == Instruction::Sub)
2072 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2073 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2074 }
2075 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2076 if (LHSI->getOpcode() == Instruction::Sub)
2077 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2078 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2079 }
2080 }
2081
2082 // -A + B --> B - A
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002083 // -A + -B --> -(A + B)
2084 if (Value *LHSV = dyn_castNegVal(LHS)) {
Chris Lattner322a9192008-02-18 17:50:16 +00002085 if (LHS->getType()->isIntOrIntVector()) {
2086 if (Value *RHSV = dyn_castNegVal(RHS)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002087 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattner322a9192008-02-18 17:50:16 +00002088 InsertNewInstBefore(NewAdd, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002089 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattner322a9192008-02-18 17:50:16 +00002090 }
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002091 }
2092
Gabor Greifa645dd32008-05-16 19:29:10 +00002093 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002094 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002095
2096 // A + -B --> A - B
2097 if (!isa<Constant>(RHS))
2098 if (Value *V = dyn_castNegVal(RHS))
Gabor Greifa645dd32008-05-16 19:29:10 +00002099 return BinaryOperator::CreateSub(LHS, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002100
2101
2102 ConstantInt *C2;
2103 if (Value *X = dyn_castFoldableMul(LHS, C2)) {
2104 if (X == RHS) // X*C + X --> X * (C+1)
Gabor Greifa645dd32008-05-16 19:29:10 +00002105 return BinaryOperator::CreateMul(RHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002106
2107 // X*C1 + X*C2 --> X * (C1+C2)
2108 ConstantInt *C1;
2109 if (X == dyn_castFoldableMul(RHS, C1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002110 return BinaryOperator::CreateMul(X, Add(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002111 }
2112
2113 // X + X*C --> X * (C+1)
2114 if (dyn_castFoldableMul(RHS, C2) == LHS)
Gabor Greifa645dd32008-05-16 19:29:10 +00002115 return BinaryOperator::CreateMul(LHS, AddOne(C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002116
2117 // X + ~X --> -1 since ~X = -X-1
2118 if (dyn_castNotVal(LHS) == RHS || dyn_castNotVal(RHS) == LHS)
2119 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
2120
2121
2122 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
2123 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2))))
2124 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2)))
2125 return R;
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002126
2127 // A+B --> A|B iff A and B have no bits set in common.
2128 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2129 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2130 APInt LHSKnownOne(IT->getBitWidth(), 0);
2131 APInt LHSKnownZero(IT->getBitWidth(), 0);
2132 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2133 if (LHSKnownZero != 0) {
2134 APInt RHSKnownOne(IT->getBitWidth(), 0);
2135 APInt RHSKnownZero(IT->getBitWidth(), 0);
2136 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2137
2138 // No bits in common -> bitwise or.
Chris Lattner130443c2008-05-19 20:03:53 +00002139 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002140 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002141 }
2142 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002143
Nick Lewycky83598a72008-02-03 07:42:09 +00002144 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky5d03b512008-02-03 08:19:11 +00002145 if (I.getType()->isIntOrIntVector()) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002146 Value *W, *X, *Y, *Z;
2147 if (match(LHS, m_Mul(m_Value(W), m_Value(X))) &&
2148 match(RHS, m_Mul(m_Value(Y), m_Value(Z)))) {
2149 if (W != Y) {
2150 if (W == Z) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002151 std::swap(Y, Z);
Nick Lewycky83598a72008-02-03 07:42:09 +00002152 } else if (Y == X) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002153 std::swap(W, X);
2154 } else if (X == Z) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002155 std::swap(Y, Z);
2156 std::swap(W, X);
2157 }
2158 }
2159
2160 if (W == Y) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002161 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewycky83598a72008-02-03 07:42:09 +00002162 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002163 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewycky83598a72008-02-03 07:42:09 +00002164 }
2165 }
2166 }
2167
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002168 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2169 Value *X = 0;
2170 if (match(LHS, m_Not(m_Value(X)))) // ~X + C --> (C-1) - X
Gabor Greifa645dd32008-05-16 19:29:10 +00002171 return BinaryOperator::CreateSub(SubOne(CRHS), X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002172
2173 // (X & FF00) + xx00 -> (X+xx00) & FF00
2174 if (LHS->hasOneUse() && match(LHS, m_And(m_Value(X), m_ConstantInt(C2)))) {
2175 Constant *Anded = And(CRHS, C2);
2176 if (Anded == CRHS) {
2177 // See if all bits from the first bit set in the Add RHS up are included
2178 // in the mask. First, get the rightmost bit.
2179 const APInt& AddRHSV = CRHS->getValue();
2180
2181 // Form a mask of all bits from the lowest bit added through the top.
2182 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2183
2184 // See if the and mask includes all of these bits.
2185 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2186
2187 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2188 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greifa645dd32008-05-16 19:29:10 +00002189 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002190 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002191 return BinaryOperator::CreateAnd(NewAdd, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002192 }
2193 }
2194 }
2195
2196 // Try to fold constant add into select arguments.
2197 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2198 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2199 return R;
2200 }
2201
2202 // add (cast *A to intptrtype) B ->
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002203 // cast (GEP (cast *A to sbyte*) B) --> intptrtype
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002204 {
2205 CastInst *CI = dyn_cast<CastInst>(LHS);
2206 Value *Other = RHS;
2207 if (!CI) {
2208 CI = dyn_cast<CastInst>(RHS);
2209 Other = LHS;
2210 }
2211 if (CI && CI->getType()->isSized() &&
2212 (CI->getType()->getPrimitiveSizeInBits() ==
2213 TD->getIntPtrType()->getPrimitiveSizeInBits())
2214 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00002215 unsigned AS =
2216 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +00002217 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
2218 PointerType::get(Type::Int8Ty, AS), I);
Gabor Greifd6da1d02008-04-06 20:25:17 +00002219 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002220 return new PtrToIntInst(I2, CI->getType());
2221 }
2222 }
Christopher Lamb244ec282007-12-18 09:34:41 +00002223
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002224 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb244ec282007-12-18 09:34:41 +00002225 {
2226 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002227 Value *A = RHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002228 if (!SI) {
2229 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002230 A = LHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002231 }
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002232 if (SI && SI->hasOneUse()) {
Christopher Lamb244ec282007-12-18 09:34:41 +00002233 Value *TV = SI->getTrueValue();
2234 Value *FV = SI->getFalseValue();
Chris Lattner641ea462008-11-16 04:46:19 +00002235 Value *N;
Christopher Lamb244ec282007-12-18 09:34:41 +00002236
2237 // Can we fold the add into the argument of the select?
2238 // We check both true and false select arguments for a matching subtract.
Chris Lattner641ea462008-11-16 04:46:19 +00002239 if (match(FV, m_Zero()) && match(TV, m_Sub(m_Value(N), m_Specific(A))))
2240 // Fold the add into the true select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002241 return SelectInst::Create(SI->getCondition(), N, A);
Chris Lattner641ea462008-11-16 04:46:19 +00002242 if (match(TV, m_Zero()) && match(FV, m_Sub(m_Value(N), m_Specific(A))))
2243 // Fold the add into the false select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002244 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb244ec282007-12-18 09:34:41 +00002245 }
2246 }
Chris Lattner55476162008-01-29 06:52:45 +00002247
2248 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2249 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2250 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2251 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002252
Chris Lattner3554f972008-05-20 05:46:13 +00002253 // Check for (add (sext x), y), see if we can merge this into an
2254 // integer add followed by a sext.
2255 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2256 // (add (sext x), cst) --> (sext (add x, cst'))
2257 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2258 Constant *CI =
2259 ConstantExpr::getTrunc(RHSC, LHSConv->getOperand(0)->getType());
2260 if (LHSConv->hasOneUse() &&
2261 ConstantExpr::getSExt(CI, I.getType()) == RHSC &&
2262 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2263 // Insert the new, smaller add.
2264 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2265 CI, "addconv");
2266 InsertNewInstBefore(NewAdd, I);
2267 return new SExtInst(NewAdd, I.getType());
2268 }
2269 }
2270
2271 // (add (sext x), (sext y)) --> (sext (add int x, y))
2272 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2273 // Only do this if x/y have the same type, if at last one of them has a
2274 // single use (so we don't increase the number of sexts), and if the
2275 // integer add will not overflow.
2276 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2277 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2278 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2279 RHSConv->getOperand(0))) {
2280 // Insert the new integer add.
2281 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2282 RHSConv->getOperand(0),
2283 "addconv");
2284 InsertNewInstBefore(NewAdd, I);
2285 return new SExtInst(NewAdd, I.getType());
2286 }
2287 }
2288 }
2289
2290 // Check for (add double (sitofp x), y), see if we can merge this into an
2291 // integer add followed by a promotion.
2292 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2293 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2294 // ... if the constant fits in the integer value. This is useful for things
2295 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2296 // requires a constant pool load, and generally allows the add to be better
2297 // instcombined.
2298 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2299 Constant *CI =
2300 ConstantExpr::getFPToSI(CFP, LHSConv->getOperand(0)->getType());
2301 if (LHSConv->hasOneUse() &&
2302 ConstantExpr::getSIToFP(CI, I.getType()) == CFP &&
2303 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2304 // Insert the new integer add.
2305 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2306 CI, "addconv");
2307 InsertNewInstBefore(NewAdd, I);
2308 return new SIToFPInst(NewAdd, I.getType());
2309 }
2310 }
2311
2312 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2313 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2314 // Only do this if x/y have the same type, if at last one of them has a
2315 // single use (so we don't increase the number of int->fp conversions),
2316 // and if the integer add will not overflow.
2317 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2318 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2319 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2320 RHSConv->getOperand(0))) {
2321 // Insert the new integer add.
2322 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2323 RHSConv->getOperand(0),
2324 "addconv");
2325 InsertNewInstBefore(NewAdd, I);
2326 return new SIToFPInst(NewAdd, I.getType());
2327 }
2328 }
2329 }
2330
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002331 return Changed ? &I : 0;
2332}
2333
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002334Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2335 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2336
Chris Lattner27fbef42008-07-17 06:07:20 +00002337 if (Op0 == Op1 && // sub X, X -> 0
2338 !I.getType()->isFPOrFPVector())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002339 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2340
2341 // If this is a 'B = x-(-A)', change to B = x+A...
2342 if (Value *V = dyn_castNegVal(Op1))
Gabor Greifa645dd32008-05-16 19:29:10 +00002343 return BinaryOperator::CreateAdd(Op0, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002344
2345 if (isa<UndefValue>(Op0))
2346 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2347 if (isa<UndefValue>(Op1))
2348 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2349
2350 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2351 // Replace (-1 - A) with (~A)...
2352 if (C->isAllOnesValue())
Gabor Greifa645dd32008-05-16 19:29:10 +00002353 return BinaryOperator::CreateNot(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002354
2355 // C - ~X == X + (1+C)
2356 Value *X = 0;
2357 if (match(Op1, m_Not(m_Value(X))))
Gabor Greifa645dd32008-05-16 19:29:10 +00002358 return BinaryOperator::CreateAdd(X, AddOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002359
2360 // -(X >>u 31) -> (X >>s 31)
2361 // -(X >>s 31) -> (X >>u 31)
2362 if (C->isZero()) {
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002363 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002364 if (SI->getOpcode() == Instruction::LShr) {
2365 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2366 // Check to see if we are shifting out everything but the sign bit.
2367 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2368 SI->getType()->getPrimitiveSizeInBits()-1) {
2369 // Ok, the transformation is safe. Insert AShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002370 return BinaryOperator::Create(Instruction::AShr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002371 SI->getOperand(0), CU, SI->getName());
2372 }
2373 }
2374 }
2375 else if (SI->getOpcode() == Instruction::AShr) {
2376 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2377 // Check to see if we are shifting out everything but the sign bit.
2378 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2379 SI->getType()->getPrimitiveSizeInBits()-1) {
2380 // Ok, the transformation is safe. Insert LShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002381 return BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002382 SI->getOperand(0), CU, SI->getName());
2383 }
2384 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002385 }
2386 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002387 }
2388
2389 // Try to fold constant sub into select arguments.
2390 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2391 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2392 return R;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002393 }
2394
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002395 if (I.getType() == Type::Int1Ty)
2396 return BinaryOperator::CreateXor(Op0, Op1);
2397
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002398 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2399 if (Op1I->getOpcode() == Instruction::Add &&
2400 !Op0->getType()->isFPOrFPVector()) {
2401 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002402 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002403 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002404 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002405 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2406 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2407 // C1-(X+C2) --> (C1-C2)-X
Gabor Greifa645dd32008-05-16 19:29:10 +00002408 return BinaryOperator::CreateSub(Subtract(CI1, CI2),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002409 Op1I->getOperand(0));
2410 }
2411 }
2412
2413 if (Op1I->hasOneUse()) {
2414 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2415 // is not used by anyone else...
2416 //
2417 if (Op1I->getOpcode() == Instruction::Sub &&
2418 !Op1I->getType()->isFPOrFPVector()) {
2419 // Swap the two operands of the subexpr...
2420 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2421 Op1I->setOperand(0, IIOp1);
2422 Op1I->setOperand(1, IIOp0);
2423
2424 // Create the new top level add instruction...
Gabor Greifa645dd32008-05-16 19:29:10 +00002425 return BinaryOperator::CreateAdd(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002426 }
2427
2428 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2429 //
2430 if (Op1I->getOpcode() == Instruction::And &&
2431 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2432 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2433
2434 Value *NewNot =
Gabor Greifa645dd32008-05-16 19:29:10 +00002435 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2436 return BinaryOperator::CreateAnd(Op0, NewNot);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002437 }
2438
2439 // 0 - (X sdiv C) -> (X sdiv -C)
2440 if (Op1I->getOpcode() == Instruction::SDiv)
2441 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2442 if (CSI->isZero())
2443 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002444 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002445 ConstantExpr::getNeg(DivRHS));
2446
2447 // X - X*C --> X * (1-C)
2448 ConstantInt *C2 = 0;
2449 if (dyn_castFoldableMul(Op1I, C2) == Op0) {
2450 Constant *CP1 = Subtract(ConstantInt::get(I.getType(), 1), C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00002451 return BinaryOperator::CreateMul(Op0, CP1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002452 }
2453 }
2454 }
2455
2456 if (!Op0->getType()->isFPOrFPVector())
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002457 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002458 if (Op0I->getOpcode() == Instruction::Add) {
2459 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2460 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2461 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2462 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2463 } else if (Op0I->getOpcode() == Instruction::Sub) {
2464 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002465 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002466 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002467 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002468
2469 ConstantInt *C1;
2470 if (Value *X = dyn_castFoldableMul(Op0, C1)) {
2471 if (X == Op1) // X*C - X --> X * (C-1)
Gabor Greifa645dd32008-05-16 19:29:10 +00002472 return BinaryOperator::CreateMul(Op1, SubOne(C1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002473
2474 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
2475 if (X == dyn_castFoldableMul(Op1, C2))
Gabor Greifa645dd32008-05-16 19:29:10 +00002476 return BinaryOperator::CreateMul(X, Subtract(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002477 }
2478 return 0;
2479}
2480
2481/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2482/// comparison only checks the sign bit. If it only checks the sign bit, set
2483/// TrueIfSigned if the result of the comparison is true when the input value is
2484/// signed.
2485static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2486 bool &TrueIfSigned) {
2487 switch (pred) {
2488 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2489 TrueIfSigned = true;
2490 return RHS->isZero();
2491 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2492 TrueIfSigned = true;
2493 return RHS->isAllOnesValue();
2494 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2495 TrueIfSigned = false;
2496 return RHS->isAllOnesValue();
2497 case ICmpInst::ICMP_UGT:
2498 // True if LHS u> RHS and RHS == high-bit-mask - 1
2499 TrueIfSigned = true;
2500 return RHS->getValue() ==
2501 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2502 case ICmpInst::ICMP_UGE:
2503 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2504 TrueIfSigned = true;
Chris Lattner60813c22008-06-02 01:29:46 +00002505 return RHS->getValue().isSignBit();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002506 default:
2507 return false;
2508 }
2509}
2510
2511Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2512 bool Changed = SimplifyCommutative(I);
2513 Value *Op0 = I.getOperand(0);
2514
2515 if (isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
2516 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2517
2518 // Simplify mul instructions with a constant RHS...
2519 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2520 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2521
2522 // ((X << C1)*C2) == (X * (C2 << C1))
2523 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2524 if (SI->getOpcode() == Instruction::Shl)
2525 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002526 return BinaryOperator::CreateMul(SI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002527 ConstantExpr::getShl(CI, ShOp));
2528
2529 if (CI->isZero())
2530 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2531 if (CI->equalsInt(1)) // X * 1 == X
2532 return ReplaceInstUsesWith(I, Op0);
2533 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greifa645dd32008-05-16 19:29:10 +00002534 return BinaryOperator::CreateNeg(Op0, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002535
2536 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2537 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greifa645dd32008-05-16 19:29:10 +00002538 return BinaryOperator::CreateShl(Op0,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002539 ConstantInt::get(Op0->getType(), Val.logBase2()));
2540 }
2541 } else if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2542 if (Op1F->isNullValue())
2543 return ReplaceInstUsesWith(I, Op1);
2544
2545 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2546 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
Chris Lattner6297fc72008-08-11 22:06:05 +00002547 if (Op1F->isExactlyValue(1.0))
2548 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2549 } else if (isa<VectorType>(Op1->getType())) {
2550 if (isa<ConstantAggregateZero>(Op1))
2551 return ReplaceInstUsesWith(I, Op1);
Nick Lewycky94418732008-11-27 20:21:08 +00002552
2553 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2554 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
2555 return BinaryOperator::CreateNeg(Op0, I.getName());
2556
2557 // As above, vector X*splat(1.0) -> X in all defined cases.
2558 if (Constant *Splat = Op1V->getSplatValue()) {
2559 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2560 if (F->isExactlyValue(1.0))
2561 return ReplaceInstUsesWith(I, Op0);
2562 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2563 if (CI->equalsInt(1))
2564 return ReplaceInstUsesWith(I, Op0);
2565 }
2566 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002567 }
2568
2569 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2570 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner58194082008-05-18 04:11:26 +00002571 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002572 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greifa645dd32008-05-16 19:29:10 +00002573 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002574 Op1, "tmp");
2575 InsertNewInstBefore(Add, I);
2576 Value *C1C2 = ConstantExpr::getMul(Op1,
2577 cast<Constant>(Op0I->getOperand(1)));
Gabor Greifa645dd32008-05-16 19:29:10 +00002578 return BinaryOperator::CreateAdd(Add, C1C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002579
2580 }
2581
2582 // Try to fold constant mul into select arguments.
2583 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2584 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2585 return R;
2586
2587 if (isa<PHINode>(Op0))
2588 if (Instruction *NV = FoldOpIntoPhi(I))
2589 return NV;
2590 }
2591
2592 if (Value *Op0v = dyn_castNegVal(Op0)) // -X * -Y = X*Y
2593 if (Value *Op1v = dyn_castNegVal(I.getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002594 return BinaryOperator::CreateMul(Op0v, Op1v);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002595
Nick Lewycky1c246402008-11-21 07:33:58 +00002596 // (X / Y) * Y = X - (X % Y)
2597 // (X / Y) * -Y = (X % Y) - X
2598 {
2599 Value *Op1 = I.getOperand(1);
2600 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2601 if (!BO ||
2602 (BO->getOpcode() != Instruction::UDiv &&
2603 BO->getOpcode() != Instruction::SDiv)) {
2604 Op1 = Op0;
2605 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2606 }
2607 Value *Neg = dyn_castNegVal(Op1);
2608 if (BO && BO->hasOneUse() &&
2609 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2610 (BO->getOpcode() == Instruction::UDiv ||
2611 BO->getOpcode() == Instruction::SDiv)) {
2612 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2613
2614 Instruction *Rem;
2615 if (BO->getOpcode() == Instruction::UDiv)
2616 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2617 else
2618 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2619
2620 InsertNewInstBefore(Rem, I);
2621 Rem->takeName(BO);
2622
2623 if (Op1BO == Op1)
2624 return BinaryOperator::CreateSub(Op0BO, Rem);
2625 else
2626 return BinaryOperator::CreateSub(Rem, Op0BO);
2627 }
2628 }
2629
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002630 if (I.getType() == Type::Int1Ty)
2631 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2632
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002633 // If one of the operands of the multiply is a cast from a boolean value, then
2634 // we know the bool is either zero or one, so this is a 'masking' multiply.
2635 // See if we can simplify things based on how the boolean was originally
2636 // formed.
2637 CastInst *BoolCast = 0;
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002638 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002639 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2640 BoolCast = CI;
2641 if (!BoolCast)
2642 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2643 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2644 BoolCast = CI;
2645 if (BoolCast) {
2646 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2647 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2648 const Type *SCOpTy = SCIOp0->getType();
2649 bool TIS = false;
2650
2651 // If the icmp is true iff the sign bit of X is set, then convert this
2652 // multiply into a shift/and combination.
2653 if (isa<ConstantInt>(SCIOp1) &&
2654 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2655 TIS) {
2656 // Shift the X value right to turn it into "all signbits".
2657 Constant *Amt = ConstantInt::get(SCIOp0->getType(),
2658 SCOpTy->getPrimitiveSizeInBits()-1);
2659 Value *V =
2660 InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00002661 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002662 BoolCast->getOperand(0)->getName()+
2663 ".mask"), I);
2664
2665 // If the multiply type is not the same as the source type, sign extend
2666 // or truncate to the multiply type.
2667 if (I.getType() != V->getType()) {
2668 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2669 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2670 Instruction::CastOps opcode =
2671 (SrcBits == DstBits ? Instruction::BitCast :
2672 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2673 V = InsertCastBefore(opcode, V, I.getType(), I);
2674 }
2675
2676 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greifa645dd32008-05-16 19:29:10 +00002677 return BinaryOperator::CreateAnd(V, OtherOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002678 }
2679 }
2680 }
2681
2682 return Changed ? &I : 0;
2683}
2684
Chris Lattner76972db2008-07-14 00:15:52 +00002685/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2686/// instruction.
2687bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2688 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2689
2690 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2691 int NonNullOperand = -1;
2692 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2693 if (ST->isNullValue())
2694 NonNullOperand = 2;
2695 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2696 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2697 if (ST->isNullValue())
2698 NonNullOperand = 1;
2699
2700 if (NonNullOperand == -1)
2701 return false;
2702
2703 Value *SelectCond = SI->getOperand(0);
2704
2705 // Change the div/rem to use 'Y' instead of the select.
2706 I.setOperand(1, SI->getOperand(NonNullOperand));
2707
2708 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2709 // problem. However, the select, or the condition of the select may have
2710 // multiple uses. Based on our knowledge that the operand must be non-zero,
2711 // propagate the known value for the select into other uses of it, and
2712 // propagate a known value of the condition into its other users.
2713
2714 // If the select and condition only have a single use, don't bother with this,
2715 // early exit.
2716 if (SI->use_empty() && SelectCond->hasOneUse())
2717 return true;
2718
2719 // Scan the current block backward, looking for other uses of SI.
2720 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2721
2722 while (BBI != BBFront) {
2723 --BBI;
2724 // If we found a call to a function, we can't assume it will return, so
2725 // information from below it cannot be propagated above it.
2726 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2727 break;
2728
2729 // Replace uses of the select or its condition with the known values.
2730 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2731 I != E; ++I) {
2732 if (*I == SI) {
2733 *I = SI->getOperand(NonNullOperand);
2734 AddToWorkList(BBI);
2735 } else if (*I == SelectCond) {
2736 *I = NonNullOperand == 1 ? ConstantInt::getTrue() :
2737 ConstantInt::getFalse();
2738 AddToWorkList(BBI);
2739 }
2740 }
2741
2742 // If we past the instruction, quit looking for it.
2743 if (&*BBI == SI)
2744 SI = 0;
2745 if (&*BBI == SelectCond)
2746 SelectCond = 0;
2747
2748 // If we ran out of things to eliminate, break out of the loop.
2749 if (SelectCond == 0 && SI == 0)
2750 break;
2751
2752 }
2753 return true;
2754}
2755
2756
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002757/// This function implements the transforms on div instructions that work
2758/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2759/// used by the visitors to those instructions.
2760/// @brief Transforms common to all three div instructions
2761Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2762 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2763
Chris Lattner653ef3c2008-02-19 06:12:18 +00002764 // undef / X -> 0 for integer.
2765 // undef / X -> undef for FP (the undef could be a snan).
2766 if (isa<UndefValue>(Op0)) {
2767 if (Op0->getType()->isFPOrFPVector())
2768 return ReplaceInstUsesWith(I, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002769 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00002770 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002771
2772 // X / undef -> undef
2773 if (isa<UndefValue>(Op1))
2774 return ReplaceInstUsesWith(I, Op1);
2775
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002776 return 0;
2777}
2778
2779/// This function implements the transforms common to both integer division
2780/// instructions (udiv and sdiv). It is called by the visitors to those integer
2781/// division instructions.
2782/// @brief Common integer divide transforms
2783Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2784 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2785
Chris Lattnercefb36c2008-05-16 02:59:42 +00002786 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky386c0132008-05-23 03:26:47 +00002787 if (Op0 == Op1) {
2788 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
2789 ConstantInt *CI = ConstantInt::get(Ty->getElementType(), 1);
2790 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
2791 return ReplaceInstUsesWith(I, ConstantVector::get(Elts));
2792 }
2793
2794 ConstantInt *CI = ConstantInt::get(I.getType(), 1);
2795 return ReplaceInstUsesWith(I, CI);
2796 }
Chris Lattnercefb36c2008-05-16 02:59:42 +00002797
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002798 if (Instruction *Common = commonDivTransforms(I))
2799 return Common;
Chris Lattner76972db2008-07-14 00:15:52 +00002800
2801 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2802 // This does not apply for fdiv.
2803 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2804 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002805
2806 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2807 // div X, 1 == X
2808 if (RHS->equalsInt(1))
2809 return ReplaceInstUsesWith(I, Op0);
2810
2811 // (X / C1) / C2 -> X / (C1*C2)
2812 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2813 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2814 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Nick Lewycky9d798f92008-02-18 22:48:05 +00002815 if (MultiplyOverflows(RHS, LHSRHS, I.getOpcode()==Instruction::SDiv))
2816 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2817 else
Gabor Greifa645dd32008-05-16 19:29:10 +00002818 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Nick Lewycky9d798f92008-02-18 22:48:05 +00002819 Multiply(RHS, LHSRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002820 }
2821
2822 if (!RHS->isZero()) { // avoid X udiv 0
2823 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2824 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2825 return R;
2826 if (isa<PHINode>(Op0))
2827 if (Instruction *NV = FoldOpIntoPhi(I))
2828 return NV;
2829 }
2830 }
2831
2832 // 0 / X == 0, we don't need to preserve faults!
2833 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
2834 if (LHS->equalsInt(0))
2835 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2836
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002837 // It can't be division by zero, hence it must be division by one.
2838 if (I.getType() == Type::Int1Ty)
2839 return ReplaceInstUsesWith(I, Op0);
2840
Nick Lewycky94418732008-11-27 20:21:08 +00002841 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2842 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
2843 // div X, 1 == X
2844 if (X->isOne())
2845 return ReplaceInstUsesWith(I, Op0);
2846 }
2847
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002848 return 0;
2849}
2850
2851Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
2852 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2853
2854 // Handle the integer div common cases
2855 if (Instruction *Common = commonIDivTransforms(I))
2856 return Common;
2857
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002858 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky240182a2008-11-27 22:41:10 +00002859 // X udiv C^2 -> X >> C
2860 // Check to see if this is an unsigned division with an exact power of 2,
2861 // if so, convert to a right shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002862 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greifa645dd32008-05-16 19:29:10 +00002863 return BinaryOperator::CreateLShr(Op0,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002864 ConstantInt::get(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky240182a2008-11-27 22:41:10 +00002865
2866 // X udiv C, where C >= signbit
2867 if (C->getValue().isNegative()) {
2868 Value *IC = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_ULT, Op0, C),
2869 I);
2870 return SelectInst::Create(IC, Constant::getNullValue(I.getType()),
2871 ConstantInt::get(I.getType(), 1));
2872 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002873 }
2874
2875 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
2876 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
2877 if (RHSI->getOpcode() == Instruction::Shl &&
2878 isa<ConstantInt>(RHSI->getOperand(0))) {
2879 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
2880 if (C1.isPowerOf2()) {
2881 Value *N = RHSI->getOperand(1);
2882 const Type *NTy = N->getType();
2883 if (uint32_t C2 = C1.logBase2()) {
2884 Constant *C2V = ConstantInt::get(NTy, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00002885 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002886 }
Gabor Greifa645dd32008-05-16 19:29:10 +00002887 return BinaryOperator::CreateLShr(Op0, N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002888 }
2889 }
2890 }
2891
2892 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
2893 // where C1&C2 are powers of two.
2894 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2895 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
2896 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
2897 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
2898 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
2899 // Compute the shift amounts
2900 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
2901 // Construct the "on true" case of the select
2902 Constant *TC = ConstantInt::get(Op0->getType(), TSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00002903 Instruction *TSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002904 Op0, TC, SI->getName()+".t");
2905 TSI = InsertNewInstBefore(TSI, I);
2906
2907 // Construct the "on false" case of the select
2908 Constant *FC = ConstantInt::get(Op0->getType(), FSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00002909 Instruction *FSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002910 Op0, FC, SI->getName()+".f");
2911 FSI = InsertNewInstBefore(FSI, I);
2912
2913 // construct the select instruction and return it.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002914 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002915 }
2916 }
2917 return 0;
2918}
2919
2920Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
2921 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2922
2923 // Handle the integer div common cases
2924 if (Instruction *Common = commonIDivTransforms(I))
2925 return Common;
2926
2927 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2928 // sdiv X, -1 == -X
2929 if (RHS->isAllOnesValue())
Gabor Greifa645dd32008-05-16 19:29:10 +00002930 return BinaryOperator::CreateNeg(Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002931 }
2932
2933 // If the sign bits of both operands are zero (i.e. we can prove they are
2934 // unsigned inputs), turn this into a udiv.
2935 if (I.getType()->isInteger()) {
2936 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
2937 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmandb3dd962007-11-05 23:16:33 +00002938 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00002939 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002940 }
2941 }
2942
2943 return 0;
2944}
2945
2946Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
2947 return commonDivTransforms(I);
2948}
2949
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002950/// This function implements the transforms on rem instructions that work
2951/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
2952/// is used by the visitors to those instructions.
2953/// @brief Transforms common to all three rem instructions
2954Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
2955 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2956
Chris Lattner653ef3c2008-02-19 06:12:18 +00002957 // 0 % X == 0 for integer, we don't need to preserve faults!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002958 if (Constant *LHS = dyn_cast<Constant>(Op0))
2959 if (LHS->isNullValue())
2960 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2961
Chris Lattner653ef3c2008-02-19 06:12:18 +00002962 if (isa<UndefValue>(Op0)) { // undef % X -> 0
2963 if (I.getType()->isFPOrFPVector())
2964 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002965 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00002966 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002967 if (isa<UndefValue>(Op1))
2968 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
2969
2970 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattner76972db2008-07-14 00:15:52 +00002971 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2972 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002973
2974 return 0;
2975}
2976
2977/// This function implements the transforms common to both integer remainder
2978/// instructions (urem and srem). It is called by the visitors to those integer
2979/// remainder instructions.
2980/// @brief Common integer remainder transforms
2981Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
2982 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2983
2984 if (Instruction *common = commonRemTransforms(I))
2985 return common;
2986
2987 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2988 // X % 0 == undef, we don't need to preserve faults!
2989 if (RHS->equalsInt(0))
2990 return ReplaceInstUsesWith(I, UndefValue::get(I.getType()));
2991
2992 if (RHS->equalsInt(1)) // X % 1 == 0
2993 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
2994
2995 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
2996 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
2997 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2998 return R;
2999 } else if (isa<PHINode>(Op0I)) {
3000 if (Instruction *NV = FoldOpIntoPhi(I))
3001 return NV;
3002 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003003
3004 // See if we can fold away this rem instruction.
3005 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3006 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3007 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3008 KnownZero, KnownOne))
3009 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003010 }
3011 }
3012
3013 return 0;
3014}
3015
3016Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3017 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3018
3019 if (Instruction *common = commonIRemTransforms(I))
3020 return common;
3021
3022 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3023 // X urem C^2 -> X and C
3024 // Check to see if this is an unsigned remainder with an exact power of 2,
3025 // if so, convert to a bitwise and.
3026 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3027 if (C->getValue().isPowerOf2())
Gabor Greifa645dd32008-05-16 19:29:10 +00003028 return BinaryOperator::CreateAnd(Op0, SubOne(C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003029 }
3030
3031 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3032 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3033 if (RHSI->getOpcode() == Instruction::Shl &&
3034 isa<ConstantInt>(RHSI->getOperand(0))) {
3035 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
3036 Constant *N1 = ConstantInt::getAllOnesValue(I.getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00003037 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003038 "tmp"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003039 return BinaryOperator::CreateAnd(Op0, Add);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003040 }
3041 }
3042 }
3043
3044 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3045 // where C1&C2 are powers of two.
3046 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3047 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3048 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3049 // STO == 0 and SFO == 0 handled above.
3050 if ((STO->getValue().isPowerOf2()) &&
3051 (SFO->getValue().isPowerOf2())) {
3052 Value *TrueAnd = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003053 BinaryOperator::CreateAnd(Op0, SubOne(STO), SI->getName()+".t"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003054 Value *FalseAnd = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003055 BinaryOperator::CreateAnd(Op0, SubOne(SFO), SI->getName()+".f"), I);
Gabor Greifd6da1d02008-04-06 20:25:17 +00003056 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003057 }
3058 }
3059 }
3060
3061 return 0;
3062}
3063
3064Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3065 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3066
Dan Gohmandb3dd962007-11-05 23:16:33 +00003067 // Handle the integer rem common cases
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003068 if (Instruction *common = commonIRemTransforms(I))
3069 return common;
3070
3071 if (Value *RHSNeg = dyn_castNegVal(Op1))
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00003072 if (!isa<Constant>(RHSNeg) ||
3073 (isa<ConstantInt>(RHSNeg) &&
3074 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003075 // X % -Y -> X % Y
3076 AddUsesToWorkList(I);
3077 I.setOperand(1, RHSNeg);
3078 return &I;
3079 }
Nick Lewycky5515c7a2008-09-30 06:08:34 +00003080
Dan Gohmandb3dd962007-11-05 23:16:33 +00003081 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003082 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00003083 if (I.getType()->isInteger()) {
3084 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3085 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3086 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00003087 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmandb3dd962007-11-05 23:16:33 +00003088 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003089 }
3090
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003091 // If it's a constant vector, flip any negative values positive.
Nick Lewyckyfd746832008-12-20 16:48:00 +00003092 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3093 unsigned VWidth = RHSV->getNumOperands();
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003094
Nick Lewyckyfd746832008-12-20 16:48:00 +00003095 bool hasNegative = false;
3096 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3097 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3098 if (RHS->getValue().isNegative())
3099 hasNegative = true;
3100
3101 if (hasNegative) {
3102 std::vector<Constant *> Elts(VWidth);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003103 for (unsigned i = 0; i != VWidth; ++i) {
3104 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3105 if (RHS->getValue().isNegative())
3106 Elts[i] = cast<ConstantInt>(ConstantExpr::getNeg(RHS));
3107 else
3108 Elts[i] = RHS;
3109 }
3110 }
3111
3112 Constant *NewRHSV = ConstantVector::get(Elts);
3113 if (NewRHSV != RHSV) {
Nick Lewycky338ecd52008-12-18 06:42:28 +00003114 AddUsesToWorkList(I);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003115 I.setOperand(1, NewRHSV);
3116 return &I;
3117 }
3118 }
3119 }
3120
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003121 return 0;
3122}
3123
3124Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3125 return commonRemTransforms(I);
3126}
3127
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003128// isOneBitSet - Return true if there is exactly one bit set in the specified
3129// constant.
3130static bool isOneBitSet(const ConstantInt *CI) {
3131 return CI->getValue().isPowerOf2();
3132}
3133
3134// isHighOnes - Return true if the constant is of the form 1+0+.
3135// This is the same as lowones(~X).
3136static bool isHighOnes(const ConstantInt *CI) {
3137 return (~CI->getValue() + 1).isPowerOf2();
3138}
3139
3140/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3141/// are carefully arranged to allow folding of expressions such as:
3142///
3143/// (A < B) | (A > B) --> (A != B)
3144///
3145/// Note that this is only valid if the first and second predicates have the
3146/// same sign. Is illegal to do: (A u< B) | (A s> B)
3147///
3148/// Three bits are used to represent the condition, as follows:
3149/// 0 A > B
3150/// 1 A == B
3151/// 2 A < B
3152///
3153/// <=> Value Definition
3154/// 000 0 Always false
3155/// 001 1 A > B
3156/// 010 2 A == B
3157/// 011 3 A >= B
3158/// 100 4 A < B
3159/// 101 5 A != B
3160/// 110 6 A <= B
3161/// 111 7 Always true
3162///
3163static unsigned getICmpCode(const ICmpInst *ICI) {
3164 switch (ICI->getPredicate()) {
3165 // False -> 0
3166 case ICmpInst::ICMP_UGT: return 1; // 001
3167 case ICmpInst::ICMP_SGT: return 1; // 001
3168 case ICmpInst::ICMP_EQ: return 2; // 010
3169 case ICmpInst::ICMP_UGE: return 3; // 011
3170 case ICmpInst::ICMP_SGE: return 3; // 011
3171 case ICmpInst::ICMP_ULT: return 4; // 100
3172 case ICmpInst::ICMP_SLT: return 4; // 100
3173 case ICmpInst::ICMP_NE: return 5; // 101
3174 case ICmpInst::ICMP_ULE: return 6; // 110
3175 case ICmpInst::ICMP_SLE: return 6; // 110
3176 // True -> 7
3177 default:
3178 assert(0 && "Invalid ICmp predicate!");
3179 return 0;
3180 }
3181}
3182
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003183/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3184/// predicate into a three bit mask. It also returns whether it is an ordered
3185/// predicate by reference.
3186static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3187 isOrdered = false;
3188 switch (CC) {
3189 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3190 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Chengf1f2cea2008-10-14 18:13:38 +00003191 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3192 case FCmpInst::FCMP_UGT: return 1; // 001
3193 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3194 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003195 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3196 case FCmpInst::FCMP_UGE: return 3; // 011
3197 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3198 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Chengf1f2cea2008-10-14 18:13:38 +00003199 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3200 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003201 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3202 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng72988052008-10-14 18:44:08 +00003203 // True -> 7
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003204 default:
3205 // Not expecting FCMP_FALSE and FCMP_TRUE;
3206 assert(0 && "Unexpected FCmp predicate!");
3207 return 0;
3208 }
3209}
3210
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003211/// getICmpValue - This is the complement of getICmpCode, which turns an
3212/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00003213/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003214/// of predicate to use in the new icmp instruction.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003215static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS) {
3216 switch (code) {
3217 default: assert(0 && "Illegal ICmp code!");
3218 case 0: return ConstantInt::getFalse();
3219 case 1:
3220 if (sign)
3221 return new ICmpInst(ICmpInst::ICMP_SGT, LHS, RHS);
3222 else
3223 return new ICmpInst(ICmpInst::ICMP_UGT, LHS, RHS);
3224 case 2: return new ICmpInst(ICmpInst::ICMP_EQ, LHS, RHS);
3225 case 3:
3226 if (sign)
3227 return new ICmpInst(ICmpInst::ICMP_SGE, LHS, RHS);
3228 else
3229 return new ICmpInst(ICmpInst::ICMP_UGE, LHS, RHS);
3230 case 4:
3231 if (sign)
3232 return new ICmpInst(ICmpInst::ICMP_SLT, LHS, RHS);
3233 else
3234 return new ICmpInst(ICmpInst::ICMP_ULT, LHS, RHS);
3235 case 5: return new ICmpInst(ICmpInst::ICMP_NE, LHS, RHS);
3236 case 6:
3237 if (sign)
3238 return new ICmpInst(ICmpInst::ICMP_SLE, LHS, RHS);
3239 else
3240 return new ICmpInst(ICmpInst::ICMP_ULE, LHS, RHS);
3241 case 7: return ConstantInt::getTrue();
3242 }
3243}
3244
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003245/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3246/// opcode and two operands into either a FCmp instruction. isordered is passed
3247/// in to determine which kind of predicate to use in the new fcmp instruction.
3248static Value *getFCmpValue(bool isordered, unsigned code,
3249 Value *LHS, Value *RHS) {
3250 switch (code) {
Evan Chengf1f2cea2008-10-14 18:13:38 +00003251 default: assert(0 && "Illegal FCmp code!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003252 case 0:
3253 if (isordered)
3254 return new FCmpInst(FCmpInst::FCMP_ORD, LHS, RHS);
3255 else
3256 return new FCmpInst(FCmpInst::FCMP_UNO, LHS, RHS);
3257 case 1:
3258 if (isordered)
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003259 return new FCmpInst(FCmpInst::FCMP_OGT, LHS, RHS);
3260 else
3261 return new FCmpInst(FCmpInst::FCMP_UGT, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003262 case 2:
3263 if (isordered)
3264 return new FCmpInst(FCmpInst::FCMP_OEQ, LHS, RHS);
3265 else
3266 return new FCmpInst(FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003267 case 3:
3268 if (isordered)
3269 return new FCmpInst(FCmpInst::FCMP_OGE, LHS, RHS);
3270 else
3271 return new FCmpInst(FCmpInst::FCMP_UGE, LHS, RHS);
3272 case 4:
3273 if (isordered)
3274 return new FCmpInst(FCmpInst::FCMP_OLT, LHS, RHS);
3275 else
3276 return new FCmpInst(FCmpInst::FCMP_ULT, LHS, RHS);
3277 case 5:
3278 if (isordered)
Evan Chengf1f2cea2008-10-14 18:13:38 +00003279 return new FCmpInst(FCmpInst::FCMP_ONE, LHS, RHS);
3280 else
3281 return new FCmpInst(FCmpInst::FCMP_UNE, LHS, RHS);
3282 case 6:
3283 if (isordered)
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003284 return new FCmpInst(FCmpInst::FCMP_OLE, LHS, RHS);
3285 else
3286 return new FCmpInst(FCmpInst::FCMP_ULE, LHS, RHS);
Evan Cheng72988052008-10-14 18:44:08 +00003287 case 7: return ConstantInt::getTrue();
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003288 }
3289}
3290
Chris Lattner2972b822008-11-16 04:55:20 +00003291/// PredicatesFoldable - Return true if both predicates match sign or if at
3292/// least one of them is an equality comparison (which is signless).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003293static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3294 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattner2972b822008-11-16 04:55:20 +00003295 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3296 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003297}
3298
3299namespace {
3300// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3301struct FoldICmpLogical {
3302 InstCombiner &IC;
3303 Value *LHS, *RHS;
3304 ICmpInst::Predicate pred;
3305 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3306 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3307 pred(ICI->getPredicate()) {}
3308 bool shouldApply(Value *V) const {
3309 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3310 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003311 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3312 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003313 return false;
3314 }
3315 Instruction *apply(Instruction &Log) const {
3316 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3317 if (ICI->getOperand(0) != LHS) {
3318 assert(ICI->getOperand(1) == LHS);
3319 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3320 }
3321
3322 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3323 unsigned LHSCode = getICmpCode(ICI);
3324 unsigned RHSCode = getICmpCode(RHSICI);
3325 unsigned Code;
3326 switch (Log.getOpcode()) {
3327 case Instruction::And: Code = LHSCode & RHSCode; break;
3328 case Instruction::Or: Code = LHSCode | RHSCode; break;
3329 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3330 default: assert(0 && "Illegal logical opcode!"); return 0;
3331 }
3332
3333 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3334 ICmpInst::isSignedPredicate(ICI->getPredicate());
3335
3336 Value *RV = getICmpValue(isSigned, Code, LHS, RHS);
3337 if (Instruction *I = dyn_cast<Instruction>(RV))
3338 return I;
3339 // Otherwise, it's a constant boolean value...
3340 return IC.ReplaceInstUsesWith(Log, RV);
3341 }
3342};
3343} // end anonymous namespace
3344
3345// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3346// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3347// guaranteed to be a binary operator.
3348Instruction *InstCombiner::OptAndOp(Instruction *Op,
3349 ConstantInt *OpRHS,
3350 ConstantInt *AndRHS,
3351 BinaryOperator &TheAnd) {
3352 Value *X = Op->getOperand(0);
3353 Constant *Together = 0;
3354 if (!Op->isShift())
3355 Together = And(AndRHS, OpRHS);
3356
3357 switch (Op->getOpcode()) {
3358 case Instruction::Xor:
3359 if (Op->hasOneUse()) {
3360 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greifa645dd32008-05-16 19:29:10 +00003361 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003362 InsertNewInstBefore(And, TheAnd);
3363 And->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003364 return BinaryOperator::CreateXor(And, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003365 }
3366 break;
3367 case Instruction::Or:
3368 if (Together == AndRHS) // (X | C) & C --> C
3369 return ReplaceInstUsesWith(TheAnd, AndRHS);
3370
3371 if (Op->hasOneUse() && Together != OpRHS) {
3372 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greifa645dd32008-05-16 19:29:10 +00003373 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003374 InsertNewInstBefore(Or, TheAnd);
3375 Or->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003376 return BinaryOperator::CreateAnd(Or, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003377 }
3378 break;
3379 case Instruction::Add:
3380 if (Op->hasOneUse()) {
3381 // Adding a one to a single bit bit-field should be turned into an XOR
3382 // of the bit. First thing to check is to see if this AND is with a
3383 // single bit constant.
3384 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3385
3386 // If there is only one bit set...
3387 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3388 // Ok, at this point, we know that we are masking the result of the
3389 // ADD down to exactly one bit. If the constant we are adding has
3390 // no bits set below this bit, then we can eliminate the ADD.
3391 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3392
3393 // Check to see if any bits below the one bit set in AndRHSV are set.
3394 if ((AddRHS & (AndRHSV-1)) == 0) {
3395 // If not, the only thing that can effect the output of the AND is
3396 // the bit specified by AndRHSV. If that bit is set, the effect of
3397 // the XOR is to toggle the bit. If it is clear, then the ADD has
3398 // no effect.
3399 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3400 TheAnd.setOperand(0, X);
3401 return &TheAnd;
3402 } else {
3403 // Pull the XOR out of the AND.
Gabor Greifa645dd32008-05-16 19:29:10 +00003404 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003405 InsertNewInstBefore(NewAnd, TheAnd);
3406 NewAnd->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003407 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003408 }
3409 }
3410 }
3411 }
3412 break;
3413
3414 case Instruction::Shl: {
3415 // We know that the AND will not produce any of the bits shifted in, so if
3416 // the anded constant includes them, clear them now!
3417 //
3418 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3419 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3420 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
3421 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShlMask);
3422
3423 if (CI->getValue() == ShlMask) {
3424 // Masking out bits that the shift already masks
3425 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3426 } else if (CI != AndRHS) { // Reducing bits set in and.
3427 TheAnd.setOperand(1, CI);
3428 return &TheAnd;
3429 }
3430 break;
3431 }
3432 case Instruction::LShr:
3433 {
3434 // We know that the AND will not produce any of the bits shifted in, so if
3435 // the anded constant includes them, clear them now! This only applies to
3436 // unsigned shifts, because a signed shr may bring in set bits!
3437 //
3438 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3439 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3440 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3441 ConstantInt *CI = ConstantInt::get(AndRHS->getValue() & ShrMask);
3442
3443 if (CI->getValue() == ShrMask) {
3444 // Masking out bits that the shift already masks.
3445 return ReplaceInstUsesWith(TheAnd, Op);
3446 } else if (CI != AndRHS) {
3447 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3448 return &TheAnd;
3449 }
3450 break;
3451 }
3452 case Instruction::AShr:
3453 // Signed shr.
3454 // See if this is shifting in some sign extension, then masking it out
3455 // with an and.
3456 if (Op->hasOneUse()) {
3457 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3458 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3459 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
3460 Constant *C = ConstantInt::get(AndRHS->getValue() & ShrMask);
3461 if (C == AndRHS) { // Masking out bits shifted in.
3462 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3463 // Make the argument unsigned.
3464 Value *ShVal = Op->getOperand(0);
3465 ShVal = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003466 BinaryOperator::CreateLShr(ShVal, OpRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003467 Op->getName()), TheAnd);
Gabor Greifa645dd32008-05-16 19:29:10 +00003468 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003469 }
3470 }
3471 break;
3472 }
3473 return 0;
3474}
3475
3476
3477/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3478/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3479/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3480/// whether to treat the V, Lo and HI as signed or not. IB is the location to
3481/// insert new instructions.
3482Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3483 bool isSigned, bool Inside,
3484 Instruction &IB) {
3485 assert(cast<ConstantInt>(ConstantExpr::getICmp((isSigned ?
3486 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3487 "Lo is not <= Hi in range emission code!");
3488
3489 if (Inside) {
3490 if (Lo == Hi) // Trivially false.
3491 return new ICmpInst(ICmpInst::ICMP_NE, V, V);
3492
3493 // V >= Min && V < Hi --> V < Hi
3494 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3495 ICmpInst::Predicate pred = (isSigned ?
3496 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
3497 return new ICmpInst(pred, V, Hi);
3498 }
3499
3500 // Emit V-Lo <u Hi-Lo
3501 Constant *NegLo = ConstantExpr::getNeg(Lo);
Gabor Greifa645dd32008-05-16 19:29:10 +00003502 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003503 InsertNewInstBefore(Add, IB);
3504 Constant *UpperBound = ConstantExpr::getAdd(NegLo, Hi);
3505 return new ICmpInst(ICmpInst::ICMP_ULT, Add, UpperBound);
3506 }
3507
3508 if (Lo == Hi) // Trivially true.
3509 return new ICmpInst(ICmpInst::ICMP_EQ, V, V);
3510
3511 // V < Min || V >= Hi -> V > Hi-1
3512 Hi = SubOne(cast<ConstantInt>(Hi));
3513 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3514 ICmpInst::Predicate pred = (isSigned ?
3515 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
3516 return new ICmpInst(pred, V, Hi);
3517 }
3518
3519 // Emit V-Lo >u Hi-1-Lo
3520 // Note that Hi has already had one subtracted from it, above.
3521 ConstantInt *NegLo = cast<ConstantInt>(ConstantExpr::getNeg(Lo));
Gabor Greifa645dd32008-05-16 19:29:10 +00003522 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003523 InsertNewInstBefore(Add, IB);
3524 Constant *LowerBound = ConstantExpr::getAdd(NegLo, Hi);
3525 return new ICmpInst(ICmpInst::ICMP_UGT, Add, LowerBound);
3526}
3527
3528// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3529// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3530// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3531// not, since all 1s are not contiguous.
3532static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3533 const APInt& V = Val->getValue();
3534 uint32_t BitWidth = Val->getType()->getBitWidth();
3535 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3536
3537 // look for the first zero bit after the run of ones
3538 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3539 // look for the first non-zero bit
3540 ME = V.getActiveBits();
3541 return true;
3542}
3543
3544/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3545/// where isSub determines whether the operator is a sub. If we can fold one of
3546/// the following xforms:
3547///
3548/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3549/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3550/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3551///
3552/// return (A +/- B).
3553///
3554Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3555 ConstantInt *Mask, bool isSub,
3556 Instruction &I) {
3557 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3558 if (!LHSI || LHSI->getNumOperands() != 2 ||
3559 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3560
3561 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3562
3563 switch (LHSI->getOpcode()) {
3564 default: return 0;
3565 case Instruction::And:
3566 if (And(N, Mask) == Mask) {
3567 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3568 if ((Mask->getValue().countLeadingZeros() +
3569 Mask->getValue().countPopulation()) ==
3570 Mask->getValue().getBitWidth())
3571 break;
3572
3573 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3574 // part, we don't need any explicit masks to take them out of A. If that
3575 // is all N is, ignore it.
3576 uint32_t MB = 0, ME = 0;
3577 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3578 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3579 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3580 if (MaskedValueIsZero(RHS, Mask))
3581 break;
3582 }
3583 }
3584 return 0;
3585 case Instruction::Or:
3586 case Instruction::Xor:
3587 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3588 if ((Mask->getValue().countLeadingZeros() +
3589 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
3590 && And(N, Mask)->isZero())
3591 break;
3592 return 0;
3593 }
3594
3595 Instruction *New;
3596 if (isSub)
Gabor Greifa645dd32008-05-16 19:29:10 +00003597 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003598 else
Gabor Greifa645dd32008-05-16 19:29:10 +00003599 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003600 return InsertNewInstBefore(New, I);
3601}
3602
Chris Lattner0631ea72008-11-16 05:06:21 +00003603/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3604Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3605 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerf3803482008-11-16 05:10:52 +00003606 Value *Val, *Val2;
Chris Lattner0631ea72008-11-16 05:06:21 +00003607 ConstantInt *LHSCst, *RHSCst;
3608 ICmpInst::Predicate LHSCC, RHSCC;
3609
Chris Lattnerf3803482008-11-16 05:10:52 +00003610 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Chris Lattner0631ea72008-11-16 05:06:21 +00003611 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
Chris Lattnerf3803482008-11-16 05:10:52 +00003612 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
Chris Lattner0631ea72008-11-16 05:06:21 +00003613 return 0;
Chris Lattnerf3803482008-11-16 05:10:52 +00003614
3615 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3616 // where C is a power of 2
3617 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3618 LHSCst->getValue().isPowerOf2()) {
3619 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3620 InsertNewInstBefore(NewOr, I);
3621 return new ICmpInst(LHSCC, NewOr, LHSCst);
3622 }
3623
3624 // From here on, we only handle:
3625 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3626 if (Val != Val2) return 0;
3627
Chris Lattner0631ea72008-11-16 05:06:21 +00003628 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3629 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3630 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3631 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3632 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3633 return 0;
3634
3635 // We can't fold (ugt x, C) & (sgt x, C2).
3636 if (!PredicatesFoldable(LHSCC, RHSCC))
3637 return 0;
3638
3639 // Ensure that the larger constant is on the RHS.
Chris Lattner665298f2008-11-16 05:14:43 +00003640 bool ShouldSwap;
Chris Lattner0631ea72008-11-16 05:06:21 +00003641 if (ICmpInst::isSignedPredicate(LHSCC) ||
3642 (ICmpInst::isEquality(LHSCC) &&
3643 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattner665298f2008-11-16 05:14:43 +00003644 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner0631ea72008-11-16 05:06:21 +00003645 else
Chris Lattner665298f2008-11-16 05:14:43 +00003646 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3647
3648 if (ShouldSwap) {
Chris Lattner0631ea72008-11-16 05:06:21 +00003649 std::swap(LHS, RHS);
3650 std::swap(LHSCst, RHSCst);
3651 std::swap(LHSCC, RHSCC);
3652 }
3653
3654 // At this point, we know we have have two icmp instructions
3655 // comparing a value against two constants and and'ing the result
3656 // together. Because of the above check, we know that we only have
3657 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3658 // (from the FoldICmpLogical check above), that the two constants
3659 // are not equal and that the larger constant is on the RHS
3660 assert(LHSCst != RHSCst && "Compares not folded above?");
3661
3662 switch (LHSCC) {
3663 default: assert(0 && "Unknown integer condition code!");
3664 case ICmpInst::ICMP_EQ:
3665 switch (RHSCC) {
3666 default: assert(0 && "Unknown integer condition code!");
3667 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3668 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3669 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
3670 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3671 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3672 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3673 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3674 return ReplaceInstUsesWith(I, LHS);
3675 }
3676 case ICmpInst::ICMP_NE:
3677 switch (RHSCC) {
3678 default: assert(0 && "Unknown integer condition code!");
3679 case ICmpInst::ICMP_ULT:
3680 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X u< 14) -> X < 13
3681 return new ICmpInst(ICmpInst::ICMP_ULT, Val, LHSCst);
3682 break; // (X != 13 & X u< 15) -> no change
3683 case ICmpInst::ICMP_SLT:
3684 if (LHSCst == SubOne(RHSCst)) // (X != 13 & X s< 14) -> X < 13
3685 return new ICmpInst(ICmpInst::ICMP_SLT, Val, LHSCst);
3686 break; // (X != 13 & X s< 15) -> no change
3687 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3688 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3689 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3690 return ReplaceInstUsesWith(I, RHS);
3691 case ICmpInst::ICMP_NE:
3692 if (LHSCst == SubOne(RHSCst)){// (X != 13 & X != 14) -> X-13 >u 1
3693 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
3694 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3695 Val->getName()+".off");
3696 InsertNewInstBefore(Add, I);
3697 return new ICmpInst(ICmpInst::ICMP_UGT, Add,
3698 ConstantInt::get(Add->getType(), 1));
3699 }
3700 break; // (X != 13 & X != 15) -> no change
3701 }
3702 break;
3703 case ICmpInst::ICMP_ULT:
3704 switch (RHSCC) {
3705 default: assert(0 && "Unknown integer condition code!");
3706 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3707 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
3708 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3709 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3710 break;
3711 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3712 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3713 return ReplaceInstUsesWith(I, LHS);
3714 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3715 break;
3716 }
3717 break;
3718 case ICmpInst::ICMP_SLT:
3719 switch (RHSCC) {
3720 default: assert(0 && "Unknown integer condition code!");
3721 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3722 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
3723 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
3724 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3725 break;
3726 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3727 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3728 return ReplaceInstUsesWith(I, LHS);
3729 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3730 break;
3731 }
3732 break;
3733 case ICmpInst::ICMP_UGT:
3734 switch (RHSCC) {
3735 default: assert(0 && "Unknown integer condition code!");
3736 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3737 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3738 return ReplaceInstUsesWith(I, RHS);
3739 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3740 break;
3741 case ICmpInst::ICMP_NE:
3742 if (RHSCst == AddOne(LHSCst)) // (X u> 13 & X != 14) -> X u> 14
3743 return new ICmpInst(LHSCC, Val, RHSCst);
3744 break; // (X u> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00003745 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Chris Lattner0631ea72008-11-16 05:06:21 +00003746 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, false, true, I);
3747 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3748 break;
3749 }
3750 break;
3751 case ICmpInst::ICMP_SGT:
3752 switch (RHSCC) {
3753 default: assert(0 && "Unknown integer condition code!");
3754 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3755 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3756 return ReplaceInstUsesWith(I, RHS);
3757 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3758 break;
3759 case ICmpInst::ICMP_NE:
3760 if (RHSCst == AddOne(LHSCst)) // (X s> 13 & X != 14) -> X s> 14
3761 return new ICmpInst(LHSCC, Val, RHSCst);
3762 break; // (X s> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00003763 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Chris Lattner0631ea72008-11-16 05:06:21 +00003764 return InsertRangeTest(Val, AddOne(LHSCst), RHSCst, true, true, I);
3765 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3766 break;
3767 }
3768 break;
3769 }
Chris Lattner0631ea72008-11-16 05:06:21 +00003770
3771 return 0;
3772}
3773
3774
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003775Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3776 bool Changed = SimplifyCommutative(I);
3777 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3778
3779 if (isa<UndefValue>(Op1)) // X & undef -> 0
3780 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3781
3782 // and X, X = X
3783 if (Op0 == Op1)
3784 return ReplaceInstUsesWith(I, Op1);
3785
3786 // See if we can simplify any instructions used by the instruction whose sole
3787 // purpose is to compute bits we don't care about.
3788 if (!isa<VectorType>(I.getType())) {
3789 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
3790 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
3791 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
3792 KnownZero, KnownOne))
3793 return &I;
3794 } else {
3795 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3796 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
3797 return ReplaceInstUsesWith(I, I.getOperand(0));
3798 } else if (isa<ConstantAggregateZero>(Op1)) {
3799 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
3800 }
3801 }
3802
3803 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3804 const APInt& AndRHSMask = AndRHS->getValue();
3805 APInt NotAndRHS(~AndRHSMask);
3806
3807 // Optimize a variety of ((val OP C1) & C2) combinations...
3808 if (isa<BinaryOperator>(Op0)) {
3809 Instruction *Op0I = cast<Instruction>(Op0);
3810 Value *Op0LHS = Op0I->getOperand(0);
3811 Value *Op0RHS = Op0I->getOperand(1);
3812 switch (Op0I->getOpcode()) {
3813 case Instruction::Xor:
3814 case Instruction::Or:
3815 // If the mask is only needed on one incoming arm, push it up.
3816 if (Op0I->hasOneUse()) {
3817 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3818 // Not masking anything out for the LHS, move to RHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00003819 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003820 Op0RHS->getName()+".masked");
3821 InsertNewInstBefore(NewRHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003822 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003823 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
3824 }
3825 if (!isa<Constant>(Op0RHS) &&
3826 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
3827 // Not masking anything out for the RHS, move to LHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00003828 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003829 Op0LHS->getName()+".masked");
3830 InsertNewInstBefore(NewLHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003831 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003832 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
3833 }
3834 }
3835
3836 break;
3837 case Instruction::Add:
3838 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
3839 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3840 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
3841 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003842 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003843 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003844 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003845 break;
3846
3847 case Instruction::Sub:
3848 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
3849 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3850 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
3851 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00003852 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00003853
Nick Lewyckya349ba42008-07-10 05:51:40 +00003854 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
3855 // has 1's for all bits that the subtraction with A might affect.
3856 if (Op0I->hasOneUse()) {
3857 uint32_t BitWidth = AndRHSMask.getBitWidth();
3858 uint32_t Zeros = AndRHSMask.countLeadingZeros();
3859 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
3860
Nick Lewyckyffed71b2008-07-09 04:32:37 +00003861 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewyckya349ba42008-07-10 05:51:40 +00003862 if (!(A && A->isZero()) && // avoid infinite recursion.
3863 MaskedValueIsZero(Op0LHS, Mask)) {
Nick Lewyckyffed71b2008-07-09 04:32:37 +00003864 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
3865 InsertNewInstBefore(NewNeg, I);
3866 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
3867 }
3868 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003869 break;
Nick Lewycky659ed4d2008-07-09 05:20:13 +00003870
3871 case Instruction::Shl:
3872 case Instruction::LShr:
3873 // (1 << x) & 1 --> zext(x == 0)
3874 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyf1b12222008-07-09 07:35:26 +00003875 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Nick Lewycky659ed4d2008-07-09 05:20:13 +00003876 Instruction *NewICmp = new ICmpInst(ICmpInst::ICMP_EQ, Op0RHS,
3877 Constant::getNullValue(I.getType()));
3878 InsertNewInstBefore(NewICmp, I);
3879 return new ZExtInst(NewICmp, I.getType());
3880 }
3881 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003882 }
3883
3884 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
3885 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
3886 return Res;
3887 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
3888 // If this is an integer truncation or change from signed-to-unsigned, and
3889 // if the source is an and/or with immediate, transform it. This
3890 // frequently occurs for bitfield accesses.
3891 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
3892 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
3893 CastOp->getNumOperands() == 2)
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003894 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003895 if (CastOp->getOpcode() == Instruction::And) {
3896 // Change: and (cast (and X, C1) to T), C2
3897 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
3898 // This will fold the two constants together, which may allow
3899 // other simplifications.
Gabor Greifa645dd32008-05-16 19:29:10 +00003900 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003901 CastOp->getOperand(0), I.getType(),
3902 CastOp->getName()+".shrunk");
3903 NewCast = InsertNewInstBefore(NewCast, I);
3904 // trunc_or_bitcast(C1)&C2
3905 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3906 C3 = ConstantExpr::getAnd(C3, AndRHS);
Gabor Greifa645dd32008-05-16 19:29:10 +00003907 return BinaryOperator::CreateAnd(NewCast, C3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003908 } else if (CastOp->getOpcode() == Instruction::Or) {
3909 // Change: and (cast (or X, C1) to T), C2
3910 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
3911 Constant *C3 = ConstantExpr::getTruncOrBitCast(AndCI,I.getType());
3912 if (ConstantExpr::getAnd(C3, AndRHS) == AndRHS) // trunc(C1)&C2
3913 return ReplaceInstUsesWith(I, AndRHS);
3914 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003915 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003916 }
3917 }
3918
3919 // Try to fold constant and into select arguments.
3920 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3921 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3922 return R;
3923 if (isa<PHINode>(Op0))
3924 if (Instruction *NV = FoldOpIntoPhi(I))
3925 return NV;
3926 }
3927
3928 Value *Op0NotVal = dyn_castNotVal(Op0);
3929 Value *Op1NotVal = dyn_castNotVal(Op1);
3930
3931 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
3932 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
3933
3934 // (~A & ~B) == (~(A | B)) - De Morgan's Law
3935 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00003936 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003937 I.getName()+".demorgan");
3938 InsertNewInstBefore(Or, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003939 return BinaryOperator::CreateNot(Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003940 }
3941
3942 {
3943 Value *A = 0, *B = 0, *C = 0, *D = 0;
3944 if (match(Op0, m_Or(m_Value(A), m_Value(B)))) {
3945 if (A == Op1 || B == Op1) // (A | ?) & A --> A
3946 return ReplaceInstUsesWith(I, Op1);
3947
3948 // (A|B) & ~(A&B) -> A^B
3949 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))))) {
3950 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00003951 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003952 }
3953 }
3954
3955 if (match(Op1, m_Or(m_Value(A), m_Value(B)))) {
3956 if (A == Op0 || B == Op0) // A & (A | ?) --> A
3957 return ReplaceInstUsesWith(I, Op0);
3958
3959 // ~(A&B) & (A|B) -> A^B
3960 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))))) {
3961 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00003962 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003963 }
3964 }
3965
3966 if (Op0->hasOneUse() &&
3967 match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
3968 if (A == Op1) { // (A^B)&A -> A&(A^B)
3969 I.swapOperands(); // Simplify below
3970 std::swap(Op0, Op1);
3971 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
3972 cast<BinaryOperator>(Op0)->swapOperands();
3973 I.swapOperands(); // Simplify below
3974 std::swap(Op0, Op1);
3975 }
3976 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00003977
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003978 if (Op1->hasOneUse() &&
3979 match(Op1, m_Xor(m_Value(A), m_Value(B)))) {
3980 if (B == Op0) { // B&(A^B) -> B&(B^A)
3981 cast<BinaryOperator>(Op1)->swapOperands();
3982 std::swap(A, B);
3983 }
3984 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greifa645dd32008-05-16 19:29:10 +00003985 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003986 InsertNewInstBefore(NotB, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003987 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003988 }
3989 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00003990
3991 // (A&((~A)|B)) -> A&B
Chris Lattner9db479f2008-12-01 05:16:26 +00003992 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A))) ||
3993 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1)))))
3994 return BinaryOperator::CreateAnd(A, Op1);
3995 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A))) ||
3996 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0)))))
3997 return BinaryOperator::CreateAnd(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003998 }
3999
4000 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4001 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
4002 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4003 return R;
4004
Chris Lattner0631ea72008-11-16 05:06:21 +00004005 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4006 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4007 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004008 }
4009
4010 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4011 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4012 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4013 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4014 const Type *SrcTy = Op0C->getOperand(0)->getType();
4015 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4016 // Only do this if the casts both really cause code to be generated.
4017 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4018 I.getType(), TD) &&
4019 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4020 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004021 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004022 Op1C->getOperand(0),
4023 I.getName());
4024 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004025 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004026 }
4027 }
4028
4029 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4030 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4031 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4032 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4033 SI0->getOperand(1) == SI1->getOperand(1) &&
4034 (SI0->hasOneUse() || SI1->hasOneUse())) {
4035 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004036 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004037 SI1->getOperand(0),
4038 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004039 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004040 SI1->getOperand(1));
4041 }
4042 }
4043
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004044 // If and'ing two fcmp, try combine them into one.
Chris Lattner91882432007-10-24 05:38:08 +00004045 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4046 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4047 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004048 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4049 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
Chris Lattner91882432007-10-24 05:38:08 +00004050 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4051 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4052 // If either of the constants are nans, then the whole thing returns
4053 // false.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00004054 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00004055 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4056 return new FCmpInst(FCmpInst::FCMP_ORD, LHS->getOperand(0),
4057 RHS->getOperand(0));
4058 }
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004059 } else {
4060 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4061 FCmpInst::Predicate Op0CC, Op1CC;
4062 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4063 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
Evan Chengf1f2cea2008-10-14 18:13:38 +00004064 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4065 // Swap RHS operands to match LHS.
4066 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4067 std::swap(Op1LHS, Op1RHS);
4068 }
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004069 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4070 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4071 if (Op0CC == Op1CC)
4072 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4073 else if (Op0CC == FCmpInst::FCMP_FALSE ||
4074 Op1CC == FCmpInst::FCMP_FALSE)
4075 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4076 else if (Op0CC == FCmpInst::FCMP_TRUE)
4077 return ReplaceInstUsesWith(I, Op1);
4078 else if (Op1CC == FCmpInst::FCMP_TRUE)
4079 return ReplaceInstUsesWith(I, Op0);
4080 bool Op0Ordered;
4081 bool Op1Ordered;
4082 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4083 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4084 if (Op1Pred == 0) {
4085 std::swap(Op0, Op1);
4086 std::swap(Op0Pred, Op1Pred);
4087 std::swap(Op0Ordered, Op1Ordered);
4088 }
4089 if (Op0Pred == 0) {
4090 // uno && ueq -> uno && (uno || eq) -> ueq
4091 // ord && olt -> ord && (ord && lt) -> olt
4092 if (Op0Ordered == Op1Ordered)
4093 return ReplaceInstUsesWith(I, Op1);
4094 // uno && oeq -> uno && (ord && eq) -> false
4095 // uno && ord -> false
4096 if (!Op0Ordered)
4097 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
4098 // ord && ueq -> ord && (uno || eq) -> oeq
4099 return cast<Instruction>(getFCmpValue(true, Op1Pred,
4100 Op0LHS, Op0RHS));
4101 }
4102 }
4103 }
4104 }
Chris Lattner91882432007-10-24 05:38:08 +00004105 }
4106 }
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004107
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004108 return Changed ? &I : 0;
4109}
4110
Chris Lattner567f5112008-10-05 02:13:19 +00004111/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4112/// capable of providing pieces of a bswap. The subexpression provides pieces
4113/// of a bswap if it is proven that each of the non-zero bytes in the output of
4114/// the expression came from the corresponding "byte swapped" byte in some other
4115/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4116/// we know that the expression deposits the low byte of %X into the high byte
4117/// of the bswap result and that all other bytes are zero. This expression is
4118/// accepted, the high byte of ByteValues is set to X to indicate a correct
4119/// match.
4120///
4121/// This function returns true if the match was unsuccessful and false if so.
4122/// On entry to the function the "OverallLeftShift" is a signed integer value
4123/// indicating the number of bytes that the subexpression is later shifted. For
4124/// example, if the expression is later right shifted by 16 bits, the
4125/// OverallLeftShift value would be -2 on entry. This is used to specify which
4126/// byte of ByteValues is actually being set.
4127///
4128/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4129/// byte is masked to zero by a user. For example, in (X & 255), X will be
4130/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4131/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4132/// always in the local (OverallLeftShift) coordinate space.
4133///
4134static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4135 SmallVector<Value*, 8> &ByteValues) {
4136 if (Instruction *I = dyn_cast<Instruction>(V)) {
4137 // If this is an or instruction, it may be an inner node of the bswap.
4138 if (I->getOpcode() == Instruction::Or) {
4139 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4140 ByteValues) ||
4141 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4142 ByteValues);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004143 }
Chris Lattner567f5112008-10-05 02:13:19 +00004144
4145 // If this is a logical shift by a constant multiple of 8, recurse with
4146 // OverallLeftShift and ByteMask adjusted.
4147 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4148 unsigned ShAmt =
4149 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4150 // Ensure the shift amount is defined and of a byte value.
4151 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4152 return true;
4153
4154 unsigned ByteShift = ShAmt >> 3;
4155 if (I->getOpcode() == Instruction::Shl) {
4156 // X << 2 -> collect(X, +2)
4157 OverallLeftShift += ByteShift;
4158 ByteMask >>= ByteShift;
4159 } else {
4160 // X >>u 2 -> collect(X, -2)
4161 OverallLeftShift -= ByteShift;
4162 ByteMask <<= ByteShift;
Chris Lattner44448592008-10-08 06:42:28 +00004163 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner567f5112008-10-05 02:13:19 +00004164 }
4165
4166 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4167 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4168
4169 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4170 ByteValues);
4171 }
4172
4173 // If this is a logical 'and' with a mask that clears bytes, clear the
4174 // corresponding bytes in ByteMask.
4175 if (I->getOpcode() == Instruction::And &&
4176 isa<ConstantInt>(I->getOperand(1))) {
4177 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4178 unsigned NumBytes = ByteValues.size();
4179 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4180 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4181
4182 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4183 // If this byte is masked out by a later operation, we don't care what
4184 // the and mask is.
4185 if ((ByteMask & (1 << i)) == 0)
4186 continue;
4187
4188 // If the AndMask is all zeros for this byte, clear the bit.
4189 APInt MaskB = AndMask & Byte;
4190 if (MaskB == 0) {
4191 ByteMask &= ~(1U << i);
4192 continue;
4193 }
4194
4195 // If the AndMask is not all ones for this byte, it's not a bytezap.
4196 if (MaskB != Byte)
4197 return true;
4198
4199 // Otherwise, this byte is kept.
4200 }
4201
4202 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4203 ByteValues);
4204 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004205 }
4206
Chris Lattner567f5112008-10-05 02:13:19 +00004207 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4208 // the input value to the bswap. Some observations: 1) if more than one byte
4209 // is demanded from this input, then it could not be successfully assembled
4210 // into a byteswap. At least one of the two bytes would not be aligned with
4211 // their ultimate destination.
4212 if (!isPowerOf2_32(ByteMask)) return true;
4213 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004214
Chris Lattner567f5112008-10-05 02:13:19 +00004215 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4216 // is demanded, it needs to go into byte 0 of the result. This means that the
4217 // byte needs to be shifted until it lands in the right byte bucket. The
4218 // shift amount depends on the position: if the byte is coming from the high
4219 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4220 // low part, it must be shifted left.
4221 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4222 if (InputByteNo < ByteValues.size()/2) {
4223 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4224 return true;
4225 } else {
4226 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4227 return true;
4228 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004229
4230 // If the destination byte value is already defined, the values are or'd
4231 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner567f5112008-10-05 02:13:19 +00004232 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004233 return true;
Chris Lattner567f5112008-10-05 02:13:19 +00004234 ByteValues[DestByteNo] = V;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004235 return false;
4236}
4237
4238/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4239/// If so, insert the new bswap intrinsic and return it.
4240Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4241 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner567f5112008-10-05 02:13:19 +00004242 if (!ITy || ITy->getBitWidth() % 16 ||
4243 // ByteMask only allows up to 32-byte values.
4244 ITy->getBitWidth() > 32*8)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004245 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4246
4247 /// ByteValues - For each byte of the result, we keep track of which value
4248 /// defines each byte.
4249 SmallVector<Value*, 8> ByteValues;
4250 ByteValues.resize(ITy->getBitWidth()/8);
4251
4252 // Try to find all the pieces corresponding to the bswap.
Chris Lattner567f5112008-10-05 02:13:19 +00004253 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4254 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004255 return 0;
4256
4257 // Check to see if all of the bytes come from the same value.
4258 Value *V = ByteValues[0];
4259 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4260
4261 // Check to make sure that all of the bytes come from the same value.
4262 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4263 if (ByteValues[i] != V)
4264 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00004265 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004266 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00004267 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00004268 return CallInst::Create(F, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004269}
4270
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004271/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4272/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4273/// we can simplify this expression to "cond ? C : D or B".
4274static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
4275 Value *C, Value *D) {
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004276 // If A is not a select of -1/0, this cannot match.
Chris Lattner641ea462008-11-16 04:46:19 +00004277 Value *Cond = 0;
Chris Lattner73c1ddb2009-01-05 23:53:12 +00004278 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond))))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004279 return 0;
4280
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004281 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Chris Lattner73c1ddb2009-01-05 23:53:12 +00004282 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004283 return SelectInst::Create(Cond, C, B);
Chris Lattner73c1ddb2009-01-05 23:53:12 +00004284 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004285 return SelectInst::Create(Cond, C, B);
4286 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Chris Lattner73c1ddb2009-01-05 23:53:12 +00004287 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004288 return SelectInst::Create(Cond, C, D);
Chris Lattner73c1ddb2009-01-05 23:53:12 +00004289 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond)))))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004290 return SelectInst::Create(Cond, C, D);
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004291 return 0;
4292}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004293
Chris Lattner0c678e52008-11-16 05:20:07 +00004294/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4295Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4296 ICmpInst *LHS, ICmpInst *RHS) {
4297 Value *Val, *Val2;
4298 ConstantInt *LHSCst, *RHSCst;
4299 ICmpInst::Predicate LHSCC, RHSCC;
4300
4301 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
4302 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val), m_ConstantInt(LHSCst))) ||
4303 !match(RHS, m_ICmp(RHSCC, m_Value(Val2), m_ConstantInt(RHSCst))))
4304 return 0;
4305
4306 // From here on, we only handle:
4307 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4308 if (Val != Val2) return 0;
4309
4310 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4311 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4312 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4313 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4314 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4315 return 0;
4316
4317 // We can't fold (ugt x, C) | (sgt x, C2).
4318 if (!PredicatesFoldable(LHSCC, RHSCC))
4319 return 0;
4320
4321 // Ensure that the larger constant is on the RHS.
4322 bool ShouldSwap;
4323 if (ICmpInst::isSignedPredicate(LHSCC) ||
4324 (ICmpInst::isEquality(LHSCC) &&
4325 ICmpInst::isSignedPredicate(RHSCC)))
4326 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4327 else
4328 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4329
4330 if (ShouldSwap) {
4331 std::swap(LHS, RHS);
4332 std::swap(LHSCst, RHSCst);
4333 std::swap(LHSCC, RHSCC);
4334 }
4335
4336 // At this point, we know we have have two icmp instructions
4337 // comparing a value against two constants and or'ing the result
4338 // together. Because of the above check, we know that we only have
4339 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4340 // FoldICmpLogical check above), that the two constants are not
4341 // equal.
4342 assert(LHSCst != RHSCst && "Compares not folded above?");
4343
4344 switch (LHSCC) {
4345 default: assert(0 && "Unknown integer condition code!");
4346 case ICmpInst::ICMP_EQ:
4347 switch (RHSCC) {
4348 default: assert(0 && "Unknown integer condition code!");
4349 case ICmpInst::ICMP_EQ:
4350 if (LHSCst == SubOne(RHSCst)) { // (X == 13 | X == 14) -> X-13 <u 2
4351 Constant *AddCST = ConstantExpr::getNeg(LHSCst);
4352 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4353 Val->getName()+".off");
4354 InsertNewInstBefore(Add, I);
4355 AddCST = Subtract(AddOne(RHSCst), LHSCst);
4356 return new ICmpInst(ICmpInst::ICMP_ULT, Add, AddCST);
4357 }
4358 break; // (X == 13 | X == 15) -> no change
4359 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4360 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4361 break;
4362 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4363 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4364 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4365 return ReplaceInstUsesWith(I, RHS);
4366 }
4367 break;
4368 case ICmpInst::ICMP_NE:
4369 switch (RHSCC) {
4370 default: assert(0 && "Unknown integer condition code!");
4371 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4372 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4373 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4374 return ReplaceInstUsesWith(I, LHS);
4375 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4376 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4377 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
4378 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4379 }
4380 break;
4381 case ICmpInst::ICMP_ULT:
4382 switch (RHSCC) {
4383 default: assert(0 && "Unknown integer condition code!");
4384 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4385 break;
4386 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4387 // If RHSCst is [us]MAXINT, it is always false. Not handling
4388 // this can cause overflow.
4389 if (RHSCst->isMaxValue(false))
4390 return ReplaceInstUsesWith(I, LHS);
4391 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), false, false, I);
4392 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4393 break;
4394 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4395 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4396 return ReplaceInstUsesWith(I, RHS);
4397 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4398 break;
4399 }
4400 break;
4401 case ICmpInst::ICMP_SLT:
4402 switch (RHSCC) {
4403 default: assert(0 && "Unknown integer condition code!");
4404 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4405 break;
4406 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4407 // If RHSCst is [us]MAXINT, it is always false. Not handling
4408 // this can cause overflow.
4409 if (RHSCst->isMaxValue(true))
4410 return ReplaceInstUsesWith(I, LHS);
4411 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst), true, false, I);
4412 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4413 break;
4414 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4415 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4416 return ReplaceInstUsesWith(I, RHS);
4417 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4418 break;
4419 }
4420 break;
4421 case ICmpInst::ICMP_UGT:
4422 switch (RHSCC) {
4423 default: assert(0 && "Unknown integer condition code!");
4424 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4425 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4426 return ReplaceInstUsesWith(I, LHS);
4427 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4428 break;
4429 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4430 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
4431 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4432 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4433 break;
4434 }
4435 break;
4436 case ICmpInst::ICMP_SGT:
4437 switch (RHSCC) {
4438 default: assert(0 && "Unknown integer condition code!");
4439 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4440 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4441 return ReplaceInstUsesWith(I, LHS);
4442 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4443 break;
4444 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4445 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
4446 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4447 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4448 break;
4449 }
4450 break;
4451 }
4452 return 0;
4453}
4454
Bill Wendlingdae376a2008-12-01 08:23:25 +00004455/// FoldOrWithConstants - This helper function folds:
4456///
Bill Wendling236a1192008-12-02 05:09:00 +00004457/// ((A | B) & C1) | (B & C2)
Bill Wendlingdae376a2008-12-01 08:23:25 +00004458///
4459/// into:
4460///
Bill Wendling236a1192008-12-02 05:09:00 +00004461/// (A & C1) | B
Bill Wendling9912f712008-12-01 08:32:40 +00004462///
Bill Wendling236a1192008-12-02 05:09:00 +00004463/// when the XOR of the two constants is "all ones" (-1).
Bill Wendling9912f712008-12-01 08:32:40 +00004464Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +00004465 Value *A, Value *B, Value *C) {
Bill Wendlingfc5b8e62008-12-02 05:06:43 +00004466 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4467 if (!CI1) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00004468
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00004469 Value *V1 = 0;
4470 ConstantInt *CI2 = 0;
4471 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)))) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00004472
Bill Wendling86ee3162008-12-02 06:18:11 +00004473 APInt Xor = CI1->getValue() ^ CI2->getValue();
4474 if (!Xor.isAllOnesValue()) return 0;
4475
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00004476 if (V1 == A || V1 == B) {
Bill Wendling86ee3162008-12-02 06:18:11 +00004477 Instruction *NewOp =
Bill Wendling6c8ecbb2008-12-02 06:22:04 +00004478 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4479 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004480 }
4481
4482 return 0;
4483}
4484
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004485Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4486 bool Changed = SimplifyCommutative(I);
4487 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4488
4489 if (isa<UndefValue>(Op1)) // X | undef -> -1
4490 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4491
4492 // or X, X = X
4493 if (Op0 == Op1)
4494 return ReplaceInstUsesWith(I, Op0);
4495
4496 // See if we can simplify any instructions used by the instruction whose sole
4497 // purpose is to compute bits we don't care about.
4498 if (!isa<VectorType>(I.getType())) {
4499 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4500 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4501 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4502 KnownZero, KnownOne))
4503 return &I;
4504 } else if (isa<ConstantAggregateZero>(Op1)) {
4505 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4506 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4507 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4508 return ReplaceInstUsesWith(I, I.getOperand(1));
4509 }
4510
4511
4512
4513 // or X, -1 == -1
4514 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4515 ConstantInt *C1 = 0; Value *X = 0;
4516 // (X & C1) | C2 --> (X | C2) & (C1|C2)
4517 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004518 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004519 InsertNewInstBefore(Or, I);
4520 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004521 return BinaryOperator::CreateAnd(Or,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004522 ConstantInt::get(RHS->getValue() | C1->getValue()));
4523 }
4524
4525 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
4526 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1))) && isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004527 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004528 InsertNewInstBefore(Or, I);
4529 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004530 return BinaryOperator::CreateXor(Or,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004531 ConstantInt::get(C1->getValue() & ~RHS->getValue()));
4532 }
4533
4534 // Try to fold constant and into select arguments.
4535 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4536 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4537 return R;
4538 if (isa<PHINode>(Op0))
4539 if (Instruction *NV = FoldOpIntoPhi(I))
4540 return NV;
4541 }
4542
4543 Value *A = 0, *B = 0;
4544 ConstantInt *C1 = 0, *C2 = 0;
4545
4546 if (match(Op0, m_And(m_Value(A), m_Value(B))))
4547 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4548 return ReplaceInstUsesWith(I, Op1);
4549 if (match(Op1, m_And(m_Value(A), m_Value(B))))
4550 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4551 return ReplaceInstUsesWith(I, Op0);
4552
4553 // (A | B) | C and A | (B | C) -> bswap if possible.
4554 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
4555 if (match(Op0, m_Or(m_Value(), m_Value())) ||
4556 match(Op1, m_Or(m_Value(), m_Value())) ||
4557 (match(Op0, m_Shift(m_Value(), m_Value())) &&
4558 match(Op1, m_Shift(m_Value(), m_Value())))) {
4559 if (Instruction *BSwap = MatchBSwap(I))
4560 return BSwap;
4561 }
4562
4563 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
4564 if (Op0->hasOneUse() && match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4565 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004566 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004567 InsertNewInstBefore(NOr, I);
4568 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004569 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004570 }
4571
4572 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
4573 if (Op1->hasOneUse() && match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1))) &&
4574 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004575 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004576 InsertNewInstBefore(NOr, I);
4577 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004578 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004579 }
4580
4581 // (A & C)|(B & D)
4582 Value *C = 0, *D = 0;
4583 if (match(Op0, m_And(m_Value(A), m_Value(C))) &&
4584 match(Op1, m_And(m_Value(B), m_Value(D)))) {
4585 Value *V1 = 0, *V2 = 0, *V3 = 0;
4586 C1 = dyn_cast<ConstantInt>(C);
4587 C2 = dyn_cast<ConstantInt>(D);
4588 if (C1 && C2) { // (A & C1)|(B & C2)
4589 // If we have: ((V + N) & C1) | (V & C2)
4590 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4591 // replace with V+N.
4592 if (C1->getValue() == ~C2->getValue()) {
4593 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
4594 match(A, m_Add(m_Value(V1), m_Value(V2)))) {
4595 // Add commutes, try both ways.
4596 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4597 return ReplaceInstUsesWith(I, A);
4598 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4599 return ReplaceInstUsesWith(I, A);
4600 }
4601 // Or commutes, try both ways.
4602 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
4603 match(B, m_Add(m_Value(V1), m_Value(V2)))) {
4604 // Add commutes, try both ways.
4605 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4606 return ReplaceInstUsesWith(I, B);
4607 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4608 return ReplaceInstUsesWith(I, B);
4609 }
4610 }
4611 V1 = 0; V2 = 0; V3 = 0;
4612 }
4613
4614 // Check to see if we have any common things being and'ed. If so, find the
4615 // terms for V1 & (V2|V3).
4616 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4617 if (A == B) // (A & C)|(A & D) == A & (C|D)
4618 V1 = A, V2 = C, V3 = D;
4619 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4620 V1 = A, V2 = B, V3 = C;
4621 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4622 V1 = C, V2 = A, V3 = D;
4623 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4624 V1 = C, V2 = A, V3 = B;
4625
4626 if (V1) {
4627 Value *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00004628 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4629 return BinaryOperator::CreateAnd(V1, Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004630 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004631 }
Dan Gohman279952c2008-10-28 22:38:57 +00004632
Dan Gohman35b76162008-10-30 20:40:10 +00004633 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004634 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D))
4635 return Match;
4636 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C))
4637 return Match;
4638 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D))
4639 return Match;
4640 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C))
4641 return Match;
Bill Wendling22ca8352008-11-30 13:52:49 +00004642
Bill Wendling22ca8352008-11-30 13:52:49 +00004643 // ((A&~B)|(~A&B)) -> A^B
Bill Wendlingc1f31132008-12-01 08:09:47 +00004644 if ((match(C, m_Not(m_Specific(D))) &&
4645 match(B, m_Not(m_Specific(A)))))
4646 return BinaryOperator::CreateXor(A, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00004647 // ((~B&A)|(~A&B)) -> A^B
Bill Wendlingc1f31132008-12-01 08:09:47 +00004648 if ((match(A, m_Not(m_Specific(D))) &&
4649 match(B, m_Not(m_Specific(C)))))
4650 return BinaryOperator::CreateXor(C, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00004651 // ((A&~B)|(B&~A)) -> A^B
Bill Wendlingc1f31132008-12-01 08:09:47 +00004652 if ((match(C, m_Not(m_Specific(B))) &&
4653 match(D, m_Not(m_Specific(A)))))
4654 return BinaryOperator::CreateXor(A, B);
Bill Wendling22ca8352008-11-30 13:52:49 +00004655 // ((~B&A)|(B&~A)) -> A^B
Bill Wendlingc1f31132008-12-01 08:09:47 +00004656 if ((match(A, m_Not(m_Specific(B))) &&
4657 match(D, m_Not(m_Specific(C)))))
4658 return BinaryOperator::CreateXor(C, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004659 }
4660
4661 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4662 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4663 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4664 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4665 SI0->getOperand(1) == SI1->getOperand(1) &&
4666 (SI0->hasOneUse() || SI1->hasOneUse())) {
4667 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004668 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004669 SI1->getOperand(0),
4670 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004671 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004672 SI1->getOperand(1));
4673 }
4674 }
4675
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004676 // ((A|B)&1)|(B&-2) -> (A&1) | B
4677 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4678 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00004679 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004680 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004681 }
4682 // (B&-2)|((A|B)&1) -> (A&1) | B
4683 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C))) ||
4684 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))))) {
Bill Wendling9912f712008-12-01 08:32:40 +00004685 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004686 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004687 }
4688
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004689 if (match(Op0, m_Not(m_Value(A)))) { // ~A | Op1
4690 if (A == Op1) // ~A | A == -1
4691 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4692 } else {
4693 A = 0;
4694 }
4695 // Note, A is still live here!
4696 if (match(Op1, m_Not(m_Value(B)))) { // Op0 | ~B
4697 if (Op0 == B)
4698 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4699
4700 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4701 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004702 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004703 I.getName()+".demorgan"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004704 return BinaryOperator::CreateNot(And);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004705 }
4706 }
4707
4708 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4709 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
4710 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
4711 return R;
4712
Chris Lattner0c678e52008-11-16 05:20:07 +00004713 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4714 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4715 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004716 }
4717
4718 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004719 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004720 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4721 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chenge3779cf2008-03-24 00:21:34 +00004722 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4723 !isa<ICmpInst>(Op1C->getOperand(0))) {
4724 const Type *SrcTy = Op0C->getOperand(0)->getType();
4725 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4726 // Only do this if the casts both really cause code to be
4727 // generated.
4728 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4729 I.getType(), TD) &&
4730 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4731 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004732 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chenge3779cf2008-03-24 00:21:34 +00004733 Op1C->getOperand(0),
4734 I.getName());
4735 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004736 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00004737 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004738 }
4739 }
Chris Lattner91882432007-10-24 05:38:08 +00004740 }
4741
4742
4743 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4744 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4745 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4746 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattnerbe9e63e2008-02-29 06:09:11 +00004747 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Evan Cheng72988052008-10-14 18:44:08 +00004748 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
Chris Lattner91882432007-10-24 05:38:08 +00004749 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4750 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4751 // If either of the constants are nans, then the whole thing returns
4752 // true.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00004753 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Chris Lattner91882432007-10-24 05:38:08 +00004754 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4755
4756 // Otherwise, no need to compare the two constants, compare the
4757 // rest.
4758 return new FCmpInst(FCmpInst::FCMP_UNO, LHS->getOperand(0),
4759 RHS->getOperand(0));
4760 }
Evan Cheng72988052008-10-14 18:44:08 +00004761 } else {
4762 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4763 FCmpInst::Predicate Op0CC, Op1CC;
4764 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS), m_Value(Op0RHS))) &&
4765 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS), m_Value(Op1RHS)))) {
4766 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4767 // Swap RHS operands to match LHS.
4768 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4769 std::swap(Op1LHS, Op1RHS);
4770 }
4771 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4772 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4773 if (Op0CC == Op1CC)
4774 return new FCmpInst((FCmpInst::Predicate)Op0CC, Op0LHS, Op0RHS);
4775 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4776 Op1CC == FCmpInst::FCMP_TRUE)
4777 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
4778 else if (Op0CC == FCmpInst::FCMP_FALSE)
4779 return ReplaceInstUsesWith(I, Op1);
4780 else if (Op1CC == FCmpInst::FCMP_FALSE)
4781 return ReplaceInstUsesWith(I, Op0);
4782 bool Op0Ordered;
4783 bool Op1Ordered;
4784 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4785 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4786 if (Op0Ordered == Op1Ordered) {
4787 // If both are ordered or unordered, return a new fcmp with
4788 // or'ed predicates.
4789 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
4790 Op0LHS, Op0RHS);
4791 if (Instruction *I = dyn_cast<Instruction>(RV))
4792 return I;
4793 // Otherwise, it's a constant boolean value...
4794 return ReplaceInstUsesWith(I, RV);
4795 }
4796 }
4797 }
4798 }
Chris Lattner91882432007-10-24 05:38:08 +00004799 }
4800 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004801
4802 return Changed ? &I : 0;
4803}
4804
Dan Gohman089efff2008-05-13 00:00:25 +00004805namespace {
4806
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004807// XorSelf - Implements: X ^ X --> 0
4808struct XorSelf {
4809 Value *RHS;
4810 XorSelf(Value *rhs) : RHS(rhs) {}
4811 bool shouldApply(Value *LHS) const { return LHS == RHS; }
4812 Instruction *apply(BinaryOperator &Xor) const {
4813 return &Xor;
4814 }
4815};
4816
Dan Gohman089efff2008-05-13 00:00:25 +00004817}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004818
4819Instruction *InstCombiner::visitXor(BinaryOperator &I) {
4820 bool Changed = SimplifyCommutative(I);
4821 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4822
Evan Chenge5cd8032008-03-25 20:07:13 +00004823 if (isa<UndefValue>(Op1)) {
4824 if (isa<UndefValue>(Op0))
4825 // Handle undef ^ undef -> 0 special case. This is a common
4826 // idiom (misuse).
4827 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004828 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chenge5cd8032008-03-25 20:07:13 +00004829 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004830
4831 // xor X, X = 0, even if X is nested in a sequence of Xor's.
4832 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1))) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00004833 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004834 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
4835 }
4836
4837 // See if we can simplify any instructions used by the instruction whose sole
4838 // purpose is to compute bits we don't care about.
4839 if (!isa<VectorType>(I.getType())) {
4840 uint32_t BitWidth = cast<IntegerType>(I.getType())->getBitWidth();
4841 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
4842 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(BitWidth),
4843 KnownZero, KnownOne))
4844 return &I;
4845 } else if (isa<ConstantAggregateZero>(Op1)) {
4846 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
4847 }
4848
4849 // Is this a ~ operation?
4850 if (Value *NotOp = dyn_castNotVal(&I)) {
4851 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
4852 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
4853 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
4854 if (Op0I->getOpcode() == Instruction::And ||
4855 Op0I->getOpcode() == Instruction::Or) {
4856 if (dyn_castNotVal(Op0I->getOperand(1))) Op0I->swapOperands();
4857 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0))) {
4858 Instruction *NotY =
Gabor Greifa645dd32008-05-16 19:29:10 +00004859 BinaryOperator::CreateNot(Op0I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004860 Op0I->getOperand(1)->getName()+".not");
4861 InsertNewInstBefore(NotY, I);
4862 if (Op0I->getOpcode() == Instruction::And)
Gabor Greifa645dd32008-05-16 19:29:10 +00004863 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004864 else
Gabor Greifa645dd32008-05-16 19:29:10 +00004865 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004866 }
4867 }
4868 }
4869 }
4870
4871
4872 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky1405e922007-08-06 20:04:16 +00004873 if (RHS == ConstantInt::getTrue() && Op0->hasOneUse()) {
Bill Wendling61741952009-01-01 01:18:23 +00004874 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewycky1405e922007-08-06 20:04:16 +00004875 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004876 return new ICmpInst(ICI->getInversePredicate(),
4877 ICI->getOperand(0), ICI->getOperand(1));
4878
Nick Lewycky1405e922007-08-06 20:04:16 +00004879 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
4880 return new FCmpInst(FCI->getInversePredicate(),
4881 FCI->getOperand(0), FCI->getOperand(1));
4882 }
4883
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00004884 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
4885 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
4886 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
4887 if (CI->hasOneUse() && Op0C->hasOneUse()) {
4888 Instruction::CastOps Opcode = Op0C->getOpcode();
4889 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
4890 if (RHS == ConstantExpr::getCast(Opcode, ConstantInt::getTrue(),
4891 Op0C->getDestTy())) {
4892 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
4893 CI->getOpcode(), CI->getInversePredicate(),
4894 CI->getOperand(0), CI->getOperand(1)), I);
4895 NewCI->takeName(CI);
4896 return CastInst::Create(Opcode, NewCI, Op0C->getType());
4897 }
4898 }
4899 }
4900 }
4901 }
4902
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004903 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
4904 // ~(c-X) == X-c-1 == X+(-c-1)
4905 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
4906 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
4907 Constant *NegOp0I0C = ConstantExpr::getNeg(Op0I0C);
4908 Constant *ConstantRHS = ConstantExpr::getSub(NegOp0I0C,
4909 ConstantInt::get(I.getType(), 1));
Gabor Greifa645dd32008-05-16 19:29:10 +00004910 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004911 }
4912
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004913 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004914 if (Op0I->getOpcode() == Instruction::Add) {
4915 // ~(X-c) --> (-c-1)-X
4916 if (RHS->isAllOnesValue()) {
4917 Constant *NegOp0CI = ConstantExpr::getNeg(Op0CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00004918 return BinaryOperator::CreateSub(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004919 ConstantExpr::getSub(NegOp0CI,
4920 ConstantInt::get(I.getType(), 1)),
4921 Op0I->getOperand(0));
4922 } else if (RHS->getValue().isSignBit()) {
4923 // (X + C) ^ signbit -> (X + C + signbit)
4924 Constant *C = ConstantInt::get(RHS->getValue() + Op0CI->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00004925 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004926
4927 }
4928 } else if (Op0I->getOpcode() == Instruction::Or) {
4929 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
4930 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
4931 Constant *NewRHS = ConstantExpr::getOr(Op0CI, RHS);
4932 // Anything in both C1 and C2 is known to be zero, remove it from
4933 // NewRHS.
4934 Constant *CommonBits = And(Op0CI, RHS);
4935 NewRHS = ConstantExpr::getAnd(NewRHS,
4936 ConstantExpr::getNot(CommonBits));
4937 AddToWorkList(Op0I);
4938 I.setOperand(0, Op0I->getOperand(0));
4939 I.setOperand(1, NewRHS);
4940 return &I;
4941 }
4942 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004943 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004944 }
4945
4946 // Try to fold constant and into select arguments.
4947 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4948 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4949 return R;
4950 if (isa<PHINode>(Op0))
4951 if (Instruction *NV = FoldOpIntoPhi(I))
4952 return NV;
4953 }
4954
4955 if (Value *X = dyn_castNotVal(Op0)) // ~A ^ A == -1
4956 if (X == Op1)
4957 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4958
4959 if (Value *X = dyn_castNotVal(Op1)) // A ^ ~A == -1
4960 if (X == Op0)
4961 return ReplaceInstUsesWith(I, Constant::getAllOnesValue(I.getType()));
4962
4963
4964 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
4965 if (Op1I) {
4966 Value *A, *B;
4967 if (match(Op1I, m_Or(m_Value(A), m_Value(B)))) {
4968 if (A == Op0) { // B^(B|A) == (A|B)^B
4969 Op1I->swapOperands();
4970 I.swapOperands();
4971 std::swap(Op0, Op1);
4972 } else if (B == Op0) { // B^(A|B) == (A|B)^B
4973 I.swapOperands(); // Simplified below.
4974 std::swap(Op0, Op1);
4975 }
Chris Lattner3b874082008-11-16 05:38:51 +00004976 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)))) {
4977 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
4978 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)))) {
4979 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004980 } else if (match(Op1I, m_And(m_Value(A), m_Value(B))) && Op1I->hasOneUse()){
4981 if (A == Op0) { // A^(A&B) -> A^(B&A)
4982 Op1I->swapOperands();
4983 std::swap(A, B);
4984 }
4985 if (B == Op0) { // A^(B&A) -> (B&A)^A
4986 I.swapOperands(); // Simplified below.
4987 std::swap(Op0, Op1);
4988 }
4989 }
4990 }
4991
4992 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
4993 if (Op0I) {
4994 Value *A, *B;
4995 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) && Op0I->hasOneUse()) {
4996 if (A == Op1) // (B|A)^B == (A|B)^B
4997 std::swap(A, B);
4998 if (B == Op1) { // (A|B)^B == A & ~B
4999 Instruction *NotB =
Gabor Greifa645dd32008-05-16 19:29:10 +00005000 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5001 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005002 }
Chris Lattner3b874082008-11-16 05:38:51 +00005003 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)))) {
5004 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
5005 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)))) {
5006 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005007 } else if (match(Op0I, m_And(m_Value(A), m_Value(B))) && Op0I->hasOneUse()){
5008 if (A == Op1) // (A&B)^A -> (B&A)^A
5009 std::swap(A, B);
5010 if (B == Op1 && // (B&A)^A == ~B & A
5011 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
5012 Instruction *N =
Gabor Greifa645dd32008-05-16 19:29:10 +00005013 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5014 return BinaryOperator::CreateAnd(N, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005015 }
5016 }
5017 }
5018
5019 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5020 if (Op0I && Op1I && Op0I->isShift() &&
5021 Op0I->getOpcode() == Op1I->getOpcode() &&
5022 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5023 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5024 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00005025 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005026 Op1I->getOperand(0),
5027 Op0I->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005028 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005029 Op1I->getOperand(1));
5030 }
5031
5032 if (Op0I && Op1I) {
5033 Value *A, *B, *C, *D;
5034 // (A & B)^(A | B) -> A ^ B
5035 if (match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5036 match(Op1I, m_Or(m_Value(C), m_Value(D)))) {
5037 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005038 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005039 }
5040 // (A | B)^(A & B) -> A ^ B
5041 if (match(Op0I, m_Or(m_Value(A), m_Value(B))) &&
5042 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5043 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005044 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005045 }
5046
5047 // (A & B)^(C & D)
5048 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
5049 match(Op0I, m_And(m_Value(A), m_Value(B))) &&
5050 match(Op1I, m_And(m_Value(C), m_Value(D)))) {
5051 // (X & Y)^(X & Y) -> (Y^Z) & X
5052 Value *X = 0, *Y = 0, *Z = 0;
5053 if (A == C)
5054 X = A, Y = B, Z = D;
5055 else if (A == D)
5056 X = A, Y = B, Z = C;
5057 else if (B == C)
5058 X = B, Y = A, Z = D;
5059 else if (B == D)
5060 X = B, Y = A, Z = C;
5061
5062 if (X) {
5063 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00005064 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5065 return BinaryOperator::CreateAnd(NewOp, X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005066 }
5067 }
5068 }
5069
5070 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5071 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
5072 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS)))
5073 return R;
5074
5075 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00005076 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005077 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5078 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5079 const Type *SrcTy = Op0C->getOperand(0)->getType();
5080 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5081 // Only do this if the casts both really cause code to be generated.
5082 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5083 I.getType(), TD) &&
5084 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5085 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00005086 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005087 Op1C->getOperand(0),
5088 I.getName());
5089 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005090 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005091 }
5092 }
Chris Lattner91882432007-10-24 05:38:08 +00005093 }
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005094
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005095 return Changed ? &I : 0;
5096}
5097
5098/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
5099/// overflowed for this type.
5100static bool AddWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5101 ConstantInt *In2, bool IsSigned = false) {
5102 Result = cast<ConstantInt>(Add(In1, In2));
5103
5104 if (IsSigned)
5105 if (In2->getValue().isNegative())
5106 return Result->getValue().sgt(In1->getValue());
5107 else
5108 return Result->getValue().slt(In1->getValue());
5109 else
5110 return Result->getValue().ult(In1->getValue());
5111}
5112
Dan Gohmanb80d5612008-09-10 23:30:57 +00005113/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5114/// overflowed for this type.
5115static bool SubWithOverflow(ConstantInt *&Result, ConstantInt *In1,
5116 ConstantInt *In2, bool IsSigned = false) {
Dan Gohman2c3b4892008-09-11 18:53:02 +00005117 Result = cast<ConstantInt>(Subtract(In1, In2));
Dan Gohmanb80d5612008-09-10 23:30:57 +00005118
5119 if (IsSigned)
5120 if (In2->getValue().isNegative())
5121 return Result->getValue().slt(In1->getValue());
5122 else
5123 return Result->getValue().sgt(In1->getValue());
5124 else
5125 return Result->getValue().ugt(In1->getValue());
5126}
5127
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005128/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5129/// code necessary to compute the offset from the base pointer (without adding
5130/// in the base pointer). Return the result as a signed integer of intptr size.
5131static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5132 TargetData &TD = IC.getTargetData();
5133 gep_type_iterator GTI = gep_type_begin(GEP);
5134 const Type *IntPtrTy = TD.getIntPtrType();
5135 Value *Result = Constant::getNullValue(IntPtrTy);
5136
5137 // Build a mask for high order bits.
Chris Lattnereba75862008-04-22 02:53:33 +00005138 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005139 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5140
Gabor Greif17396002008-06-12 21:37:33 +00005141 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5142 ++i, ++GTI) {
5143 Value *Op = *i;
Duncan Sandsd68f13b2009-01-12 20:38:59 +00005144 uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType()) & PtrSizeMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005145 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5146 if (OpC->isZero()) continue;
5147
5148 // Handle a struct index, which adds its field offset to the pointer.
5149 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5150 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5151
5152 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
5153 Result = ConstantInt::get(RC->getValue() + APInt(IntPtrWidth, Size));
5154 else
5155 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00005156 BinaryOperator::CreateAdd(Result,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005157 ConstantInt::get(IntPtrTy, Size),
5158 GEP->getName()+".offs"), I);
5159 continue;
5160 }
5161
5162 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5163 Constant *OC = ConstantExpr::getIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5164 Scale = ConstantExpr::getMul(OC, Scale);
5165 if (Constant *RC = dyn_cast<Constant>(Result))
5166 Result = ConstantExpr::getAdd(RC, Scale);
5167 else {
5168 // Emit an add instruction.
5169 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00005170 BinaryOperator::CreateAdd(Result, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005171 GEP->getName()+".offs"), I);
5172 }
5173 continue;
5174 }
5175 // Convert to correct type.
5176 if (Op->getType() != IntPtrTy) {
5177 if (Constant *OpC = dyn_cast<Constant>(Op))
5178 Op = ConstantExpr::getSExt(OpC, IntPtrTy);
5179 else
5180 Op = IC.InsertNewInstBefore(new SExtInst(Op, IntPtrTy,
5181 Op->getName()+".c"), I);
5182 }
5183 if (Size != 1) {
5184 Constant *Scale = ConstantInt::get(IntPtrTy, Size);
5185 if (Constant *OpC = dyn_cast<Constant>(Op))
5186 Op = ConstantExpr::getMul(OpC, Scale);
5187 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greifa645dd32008-05-16 19:29:10 +00005188 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005189 GEP->getName()+".idx"), I);
5190 }
5191
5192 // Emit an add instruction.
5193 if (isa<Constant>(Op) && isa<Constant>(Result))
5194 Result = ConstantExpr::getAdd(cast<Constant>(Op),
5195 cast<Constant>(Result));
5196 else
Gabor Greifa645dd32008-05-16 19:29:10 +00005197 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005198 GEP->getName()+".offs"), I);
5199 }
5200 return Result;
5201}
5202
Chris Lattnereba75862008-04-22 02:53:33 +00005203
5204/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5205/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5206/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5207/// complex, and scales are involved. The above expression would also be legal
5208/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5209/// later form is less amenable to optimization though, and we are allowed to
5210/// generate the first by knowing that pointer arithmetic doesn't overflow.
5211///
5212/// If we can't emit an optimized form for this expression, this returns null.
5213///
5214static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5215 InstCombiner &IC) {
Chris Lattnereba75862008-04-22 02:53:33 +00005216 TargetData &TD = IC.getTargetData();
5217 gep_type_iterator GTI = gep_type_begin(GEP);
5218
5219 // Check to see if this gep only has a single variable index. If so, and if
5220 // any constant indices are a multiple of its scale, then we can compute this
5221 // in terms of the scale of the variable index. For example, if the GEP
5222 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5223 // because the expression will cross zero at the same point.
5224 unsigned i, e = GEP->getNumOperands();
5225 int64_t Offset = 0;
5226 for (i = 1; i != e; ++i, ++GTI) {
5227 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5228 // Compute the aggregate offset of constant indices.
5229 if (CI->isZero()) continue;
5230
5231 // Handle a struct index, which adds its field offset to the pointer.
5232 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5233 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5234 } else {
Duncan Sandsd68f13b2009-01-12 20:38:59 +00005235 uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005236 Offset += Size*CI->getSExtValue();
5237 }
5238 } else {
5239 // Found our variable index.
5240 break;
5241 }
5242 }
5243
5244 // If there are no variable indices, we must have a constant offset, just
5245 // evaluate it the general way.
5246 if (i == e) return 0;
5247
5248 Value *VariableIdx = GEP->getOperand(i);
5249 // Determine the scale factor of the variable element. For example, this is
5250 // 4 if the variable index is into an array of i32.
Duncan Sandsd68f13b2009-01-12 20:38:59 +00005251 uint64_t VariableScale = TD.getTypePaddedSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005252
5253 // Verify that there are no other variable indices. If so, emit the hard way.
5254 for (++i, ++GTI; i != e; ++i, ++GTI) {
5255 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5256 if (!CI) return 0;
5257
5258 // Compute the aggregate offset of constant indices.
5259 if (CI->isZero()) continue;
5260
5261 // Handle a struct index, which adds its field offset to the pointer.
5262 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5263 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5264 } else {
Duncan Sandsd68f13b2009-01-12 20:38:59 +00005265 uint64_t Size = TD.getTypePaddedSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005266 Offset += Size*CI->getSExtValue();
5267 }
5268 }
5269
5270 // Okay, we know we have a single variable index, which must be a
5271 // pointer/array/vector index. If there is no offset, life is simple, return
5272 // the index.
5273 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5274 if (Offset == 0) {
5275 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5276 // we don't need to bother extending: the extension won't affect where the
5277 // computation crosses zero.
5278 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5279 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5280 VariableIdx->getNameStart(), &I);
5281 return VariableIdx;
5282 }
5283
5284 // Otherwise, there is an index. The computation we will do will be modulo
5285 // the pointer size, so get it.
5286 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5287
5288 Offset &= PtrSizeMask;
5289 VariableScale &= PtrSizeMask;
5290
5291 // To do this transformation, any constant index must be a multiple of the
5292 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5293 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5294 // multiple of the variable scale.
5295 int64_t NewOffs = Offset / (int64_t)VariableScale;
5296 if (Offset != NewOffs*(int64_t)VariableScale)
5297 return 0;
5298
5299 // Okay, we can do this evaluation. Start by converting the index to intptr.
5300 const Type *IntPtrTy = TD.getIntPtrType();
5301 if (VariableIdx->getType() != IntPtrTy)
Gabor Greifa645dd32008-05-16 19:29:10 +00005302 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattnereba75862008-04-22 02:53:33 +00005303 true /*SExt*/,
5304 VariableIdx->getNameStart(), &I);
5305 Constant *OffsetVal = ConstantInt::get(IntPtrTy, NewOffs);
Gabor Greifa645dd32008-05-16 19:29:10 +00005306 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattnereba75862008-04-22 02:53:33 +00005307}
5308
5309
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005310/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5311/// else. At this point we know that the GEP is on the LHS of the comparison.
5312Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5313 ICmpInst::Predicate Cond,
5314 Instruction &I) {
5315 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5316
Chris Lattnereba75862008-04-22 02:53:33 +00005317 // Look through bitcasts.
5318 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5319 RHS = BCI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005320
5321 Value *PtrBase = GEPLHS->getOperand(0);
5322 if (PtrBase == RHS) {
Chris Lattneraf97d022008-02-05 04:45:32 +00005323 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattnereba75862008-04-22 02:53:33 +00005324 // This transformation (ignoring the base and scales) is valid because we
5325 // know pointers can't overflow. See if we can output an optimized form.
5326 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5327
5328 // If not, synthesize the offset the hard way.
5329 if (Offset == 0)
5330 Offset = EmitGEPOffset(GEPLHS, I, *this);
Chris Lattneraf97d022008-02-05 04:45:32 +00005331 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
5332 Constant::getNullValue(Offset->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005333 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5334 // If the base pointers are different, but the indices are the same, just
5335 // compare the base pointer.
5336 if (PtrBase != GEPRHS->getOperand(0)) {
5337 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5338 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5339 GEPRHS->getOperand(0)->getType();
5340 if (IndicesTheSame)
5341 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5342 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5343 IndicesTheSame = false;
5344 break;
5345 }
5346
5347 // If all indices are the same, just compare the base pointers.
5348 if (IndicesTheSame)
5349 return new ICmpInst(ICmpInst::getSignedPredicate(Cond),
5350 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5351
5352 // Otherwise, the base pointers are different and the indices are
5353 // different, bail out.
5354 return 0;
5355 }
5356
5357 // If one of the GEPs has all zero indices, recurse.
5358 bool AllZeros = true;
5359 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5360 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5361 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5362 AllZeros = false;
5363 break;
5364 }
5365 if (AllZeros)
5366 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5367 ICmpInst::getSwappedPredicate(Cond), I);
5368
5369 // If the other GEP has all zero indices, recurse.
5370 AllZeros = true;
5371 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5372 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5373 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5374 AllZeros = false;
5375 break;
5376 }
5377 if (AllZeros)
5378 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5379
5380 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5381 // If the GEPs only differ by one index, compare it.
5382 unsigned NumDifferences = 0; // Keep track of # differences.
5383 unsigned DiffOperand = 0; // The operand that differs.
5384 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5385 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5386 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5387 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5388 // Irreconcilable differences.
5389 NumDifferences = 2;
5390 break;
5391 } else {
5392 if (NumDifferences++) break;
5393 DiffOperand = i;
5394 }
5395 }
5396
5397 if (NumDifferences == 0) // SAME GEP?
5398 return ReplaceInstUsesWith(I, // No comparison is needed here.
Nick Lewycky2de09a92007-09-06 02:40:25 +00005399 ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005400 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky2de09a92007-09-06 02:40:25 +00005401
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005402 else if (NumDifferences == 1) {
5403 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5404 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5405 // Make sure we do a signed comparison here.
5406 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
5407 }
5408 }
5409
5410 // Only lower this if the icmp is the only user of the GEP or if we expect
5411 // the result to fold to a constant!
5412 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5413 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5414 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5415 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5416 Value *R = EmitGEPOffset(GEPRHS, I, *this);
5417 return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
5418 }
5419 }
5420 return 0;
5421}
5422
Chris Lattnere6b62d92008-05-19 20:18:56 +00005423/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5424///
5425Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5426 Instruction *LHSI,
5427 Constant *RHSC) {
5428 if (!isa<ConstantFP>(RHSC)) return 0;
5429 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5430
5431 // Get the width of the mantissa. We don't want to hack on conversions that
5432 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner9ce836b2008-05-19 21:17:23 +00005433 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005434 if (MantissaWidth == -1) return 0; // Unknown.
5435
5436 // Check to see that the input is converted from an integer type that is small
5437 // enough that preserves all bits. TODO: check here for "known" sign bits.
5438 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
5439 unsigned InputSize = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
5440
5441 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendling20636df2008-11-09 04:26:50 +00005442 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5443 if (LHSUnsigned)
Chris Lattnere6b62d92008-05-19 20:18:56 +00005444 ++InputSize;
5445
5446 // If the conversion would lose info, don't hack on this.
5447 if ((int)InputSize > MantissaWidth)
5448 return 0;
5449
5450 // Otherwise, we can potentially simplify the comparison. We know that it
5451 // will always come through as an integer value and we know the constant is
5452 // not a NAN (it would have been previously simplified).
5453 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5454
5455 ICmpInst::Predicate Pred;
5456 switch (I.getPredicate()) {
5457 default: assert(0 && "Unexpected predicate!");
5458 case FCmpInst::FCMP_UEQ:
Bill Wendling20636df2008-11-09 04:26:50 +00005459 case FCmpInst::FCMP_OEQ:
5460 Pred = ICmpInst::ICMP_EQ;
5461 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005462 case FCmpInst::FCMP_UGT:
Bill Wendling20636df2008-11-09 04:26:50 +00005463 case FCmpInst::FCMP_OGT:
5464 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5465 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005466 case FCmpInst::FCMP_UGE:
Bill Wendling20636df2008-11-09 04:26:50 +00005467 case FCmpInst::FCMP_OGE:
5468 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5469 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005470 case FCmpInst::FCMP_ULT:
Bill Wendling20636df2008-11-09 04:26:50 +00005471 case FCmpInst::FCMP_OLT:
5472 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5473 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005474 case FCmpInst::FCMP_ULE:
Bill Wendling20636df2008-11-09 04:26:50 +00005475 case FCmpInst::FCMP_OLE:
5476 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5477 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005478 case FCmpInst::FCMP_UNE:
Bill Wendling20636df2008-11-09 04:26:50 +00005479 case FCmpInst::FCMP_ONE:
5480 Pred = ICmpInst::ICMP_NE;
5481 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005482 case FCmpInst::FCMP_ORD:
Eli Friedmanc9c96242008-11-30 22:48:49 +00005483 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnere6b62d92008-05-19 20:18:56 +00005484 case FCmpInst::FCMP_UNO:
Eli Friedmanc9c96242008-11-30 22:48:49 +00005485 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnere6b62d92008-05-19 20:18:56 +00005486 }
5487
5488 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5489
5490 // Now we know that the APFloat is a normal number, zero or inf.
5491
Chris Lattnerf13ff492008-05-20 03:50:52 +00005492 // See if the FP constant is too large for the integer. For example,
Chris Lattnere6b62d92008-05-19 20:18:56 +00005493 // comparing an i8 to 300.0.
5494 unsigned IntWidth = IntTy->getPrimitiveSizeInBits();
5495
Bill Wendling20636df2008-11-09 04:26:50 +00005496 if (!LHSUnsigned) {
5497 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5498 // and large values.
5499 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5500 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5501 APFloat::rmNearestTiesToEven);
5502 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5503 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5504 Pred == ICmpInst::ICMP_SLE)
Eli Friedmanc9c96242008-11-30 22:48:49 +00005505 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5506 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendling20636df2008-11-09 04:26:50 +00005507 }
5508 } else {
5509 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5510 // +INF and large values.
5511 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5512 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5513 APFloat::rmNearestTiesToEven);
5514 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5515 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5516 Pred == ICmpInst::ICMP_ULE)
Eli Friedmanc9c96242008-11-30 22:48:49 +00005517 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5518 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendling20636df2008-11-09 04:26:50 +00005519 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005520 }
5521
Bill Wendling20636df2008-11-09 04:26:50 +00005522 if (!LHSUnsigned) {
5523 // See if the RHS value is < SignedMin.
5524 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5525 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5526 APFloat::rmNearestTiesToEven);
5527 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5528 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5529 Pred == ICmpInst::ICMP_SGE)
Eli Friedmanc9c96242008-11-30 22:48:49 +00005530 return ReplaceInstUsesWith(I,ConstantInt::getTrue());
5531 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendling20636df2008-11-09 04:26:50 +00005532 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005533 }
5534
Bill Wendling20636df2008-11-09 04:26:50 +00005535 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5536 // [0, UMAX], but it may still be fractional. See if it is fractional by
5537 // casting the FP value to the integer value and back, checking for equality.
5538 // Don't do this for zero, because -0.0 is not fractional.
Chris Lattnere6b62d92008-05-19 20:18:56 +00005539 Constant *RHSInt = ConstantExpr::getFPToSI(RHSC, IntTy);
5540 if (!RHS.isZero() &&
5541 ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) != RHSC) {
Bill Wendling20636df2008-11-09 04:26:50 +00005542 // If we had a comparison against a fractional value, we have to adjust the
5543 // compare predicate and sometimes the value. RHSC is rounded towards zero
5544 // at this point.
Chris Lattnere6b62d92008-05-19 20:18:56 +00005545 switch (Pred) {
5546 default: assert(0 && "Unexpected integer comparison!");
5547 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Eli Friedmanc9c96242008-11-30 22:48:49 +00005548 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnere6b62d92008-05-19 20:18:56 +00005549 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Eli Friedmanc9c96242008-11-30 22:48:49 +00005550 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendling20636df2008-11-09 04:26:50 +00005551 case ICmpInst::ICMP_ULE:
5552 // (float)int <= 4.4 --> int <= 4
5553 // (float)int <= -4.4 --> false
5554 if (RHS.isNegative())
Eli Friedmanc9c96242008-11-30 22:48:49 +00005555 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendling20636df2008-11-09 04:26:50 +00005556 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005557 case ICmpInst::ICMP_SLE:
5558 // (float)int <= 4.4 --> int <= 4
5559 // (float)int <= -4.4 --> int < -4
5560 if (RHS.isNegative())
5561 Pred = ICmpInst::ICMP_SLT;
5562 break;
Bill Wendling20636df2008-11-09 04:26:50 +00005563 case ICmpInst::ICMP_ULT:
5564 // (float)int < -4.4 --> false
5565 // (float)int < 4.4 --> int <= 4
5566 if (RHS.isNegative())
Eli Friedmanc9c96242008-11-30 22:48:49 +00005567 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Bill Wendling20636df2008-11-09 04:26:50 +00005568 Pred = ICmpInst::ICMP_ULE;
5569 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005570 case ICmpInst::ICMP_SLT:
5571 // (float)int < -4.4 --> int < -4
5572 // (float)int < 4.4 --> int <= 4
5573 if (!RHS.isNegative())
5574 Pred = ICmpInst::ICMP_SLE;
5575 break;
Bill Wendling20636df2008-11-09 04:26:50 +00005576 case ICmpInst::ICMP_UGT:
5577 // (float)int > 4.4 --> int > 4
5578 // (float)int > -4.4 --> true
5579 if (RHS.isNegative())
Eli Friedmanc9c96242008-11-30 22:48:49 +00005580 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Bill Wendling20636df2008-11-09 04:26:50 +00005581 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005582 case ICmpInst::ICMP_SGT:
5583 // (float)int > 4.4 --> int > 4
5584 // (float)int > -4.4 --> int >= -4
5585 if (RHS.isNegative())
5586 Pred = ICmpInst::ICMP_SGE;
5587 break;
Bill Wendling20636df2008-11-09 04:26:50 +00005588 case ICmpInst::ICMP_UGE:
5589 // (float)int >= -4.4 --> true
5590 // (float)int >= 4.4 --> int > 4
5591 if (!RHS.isNegative())
Eli Friedmanc9c96242008-11-30 22:48:49 +00005592 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Bill Wendling20636df2008-11-09 04:26:50 +00005593 Pred = ICmpInst::ICMP_UGT;
5594 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005595 case ICmpInst::ICMP_SGE:
5596 // (float)int >= -4.4 --> int >= -4
5597 // (float)int >= 4.4 --> int > 4
5598 if (!RHS.isNegative())
5599 Pred = ICmpInst::ICMP_SGT;
5600 break;
5601 }
5602 }
5603
5604 // Lower this FP comparison into an appropriate integer version of the
5605 // comparison.
5606 return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
5607}
5608
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005609Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5610 bool Changed = SimplifyCompare(I);
5611 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5612
5613 // Fold trivial predicates.
5614 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Eli Friedmanc9c96242008-11-30 22:48:49 +00005615 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005616 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Eli Friedmanc9c96242008-11-30 22:48:49 +00005617 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005618
5619 // Simplify 'fcmp pred X, X'
5620 if (Op0 == Op1) {
5621 switch (I.getPredicate()) {
5622 default: assert(0 && "Unknown predicate!");
5623 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5624 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5625 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Eli Friedmanc9c96242008-11-30 22:48:49 +00005626 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005627 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5628 case FCmpInst::FCMP_OLT: // True if ordered and less than
5629 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Eli Friedmanc9c96242008-11-30 22:48:49 +00005630 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005631
5632 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5633 case FCmpInst::FCMP_ULT: // True if unordered or less than
5634 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5635 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5636 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5637 I.setPredicate(FCmpInst::FCMP_UNO);
5638 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5639 return &I;
5640
5641 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5642 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5643 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5644 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5645 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5646 I.setPredicate(FCmpInst::FCMP_ORD);
5647 I.setOperand(1, Constant::getNullValue(Op0->getType()));
5648 return &I;
5649 }
5650 }
5651
5652 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
5653 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
5654
5655 // Handle fcmp with constant RHS
5656 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnere6b62d92008-05-19 20:18:56 +00005657 // If the constant is a nan, see if we can fold the comparison based on it.
5658 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5659 if (CFP->getValueAPF().isNaN()) {
5660 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Eli Friedmanc9c96242008-11-30 22:48:49 +00005661 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnerf13ff492008-05-20 03:50:52 +00005662 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5663 "Comparison must be either ordered or unordered!");
5664 // True if unordered.
Eli Friedmanc9c96242008-11-30 22:48:49 +00005665 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnere6b62d92008-05-19 20:18:56 +00005666 }
5667 }
5668
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005669 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5670 switch (LHSI->getOpcode()) {
5671 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00005672 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5673 // block. If in the same block, we're encouraging jump threading. If
5674 // not, we are just pessimizing the code by making an i1 phi.
5675 if (LHSI->getParent() == I.getParent())
5676 if (Instruction *NV = FoldOpIntoPhi(I))
5677 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005678 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005679 case Instruction::SIToFP:
5680 case Instruction::UIToFP:
5681 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5682 return NV;
5683 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005684 case Instruction::Select:
5685 // If either operand of the select is a constant, we can fold the
5686 // comparison into the select arms, which will cause one to be
5687 // constant folded and the select turned into a bitwise or.
5688 Value *Op1 = 0, *Op2 = 0;
5689 if (LHSI->hasOneUse()) {
5690 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5691 // Fold the known value into the constant operand.
5692 Op1 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5693 // Insert a new FCmp of the other select operand.
5694 Op2 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5695 LHSI->getOperand(2), RHSC,
5696 I.getName()), I);
5697 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5698 // Fold the known value into the constant operand.
5699 Op2 = ConstantExpr::getCompare(I.getPredicate(), C, RHSC);
5700 // Insert a new FCmp of the other select operand.
5701 Op1 = InsertNewInstBefore(new FCmpInst(I.getPredicate(),
5702 LHSI->getOperand(1), RHSC,
5703 I.getName()), I);
5704 }
5705 }
5706
5707 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00005708 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005709 break;
5710 }
5711 }
5712
5713 return Changed ? &I : 0;
5714}
5715
5716Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5717 bool Changed = SimplifyCompare(I);
5718 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5719 const Type *Ty = Op0->getType();
5720
5721 // icmp X, X
5722 if (Op0 == Op1)
5723 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005724 I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005725
5726 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
5727 return ReplaceInstUsesWith(I, UndefValue::get(Type::Int1Ty));
Christopher Lambf78cd322007-12-18 21:32:20 +00005728
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005729 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5730 // addresses never equal each other! We already know that Op0 != Op1.
5731 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5732 isa<ConstantPointerNull>(Op0)) &&
5733 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5734 isa<ConstantPointerNull>(Op1)))
5735 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005736 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005737
5738 // icmp's with boolean values can always be turned into bitwise operations
5739 if (Ty == Type::Int1Ty) {
5740 switch (I.getPredicate()) {
5741 default: assert(0 && "Invalid icmp instruction!");
Chris Lattnera02893d2008-07-11 04:20:58 +00005742 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greifa645dd32008-05-16 19:29:10 +00005743 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005744 InsertNewInstBefore(Xor, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005745 return BinaryOperator::CreateNot(Xor);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005746 }
Chris Lattnera02893d2008-07-11 04:20:58 +00005747 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greifa645dd32008-05-16 19:29:10 +00005748 return BinaryOperator::CreateXor(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005749
5750 case ICmpInst::ICMP_UGT:
Chris Lattnera02893d2008-07-11 04:20:58 +00005751 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005752 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00005753 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Gabor Greifa645dd32008-05-16 19:29:10 +00005754 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005755 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005756 return BinaryOperator::CreateAnd(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005757 }
Chris Lattnera02893d2008-07-11 04:20:58 +00005758 case ICmpInst::ICMP_SGT:
5759 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005760 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00005761 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
5762 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5763 InsertNewInstBefore(Not, I);
5764 return BinaryOperator::CreateAnd(Not, Op0);
5765 }
5766 case ICmpInst::ICMP_UGE:
5767 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
5768 // FALL THROUGH
5769 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Gabor Greifa645dd32008-05-16 19:29:10 +00005770 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005771 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005772 return BinaryOperator::CreateOr(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005773 }
Chris Lattnera02893d2008-07-11 04:20:58 +00005774 case ICmpInst::ICMP_SGE:
5775 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
5776 // FALL THROUGH
5777 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
5778 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
5779 InsertNewInstBefore(Not, I);
5780 return BinaryOperator::CreateOr(Not, Op0);
5781 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005782 }
5783 }
5784
Dan Gohman58c09632008-09-16 18:46:06 +00005785 // See if we are doing a comparison with a constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005786 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Chris Lattner3d816532008-07-11 04:09:09 +00005787 Value *A, *B;
Christopher Lambfa6b3102007-12-20 07:21:11 +00005788
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00005789 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
5790 if (I.isEquality() && CI->isNullValue() &&
5791 match(Op0, m_Sub(m_Value(A), m_Value(B)))) {
5792 // (icmp cond A B) if cond is equality
5793 return new ICmpInst(I.getPredicate(), A, B);
Owen Anderson42f61ed2007-12-28 07:42:12 +00005794 }
Christopher Lambfa6b3102007-12-20 07:21:11 +00005795
Dan Gohman58c09632008-09-16 18:46:06 +00005796 // If we have an icmp le or icmp ge instruction, turn it into the
5797 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
5798 // them being folded in the code below.
Chris Lattner62d0f232008-07-11 05:08:55 +00005799 switch (I.getPredicate()) {
5800 default: break;
5801 case ICmpInst::ICMP_ULE:
5802 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
5803 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5804 return new ICmpInst(ICmpInst::ICMP_ULT, Op0, AddOne(CI));
5805 case ICmpInst::ICMP_SLE:
5806 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
5807 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5808 return new ICmpInst(ICmpInst::ICMP_SLT, Op0, AddOne(CI));
5809 case ICmpInst::ICMP_UGE:
5810 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
5811 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5812 return new ICmpInst( ICmpInst::ICMP_UGT, Op0, SubOne(CI));
5813 case ICmpInst::ICMP_SGE:
5814 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
5815 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5816 return new ICmpInst(ICmpInst::ICMP_SGT, Op0, SubOne(CI));
5817 }
5818
Chris Lattnera1308652008-07-11 05:40:05 +00005819 // See if we can fold the comparison based on range information we can get
5820 // by checking whether bits are known to be zero or one in the input.
5821 uint32_t BitWidth = cast<IntegerType>(Ty)->getBitWidth();
5822 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
5823
5824 // If this comparison is a normal comparison, it demands all
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005825 // bits, if it is a sign bit comparison, it only demands the sign bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005826 bool UnusedBit;
5827 bool isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
5828
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005829 if (SimplifyDemandedBits(Op0,
5830 isSignBit ? APInt::getSignBit(BitWidth)
5831 : APInt::getAllOnesValue(BitWidth),
5832 KnownZero, KnownOne, 0))
5833 return &I;
5834
5835 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner62d0f232008-07-11 05:08:55 +00005836 // in. Compute the Min, Max and RHS values based on the known bits. For the
5837 // EQ and NE we use unsigned values.
5838 APInt Min(BitWidth, 0), Max(BitWidth, 0);
Chris Lattner62d0f232008-07-11 05:08:55 +00005839 if (ICmpInst::isSignedPredicate(I.getPredicate()))
5840 ComputeSignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne, Min, Max);
5841 else
5842 ComputeUnsignedMinMaxValuesFromKnownBits(Ty, KnownZero, KnownOne,Min,Max);
5843
Chris Lattnera1308652008-07-11 05:40:05 +00005844 // If Min and Max are known to be the same, then SimplifyDemandedBits
5845 // figured out that the LHS is a constant. Just constant fold this now so
5846 // that code below can assume that Min != Max.
5847 if (Min == Max)
5848 return ReplaceInstUsesWith(I, ConstantExpr::getICmp(I.getPredicate(),
5849 ConstantInt::get(Min),
5850 CI));
5851
5852 // Based on the range information we know about the LHS, see if we can
5853 // simplify this comparison. For example, (x&4) < 8 is always true.
5854 const APInt &RHSVal = CI->getValue();
Chris Lattner62d0f232008-07-11 05:08:55 +00005855 switch (I.getPredicate()) { // LE/GE have been folded already.
5856 default: assert(0 && "Unknown icmp opcode!");
5857 case ICmpInst::ICMP_EQ:
5858 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5859 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
5860 break;
5861 case ICmpInst::ICMP_NE:
5862 if (Max.ult(RHSVal) || Min.ugt(RHSVal))
5863 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
5864 break;
5865 case ICmpInst::ICMP_ULT:
Chris Lattnera1308652008-07-11 05:40:05 +00005866 if (Max.ult(RHSVal)) // A <u C -> true iff max(A) < C
Chris Lattner62d0f232008-07-11 05:08:55 +00005867 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera1308652008-07-11 05:40:05 +00005868 if (Min.uge(RHSVal)) // A <u C -> false iff min(A) >= C
Chris Lattner62d0f232008-07-11 05:08:55 +00005869 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnera1308652008-07-11 05:40:05 +00005870 if (RHSVal == Max) // A <u MAX -> A != MAX
5871 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5872 if (RHSVal == Min+1) // A <u MIN+1 -> A == MIN
5873 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
5874
5875 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
5876 if (CI->isMinValue(true))
5877 return new ICmpInst(ICmpInst::ICMP_SGT, Op0,
5878 ConstantInt::getAllOnesValue(Op0->getType()));
Chris Lattner62d0f232008-07-11 05:08:55 +00005879 break;
5880 case ICmpInst::ICMP_UGT:
Chris Lattnera1308652008-07-11 05:40:05 +00005881 if (Min.ugt(RHSVal)) // A >u C -> true iff min(A) > C
Chris Lattner62d0f232008-07-11 05:08:55 +00005882 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera1308652008-07-11 05:40:05 +00005883 if (Max.ule(RHSVal)) // A >u C -> false iff max(A) <= C
Chris Lattner62d0f232008-07-11 05:08:55 +00005884 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnera1308652008-07-11 05:40:05 +00005885
5886 if (RHSVal == Min) // A >u MIN -> A != MIN
5887 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5888 if (RHSVal == Max-1) // A >u MAX-1 -> A == MAX
5889 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
5890
5891 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
5892 if (CI->isMaxValue(true))
5893 return new ICmpInst(ICmpInst::ICMP_SLT, Op0,
5894 ConstantInt::getNullValue(Op0->getType()));
Chris Lattner62d0f232008-07-11 05:08:55 +00005895 break;
5896 case ICmpInst::ICMP_SLT:
Chris Lattnera1308652008-07-11 05:40:05 +00005897 if (Max.slt(RHSVal)) // A <s C -> true iff max(A) < C
Chris Lattner62d0f232008-07-11 05:08:55 +00005898 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattner611b43e2008-07-11 06:40:29 +00005899 if (Min.sge(RHSVal)) // A <s C -> false iff min(A) >= C
Chris Lattner62d0f232008-07-11 05:08:55 +00005900 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnera1308652008-07-11 05:40:05 +00005901 if (RHSVal == Max) // A <s MAX -> A != MAX
5902 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
Chris Lattner3496f3e2008-07-11 06:36:01 +00005903 if (RHSVal == Min+1) // A <s MIN+1 -> A == MIN
Chris Lattner55ab3152008-07-11 06:38:16 +00005904 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, SubOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00005905 break;
5906 case ICmpInst::ICMP_SGT:
Chris Lattnera1308652008-07-11 05:40:05 +00005907 if (Min.sgt(RHSVal)) // A >s C -> true iff min(A) > C
Chris Lattner62d0f232008-07-11 05:08:55 +00005908 return ReplaceInstUsesWith(I, ConstantInt::getTrue());
Chris Lattnera1308652008-07-11 05:40:05 +00005909 if (Max.sle(RHSVal)) // A >s C -> false iff max(A) <= C
Chris Lattner62d0f232008-07-11 05:08:55 +00005910 return ReplaceInstUsesWith(I, ConstantInt::getFalse());
Chris Lattnera1308652008-07-11 05:40:05 +00005911
5912 if (RHSVal == Min) // A >s MIN -> A != MIN
5913 return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
5914 if (RHSVal == Max-1) // A >s MAX-1 -> A == MAX
5915 return new ICmpInst(ICmpInst::ICMP_EQ, Op0, AddOne(CI));
Chris Lattner62d0f232008-07-11 05:08:55 +00005916 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005917 }
Dan Gohman58c09632008-09-16 18:46:06 +00005918 }
5919
5920 // Test if the ICmpInst instruction is used exclusively by a select as
5921 // part of a minimum or maximum operation. If so, refrain from doing
5922 // any other folding. This helps out other analyses which understand
5923 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
5924 // and CodeGen. And in this case, at least one of the comparison
5925 // operands has at least one user besides the compare (the select),
5926 // which would often largely negate the benefit of folding anyway.
5927 if (I.hasOneUse())
5928 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
5929 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
5930 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
5931 return 0;
5932
5933 // See if we are doing a comparison between a constant and an instruction that
5934 // can be folded into the comparison.
5935 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005936 // Since the RHS is a ConstantInt (CI), if the left hand side is an
5937 // instruction, see if that instruction also has constants so that the
5938 // instruction can be folded into the icmp
5939 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5940 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
5941 return Res;
5942 }
5943
5944 // Handle icmp with constant (but not simple integer constant) RHS
5945 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
5946 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5947 switch (LHSI->getOpcode()) {
5948 case Instruction::GetElementPtr:
5949 if (RHSC->isNullValue()) {
5950 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
5951 bool isAllZeros = true;
5952 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
5953 if (!isa<Constant>(LHSI->getOperand(i)) ||
5954 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
5955 isAllZeros = false;
5956 break;
5957 }
5958 if (isAllZeros)
5959 return new ICmpInst(I.getPredicate(), LHSI->getOperand(0),
5960 Constant::getNullValue(LHSI->getOperand(0)->getType()));
5961 }
5962 break;
5963
5964 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00005965 // Only fold icmp into the PHI if the phi and fcmp are in the same
5966 // block. If in the same block, we're encouraging jump threading. If
5967 // not, we are just pessimizing the code by making an i1 phi.
5968 if (LHSI->getParent() == I.getParent())
5969 if (Instruction *NV = FoldOpIntoPhi(I))
5970 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005971 break;
5972 case Instruction::Select: {
5973 // If either operand of the select is a constant, we can fold the
5974 // comparison into the select arms, which will cause one to be
5975 // constant folded and the select turned into a bitwise or.
5976 Value *Op1 = 0, *Op2 = 0;
5977 if (LHSI->hasOneUse()) {
5978 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5979 // Fold the known value into the constant operand.
5980 Op1 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5981 // Insert a new ICmp of the other select operand.
5982 Op2 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5983 LHSI->getOperand(2), RHSC,
5984 I.getName()), I);
5985 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5986 // Fold the known value into the constant operand.
5987 Op2 = ConstantExpr::getICmp(I.getPredicate(), C, RHSC);
5988 // Insert a new ICmp of the other select operand.
5989 Op1 = InsertNewInstBefore(new ICmpInst(I.getPredicate(),
5990 LHSI->getOperand(1), RHSC,
5991 I.getName()), I);
5992 }
5993 }
5994
5995 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00005996 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005997 break;
5998 }
5999 case Instruction::Malloc:
6000 // If we have (malloc != null), and if the malloc has a single use, we
6001 // can assume it is successful and remove the malloc.
6002 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6003 AddToWorkList(LHSI);
6004 return ReplaceInstUsesWith(I, ConstantInt::get(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00006005 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006006 }
6007 break;
6008 }
6009 }
6010
6011 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6012 if (User *GEP = dyn_castGetElementPtr(Op0))
6013 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6014 return NI;
6015 if (User *GEP = dyn_castGetElementPtr(Op1))
6016 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6017 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6018 return NI;
6019
6020 // Test to see if the operands of the icmp are casted versions of other
6021 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6022 // now.
6023 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6024 if (isa<PointerType>(Op0->getType()) &&
6025 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6026 // We keep moving the cast from the left operand over to the right
6027 // operand, where it can often be eliminated completely.
6028 Op0 = CI->getOperand(0);
6029
6030 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6031 // so eliminate it as well.
6032 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6033 Op1 = CI2->getOperand(0);
6034
6035 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006036 if (Op0->getType() != Op1->getType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006037 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
6038 Op1 = ConstantExpr::getBitCast(Op1C, Op0->getType());
6039 } else {
6040 // Otherwise, cast the RHS right before the icmp
Chris Lattner13c2d6e2008-01-13 22:23:22 +00006041 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006042 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006043 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006044 return new ICmpInst(I.getPredicate(), Op0, Op1);
6045 }
6046 }
6047
6048 if (isa<CastInst>(Op0)) {
6049 // Handle the special case of: icmp (cast bool to X), <cst>
6050 // This comes up when you have code like
6051 // int X = A < B;
6052 // if (X) ...
6053 // For generality, we handle any zero-extension of any operand comparison
6054 // with a constant or another cast from the same type.
6055 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6056 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6057 return R;
6058 }
6059
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006060 // See if it's the same type of instruction on the left and right.
6061 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6062 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006063 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
6064 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1) &&
6065 I.isEquality()) {
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00006066 switch (Op0I->getOpcode()) {
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006067 default: break;
6068 case Instruction::Add:
6069 case Instruction::Sub:
6070 case Instruction::Xor:
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006071 // a+x icmp eq/ne b+x --> a icmp b
6072 return new ICmpInst(I.getPredicate(), Op0I->getOperand(0),
6073 Op1I->getOperand(0));
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006074 break;
6075 case Instruction::Mul:
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006076 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6077 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6078 // Mask = -1 >> count-trailing-zeros(Cst).
6079 if (!CI->isZero() && !CI->isOne()) {
6080 const APInt &AP = CI->getValue();
6081 ConstantInt *Mask = ConstantInt::get(
6082 APInt::getLowBitsSet(AP.getBitWidth(),
6083 AP.getBitWidth() -
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006084 AP.countTrailingZeros()));
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006085 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6086 Mask);
6087 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6088 Mask);
6089 InsertNewInstBefore(And1, I);
6090 InsertNewInstBefore(And2, I);
6091 return new ICmpInst(I.getPredicate(), And1, And2);
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006092 }
6093 }
6094 break;
6095 }
6096 }
6097 }
6098 }
6099
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006100 // ~x < ~y --> y < x
6101 { Value *A, *B;
6102 if (match(Op0, m_Not(m_Value(A))) &&
6103 match(Op1, m_Not(m_Value(B))))
6104 return new ICmpInst(I.getPredicate(), B, A);
6105 }
6106
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006107 if (I.isEquality()) {
6108 Value *A, *B, *C, *D;
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006109
6110 // -x == -y --> x == y
6111 if (match(Op0, m_Neg(m_Value(A))) &&
6112 match(Op1, m_Neg(m_Value(B))))
6113 return new ICmpInst(I.getPredicate(), A, B);
6114
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006115 if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
6116 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6117 Value *OtherVal = A == Op1 ? B : A;
6118 return new ICmpInst(I.getPredicate(), OtherVal,
6119 Constant::getNullValue(A->getType()));
6120 }
6121
6122 if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
6123 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattner3b874082008-11-16 05:38:51 +00006124 ConstantInt *C1, *C2;
6125 if (match(B, m_ConstantInt(C1)) &&
6126 match(D, m_ConstantInt(C2)) && Op1->hasOneUse()) {
6127 Constant *NC = ConstantInt::get(C1->getValue() ^ C2->getValue());
6128 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
6129 return new ICmpInst(I.getPredicate(), A,
6130 InsertNewInstBefore(Xor, I));
6131 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006132
6133 // A^B == A^D -> B == D
6134 if (A == C) return new ICmpInst(I.getPredicate(), B, D);
6135 if (A == D) return new ICmpInst(I.getPredicate(), B, C);
6136 if (B == C) return new ICmpInst(I.getPredicate(), A, D);
6137 if (B == D) return new ICmpInst(I.getPredicate(), A, C);
6138 }
6139 }
6140
6141 if (match(Op1, m_Xor(m_Value(A), m_Value(B))) &&
6142 (A == Op0 || B == Op0)) {
6143 // A == (A^B) -> B == 0
6144 Value *OtherVal = A == Op0 ? B : A;
6145 return new ICmpInst(I.getPredicate(), OtherVal,
6146 Constant::getNullValue(A->getType()));
6147 }
Chris Lattner3b874082008-11-16 05:38:51 +00006148
6149 // (A-B) == A -> B == 0
6150 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B))))
6151 return new ICmpInst(I.getPredicate(), B,
6152 Constant::getNullValue(B->getType()));
6153
6154 // A == (A-B) -> B == 0
6155 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B))))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006156 return new ICmpInst(I.getPredicate(), B,
6157 Constant::getNullValue(B->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006158
6159 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6160 if (Op0->hasOneUse() && Op1->hasOneUse() &&
6161 match(Op0, m_And(m_Value(A), m_Value(B))) &&
6162 match(Op1, m_And(m_Value(C), m_Value(D)))) {
6163 Value *X = 0, *Y = 0, *Z = 0;
6164
6165 if (A == C) {
6166 X = B; Y = D; Z = A;
6167 } else if (A == D) {
6168 X = B; Y = C; Z = A;
6169 } else if (B == C) {
6170 X = A; Y = D; Z = B;
6171 } else if (B == D) {
6172 X = A; Y = C; Z = B;
6173 }
6174
6175 if (X) { // Build (X^Y) & Z
Gabor Greifa645dd32008-05-16 19:29:10 +00006176 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6177 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006178 I.setOperand(0, Op1);
6179 I.setOperand(1, Constant::getNullValue(Op1->getType()));
6180 return &I;
6181 }
6182 }
6183 }
6184 return Changed ? &I : 0;
6185}
6186
6187
6188/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6189/// and CmpRHS are both known to be integer constants.
6190Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6191 ConstantInt *DivRHS) {
6192 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6193 const APInt &CmpRHSV = CmpRHS->getValue();
6194
6195 // FIXME: If the operand types don't match the type of the divide
6196 // then don't attempt this transform. The code below doesn't have the
6197 // logic to deal with a signed divide and an unsigned compare (and
6198 // vice versa). This is because (x /s C1) <s C2 produces different
6199 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6200 // (x /u C1) <u C2. Simply casting the operands and result won't
6201 // work. :( The if statement below tests that condition and bails
6202 // if it finds it.
6203 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6204 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6205 return 0;
6206 if (DivRHS->isZero())
6207 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006208 if (DivIsSigned && DivRHS->isAllOnesValue())
6209 return 0; // The overflow computation also screws up here
6210 if (DivRHS->isOne())
6211 return 0; // Not worth bothering, and eliminates some funny cases
6212 // with INT_MIN.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006213
6214 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6215 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6216 // C2 (CI). By solving for X we can turn this into a range check
6217 // instead of computing a divide.
6218 ConstantInt *Prod = Multiply(CmpRHS, DivRHS);
6219
6220 // Determine if the product overflows by seeing if the product is
6221 // not equal to the divide. Make sure we do the same kind of divide
6222 // as in the LHS instruction that we're folding.
6223 bool ProdOV = (DivIsSigned ? ConstantExpr::getSDiv(Prod, DivRHS) :
6224 ConstantExpr::getUDiv(Prod, DivRHS)) != CmpRHS;
6225
6226 // Get the ICmp opcode
6227 ICmpInst::Predicate Pred = ICI.getPredicate();
6228
6229 // Figure out the interval that is being checked. For example, a comparison
6230 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6231 // Compute this interval based on the constants involved and the signedness of
6232 // the compare/divide. This computes a half-open interval, keeping track of
6233 // whether either value in the interval overflows. After analysis each
6234 // overflow variable is set to 0 if it's corresponding bound variable is valid
6235 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6236 int LoOverflow = 0, HiOverflow = 0;
6237 ConstantInt *LoBound = 0, *HiBound = 0;
6238
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006239 if (!DivIsSigned) { // udiv
6240 // e.g. X/5 op 3 --> [15, 20)
6241 LoBound = Prod;
6242 HiOverflow = LoOverflow = ProdOV;
6243 if (!HiOverflow)
6244 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, false);
Dan Gohman5dceed12008-02-13 22:09:18 +00006245 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006246 if (CmpRHSV == 0) { // (X / pos) op 0
6247 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
6248 LoBound = cast<ConstantInt>(ConstantExpr::getNeg(SubOne(DivRHS)));
6249 HiBound = DivRHS;
Dan Gohman5dceed12008-02-13 22:09:18 +00006250 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006251 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6252 HiOverflow = LoOverflow = ProdOV;
6253 if (!HiOverflow)
6254 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, true);
6255 } else { // (X / pos) op neg
6256 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006257 HiBound = AddOne(Prod);
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006258 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6259 if (!LoOverflow) {
6260 ConstantInt* DivNeg = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6261 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg,
6262 true) ? -1 : 0;
6263 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006264 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006265 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006266 if (CmpRHSV == 0) { // (X / neg) op 0
6267 // e.g. X/-5 op 0 --> [-4, 5)
6268 LoBound = AddOne(DivRHS);
6269 HiBound = cast<ConstantInt>(ConstantExpr::getNeg(DivRHS));
6270 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6271 HiOverflow = 1; // [INTMIN+1, overflow)
6272 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6273 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006274 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006275 // e.g. X/-5 op 3 --> [-19, -14)
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006276 HiBound = AddOne(Prod);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006277 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6278 if (!LoOverflow)
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006279 LoOverflow = AddWithOverflow(LoBound, HiBound, DivRHS, true) ? -1 : 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006280 } else { // (X / neg) op neg
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006281 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6282 LoOverflow = HiOverflow = ProdOV;
Dan Gohman45408ea2008-09-11 00:25:00 +00006283 if (!HiOverflow)
6284 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006285 }
6286
6287 // Dividing by a negative swaps the condition. LT <-> GT
6288 Pred = ICmpInst::getSwappedPredicate(Pred);
6289 }
6290
6291 Value *X = DivI->getOperand(0);
6292 switch (Pred) {
6293 default: assert(0 && "Unhandled icmp opcode!");
6294 case ICmpInst::ICMP_EQ:
6295 if (LoOverflow && HiOverflow)
6296 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6297 else if (HiOverflow)
6298 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6299 ICmpInst::ICMP_UGE, X, LoBound);
6300 else if (LoOverflow)
6301 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6302 ICmpInst::ICMP_ULT, X, HiBound);
6303 else
6304 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6305 case ICmpInst::ICMP_NE:
6306 if (LoOverflow && HiOverflow)
6307 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6308 else if (HiOverflow)
6309 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT :
6310 ICmpInst::ICMP_ULT, X, LoBound);
6311 else if (LoOverflow)
6312 return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE :
6313 ICmpInst::ICMP_UGE, X, HiBound);
6314 else
6315 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6316 case ICmpInst::ICMP_ULT:
6317 case ICmpInst::ICMP_SLT:
6318 if (LoOverflow == +1) // Low bound is greater than input range.
6319 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6320 if (LoOverflow == -1) // Low bound is less than input range.
6321 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6322 return new ICmpInst(Pred, X, LoBound);
6323 case ICmpInst::ICMP_UGT:
6324 case ICmpInst::ICMP_SGT:
6325 if (HiOverflow == +1) // High bound greater than input range.
6326 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6327 else if (HiOverflow == -1) // High bound less than input range.
6328 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6329 if (Pred == ICmpInst::ICMP_UGT)
6330 return new ICmpInst(ICmpInst::ICMP_UGE, X, HiBound);
6331 else
6332 return new ICmpInst(ICmpInst::ICMP_SGE, X, HiBound);
6333 }
6334}
6335
6336
6337/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6338///
6339Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6340 Instruction *LHSI,
6341 ConstantInt *RHS) {
6342 const APInt &RHSV = RHS->getValue();
6343
6344 switch (LHSI->getOpcode()) {
Chris Lattner56be1232009-01-09 07:47:06 +00006345 case Instruction::Trunc:
6346 if (ICI.isEquality() && LHSI->hasOneUse()) {
6347 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6348 // of the high bits truncated out of x are known.
6349 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6350 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6351 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6352 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6353 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6354
6355 // If all the high bits are known, we can do this xform.
6356 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6357 // Pull in the high bits from known-ones set.
6358 APInt NewRHS(RHS->getValue());
6359 NewRHS.zext(SrcBits);
6360 NewRHS |= KnownOne;
6361 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6362 ConstantInt::get(NewRHS));
6363 }
6364 }
6365 break;
6366
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006367 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6368 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6369 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6370 // fold the xor.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006371 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6372 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006373 Value *CompareVal = LHSI->getOperand(0);
6374
6375 // If the sign bit of the XorCST is not set, there is no change to
6376 // the operation, just stop using the Xor.
6377 if (!XorCST->getValue().isNegative()) {
6378 ICI.setOperand(0, CompareVal);
6379 AddToWorkList(LHSI);
6380 return &ICI;
6381 }
6382
6383 // Was the old condition true if the operand is positive?
6384 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6385
6386 // If so, the new one isn't.
6387 isTrueIfPositive ^= true;
6388
6389 if (isTrueIfPositive)
6390 return new ICmpInst(ICmpInst::ICMP_SGT, CompareVal, SubOne(RHS));
6391 else
6392 return new ICmpInst(ICmpInst::ICMP_SLT, CompareVal, AddOne(RHS));
6393 }
6394 }
6395 break;
6396 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6397 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6398 LHSI->getOperand(0)->hasOneUse()) {
6399 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6400
6401 // If the LHS is an AND of a truncating cast, we can widen the
6402 // and/compare to be the input width without changing the value
6403 // produced, eliminating a cast.
6404 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6405 // We can do this transformation if either the AND constant does not
6406 // have its sign bit set or if it is an equality comparison.
6407 // Extending a relational comparison when we're checking the sign
6408 // bit would not work.
6409 if (Cast->hasOneUse() &&
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00006410 (ICI.isEquality() ||
6411 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006412 uint32_t BitWidth =
6413 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6414 APInt NewCST = AndCST->getValue();
6415 NewCST.zext(BitWidth);
6416 APInt NewCI = RHSV;
6417 NewCI.zext(BitWidth);
6418 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00006419 BinaryOperator::CreateAnd(Cast->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006420 ConstantInt::get(NewCST),LHSI->getName());
6421 InsertNewInstBefore(NewAnd, ICI);
6422 return new ICmpInst(ICI.getPredicate(), NewAnd,
6423 ConstantInt::get(NewCI));
6424 }
6425 }
6426
6427 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6428 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6429 // happens a LOT in code produced by the C front-end, for bitfield
6430 // access.
6431 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6432 if (Shift && !Shift->isShift())
6433 Shift = 0;
6434
6435 ConstantInt *ShAmt;
6436 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6437 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6438 const Type *AndTy = AndCST->getType(); // Type of the and.
6439
6440 // We can fold this as long as we can't shift unknown bits
6441 // into the mask. This can only happen with signed shift
6442 // rights, as they sign-extend.
6443 if (ShAmt) {
6444 bool CanFold = Shift->isLogicalShift();
6445 if (!CanFold) {
6446 // To test for the bad case of the signed shr, see if any
6447 // of the bits shifted in could be tested after the mask.
6448 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6449 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6450
6451 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6452 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6453 AndCST->getValue()) == 0)
6454 CanFold = true;
6455 }
6456
6457 if (CanFold) {
6458 Constant *NewCst;
6459 if (Shift->getOpcode() == Instruction::Shl)
6460 NewCst = ConstantExpr::getLShr(RHS, ShAmt);
6461 else
6462 NewCst = ConstantExpr::getShl(RHS, ShAmt);
6463
6464 // Check to see if we are shifting out any of the bits being
6465 // compared.
6466 if (ConstantExpr::get(Shift->getOpcode(), NewCst, ShAmt) != RHS) {
6467 // If we shifted bits out, the fold is not going to work out.
6468 // As a special case, check to see if this means that the
6469 // result is always true or false now.
6470 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6471 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6472 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6473 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6474 } else {
6475 ICI.setOperand(1, NewCst);
6476 Constant *NewAndCST;
6477 if (Shift->getOpcode() == Instruction::Shl)
6478 NewAndCST = ConstantExpr::getLShr(AndCST, ShAmt);
6479 else
6480 NewAndCST = ConstantExpr::getShl(AndCST, ShAmt);
6481 LHSI->setOperand(1, NewAndCST);
6482 LHSI->setOperand(0, Shift->getOperand(0));
6483 AddToWorkList(Shift); // Shift is dead.
6484 AddUsesToWorkList(ICI);
6485 return &ICI;
6486 }
6487 }
6488 }
6489
6490 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6491 // preferable because it allows the C<<Y expression to be hoisted out
6492 // of a loop if Y is invariant and X is not.
6493 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
6494 ICI.isEquality() && !Shift->isArithmeticShift() &&
6495 isa<Instruction>(Shift->getOperand(0))) {
6496 // Compute C << Y.
6497 Value *NS;
6498 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006499 NS = BinaryOperator::CreateShl(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006500 Shift->getOperand(1), "tmp");
6501 } else {
6502 // Insert a logical shift.
Gabor Greifa645dd32008-05-16 19:29:10 +00006503 NS = BinaryOperator::CreateLShr(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006504 Shift->getOperand(1), "tmp");
6505 }
6506 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6507
6508 // Compute X & (C << Y).
6509 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00006510 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006511 InsertNewInstBefore(NewAnd, ICI);
6512
6513 ICI.setOperand(0, NewAnd);
6514 return &ICI;
6515 }
6516 }
6517 break;
6518
6519 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6520 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6521 if (!ShAmt) break;
6522
6523 uint32_t TypeBits = RHSV.getBitWidth();
6524
6525 // Check that the shift amount is in range. If not, don't perform
6526 // undefined shifts. When the shift is visited it will be
6527 // simplified.
6528 if (ShAmt->uge(TypeBits))
6529 break;
6530
6531 if (ICI.isEquality()) {
6532 // If we are comparing against bits always shifted out, the
6533 // comparison cannot succeed.
6534 Constant *Comp =
6535 ConstantExpr::getShl(ConstantExpr::getLShr(RHS, ShAmt), ShAmt);
6536 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6537 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6538 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6539 return ReplaceInstUsesWith(ICI, Cst);
6540 }
6541
6542 if (LHSI->hasOneUse()) {
6543 // Otherwise strength reduce the shift into an and.
6544 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6545 Constant *Mask =
6546 ConstantInt::get(APInt::getLowBitsSet(TypeBits, TypeBits-ShAmtVal));
6547
6548 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006549 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006550 Mask, LHSI->getName()+".mask");
6551 Value *And = InsertNewInstBefore(AndI, ICI);
6552 return new ICmpInst(ICI.getPredicate(), And,
6553 ConstantInt::get(RHSV.lshr(ShAmtVal)));
6554 }
6555 }
6556
6557 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6558 bool TrueIfSigned = false;
6559 if (LHSI->hasOneUse() &&
6560 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6561 // (X << 31) <s 0 --> (X&1) != 0
6562 Constant *Mask = ConstantInt::get(APInt(TypeBits, 1) <<
6563 (TypeBits-ShAmt->getZExtValue()-1));
6564 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006565 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006566 Mask, LHSI->getName()+".mask");
6567 Value *And = InsertNewInstBefore(AndI, ICI);
6568
6569 return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
6570 And, Constant::getNullValue(And->getType()));
6571 }
6572 break;
6573 }
6574
6575 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6576 case Instruction::AShr: {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006577 // Only handle equality comparisons of shift-by-constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006578 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner5ee84f82008-03-21 05:19:58 +00006579 if (!ShAmt || !ICI.isEquality()) break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006580
Chris Lattner5ee84f82008-03-21 05:19:58 +00006581 // Check that the shift amount is in range. If not, don't perform
6582 // undefined shifts. When the shift is visited it will be
6583 // simplified.
6584 uint32_t TypeBits = RHSV.getBitWidth();
6585 if (ShAmt->uge(TypeBits))
6586 break;
6587
6588 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006589
Chris Lattner5ee84f82008-03-21 05:19:58 +00006590 // If we are comparing against bits always shifted out, the
6591 // comparison cannot succeed.
6592 APInt Comp = RHSV << ShAmtVal;
6593 if (LHSI->getOpcode() == Instruction::LShr)
6594 Comp = Comp.lshr(ShAmtVal);
6595 else
6596 Comp = Comp.ashr(ShAmtVal);
6597
6598 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6599 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6600 Constant *Cst = ConstantInt::get(Type::Int1Ty, IsICMP_NE);
6601 return ReplaceInstUsesWith(ICI, Cst);
6602 }
6603
6604 // Otherwise, check to see if the bits shifted out are known to be zero.
6605 // If so, we can compare against the unshifted value:
6606 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengfb9292a2008-04-23 00:38:06 +00006607 if (LHSI->hasOneUse() &&
6608 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00006609 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
6610 return new ICmpInst(ICI.getPredicate(), LHSI->getOperand(0),
6611 ConstantExpr::getShl(RHS, ShAmt));
6612 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006613
Evan Chengfb9292a2008-04-23 00:38:06 +00006614 if (LHSI->hasOneUse()) {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006615 // Otherwise strength reduce the shift into an and.
6616 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
6617 Constant *Mask = ConstantInt::get(Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006618
Chris Lattner5ee84f82008-03-21 05:19:58 +00006619 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006620 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00006621 Mask, LHSI->getName()+".mask");
6622 Value *And = InsertNewInstBefore(AndI, ICI);
6623 return new ICmpInst(ICI.getPredicate(), And,
6624 ConstantExpr::getShl(RHS, ShAmt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006625 }
6626 break;
6627 }
6628
6629 case Instruction::SDiv:
6630 case Instruction::UDiv:
6631 // Fold: icmp pred ([us]div X, C1), C2 -> range test
6632 // Fold this div into the comparison, producing a range check.
6633 // Determine, based on the divide type, what the range is being
6634 // checked. If there is an overflow on the low or high side, remember
6635 // it, otherwise compute the range [low, hi) bounding the new value.
6636 // See: InsertRangeTest above for the kinds of replacements possible.
6637 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
6638 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
6639 DivRHS))
6640 return R;
6641 break;
Nick Lewycky0185bbf2008-02-03 16:33:09 +00006642
6643 case Instruction::Add:
6644 // Fold: icmp pred (add, X, C1), C2
6645
6646 if (!ICI.isEquality()) {
6647 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6648 if (!LHSC) break;
6649 const APInt &LHSV = LHSC->getValue();
6650
6651 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
6652 .subtract(LHSV);
6653
6654 if (ICI.isSignedPredicate()) {
6655 if (CR.getLower().isSignBit()) {
6656 return new ICmpInst(ICmpInst::ICMP_SLT, LHSI->getOperand(0),
6657 ConstantInt::get(CR.getUpper()));
6658 } else if (CR.getUpper().isSignBit()) {
6659 return new ICmpInst(ICmpInst::ICMP_SGE, LHSI->getOperand(0),
6660 ConstantInt::get(CR.getLower()));
6661 }
6662 } else {
6663 if (CR.getLower().isMinValue()) {
6664 return new ICmpInst(ICmpInst::ICMP_ULT, LHSI->getOperand(0),
6665 ConstantInt::get(CR.getUpper()));
6666 } else if (CR.getUpper().isMinValue()) {
6667 return new ICmpInst(ICmpInst::ICMP_UGE, LHSI->getOperand(0),
6668 ConstantInt::get(CR.getLower()));
6669 }
6670 }
6671 }
6672 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006673 }
6674
6675 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
6676 if (ICI.isEquality()) {
6677 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
6678
6679 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
6680 // the second operand is a constant, simplify a bit.
6681 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
6682 switch (BO->getOpcode()) {
6683 case Instruction::SRem:
6684 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
6685 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
6686 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
6687 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
6688 Instruction *NewRem =
Gabor Greifa645dd32008-05-16 19:29:10 +00006689 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006690 BO->getName());
6691 InsertNewInstBefore(NewRem, ICI);
6692 return new ICmpInst(ICI.getPredicate(), NewRem,
6693 Constant::getNullValue(BO->getType()));
6694 }
6695 }
6696 break;
6697 case Instruction::Add:
6698 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
6699 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6700 if (BO->hasOneUse())
6701 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6702 Subtract(RHS, BOp1C));
6703 } else if (RHSV == 0) {
6704 // Replace ((add A, B) != 0) with (A != -B) if A or B is
6705 // efficiently invertible, or if the add has just this one use.
6706 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
6707
6708 if (Value *NegVal = dyn_castNegVal(BOp1))
6709 return new ICmpInst(ICI.getPredicate(), BOp0, NegVal);
6710 else if (Value *NegVal = dyn_castNegVal(BOp0))
6711 return new ICmpInst(ICI.getPredicate(), NegVal, BOp1);
6712 else if (BO->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006713 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006714 InsertNewInstBefore(Neg, ICI);
6715 Neg->takeName(BO);
6716 return new ICmpInst(ICI.getPredicate(), BOp0, Neg);
6717 }
6718 }
6719 break;
6720 case Instruction::Xor:
6721 // For the xor case, we can xor two constants together, eliminating
6722 // the explicit xor.
6723 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
6724 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6725 ConstantExpr::getXor(RHS, BOC));
6726
6727 // FALLTHROUGH
6728 case Instruction::Sub:
6729 // Replace (([sub|xor] A, B) != 0) with (A != B)
6730 if (RHSV == 0)
6731 return new ICmpInst(ICI.getPredicate(), BO->getOperand(0),
6732 BO->getOperand(1));
6733 break;
6734
6735 case Instruction::Or:
6736 // If bits are being or'd in that are not present in the constant we
6737 // are comparing against, then the comparison could never succeed!
6738 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
6739 Constant *NotCI = ConstantExpr::getNot(RHS);
6740 if (!ConstantExpr::getAnd(BOC, NotCI)->isNullValue())
6741 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6742 isICMP_NE));
6743 }
6744 break;
6745
6746 case Instruction::And:
6747 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
6748 // If bits are being compared against that are and'd out, then the
6749 // comparison can never succeed!
6750 if ((RHSV & ~BOC->getValue()) != 0)
6751 return ReplaceInstUsesWith(ICI, ConstantInt::get(Type::Int1Ty,
6752 isICMP_NE));
6753
6754 // If we have ((X & C) == C), turn it into ((X & C) != 0).
6755 if (RHS == BOC && RHSV.isPowerOf2())
6756 return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ :
6757 ICmpInst::ICMP_NE, LHSI,
6758 Constant::getNullValue(RHS->getType()));
6759
6760 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner60813c22008-06-02 01:29:46 +00006761 if (BOC->getValue().isSignBit()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006762 Value *X = BO->getOperand(0);
6763 Constant *Zero = Constant::getNullValue(X->getType());
6764 ICmpInst::Predicate pred = isICMP_NE ?
6765 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
6766 return new ICmpInst(pred, X, Zero);
6767 }
6768
6769 // ((X & ~7) == 0) --> X < 8
6770 if (RHSV == 0 && isHighOnes(BOC)) {
6771 Value *X = BO->getOperand(0);
6772 Constant *NegX = ConstantExpr::getNeg(BOC);
6773 ICmpInst::Predicate pred = isICMP_NE ?
6774 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
6775 return new ICmpInst(pred, X, NegX);
6776 }
6777 }
6778 default: break;
6779 }
6780 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
6781 // Handle icmp {eq|ne} <intrinsic>, intcst.
6782 if (II->getIntrinsicID() == Intrinsic::bswap) {
6783 AddToWorkList(II);
6784 ICI.setOperand(0, II->getOperand(1));
6785 ICI.setOperand(1, ConstantInt::get(RHSV.byteSwap()));
6786 return &ICI;
6787 }
6788 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006789 }
6790 return 0;
6791}
6792
6793/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
6794/// We only handle extending casts so far.
6795///
6796Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
6797 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
6798 Value *LHSCIOp = LHSCI->getOperand(0);
6799 const Type *SrcTy = LHSCIOp->getType();
6800 const Type *DestTy = LHSCI->getType();
6801 Value *RHSCIOp;
6802
6803 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
6804 // integer type is the same size as the pointer type.
6805 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
6806 getTargetData().getPointerSizeInBits() ==
6807 cast<IntegerType>(DestTy)->getBitWidth()) {
6808 Value *RHSOp = 0;
6809 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
6810 RHSOp = ConstantExpr::getIntToPtr(RHSC, SrcTy);
6811 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
6812 RHSOp = RHSC->getOperand(0);
6813 // If the pointer types don't match, insert a bitcast.
6814 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner13c2d6e2008-01-13 22:23:22 +00006815 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006816 }
6817
6818 if (RHSOp)
6819 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSOp);
6820 }
6821
6822 // The code below only handles extension cast instructions, so far.
6823 // Enforce this.
6824 if (LHSCI->getOpcode() != Instruction::ZExt &&
6825 LHSCI->getOpcode() != Instruction::SExt)
6826 return 0;
6827
6828 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
6829 bool isSignedCmp = ICI.isSignedPredicate();
6830
6831 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
6832 // Not an extension from the same type?
6833 RHSCIOp = CI->getOperand(0);
6834 if (RHSCIOp->getType() != LHSCIOp->getType())
6835 return 0;
6836
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00006837 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006838 // and the other is a zext), then we can't handle this.
6839 if (CI->getOpcode() != LHSCI->getOpcode())
6840 return 0;
6841
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00006842 // Deal with equality cases early.
6843 if (ICI.isEquality())
6844 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6845
6846 // A signed comparison of sign extended values simplifies into a
6847 // signed comparison.
6848 if (isSignedCmp && isSignedExt)
6849 return new ICmpInst(ICI.getPredicate(), LHSCIOp, RHSCIOp);
6850
6851 // The other three cases all fold into an unsigned comparison.
6852 return new ICmpInst(ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006853 }
6854
6855 // If we aren't dealing with a constant on the RHS, exit early
6856 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
6857 if (!CI)
6858 return 0;
6859
6860 // Compute the constant that would happen if we truncated to SrcTy then
6861 // reextended to DestTy.
6862 Constant *Res1 = ConstantExpr::getTrunc(CI, SrcTy);
6863 Constant *Res2 = ConstantExpr::getCast(LHSCI->getOpcode(), Res1, DestTy);
6864
6865 // If the re-extended constant didn't change...
6866 if (Res2 == CI) {
6867 // Make sure that sign of the Cmp and the sign of the Cast are the same.
6868 // For example, we might have:
6869 // %A = sext short %X to uint
6870 // %B = icmp ugt uint %A, 1330
6871 // It is incorrect to transform this into
6872 // %B = icmp ugt short %X, 1330
6873 // because %A may have negative value.
6874 //
Chris Lattner3d816532008-07-11 04:09:09 +00006875 // However, we allow this when the compare is EQ/NE, because they are
6876 // signless.
6877 if (isSignedExt == isSignedCmp || ICI.isEquality())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006878 return new ICmpInst(ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattner3d816532008-07-11 04:09:09 +00006879 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006880 }
6881
6882 // The re-extended constant changed so the constant cannot be represented
6883 // in the shorter type. Consequently, we cannot emit a simple comparison.
6884
6885 // First, handle some easy cases. We know the result cannot be equal at this
6886 // point so handle the ICI.isEquality() cases
6887 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
6888 return ReplaceInstUsesWith(ICI, ConstantInt::getFalse());
6889 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
6890 return ReplaceInstUsesWith(ICI, ConstantInt::getTrue());
6891
6892 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
6893 // should have been folded away previously and not enter in here.
6894 Value *Result;
6895 if (isSignedCmp) {
6896 // We're performing a signed comparison.
6897 if (cast<ConstantInt>(CI)->getValue().isNegative())
6898 Result = ConstantInt::getFalse(); // X < (small) --> false
6899 else
6900 Result = ConstantInt::getTrue(); // X < (large) --> true
6901 } else {
6902 // We're performing an unsigned comparison.
6903 if (isSignedExt) {
6904 // We're performing an unsigned comp with a sign extended value.
6905 // This is true if the input is >= 0. [aka >s -1]
6906 Constant *NegOne = ConstantInt::getAllOnesValue(SrcTy);
6907 Result = InsertNewInstBefore(new ICmpInst(ICmpInst::ICMP_SGT, LHSCIOp,
6908 NegOne, ICI.getName()), ICI);
6909 } else {
6910 // Unsigned extend & unsigned compare -> always true.
6911 Result = ConstantInt::getTrue();
6912 }
6913 }
6914
6915 // Finally, return the value computed.
6916 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattner3d816532008-07-11 04:09:09 +00006917 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006918 return ReplaceInstUsesWith(ICI, Result);
Chris Lattner3d816532008-07-11 04:09:09 +00006919
6920 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
6921 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
6922 "ICmp should be folded!");
6923 if (Constant *CI = dyn_cast<Constant>(Result))
6924 return ReplaceInstUsesWith(ICI, ConstantExpr::getNot(CI));
6925 return BinaryOperator::CreateNot(Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006926}
6927
6928Instruction *InstCombiner::visitShl(BinaryOperator &I) {
6929 return commonShiftTransforms(I);
6930}
6931
6932Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
6933 return commonShiftTransforms(I);
6934}
6935
6936Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00006937 if (Instruction *R = commonShiftTransforms(I))
6938 return R;
6939
6940 Value *Op0 = I.getOperand(0);
6941
6942 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
6943 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
6944 if (CSI->isAllOnesValue())
6945 return ReplaceInstUsesWith(I, CSI);
6946
6947 // See if we can turn a signed shr into an unsigned shr.
Nate Begemanbb1ce942008-07-29 15:49:41 +00006948 if (!isa<VectorType>(I.getType()) &&
6949 MaskedValueIsZero(Op0,
Chris Lattnere3c504f2007-12-06 01:59:46 +00006950 APInt::getSignBit(I.getType()->getPrimitiveSizeInBits())))
Gabor Greifa645dd32008-05-16 19:29:10 +00006951 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
Chris Lattnere3c504f2007-12-06 01:59:46 +00006952
6953 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006954}
6955
6956Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
6957 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
6958 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
6959
6960 // shl X, 0 == X and shr X, 0 == X
6961 // shl 0, X == 0 and shr 0, X == 0
6962 if (Op1 == Constant::getNullValue(Op1->getType()) ||
6963 Op0 == Constant::getNullValue(Op0->getType()))
6964 return ReplaceInstUsesWith(I, Op0);
6965
6966 if (isa<UndefValue>(Op0)) {
6967 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
6968 return ReplaceInstUsesWith(I, Op0);
6969 else // undef << X -> 0, undef >>u X -> 0
6970 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6971 }
6972 if (isa<UndefValue>(Op1)) {
6973 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
6974 return ReplaceInstUsesWith(I, Op0);
6975 else // X << undef, X >>u undef -> 0
6976 return ReplaceInstUsesWith(I, Constant::getNullValue(I.getType()));
6977 }
6978
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006979 // Try to fold constant and into select arguments.
6980 if (isa<Constant>(Op0))
6981 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
6982 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
6983 return R;
6984
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006985 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
6986 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
6987 return Res;
6988 return 0;
6989}
6990
6991Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
6992 BinaryOperator &I) {
6993 bool isLeftShift = I.getOpcode() == Instruction::Shl;
6994
6995 // See if we can simplify any instructions used by the instruction whose sole
6996 // purpose is to compute bits we don't care about.
6997 uint32_t TypeBits = Op0->getType()->getPrimitiveSizeInBits();
6998 APInt KnownZero(TypeBits, 0), KnownOne(TypeBits, 0);
6999 if (SimplifyDemandedBits(&I, APInt::getAllOnesValue(TypeBits),
7000 KnownZero, KnownOne))
7001 return &I;
7002
7003 // shl uint X, 32 = 0 and shr ubyte Y, 9 = 0, ... just don't eliminate shr
7004 // of a signed value.
7005 //
7006 if (Op1->uge(TypeBits)) {
7007 if (I.getOpcode() != Instruction::AShr)
7008 return ReplaceInstUsesWith(I, Constant::getNullValue(Op0->getType()));
7009 else {
7010 I.setOperand(1, ConstantInt::get(I.getType(), TypeBits-1));
7011 return &I;
7012 }
7013 }
7014
7015 // ((X*C1) << C2) == (X * (C1 << C2))
7016 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7017 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7018 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00007019 return BinaryOperator::CreateMul(BO->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007020 ConstantExpr::getShl(BOOp, Op1));
7021
7022 // Try to fold constant and into select arguments.
7023 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7024 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7025 return R;
7026 if (isa<PHINode>(Op0))
7027 if (Instruction *NV = FoldOpIntoPhi(I))
7028 return NV;
7029
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007030 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7031 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7032 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7033 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7034 // place. Don't try to do this transformation in this case. Also, we
7035 // require that the input operand is a shift-by-constant so that we have
7036 // confidence that the shifts will get folded together. We could do this
7037 // xform in more cases, but it is unlikely to be profitable.
7038 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7039 isa<ConstantInt>(TrOp->getOperand(1))) {
7040 // Okay, we'll do this xform. Make the shift of shift.
7041 Constant *ShAmt = ConstantExpr::getZExt(Op1, TrOp->getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00007042 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007043 I.getName());
7044 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7045
7046 // For logical shifts, the truncation has the effect of making the high
7047 // part of the register be zeros. Emulate this by inserting an AND to
7048 // clear the top bits as needed. This 'and' will usually be zapped by
7049 // other xforms later if dead.
7050 unsigned SrcSize = TrOp->getType()->getPrimitiveSizeInBits();
7051 unsigned DstSize = TI->getType()->getPrimitiveSizeInBits();
7052 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7053
7054 // The mask we constructed says what the trunc would do if occurring
7055 // between the shifts. We want to know the effect *after* the second
7056 // shift. We know that it is a logical shift by a constant, so adjust the
7057 // mask as appropriate.
7058 if (I.getOpcode() == Instruction::Shl)
7059 MaskV <<= Op1->getZExtValue();
7060 else {
7061 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7062 MaskV = MaskV.lshr(Op1->getZExtValue());
7063 }
7064
Gabor Greifa645dd32008-05-16 19:29:10 +00007065 Instruction *And = BinaryOperator::CreateAnd(NSh, ConstantInt::get(MaskV),
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007066 TI->getName());
7067 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7068
7069 // Return the value truncated to the interesting size.
7070 return new TruncInst(And, I.getType());
7071 }
7072 }
7073
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007074 if (Op0->hasOneUse()) {
7075 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7076 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7077 Value *V1, *V2;
7078 ConstantInt *CC;
7079 switch (Op0BO->getOpcode()) {
7080 default: break;
7081 case Instruction::Add:
7082 case Instruction::And:
7083 case Instruction::Or:
7084 case Instruction::Xor: {
7085 // These operators commute.
7086 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7087 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Chris Lattner3b874082008-11-16 05:38:51 +00007088 match(Op0BO->getOperand(1), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greifa645dd32008-05-16 19:29:10 +00007089 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007090 Op0BO->getOperand(0), Op1,
7091 Op0BO->getName());
7092 InsertNewInstBefore(YS, I); // (Y << C)
7093 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00007094 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007095 Op0BO->getOperand(1)->getName());
7096 InsertNewInstBefore(X, I); // (X + (Y << C))
7097 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greifa645dd32008-05-16 19:29:10 +00007098 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007099 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7100 }
7101
7102 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7103 Value *Op0BOOp1 = Op0BO->getOperand(1);
7104 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7105 match(Op0BOOp1,
Chris Lattner3b874082008-11-16 05:38:51 +00007106 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
7107 m_ConstantInt(CC))) &&
7108 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007109 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007110 Op0BO->getOperand(0), Op1,
7111 Op0BO->getName());
7112 InsertNewInstBefore(YS, I); // (Y << C)
7113 Instruction *XM =
Gabor Greifa645dd32008-05-16 19:29:10 +00007114 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007115 V1->getName()+".mask");
7116 InsertNewInstBefore(XM, I); // X & (CC << C)
7117
Gabor Greifa645dd32008-05-16 19:29:10 +00007118 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007119 }
7120 }
7121
7122 // FALL THROUGH.
7123 case Instruction::Sub: {
7124 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7125 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Chris Lattner3b874082008-11-16 05:38:51 +00007126 match(Op0BO->getOperand(0), m_Shr(m_Value(V1), m_Specific(Op1)))){
Gabor Greifa645dd32008-05-16 19:29:10 +00007127 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007128 Op0BO->getOperand(1), Op1,
7129 Op0BO->getName());
7130 InsertNewInstBefore(YS, I); // (Y << C)
7131 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00007132 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007133 Op0BO->getOperand(0)->getName());
7134 InsertNewInstBefore(X, I); // (X + (Y << C))
7135 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Gabor Greifa645dd32008-05-16 19:29:10 +00007136 return BinaryOperator::CreateAnd(X, ConstantInt::get(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007137 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7138 }
7139
7140 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7141 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7142 match(Op0BO->getOperand(0),
7143 m_And(m_Shr(m_Value(V1), m_Value(V2)),
7144 m_ConstantInt(CC))) && V2 == Op1 &&
7145 cast<BinaryOperator>(Op0BO->getOperand(0))
7146 ->getOperand(0)->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007147 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007148 Op0BO->getOperand(1), Op1,
7149 Op0BO->getName());
7150 InsertNewInstBefore(YS, I); // (Y << C)
7151 Instruction *XM =
Gabor Greifa645dd32008-05-16 19:29:10 +00007152 BinaryOperator::CreateAnd(V1, ConstantExpr::getShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007153 V1->getName()+".mask");
7154 InsertNewInstBefore(XM, I); // X & (CC << C)
7155
Gabor Greifa645dd32008-05-16 19:29:10 +00007156 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007157 }
7158
7159 break;
7160 }
7161 }
7162
7163
7164 // If the operand is an bitwise operator with a constant RHS, and the
7165 // shift is the only use, we can pull it out of the shift.
7166 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7167 bool isValid = true; // Valid only for And, Or, Xor
7168 bool highBitSet = false; // Transform if high bit of constant set?
7169
7170 switch (Op0BO->getOpcode()) {
7171 default: isValid = false; break; // Do not perform transform!
7172 case Instruction::Add:
7173 isValid = isLeftShift;
7174 break;
7175 case Instruction::Or:
7176 case Instruction::Xor:
7177 highBitSet = false;
7178 break;
7179 case Instruction::And:
7180 highBitSet = true;
7181 break;
7182 }
7183
7184 // If this is a signed shift right, and the high bit is modified
7185 // by the logical operation, do not perform the transformation.
7186 // The highBitSet boolean indicates the value of the high bit of
7187 // the constant which would cause it to be modified for this
7188 // operation.
7189 //
Chris Lattner15b76e32007-12-06 06:25:04 +00007190 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007191 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007192
7193 if (isValid) {
7194 Constant *NewRHS = ConstantExpr::get(I.getOpcode(), Op0C, Op1);
7195
7196 Instruction *NewShift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007197 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007198 InsertNewInstBefore(NewShift, I);
7199 NewShift->takeName(Op0BO);
7200
Gabor Greifa645dd32008-05-16 19:29:10 +00007201 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007202 NewRHS);
7203 }
7204 }
7205 }
7206 }
7207
7208 // Find out if this is a shift of a shift by a constant.
7209 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7210 if (ShiftOp && !ShiftOp->isShift())
7211 ShiftOp = 0;
7212
7213 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7214 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7215 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7216 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7217 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7218 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7219 Value *X = ShiftOp->getOperand(0);
7220
7221 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
7222 if (AmtSum > TypeBits)
7223 AmtSum = TypeBits;
7224
7225 const IntegerType *Ty = cast<IntegerType>(I.getType());
7226
7227 // Check for (X << c1) << c2 and (X >> c1) >> c2
7228 if (I.getOpcode() == ShiftOp->getOpcode()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007229 return BinaryOperator::Create(I.getOpcode(), X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007230 ConstantInt::get(Ty, AmtSum));
7231 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7232 I.getOpcode() == Instruction::AShr) {
7233 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Gabor Greifa645dd32008-05-16 19:29:10 +00007234 return BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007235 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7236 I.getOpcode() == Instruction::LShr) {
7237 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
7238 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007239 BinaryOperator::CreateAShr(X, ConstantInt::get(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007240 InsertNewInstBefore(Shift, I);
7241
7242 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007243 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007244 }
7245
7246 // Okay, if we get here, one shift must be left, and the other shift must be
7247 // right. See if the amounts are equal.
7248 if (ShiftAmt1 == ShiftAmt2) {
7249 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7250 if (I.getOpcode() == Instruction::Shl) {
7251 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greifa645dd32008-05-16 19:29:10 +00007252 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007253 }
7254 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7255 if (I.getOpcode() == Instruction::LShr) {
7256 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Gabor Greifa645dd32008-05-16 19:29:10 +00007257 return BinaryOperator::CreateAnd(X, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007258 }
7259 // We can simplify ((X << C) >>s C) into a trunc + sext.
7260 // NOTE: we could do this for any C, but that would make 'unusual' integer
7261 // types. For now, just stick to ones well-supported by the code
7262 // generators.
7263 const Type *SExtType = 0;
7264 switch (Ty->getBitWidth() - ShiftAmt1) {
7265 case 1 :
7266 case 8 :
7267 case 16 :
7268 case 32 :
7269 case 64 :
7270 case 128:
7271 SExtType = IntegerType::get(Ty->getBitWidth() - ShiftAmt1);
7272 break;
7273 default: break;
7274 }
7275 if (SExtType) {
7276 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7277 InsertNewInstBefore(NewTrunc, I);
7278 return new SExtInst(NewTrunc, Ty);
7279 }
7280 // Otherwise, we can't handle it yet.
7281 } else if (ShiftAmt1 < ShiftAmt2) {
7282 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7283
7284 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7285 if (I.getOpcode() == Instruction::Shl) {
7286 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7287 ShiftOp->getOpcode() == Instruction::AShr);
7288 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007289 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007290 InsertNewInstBefore(Shift, I);
7291
7292 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007293 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007294 }
7295
7296 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7297 if (I.getOpcode() == Instruction::LShr) {
7298 assert(ShiftOp->getOpcode() == Instruction::Shl);
7299 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007300 BinaryOperator::CreateLShr(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007301 InsertNewInstBefore(Shift, I);
7302
7303 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007304 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007305 }
7306
7307 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7308 } else {
7309 assert(ShiftAmt2 < ShiftAmt1);
7310 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7311
7312 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7313 if (I.getOpcode() == Instruction::Shl) {
7314 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7315 ShiftOp->getOpcode() == Instruction::AShr);
7316 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007317 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007318 ConstantInt::get(Ty, ShiftDiff));
7319 InsertNewInstBefore(Shift, I);
7320
7321 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007322 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007323 }
7324
7325 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7326 if (I.getOpcode() == Instruction::LShr) {
7327 assert(ShiftOp->getOpcode() == Instruction::Shl);
7328 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007329 BinaryOperator::CreateShl(X, ConstantInt::get(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007330 InsertNewInstBefore(Shift, I);
7331
7332 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Gabor Greifa645dd32008-05-16 19:29:10 +00007333 return BinaryOperator::CreateAnd(Shift, ConstantInt::get(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007334 }
7335
7336 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7337 }
7338 }
7339 return 0;
7340}
7341
7342
7343/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7344/// expression. If so, decompose it, returning some value X, such that Val is
7345/// X*Scale+Offset.
7346///
7347static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
7348 int &Offset) {
7349 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7350 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7351 Offset = CI->getZExtValue();
Chris Lattnerc59171a2007-10-12 05:30:59 +00007352 Scale = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007353 return ConstantInt::get(Type::Int32Ty, 0);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007354 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7355 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7356 if (I->getOpcode() == Instruction::Shl) {
7357 // This is a value scaled by '1 << the shift amt'.
7358 Scale = 1U << RHS->getZExtValue();
7359 Offset = 0;
7360 return I->getOperand(0);
7361 } else if (I->getOpcode() == Instruction::Mul) {
7362 // This value is scaled by 'RHS'.
7363 Scale = RHS->getZExtValue();
7364 Offset = 0;
7365 return I->getOperand(0);
7366 } else if (I->getOpcode() == Instruction::Add) {
7367 // We have X+C. Check to see if we really have (X*C2)+C1,
7368 // where C1 is divisible by C2.
7369 unsigned SubScale;
7370 Value *SubVal =
7371 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale, Offset);
7372 Offset += RHS->getZExtValue();
7373 Scale = SubScale;
7374 return SubVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007375 }
7376 }
7377 }
7378
7379 // Otherwise, we can't look past this.
7380 Scale = 1;
7381 Offset = 0;
7382 return Val;
7383}
7384
7385
7386/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7387/// try to eliminate the cast by moving the type information into the alloc.
7388Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7389 AllocationInst &AI) {
7390 const PointerType *PTy = cast<PointerType>(CI.getType());
7391
7392 // Remove any uses of AI that are dead.
7393 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7394
7395 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7396 Instruction *User = cast<Instruction>(*UI++);
7397 if (isInstructionTriviallyDead(User)) {
7398 while (UI != E && *UI == User)
7399 ++UI; // If this instruction uses AI more than once, don't break UI.
7400
7401 ++NumDeadInst;
7402 DOUT << "IC: DCE: " << *User;
7403 EraseInstFromFunction(*User);
7404 }
7405 }
7406
7407 // Get the type really allocated and the type casted to.
7408 const Type *AllocElTy = AI.getAllocatedType();
7409 const Type *CastElTy = PTy->getElementType();
7410 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7411
7412 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7413 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7414 if (CastElTyAlign < AllocElTyAlign) return 0;
7415
7416 // If the allocation has multiple uses, only promote it if we are strictly
7417 // increasing the alignment of the resultant allocation. If we keep it the
7418 // same, we open the door to infinite loops of various kinds.
7419 if (!AI.hasOneUse() && CastElTyAlign == AllocElTyAlign) return 0;
7420
Duncan Sandsd68f13b2009-01-12 20:38:59 +00007421 uint64_t AllocElTySize = TD->getTypePaddedSize(AllocElTy);
7422 uint64_t CastElTySize = TD->getTypePaddedSize(CastElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007423 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7424
7425 // See if we can satisfy the modulus by pulling a scale out of the array
7426 // size argument.
7427 unsigned ArraySizeScale;
7428 int ArrayOffset;
7429 Value *NumElements = // See if the array size is a decomposable linear expr.
7430 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale, ArrayOffset);
7431
7432 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7433 // do the xform.
7434 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7435 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7436
7437 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7438 Value *Amt = 0;
7439 if (Scale == 1) {
7440 Amt = NumElements;
7441 } else {
7442 // If the allocation size is constant, form a constant mul expression
7443 Amt = ConstantInt::get(Type::Int32Ty, Scale);
7444 if (isa<ConstantInt>(NumElements))
7445 Amt = Multiply(cast<ConstantInt>(NumElements), cast<ConstantInt>(Amt));
7446 // otherwise multiply the amount and the number of elements
7447 else if (Scale != 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007448 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007449 Amt = InsertNewInstBefore(Tmp, AI);
7450 }
7451 }
7452
7453 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
7454 Value *Off = ConstantInt::get(Type::Int32Ty, Offset, true);
Gabor Greifa645dd32008-05-16 19:29:10 +00007455 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007456 Amt = InsertNewInstBefore(Tmp, AI);
7457 }
7458
7459 AllocationInst *New;
7460 if (isa<MallocInst>(AI))
7461 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7462 else
7463 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7464 InsertNewInstBefore(New, AI);
7465 New->takeName(&AI);
7466
7467 // If the allocation has multiple uses, insert a cast and change all things
7468 // that used it to use the new cast. This will also hack on CI, but it will
7469 // die soon.
7470 if (!AI.hasOneUse()) {
7471 AddUsesToWorkList(AI);
7472 // New is the allocation instruction, pointer typed. AI is the original
7473 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7474 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7475 InsertNewInstBefore(NewCast, AI);
7476 AI.replaceAllUsesWith(NewCast);
7477 }
7478 return ReplaceInstUsesWith(CI, New);
7479}
7480
7481/// CanEvaluateInDifferentType - Return true if we can take the specified value
7482/// and return it as type Ty without inserting any new casts and without
7483/// changing the computed value. This is used by code that tries to decide
7484/// whether promoting or shrinking integer operations to wider or smaller types
7485/// will allow us to eliminate a truncate or extend.
7486///
7487/// This is a truncation operation if Ty is smaller than V->getType(), or an
7488/// extension operation if Ty is larger.
Chris Lattner4200c2062008-06-18 04:00:49 +00007489///
7490/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7491/// should return true if trunc(V) can be computed by computing V in the smaller
7492/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7493/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7494/// efficiently truncated.
7495///
7496/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7497/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7498/// the final result.
Evan Cheng814a00c2009-01-16 02:11:43 +00007499bool InstCombiner::CanEvaluateInDifferentType(Value *V, const IntegerType *Ty,
7500 unsigned CastOpc,
7501 int &NumCastsRemoved){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007502 // We can always evaluate constants in another type.
7503 if (isa<ConstantInt>(V))
7504 return true;
7505
7506 Instruction *I = dyn_cast<Instruction>(V);
7507 if (!I) return false;
7508
7509 const IntegerType *OrigTy = cast<IntegerType>(V->getType());
7510
Chris Lattneref70bb82007-08-02 06:11:14 +00007511 // If this is an extension or truncate, we can often eliminate it.
7512 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7513 // If this is a cast from the destination type, we can trivially eliminate
7514 // it, and this will remove a cast overall.
7515 if (I->getOperand(0)->getType() == Ty) {
7516 // If the first operand is itself a cast, and is eliminable, do not count
7517 // this as an eliminable cast. We would prefer to eliminate those two
7518 // casts first.
Chris Lattner4200c2062008-06-18 04:00:49 +00007519 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattneref70bb82007-08-02 06:11:14 +00007520 ++NumCastsRemoved;
7521 return true;
7522 }
7523 }
7524
7525 // We can't extend or shrink something that has multiple uses: doing so would
7526 // require duplicating the instruction in general, which isn't profitable.
7527 if (!I->hasOneUse()) return false;
7528
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007529 unsigned Opc = I->getOpcode();
7530 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007531 case Instruction::Add:
7532 case Instruction::Sub:
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007533 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007534 case Instruction::And:
7535 case Instruction::Or:
7536 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007537 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00007538 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007539 NumCastsRemoved) &&
Chris Lattneref70bb82007-08-02 06:11:14 +00007540 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007541 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007542
7543 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007544 // If we are truncating the result of this SHL, and if it's a shift of a
7545 // constant amount, we can always perform a SHL in a smaller type.
7546 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7547 uint32_t BitWidth = Ty->getBitWidth();
7548 if (BitWidth < OrigTy->getBitWidth() &&
7549 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00007550 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007551 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007552 }
7553 break;
7554 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007555 // If this is a truncate of a logical shr, we can truncate it to a smaller
7556 // lshr iff we know that the bits we would otherwise be shifting in are
7557 // already zeros.
7558 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
7559 uint32_t OrigBitWidth = OrigTy->getBitWidth();
7560 uint32_t BitWidth = Ty->getBitWidth();
7561 if (BitWidth < OrigBitWidth &&
7562 MaskedValueIsZero(I->getOperand(0),
7563 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7564 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00007565 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007566 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007567 }
7568 }
7569 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007570 case Instruction::ZExt:
7571 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00007572 case Instruction::Trunc:
7573 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00007574 // can safely replace it. Note that replacing it does not reduce the number
7575 // of casts in the input.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007576 if (Opc == CastOpc)
7577 return true;
7578
7579 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng7bb0d952009-01-15 17:09:07 +00007580 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007581 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007582 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007583 case Instruction::Select: {
7584 SelectInst *SI = cast<SelectInst>(I);
7585 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007586 NumCastsRemoved) &&
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007587 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007588 NumCastsRemoved);
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007589 }
Chris Lattner4200c2062008-06-18 04:00:49 +00007590 case Instruction::PHI: {
7591 // We can change a phi if we can change all operands.
7592 PHINode *PN = cast<PHINode>(I);
7593 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
7594 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007595 NumCastsRemoved))
Chris Lattner4200c2062008-06-18 04:00:49 +00007596 return false;
7597 return true;
7598 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007599 default:
7600 // TODO: Can handle more cases here.
7601 break;
7602 }
7603
7604 return false;
7605}
7606
7607/// EvaluateInDifferentType - Given an expression that
7608/// CanEvaluateInDifferentType returns true for, actually insert the code to
7609/// evaluate the expression.
7610Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
7611 bool isSigned) {
7612 if (Constant *C = dyn_cast<Constant>(V))
7613 return ConstantExpr::getIntegerCast(C, Ty, isSigned /*Sext or ZExt*/);
7614
7615 // Otherwise, it must be an instruction.
7616 Instruction *I = cast<Instruction>(V);
7617 Instruction *Res = 0;
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007618 unsigned Opc = I->getOpcode();
7619 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007620 case Instruction::Add:
7621 case Instruction::Sub:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00007622 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007623 case Instruction::And:
7624 case Instruction::Or:
7625 case Instruction::Xor:
7626 case Instruction::AShr:
7627 case Instruction::LShr:
7628 case Instruction::Shl: {
7629 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
7630 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007631 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007632 break;
7633 }
7634 case Instruction::Trunc:
7635 case Instruction::ZExt:
7636 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007637 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00007638 // just return the source. There's no need to insert it because it is not
7639 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007640 if (I->getOperand(0)->getType() == Ty)
7641 return I->getOperand(0);
7642
Chris Lattner4200c2062008-06-18 04:00:49 +00007643 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greifa645dd32008-05-16 19:29:10 +00007644 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner4200c2062008-06-18 04:00:49 +00007645 Ty);
Chris Lattneref70bb82007-08-02 06:11:14 +00007646 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007647 case Instruction::Select: {
7648 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
7649 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
7650 Res = SelectInst::Create(I->getOperand(0), True, False);
7651 break;
7652 }
Chris Lattner4200c2062008-06-18 04:00:49 +00007653 case Instruction::PHI: {
7654 PHINode *OPN = cast<PHINode>(I);
7655 PHINode *NPN = PHINode::Create(Ty);
7656 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
7657 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
7658 NPN->addIncoming(V, OPN->getIncomingBlock(i));
7659 }
7660 Res = NPN;
7661 break;
7662 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007663 default:
7664 // TODO: Can handle more cases here.
7665 assert(0 && "Unreachable!");
7666 break;
7667 }
7668
Chris Lattner4200c2062008-06-18 04:00:49 +00007669 Res->takeName(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007670 return InsertNewInstBefore(Res, *I);
7671}
7672
7673/// @brief Implement the transforms common to all CastInst visitors.
7674Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
7675 Value *Src = CI.getOperand(0);
7676
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007677 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
7678 // eliminate it now.
7679 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
7680 if (Instruction::CastOps opc =
7681 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
7682 // The first cast (CSrc) is eliminable so we need to fix up or replace
7683 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greifa645dd32008-05-16 19:29:10 +00007684 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007685 }
7686 }
7687
7688 // If we are casting a select then fold the cast into the select
7689 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
7690 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
7691 return NV;
7692
7693 // If we are casting a PHI then fold the cast into the PHI
7694 if (isa<PHINode>(Src))
7695 if (Instruction *NV = FoldOpIntoPhi(CI))
7696 return NV;
7697
7698 return 0;
7699}
7700
Chris Lattner94ccd5f2009-01-09 05:44:56 +00007701/// FindElementAtOffset - Given a type and a constant offset, determine whether
7702/// or not there is a sequence of GEP indices into the type that will land us at
7703/// the specified offset. If so, fill them into NewIndices and return true,
7704/// otherwise return false.
7705static bool FindElementAtOffset(const Type *Ty, int64_t Offset,
7706 SmallVectorImpl<Value*> &NewIndices,
7707 const TargetData *TD) {
7708 if (!Ty->isSized()) return false;
7709
7710 // Start with the index over the outer type. Note that the type size
7711 // might be zero (even if the offset isn't zero) if the indexed type
7712 // is something like [0 x {int, int}]
7713 const Type *IntPtrTy = TD->getIntPtrType();
7714 int64_t FirstIdx = 0;
Duncan Sandsd68f13b2009-01-12 20:38:59 +00007715 if (int64_t TySize = TD->getTypePaddedSize(Ty)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00007716 FirstIdx = Offset/TySize;
Chris Lattner0bd6f2b2009-01-11 20:41:36 +00007717 Offset -= FirstIdx*TySize;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00007718
Chris Lattnerce48c462009-01-11 20:15:20 +00007719 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner94ccd5f2009-01-09 05:44:56 +00007720 if (Offset < 0) {
7721 --FirstIdx;
7722 Offset += TySize;
7723 assert(Offset >= 0);
7724 }
7725 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
7726 }
7727
7728 NewIndices.push_back(ConstantInt::get(IntPtrTy, FirstIdx));
7729
7730 // Index into the types. If we fail, set OrigBase to null.
7731 while (Offset) {
Chris Lattnerce48c462009-01-11 20:15:20 +00007732 // Indexing into tail padding between struct/array elements.
7733 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
7734 return false;
7735
Chris Lattner94ccd5f2009-01-09 05:44:56 +00007736 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
7737 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerce48c462009-01-11 20:15:20 +00007738 assert(Offset < (int64_t)SL->getSizeInBytes() &&
7739 "Offset must stay within the indexed type");
7740
Chris Lattner94ccd5f2009-01-09 05:44:56 +00007741 unsigned Elt = SL->getElementContainingOffset(Offset);
7742 NewIndices.push_back(ConstantInt::get(Type::Int32Ty, Elt));
7743
7744 Offset -= SL->getElementOffset(Elt);
7745 Ty = STy->getElementType(Elt);
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00007746 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsd68f13b2009-01-12 20:38:59 +00007747 uint64_t EltSize = TD->getTypePaddedSize(AT->getElementType());
Chris Lattnerce48c462009-01-11 20:15:20 +00007748 assert(EltSize && "Cannot index into a zero-sized array");
7749 NewIndices.push_back(ConstantInt::get(IntPtrTy,Offset/EltSize));
7750 Offset %= EltSize;
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00007751 Ty = AT->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00007752 } else {
Chris Lattnerce48c462009-01-11 20:15:20 +00007753 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner94ccd5f2009-01-09 05:44:56 +00007754 return false;
7755 }
7756 }
7757
7758 return true;
7759}
7760
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007761/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
7762Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
7763 Value *Src = CI.getOperand(0);
7764
7765 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
7766 // If casting the result of a getelementptr instruction with no offset, turn
7767 // this into a cast of the original pointer!
7768 if (GEP->hasAllZeroIndices()) {
7769 // Changing the cast operand is usually not a good idea but it is safe
7770 // here because the pointer operand is being replaced with another
7771 // pointer operand so the opcode doesn't need to change.
7772 AddToWorkList(GEP);
7773 CI.setOperand(0, GEP->getOperand(0));
7774 return &CI;
7775 }
7776
7777 // If the GEP has a single use, and the base pointer is a bitcast, and the
7778 // GEP computes a constant offset, see if we can convert these three
7779 // instructions into fewer. This typically happens with unions and other
7780 // non-type-safe code.
7781 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
7782 if (GEP->hasAllConstantIndices()) {
7783 // We are guaranteed to get a constant from EmitGEPOffset.
7784 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
7785 int64_t Offset = OffsetV->getSExtValue();
7786
7787 // Get the base pointer input of the bitcast, and the type it points to.
7788 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
7789 const Type *GEPIdxTy =
7790 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00007791 SmallVector<Value*, 8> NewIndices;
7792 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD)) {
7793 // If we were able to index down into an element, create the GEP
7794 // and bitcast the result. This eliminates one bitcast, potentially
7795 // two.
7796 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
7797 NewIndices.begin(),
7798 NewIndices.end(), "");
7799 InsertNewInstBefore(NGEP, CI);
7800 NGEP->takeName(GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007801
Chris Lattner94ccd5f2009-01-09 05:44:56 +00007802 if (isa<BitCastInst>(CI))
7803 return new BitCastInst(NGEP, CI.getType());
7804 assert(isa<PtrToIntInst>(CI));
7805 return new PtrToIntInst(NGEP, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007806 }
7807 }
7808 }
7809 }
7810
7811 return commonCastTransforms(CI);
7812}
7813
7814
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007815/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
7816/// integer types. This function implements the common transforms for all those
7817/// cases.
7818/// @brief Implement the transforms common to CastInst with integer operands
7819Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
7820 if (Instruction *Result = commonCastTransforms(CI))
7821 return Result;
7822
7823 Value *Src = CI.getOperand(0);
7824 const Type *SrcTy = Src->getType();
7825 const Type *DestTy = CI.getType();
7826 uint32_t SrcBitSize = SrcTy->getPrimitiveSizeInBits();
7827 uint32_t DestBitSize = DestTy->getPrimitiveSizeInBits();
7828
7829 // See if we can simplify any instructions used by the LHS whose sole
7830 // purpose is to compute bits we don't care about.
7831 APInt KnownZero(DestBitSize, 0), KnownOne(DestBitSize, 0);
7832 if (SimplifyDemandedBits(&CI, APInt::getAllOnesValue(DestBitSize),
7833 KnownZero, KnownOne))
7834 return &CI;
7835
7836 // If the source isn't an instruction or has more than one use then we
7837 // can't do anything more.
7838 Instruction *SrcI = dyn_cast<Instruction>(Src);
7839 if (!SrcI || !Src->hasOneUse())
7840 return 0;
7841
7842 // Attempt to propagate the cast into the instruction for int->int casts.
7843 int NumCastsRemoved = 0;
7844 if (!isa<BitCastInst>(CI) &&
7845 CanEvaluateInDifferentType(SrcI, cast<IntegerType>(DestTy),
Evan Cheng814a00c2009-01-16 02:11:43 +00007846 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007847 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00007848 // eliminates the cast, so it is always a win. If this is a zero-extension,
7849 // we need to do an AND to maintain the clear top-part of the computation,
7850 // so we require that the input have eliminated at least one cast. If this
7851 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007852 // require that two casts have been eliminated.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007853 bool DoXForm = false;
7854 bool JustReplace = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007855 switch (CI.getOpcode()) {
7856 default:
7857 // All the others use floating point so we shouldn't actually
7858 // get here because of the check above.
7859 assert(0 && "Unknown cast type");
7860 case Instruction::Trunc:
7861 DoXForm = true;
7862 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00007863 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007864 DoXForm = NumCastsRemoved >= 1;
Evan Cheng814a00c2009-01-16 02:11:43 +00007865 if (!DoXForm) {
7866 // If it's unnecessary to issue an AND to clear the high bits, it's
7867 // always profitable to do this xform.
7868 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy,
7869 CI.getOpcode() == Instruction::SExt);
7870 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
7871 if (MaskedValueIsZero(TryRes, Mask))
7872 return ReplaceInstUsesWith(CI, TryRes);
7873 else if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
7874 if (TryI->use_empty())
7875 EraseInstFromFunction(*TryI);
7876 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007877 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00007878 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007879 case Instruction::SExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007880 DoXForm = NumCastsRemoved >= 2;
Evan Cheng814a00c2009-01-16 02:11:43 +00007881 if (!DoXForm && !isa<TruncInst>(SrcI)) {
7882 // If we do not have to emit the truncate + sext pair, then it's always
7883 // profitable to do this xform.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007884 //
7885 // It's not safe to eliminate the trunc + sext pair if one of the
7886 // eliminated cast is a truncate. e.g.
7887 // t2 = trunc i32 t1 to i16
7888 // t3 = sext i16 t2 to i32
7889 // !=
7890 // i32 t1
Evan Cheng814a00c2009-01-16 02:11:43 +00007891 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy,
7892 CI.getOpcode() == Instruction::SExt);
7893 unsigned NumSignBits = ComputeNumSignBits(TryRes);
7894 if (NumSignBits > (DestBitSize - SrcBitSize))
7895 return ReplaceInstUsesWith(CI, TryRes);
7896 else if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
7897 if (TryI->use_empty())
7898 EraseInstFromFunction(*TryI);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007899 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007900 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007901 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007902 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007903
7904 if (DoXForm) {
7905 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
7906 CI.getOpcode() == Instruction::SExt);
Evan Cheng814a00c2009-01-16 02:11:43 +00007907 if (JustReplace)
7908 // Just replace this cast with the result.
7909 return ReplaceInstUsesWith(CI, Res);
7910
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007911 assert(Res->getType() == DestTy);
7912 switch (CI.getOpcode()) {
7913 default: assert(0 && "Unknown cast type!");
7914 case Instruction::Trunc:
7915 case Instruction::BitCast:
7916 // Just replace this cast with the result.
7917 return ReplaceInstUsesWith(CI, Res);
7918 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007919 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng814a00c2009-01-16 02:11:43 +00007920
7921 // If the high bits are already zero, just replace this cast with the
7922 // result.
7923 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
7924 if (MaskedValueIsZero(Res, Mask))
7925 return ReplaceInstUsesWith(CI, Res);
7926
7927 // We need to emit an AND to clear the high bits.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007928 Constant *C = ConstantInt::get(APInt::getLowBitsSet(DestBitSize,
7929 SrcBitSize));
Gabor Greifa645dd32008-05-16 19:29:10 +00007930 return BinaryOperator::CreateAnd(Res, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007931 }
Evan Cheng814a00c2009-01-16 02:11:43 +00007932 case Instruction::SExt: {
7933 // If the high bits are already filled with sign bit, just replace this
7934 // cast with the result.
7935 unsigned NumSignBits = ComputeNumSignBits(Res);
7936 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007937 return ReplaceInstUsesWith(CI, Res);
7938
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007939 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greifa645dd32008-05-16 19:29:10 +00007940 return CastInst::Create(Instruction::SExt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007941 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
7942 CI), DestTy);
7943 }
Evan Cheng814a00c2009-01-16 02:11:43 +00007944 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007945 }
7946 }
7947
7948 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
7949 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
7950
7951 switch (SrcI->getOpcode()) {
7952 case Instruction::Add:
7953 case Instruction::Mul:
7954 case Instruction::And:
7955 case Instruction::Or:
7956 case Instruction::Xor:
7957 // If we are discarding information, rewrite.
7958 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
7959 // Don't insert two casts if they cannot be eliminated. We allow
7960 // two casts to be inserted if the sizes are the same. This could
7961 // only be converting signedness, which is a noop.
7962 if (DestBitSize == SrcBitSize ||
7963 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
7964 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
7965 Instruction::CastOps opcode = CI.getOpcode();
Eli Friedman722b4792008-11-30 21:09:11 +00007966 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
7967 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007968 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007969 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7970 }
7971 }
7972
7973 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
7974 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
7975 SrcI->getOpcode() == Instruction::Xor &&
7976 Op1 == ConstantInt::getTrue() &&
7977 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedman722b4792008-11-30 21:09:11 +00007978 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007979 return BinaryOperator::CreateXor(New, ConstantInt::get(CI.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007980 }
7981 break;
7982 case Instruction::SDiv:
7983 case Instruction::UDiv:
7984 case Instruction::SRem:
7985 case Instruction::URem:
7986 // If we are just changing the sign, rewrite.
7987 if (DestBitSize == SrcBitSize) {
7988 // Don't insert two casts if they cannot be eliminated. We allow
7989 // two casts to be inserted if the sizes are the same. This could
7990 // only be converting signedness, which is a noop.
7991 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
7992 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedman722b4792008-11-30 21:09:11 +00007993 Value *Op0c = InsertCastBefore(Instruction::BitCast,
7994 Op0, DestTy, *SrcI);
7995 Value *Op1c = InsertCastBefore(Instruction::BitCast,
7996 Op1, DestTy, *SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00007997 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007998 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
7999 }
8000 }
8001 break;
8002
8003 case Instruction::Shl:
8004 // Allow changing the sign of the source operand. Do not allow
8005 // changing the size of the shift, UNLESS the shift amount is a
8006 // constant. We must not change variable sized shifts to a smaller
8007 // size, because it is undefined to shift more bits out than exist
8008 // in the value.
8009 if (DestBitSize == SrcBitSize ||
8010 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
8011 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8012 Instruction::BitCast : Instruction::Trunc);
Eli Friedman722b4792008-11-30 21:09:11 +00008013 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8014 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008015 return BinaryOperator::CreateShl(Op0c, Op1c);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008016 }
8017 break;
8018 case Instruction::AShr:
8019 // If this is a signed shr, and if all bits shifted in are about to be
8020 // truncated off, turn it into an unsigned shr to allow greater
8021 // simplifications.
8022 if (DestBitSize < SrcBitSize &&
8023 isa<ConstantInt>(Op1)) {
8024 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
8025 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8026 // Insert the new logical shift right.
Gabor Greifa645dd32008-05-16 19:29:10 +00008027 return BinaryOperator::CreateLShr(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008028 }
8029 }
8030 break;
8031 }
8032 return 0;
8033}
8034
8035Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8036 if (Instruction *Result = commonIntCastTransforms(CI))
8037 return Result;
8038
8039 Value *Src = CI.getOperand(0);
8040 const Type *Ty = CI.getType();
8041 uint32_t DestBitWidth = Ty->getPrimitiveSizeInBits();
8042 uint32_t SrcBitWidth = cast<IntegerType>(Src->getType())->getBitWidth();
8043
8044 if (Instruction *SrcI = dyn_cast<Instruction>(Src)) {
8045 switch (SrcI->getOpcode()) {
8046 default: break;
8047 case Instruction::LShr:
8048 // We can shrink lshr to something smaller if we know the bits shifted in
8049 // are already zeros.
8050 if (ConstantInt *ShAmtV = dyn_cast<ConstantInt>(SrcI->getOperand(1))) {
8051 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8052
8053 // Get a mask for the bits shifting in.
8054 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8055 Value* SrcIOp0 = SrcI->getOperand(0);
8056 if (SrcI->hasOneUse() && MaskedValueIsZero(SrcIOp0, Mask)) {
8057 if (ShAmt >= DestBitWidth) // All zeros.
8058 return ReplaceInstUsesWith(CI, Constant::getNullValue(Ty));
8059
8060 // Okay, we can shrink this. Truncate the input, then return a new
8061 // shift.
8062 Value *V1 = InsertCastBefore(Instruction::Trunc, SrcIOp0, Ty, CI);
8063 Value *V2 = InsertCastBefore(Instruction::Trunc, SrcI->getOperand(1),
8064 Ty, CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008065 return BinaryOperator::CreateLShr(V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008066 }
8067 } else { // This is a variable shr.
8068
8069 // Turn 'trunc (lshr X, Y) to bool' into '(X & (1 << Y)) != 0'. This is
8070 // more LLVM instructions, but allows '1 << Y' to be hoisted if
8071 // loop-invariant and CSE'd.
8072 if (CI.getType() == Type::Int1Ty && SrcI->hasOneUse()) {
8073 Value *One = ConstantInt::get(SrcI->getType(), 1);
8074
8075 Value *V = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00008076 BinaryOperator::CreateShl(One, SrcI->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008077 "tmp"), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008078 V = InsertNewInstBefore(BinaryOperator::CreateAnd(V,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008079 SrcI->getOperand(0),
8080 "tmp"), CI);
8081 Value *Zero = Constant::getNullValue(V->getType());
8082 return new ICmpInst(ICmpInst::ICMP_NE, V, Zero);
8083 }
8084 }
8085 break;
8086 }
8087 }
8088
8089 return 0;
8090}
8091
Evan Chenge3779cf2008-03-24 00:21:34 +00008092/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8093/// in order to eliminate the icmp.
8094Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8095 bool DoXform) {
8096 // If we are just checking for a icmp eq of a single bit and zext'ing it
8097 // to an integer, then shift the bit to the appropriate place and then
8098 // cast to integer to avoid the comparison.
8099 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8100 const APInt &Op1CV = Op1C->getValue();
8101
8102 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8103 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8104 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8105 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8106 if (!DoXform) return ICI;
8107
8108 Value *In = ICI->getOperand(0);
8109 Value *Sh = ConstantInt::get(In->getType(),
8110 In->getType()->getPrimitiveSizeInBits()-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008111 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chenge3779cf2008-03-24 00:21:34 +00008112 In->getName()+".lobit"),
8113 CI);
8114 if (In->getType() != CI.getType())
Gabor Greifa645dd32008-05-16 19:29:10 +00008115 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chenge3779cf2008-03-24 00:21:34 +00008116 false/*ZExt*/, "tmp", &CI);
8117
8118 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
8119 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008120 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chenge3779cf2008-03-24 00:21:34 +00008121 In->getName()+".not"),
8122 CI);
8123 }
8124
8125 return ReplaceInstUsesWith(CI, In);
8126 }
8127
8128
8129
8130 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8131 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8132 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8133 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8134 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8135 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8136 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8137 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8138 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8139 // This only works for EQ and NE
8140 ICI->isEquality()) {
8141 // If Op1C some other power of two, convert:
8142 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8143 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8144 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8145 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8146
8147 APInt KnownZeroMask(~KnownZero);
8148 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8149 if (!DoXform) return ICI;
8150
8151 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8152 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8153 // (X&4) == 2 --> false
8154 // (X&4) != 2 --> true
8155 Constant *Res = ConstantInt::get(Type::Int1Ty, isNE);
8156 Res = ConstantExpr::getZExt(Res, CI.getType());
8157 return ReplaceInstUsesWith(CI, Res);
8158 }
8159
8160 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8161 Value *In = ICI->getOperand(0);
8162 if (ShiftAmt) {
8163 // Perform a logical shr by shiftamt.
8164 // Insert the shift to put the result in the low bit.
Gabor Greifa645dd32008-05-16 19:29:10 +00008165 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Evan Chenge3779cf2008-03-24 00:21:34 +00008166 ConstantInt::get(In->getType(), ShiftAmt),
8167 In->getName()+".lobit"), CI);
8168 }
8169
8170 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
8171 Constant *One = ConstantInt::get(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008172 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00008173 InsertNewInstBefore(cast<Instruction>(In), CI);
8174 }
8175
8176 if (CI.getType() == In->getType())
8177 return ReplaceInstUsesWith(CI, In);
8178 else
Gabor Greifa645dd32008-05-16 19:29:10 +00008179 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chenge3779cf2008-03-24 00:21:34 +00008180 }
8181 }
8182 }
8183
8184 return 0;
8185}
8186
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008187Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8188 // If one of the common conversion will work ..
8189 if (Instruction *Result = commonIntCastTransforms(CI))
8190 return Result;
8191
8192 Value *Src = CI.getOperand(0);
8193
8194 // If this is a cast of a cast
8195 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
8196 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8197 // types and if the sizes are just right we can convert this into a logical
8198 // 'and' which will be much cheaper than the pair of casts.
8199 if (isa<TruncInst>(CSrc)) {
8200 // Get the sizes of the types involved
8201 Value *A = CSrc->getOperand(0);
8202 uint32_t SrcSize = A->getType()->getPrimitiveSizeInBits();
8203 uint32_t MidSize = CSrc->getType()->getPrimitiveSizeInBits();
8204 uint32_t DstSize = CI.getType()->getPrimitiveSizeInBits();
8205 // If we're actually extending zero bits and the trunc is a no-op
8206 if (MidSize < DstSize && SrcSize == DstSize) {
8207 // Replace both of the casts with an And of the type mask.
8208 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
8209 Constant *AndConst = ConstantInt::get(AndValue);
8210 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +00008211 BinaryOperator::CreateAnd(CSrc->getOperand(0), AndConst);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008212 // Unfortunately, if the type changed, we need to cast it back.
8213 if (And->getType() != CI.getType()) {
8214 And->setName(CSrc->getName()+".mask");
8215 InsertNewInstBefore(And, CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008216 And = CastInst::CreateIntegerCast(And, CI.getType(), false/*ZExt*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008217 }
8218 return And;
8219 }
8220 }
8221 }
8222
Evan Chenge3779cf2008-03-24 00:21:34 +00008223 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8224 return transformZExtICmp(ICI, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008225
Evan Chenge3779cf2008-03-24 00:21:34 +00008226 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8227 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8228 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8229 // of the (zext icmp) will be transformed.
8230 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8231 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8232 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8233 (transformZExtICmp(LHS, CI, false) ||
8234 transformZExtICmp(RHS, CI, false))) {
8235 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8236 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008237 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008238 }
Evan Chenge3779cf2008-03-24 00:21:34 +00008239 }
8240
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008241 return 0;
8242}
8243
8244Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8245 if (Instruction *I = commonIntCastTransforms(CI))
8246 return I;
8247
8248 Value *Src = CI.getOperand(0);
8249
Dan Gohman35b76162008-10-30 20:40:10 +00008250 // Canonicalize sign-extend from i1 to a select.
8251 if (Src->getType() == Type::Int1Ty)
8252 return SelectInst::Create(Src,
8253 ConstantInt::getAllOnesValue(CI.getType()),
8254 Constant::getNullValue(CI.getType()));
Dan Gohmanf0f12022008-05-20 21:01:12 +00008255
8256 // See if the value being truncated is already sign extended. If so, just
8257 // eliminate the trunc/sext pair.
8258 if (getOpcode(Src) == Instruction::Trunc) {
8259 Value *Op = cast<User>(Src)->getOperand(0);
8260 unsigned OpBits = cast<IntegerType>(Op->getType())->getBitWidth();
8261 unsigned MidBits = cast<IntegerType>(Src->getType())->getBitWidth();
8262 unsigned DestBits = cast<IntegerType>(CI.getType())->getBitWidth();
8263 unsigned NumSignBits = ComputeNumSignBits(Op);
8264
8265 if (OpBits == DestBits) {
8266 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8267 // bits, it is already ready.
8268 if (NumSignBits > DestBits-MidBits)
8269 return ReplaceInstUsesWith(CI, Op);
8270 } else if (OpBits < DestBits) {
8271 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8272 // bits, just sext from i32.
8273 if (NumSignBits > OpBits-MidBits)
8274 return new SExtInst(Op, CI.getType(), "tmp");
8275 } else {
8276 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8277 // bits, just truncate to i32.
8278 if (NumSignBits > OpBits-MidBits)
8279 return new TruncInst(Op, CI.getType(), "tmp");
8280 }
8281 }
Chris Lattner8a2d0592008-08-06 07:35:52 +00008282
8283 // If the input is a shl/ashr pair of a same constant, then this is a sign
8284 // extension from a smaller value. If we could trust arbitrary bitwidth
8285 // integers, we could turn this into a truncate to the smaller bit and then
8286 // use a sext for the whole extension. Since we don't, look deeper and check
8287 // for a truncate. If the source and dest are the same type, eliminate the
8288 // trunc and extend and just do shifts. For example, turn:
8289 // %a = trunc i32 %i to i8
8290 // %b = shl i8 %a, 6
8291 // %c = ashr i8 %b, 6
8292 // %d = sext i8 %c to i32
8293 // into:
8294 // %a = shl i32 %i, 30
8295 // %d = ashr i32 %a, 30
8296 Value *A = 0;
8297 ConstantInt *BA = 0, *CA = 0;
8298 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
8299 m_ConstantInt(CA))) &&
8300 BA == CA && isa<TruncInst>(A)) {
8301 Value *I = cast<TruncInst>(A)->getOperand(0);
8302 if (I->getType() == CI.getType()) {
8303 unsigned MidSize = Src->getType()->getPrimitiveSizeInBits();
8304 unsigned SrcDstSize = CI.getType()->getPrimitiveSizeInBits();
8305 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
8306 Constant *ShAmtV = ConstantInt::get(CI.getType(), ShAmt);
8307 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8308 CI.getName()), CI);
8309 return BinaryOperator::CreateAShr(I, ShAmtV);
8310 }
8311 }
8312
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008313 return 0;
8314}
8315
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008316/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8317/// in the specified FP type without changing its value.
Chris Lattner5e0610f2008-04-20 00:41:09 +00008318static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem) {
Dale Johannesen6e547b42008-10-09 23:00:39 +00008319 bool losesInfo;
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008320 APFloat F = CFP->getValueAPF();
Dale Johannesen6e547b42008-10-09 23:00:39 +00008321 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8322 if (!losesInfo)
Chris Lattner5e0610f2008-04-20 00:41:09 +00008323 return ConstantFP::get(F);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008324 return 0;
8325}
8326
8327/// LookThroughFPExtensions - If this is an fp extension instruction, look
8328/// through it until we get the source value.
8329static Value *LookThroughFPExtensions(Value *V) {
8330 if (Instruction *I = dyn_cast<Instruction>(V))
8331 if (I->getOpcode() == Instruction::FPExt)
8332 return LookThroughFPExtensions(I->getOperand(0));
8333
8334 // If this value is a constant, return the constant in the smallest FP type
8335 // that can accurately represent it. This allows us to turn
8336 // (float)((double)X+2.0) into x+2.0f.
8337 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8338 if (CFP->getType() == Type::PPC_FP128Ty)
8339 return V; // No constant folding of this.
8340 // See if the value can be truncated to float and then reextended.
Chris Lattner5e0610f2008-04-20 00:41:09 +00008341 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008342 return V;
8343 if (CFP->getType() == Type::DoubleTy)
8344 return V; // Won't shrink.
Chris Lattner5e0610f2008-04-20 00:41:09 +00008345 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008346 return V;
8347 // Don't try to shrink to various long double types.
8348 }
8349
8350 return V;
8351}
8352
8353Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8354 if (Instruction *I = commonCastTransforms(CI))
8355 return I;
8356
8357 // If we have fptrunc(add (fpextend x), (fpextend y)), where x and y are
8358 // smaller than the destination type, we can eliminate the truncate by doing
8359 // the add as the smaller type. This applies to add/sub/mul/div as well as
8360 // many builtins (sqrt, etc).
8361 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8362 if (OpI && OpI->hasOneUse()) {
8363 switch (OpI->getOpcode()) {
8364 default: break;
8365 case Instruction::Add:
8366 case Instruction::Sub:
8367 case Instruction::Mul:
8368 case Instruction::FDiv:
8369 case Instruction::FRem:
8370 const Type *SrcTy = OpI->getType();
8371 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0));
8372 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1));
8373 if (LHSTrunc->getType() != SrcTy &&
8374 RHSTrunc->getType() != SrcTy) {
8375 unsigned DstSize = CI.getType()->getPrimitiveSizeInBits();
8376 // If the source types were both smaller than the destination type of
8377 // the cast, do this xform.
8378 if (LHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize &&
8379 RHSTrunc->getType()->getPrimitiveSizeInBits() <= DstSize) {
8380 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8381 CI.getType(), CI);
8382 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8383 CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008384 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008385 }
8386 }
8387 break;
8388 }
8389 }
8390 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008391}
8392
8393Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8394 return commonCastTransforms(CI);
8395}
8396
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008397Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00008398 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8399 if (OpI == 0)
8400 return commonCastTransforms(FI);
8401
8402 // fptoui(uitofp(X)) --> X
8403 // fptoui(sitofp(X)) --> X
8404 // This is safe if the intermediate type has enough bits in its mantissa to
8405 // accurately represent all values of X. For example, do not do this with
8406 // i64->float->i64. This is also safe for sitofp case, because any negative
8407 // 'X' value would cause an undefined result for the fptoui.
8408 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8409 OpI->getOperand(0)->getType() == FI.getType() &&
8410 (int)FI.getType()->getPrimitiveSizeInBits() < /*extra bit for sign */
8411 OpI->getType()->getFPMantissaWidth())
8412 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008413
8414 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008415}
8416
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008417Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00008418 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8419 if (OpI == 0)
8420 return commonCastTransforms(FI);
8421
8422 // fptosi(sitofp(X)) --> X
8423 // fptosi(uitofp(X)) --> X
8424 // This is safe if the intermediate type has enough bits in its mantissa to
8425 // accurately represent all values of X. For example, do not do this with
8426 // i64->float->i64. This is also safe for sitofp case, because any negative
8427 // 'X' value would cause an undefined result for the fptoui.
8428 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8429 OpI->getOperand(0)->getType() == FI.getType() &&
8430 (int)FI.getType()->getPrimitiveSizeInBits() <=
8431 OpI->getType()->getFPMantissaWidth())
8432 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008433
8434 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008435}
8436
8437Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8438 return commonCastTransforms(CI);
8439}
8440
8441Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8442 return commonCastTransforms(CI);
8443}
8444
8445Instruction *InstCombiner::visitPtrToInt(CastInst &CI) {
8446 return commonPointerCastTransforms(CI);
8447}
8448
Chris Lattner7c1626482008-01-08 07:23:51 +00008449Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
8450 if (Instruction *I = commonCastTransforms(CI))
8451 return I;
8452
8453 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8454 if (!DestPointee->isSized()) return 0;
8455
8456 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8457 ConstantInt *Cst;
8458 Value *X;
8459 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
8460 m_ConstantInt(Cst)))) {
8461 // If the source and destination operands have the same type, see if this
8462 // is a single-index GEP.
8463 if (X->getType() == CI.getType()) {
8464 // Get the size of the pointee type.
Duncan Sandsd68f13b2009-01-12 20:38:59 +00008465 uint64_t Size = TD->getTypePaddedSize(DestPointee);
Chris Lattner7c1626482008-01-08 07:23:51 +00008466
8467 // Convert the constant to intptr type.
8468 APInt Offset = Cst->getValue();
8469 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8470
8471 // If Offset is evenly divisible by Size, we can do this xform.
8472 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8473 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Gabor Greifd6da1d02008-04-06 20:25:17 +00008474 return GetElementPtrInst::Create(X, ConstantInt::get(Offset));
Chris Lattner7c1626482008-01-08 07:23:51 +00008475 }
8476 }
8477 // TODO: Could handle other cases, e.g. where add is indexing into field of
8478 // struct etc.
8479 } else if (CI.getOperand(0)->hasOneUse() &&
8480 match(CI.getOperand(0), m_Add(m_Value(X), m_ConstantInt(Cst)))) {
8481 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8482 // "inttoptr+GEP" instead of "add+intptr".
8483
8484 // Get the size of the pointee type.
Duncan Sandsd68f13b2009-01-12 20:38:59 +00008485 uint64_t Size = TD->getTypePaddedSize(DestPointee);
Chris Lattner7c1626482008-01-08 07:23:51 +00008486
8487 // Convert the constant to intptr type.
8488 APInt Offset = Cst->getValue();
8489 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8490
8491 // If Offset is evenly divisible by Size, we can do this xform.
8492 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8493 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8494
8495 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8496 "tmp"), CI);
Gabor Greifd6da1d02008-04-06 20:25:17 +00008497 return GetElementPtrInst::Create(P, ConstantInt::get(Offset), "tmp");
Chris Lattner7c1626482008-01-08 07:23:51 +00008498 }
8499 }
8500 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008501}
8502
8503Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8504 // If the operands are integer typed then apply the integer transforms,
8505 // otherwise just apply the common ones.
8506 Value *Src = CI.getOperand(0);
8507 const Type *SrcTy = Src->getType();
8508 const Type *DestTy = CI.getType();
8509
8510 if (SrcTy->isInteger() && DestTy->isInteger()) {
8511 if (Instruction *Result = commonIntCastTransforms(CI))
8512 return Result;
8513 } else if (isa<PointerType>(SrcTy)) {
8514 if (Instruction *I = commonPointerCastTransforms(CI))
8515 return I;
8516 } else {
8517 if (Instruction *Result = commonCastTransforms(CI))
8518 return Result;
8519 }
8520
8521
8522 // Get rid of casts from one type to the same type. These are useless and can
8523 // be replaced by the operand.
8524 if (DestTy == Src->getType())
8525 return ReplaceInstUsesWith(CI, Src);
8526
8527 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
8528 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
8529 const Type *DstElTy = DstPTy->getElementType();
8530 const Type *SrcElTy = SrcPTy->getElementType();
8531
Nate Begemandf5b3612008-03-31 00:22:16 +00008532 // If the address spaces don't match, don't eliminate the bitcast, which is
8533 // required for changing types.
8534 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
8535 return 0;
8536
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008537 // If we are casting a malloc or alloca to a pointer to a type of the same
8538 // size, rewrite the allocation instruction to allocate the "right" type.
8539 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
8540 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
8541 return V;
8542
8543 // If the source and destination are pointers, and this cast is equivalent
8544 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
8545 // This can enhance SROA and other transforms that want type-safe pointers.
8546 Constant *ZeroUInt = Constant::getNullValue(Type::Int32Ty);
8547 unsigned NumZeros = 0;
8548 while (SrcElTy != DstElTy &&
8549 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
8550 SrcElTy->getNumContainedTypes() /* not "{}" */) {
8551 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
8552 ++NumZeros;
8553 }
8554
8555 // If we found a path from the src to dest, create the getelementptr now.
8556 if (SrcElTy == DstElTy) {
8557 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greifd6da1d02008-04-06 20:25:17 +00008558 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
8559 ((Instruction*) NULL));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008560 }
8561 }
8562
8563 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
8564 if (SVI->hasOneUse()) {
8565 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
8566 // a bitconvert to a vector with the same # elts.
8567 if (isa<VectorType>(DestTy) &&
Mon P Wangbff5d9c2008-11-10 04:46:22 +00008568 cast<VectorType>(DestTy)->getNumElements() ==
8569 SVI->getType()->getNumElements() &&
8570 SVI->getType()->getNumElements() ==
8571 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008572 CastInst *Tmp;
8573 // If either of the operands is a cast from CI.getType(), then
8574 // evaluating the shuffle in the casted destination's type will allow
8575 // us to eliminate at least one cast.
8576 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
8577 Tmp->getOperand(0)->getType() == DestTy) ||
8578 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
8579 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedman722b4792008-11-30 21:09:11 +00008580 Value *LHS = InsertCastBefore(Instruction::BitCast,
8581 SVI->getOperand(0), DestTy, CI);
8582 Value *RHS = InsertCastBefore(Instruction::BitCast,
8583 SVI->getOperand(1), DestTy, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008584 // Return a new shuffle vector. Use the same element ID's, as we
8585 // know the vector types match #elts.
8586 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
8587 }
8588 }
8589 }
8590 }
8591 return 0;
8592}
8593
8594/// GetSelectFoldableOperands - We want to turn code that looks like this:
8595/// %C = or %A, %B
8596/// %D = select %cond, %C, %A
8597/// into:
8598/// %C = select %cond, %B, 0
8599/// %D = or %A, %C
8600///
8601/// Assuming that the specified instruction is an operand to the select, return
8602/// a bitmask indicating which operands of this instruction are foldable if they
8603/// equal the other incoming value of the select.
8604///
8605static unsigned GetSelectFoldableOperands(Instruction *I) {
8606 switch (I->getOpcode()) {
8607 case Instruction::Add:
8608 case Instruction::Mul:
8609 case Instruction::And:
8610 case Instruction::Or:
8611 case Instruction::Xor:
8612 return 3; // Can fold through either operand.
8613 case Instruction::Sub: // Can only fold on the amount subtracted.
8614 case Instruction::Shl: // Can only fold on the shift amount.
8615 case Instruction::LShr:
8616 case Instruction::AShr:
8617 return 1;
8618 default:
8619 return 0; // Cannot fold
8620 }
8621}
8622
8623/// GetSelectFoldableConstant - For the same transformation as the previous
8624/// function, return the identity constant that goes into the select.
8625static Constant *GetSelectFoldableConstant(Instruction *I) {
8626 switch (I->getOpcode()) {
8627 default: assert(0 && "This cannot happen!"); abort();
8628 case Instruction::Add:
8629 case Instruction::Sub:
8630 case Instruction::Or:
8631 case Instruction::Xor:
8632 case Instruction::Shl:
8633 case Instruction::LShr:
8634 case Instruction::AShr:
8635 return Constant::getNullValue(I->getType());
8636 case Instruction::And:
8637 return Constant::getAllOnesValue(I->getType());
8638 case Instruction::Mul:
8639 return ConstantInt::get(I->getType(), 1);
8640 }
8641}
8642
8643/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
8644/// have the same opcode and only one use each. Try to simplify this.
8645Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
8646 Instruction *FI) {
8647 if (TI->getNumOperands() == 1) {
8648 // If this is a non-volatile load or a cast from the same type,
8649 // merge.
8650 if (TI->isCast()) {
8651 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
8652 return 0;
8653 } else {
8654 return 0; // unknown unary op.
8655 }
8656
8657 // Fold this by inserting a select from the input values.
Gabor Greifd6da1d02008-04-06 20:25:17 +00008658 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
8659 FI->getOperand(0), SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008660 InsertNewInstBefore(NewSI, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008661 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008662 TI->getType());
8663 }
8664
8665 // Only handle binary operators here.
8666 if (!isa<BinaryOperator>(TI))
8667 return 0;
8668
8669 // Figure out if the operations have any operands in common.
8670 Value *MatchOp, *OtherOpT, *OtherOpF;
8671 bool MatchIsOpZero;
8672 if (TI->getOperand(0) == FI->getOperand(0)) {
8673 MatchOp = TI->getOperand(0);
8674 OtherOpT = TI->getOperand(1);
8675 OtherOpF = FI->getOperand(1);
8676 MatchIsOpZero = true;
8677 } else if (TI->getOperand(1) == FI->getOperand(1)) {
8678 MatchOp = TI->getOperand(1);
8679 OtherOpT = TI->getOperand(0);
8680 OtherOpF = FI->getOperand(0);
8681 MatchIsOpZero = false;
8682 } else if (!TI->isCommutative()) {
8683 return 0;
8684 } else if (TI->getOperand(0) == FI->getOperand(1)) {
8685 MatchOp = TI->getOperand(0);
8686 OtherOpT = TI->getOperand(1);
8687 OtherOpF = FI->getOperand(0);
8688 MatchIsOpZero = true;
8689 } else if (TI->getOperand(1) == FI->getOperand(0)) {
8690 MatchOp = TI->getOperand(1);
8691 OtherOpT = TI->getOperand(0);
8692 OtherOpF = FI->getOperand(1);
8693 MatchIsOpZero = true;
8694 } else {
8695 return 0;
8696 }
8697
8698 // If we reach here, they do have operations in common.
Gabor Greifd6da1d02008-04-06 20:25:17 +00008699 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
8700 OtherOpF, SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008701 InsertNewInstBefore(NewSI, SI);
8702
8703 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
8704 if (MatchIsOpZero)
Gabor Greifa645dd32008-05-16 19:29:10 +00008705 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008706 else
Gabor Greifa645dd32008-05-16 19:29:10 +00008707 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008708 }
8709 assert(0 && "Shouldn't get here");
8710 return 0;
8711}
8712
Dan Gohman58c09632008-09-16 18:46:06 +00008713/// visitSelectInstWithICmp - Visit a SelectInst that has an
8714/// ICmpInst as its first operand.
8715///
8716Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
8717 ICmpInst *ICI) {
8718 bool Changed = false;
8719 ICmpInst::Predicate Pred = ICI->getPredicate();
8720 Value *CmpLHS = ICI->getOperand(0);
8721 Value *CmpRHS = ICI->getOperand(1);
8722 Value *TrueVal = SI.getTrueValue();
8723 Value *FalseVal = SI.getFalseValue();
8724
8725 // Check cases where the comparison is with a constant that
8726 // can be adjusted to fit the min/max idiom. We may edit ICI in
8727 // place here, so make sure the select is the only user.
8728 if (ICI->hasOneUse())
Dan Gohman35b76162008-10-30 20:40:10 +00008729 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman58c09632008-09-16 18:46:06 +00008730 switch (Pred) {
8731 default: break;
8732 case ICmpInst::ICMP_ULT:
8733 case ICmpInst::ICMP_SLT: {
8734 // X < MIN ? T : F --> F
8735 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
8736 return ReplaceInstUsesWith(SI, FalseVal);
8737 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
8738 Constant *AdjustedRHS = SubOne(CI);
8739 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8740 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8741 Pred = ICmpInst::getSwappedPredicate(Pred);
8742 CmpRHS = AdjustedRHS;
8743 std::swap(FalseVal, TrueVal);
8744 ICI->setPredicate(Pred);
8745 ICI->setOperand(1, CmpRHS);
8746 SI.setOperand(1, TrueVal);
8747 SI.setOperand(2, FalseVal);
8748 Changed = true;
8749 }
8750 break;
8751 }
8752 case ICmpInst::ICMP_UGT:
8753 case ICmpInst::ICMP_SGT: {
8754 // X > MAX ? T : F --> F
8755 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
8756 return ReplaceInstUsesWith(SI, FalseVal);
8757 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
8758 Constant *AdjustedRHS = AddOne(CI);
8759 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
8760 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
8761 Pred = ICmpInst::getSwappedPredicate(Pred);
8762 CmpRHS = AdjustedRHS;
8763 std::swap(FalseVal, TrueVal);
8764 ICI->setPredicate(Pred);
8765 ICI->setOperand(1, CmpRHS);
8766 SI.setOperand(1, TrueVal);
8767 SI.setOperand(2, FalseVal);
8768 Changed = true;
8769 }
8770 break;
8771 }
8772 }
8773
Dan Gohman35b76162008-10-30 20:40:10 +00008774 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
8775 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattner3b874082008-11-16 05:38:51 +00008776 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Chris Lattner73c1ddb2009-01-05 23:53:12 +00008777 if (match(TrueVal, m_ConstantInt<-1>()) &&
8778 match(FalseVal, m_ConstantInt<0>()))
Chris Lattner3b874082008-11-16 05:38:51 +00008779 Pred = ICI->getPredicate();
Chris Lattner73c1ddb2009-01-05 23:53:12 +00008780 else if (match(TrueVal, m_ConstantInt<0>()) &&
8781 match(FalseVal, m_ConstantInt<-1>()))
Chris Lattner3b874082008-11-16 05:38:51 +00008782 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
8783
Dan Gohman35b76162008-10-30 20:40:10 +00008784 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
8785 // If we are just checking for a icmp eq of a single bit and zext'ing it
8786 // to an integer, then shift the bit to the appropriate place and then
8787 // cast to integer to avoid the comparison.
8788 const APInt &Op1CV = CI->getValue();
8789
8790 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
8791 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
8792 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattner3b874082008-11-16 05:38:51 +00008793 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman35b76162008-10-30 20:40:10 +00008794 Value *In = ICI->getOperand(0);
8795 Value *Sh = ConstantInt::get(In->getType(),
8796 In->getType()->getPrimitiveSizeInBits()-1);
8797 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
8798 In->getName()+".lobit"),
8799 *ICI);
Dan Gohman47a60772008-11-02 00:17:33 +00008800 if (In->getType() != SI.getType())
8801 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman35b76162008-10-30 20:40:10 +00008802 true/*SExt*/, "tmp", ICI);
8803
8804 if (Pred == ICmpInst::ICMP_SGT)
8805 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
8806 In->getName()+".not"), *ICI);
8807
8808 return ReplaceInstUsesWith(SI, In);
8809 }
8810 }
8811 }
8812
Dan Gohman58c09632008-09-16 18:46:06 +00008813 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
8814 // Transform (X == Y) ? X : Y -> Y
8815 if (Pred == ICmpInst::ICMP_EQ)
8816 return ReplaceInstUsesWith(SI, FalseVal);
8817 // Transform (X != Y) ? X : Y -> X
8818 if (Pred == ICmpInst::ICMP_NE)
8819 return ReplaceInstUsesWith(SI, TrueVal);
8820 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8821
8822 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
8823 // Transform (X == Y) ? Y : X -> X
8824 if (Pred == ICmpInst::ICMP_EQ)
8825 return ReplaceInstUsesWith(SI, FalseVal);
8826 // Transform (X != Y) ? Y : X -> Y
8827 if (Pred == ICmpInst::ICMP_NE)
8828 return ReplaceInstUsesWith(SI, TrueVal);
8829 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
8830 }
8831
8832 /// NOTE: if we wanted to, this is where to detect integer ABS
8833
8834 return Changed ? &SI : 0;
8835}
8836
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008837Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
8838 Value *CondVal = SI.getCondition();
8839 Value *TrueVal = SI.getTrueValue();
8840 Value *FalseVal = SI.getFalseValue();
8841
8842 // select true, X, Y -> X
8843 // select false, X, Y -> Y
8844 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
8845 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
8846
8847 // select C, X, X -> X
8848 if (TrueVal == FalseVal)
8849 return ReplaceInstUsesWith(SI, TrueVal);
8850
8851 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
8852 return ReplaceInstUsesWith(SI, FalseVal);
8853 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
8854 return ReplaceInstUsesWith(SI, TrueVal);
8855 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
8856 if (isa<Constant>(TrueVal))
8857 return ReplaceInstUsesWith(SI, TrueVal);
8858 else
8859 return ReplaceInstUsesWith(SI, FalseVal);
8860 }
8861
8862 if (SI.getType() == Type::Int1Ty) {
8863 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
8864 if (C->getZExtValue()) {
8865 // Change: A = select B, true, C --> A = or B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00008866 return BinaryOperator::CreateOr(CondVal, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008867 } else {
8868 // Change: A = select B, false, C --> A = and !B, C
8869 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00008870 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008871 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008872 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008873 }
8874 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
8875 if (C->getZExtValue() == false) {
8876 // Change: A = select B, C, false --> A = and B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00008877 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008878 } else {
8879 // Change: A = select B, C, true --> A = or !B, C
8880 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00008881 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008882 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008883 return BinaryOperator::CreateOr(NotCond, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008884 }
8885 }
Chris Lattner53f85a72007-11-25 21:27:53 +00008886
8887 // select a, b, a -> a&b
8888 // select a, a, b -> a|b
8889 if (CondVal == TrueVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00008890 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner53f85a72007-11-25 21:27:53 +00008891 else if (CondVal == FalseVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00008892 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008893 }
8894
8895 // Selecting between two integer constants?
8896 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
8897 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
8898 // select C, 1, 0 -> zext C to int
8899 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00008900 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008901 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
8902 // select C, 0, 1 -> zext !C to int
8903 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00008904 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008905 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008906 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008907 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008908
8909 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
8910
8911 // (x <s 0) ? -1 : 0 -> ashr x, 31
8912 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
8913 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
8914 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
8915 // The comparison constant and the result are not neccessarily the
8916 // same width. Make an all-ones value by inserting a AShr.
8917 Value *X = IC->getOperand(0);
8918 uint32_t Bits = X->getType()->getPrimitiveSizeInBits();
8919 Constant *ShAmt = ConstantInt::get(X->getType(), Bits-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008920 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008921 ShAmt, "ones");
8922 InsertNewInstBefore(SRA, SI);
Eli Friedman722b4792008-11-30 21:09:11 +00008923
8924 // Then cast to the appropriate width.
8925 return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008926 }
8927 }
8928
8929
8930 // If one of the constants is zero (we know they can't both be) and we
8931 // have an icmp instruction with zero, and we have an 'and' with the
8932 // non-constant value, eliminate this whole mess. This corresponds to
8933 // cases like this: ((X & 27) ? 27 : 0)
8934 if (TrueValC->isZero() || FalseValC->isZero())
8935 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
8936 cast<Constant>(IC->getOperand(1))->isNullValue())
8937 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
8938 if (ICA->getOpcode() == Instruction::And &&
8939 isa<ConstantInt>(ICA->getOperand(1)) &&
8940 (ICA->getOperand(1) == TrueValC ||
8941 ICA->getOperand(1) == FalseValC) &&
8942 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
8943 // Okay, now we know that everything is set up, we just don't
8944 // know whether we have a icmp_ne or icmp_eq and whether the
8945 // true or false val is the zero.
8946 bool ShouldNotVal = !TrueValC->isZero();
8947 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
8948 Value *V = ICA;
8949 if (ShouldNotVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00008950 V = InsertNewInstBefore(BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008951 Instruction::Xor, V, ICA->getOperand(1)), SI);
8952 return ReplaceInstUsesWith(SI, V);
8953 }
8954 }
8955 }
8956
8957 // See if we are selecting two values based on a comparison of the two values.
8958 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
8959 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
8960 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen2e1b7692007-10-03 17:45:27 +00008961 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8962 // This is not safe in general for floating point:
8963 // consider X== -0, Y== +0.
8964 // It becomes safe if either operand is a nonzero constant.
8965 ConstantFP *CFPt, *CFPf;
8966 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8967 !CFPt->getValueAPF().isZero()) ||
8968 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8969 !CFPf->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008970 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen2e1b7692007-10-03 17:45:27 +00008971 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008972 // Transform (X != Y) ? X : Y -> X
8973 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8974 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00008975 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008976
8977 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
8978 // Transform (X == Y) ? Y : X -> X
Dale Johannesen2e1b7692007-10-03 17:45:27 +00008979 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
8980 // This is not safe in general for floating point:
8981 // consider X== -0, Y== +0.
8982 // It becomes safe if either operand is a nonzero constant.
8983 ConstantFP *CFPt, *CFPf;
8984 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
8985 !CFPt->getValueAPF().isZero()) ||
8986 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
8987 !CFPf->getValueAPF().isZero()))
8988 return ReplaceInstUsesWith(SI, FalseVal);
8989 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008990 // Transform (X != Y) ? Y : X -> Y
8991 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
8992 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00008993 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008994 }
Dan Gohman58c09632008-09-16 18:46:06 +00008995 // NOTE: if we wanted to, this is where to detect ABS
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008996 }
8997
8998 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman58c09632008-09-16 18:46:06 +00008999 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9000 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9001 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009002
9003 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9004 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9005 if (TI->hasOneUse() && FI->hasOneUse()) {
9006 Instruction *AddOp = 0, *SubOp = 0;
9007
9008 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9009 if (TI->getOpcode() == FI->getOpcode())
9010 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9011 return IV;
9012
9013 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9014 // even legal for FP.
9015 if (TI->getOpcode() == Instruction::Sub &&
9016 FI->getOpcode() == Instruction::Add) {
9017 AddOp = FI; SubOp = TI;
9018 } else if (FI->getOpcode() == Instruction::Sub &&
9019 TI->getOpcode() == Instruction::Add) {
9020 AddOp = TI; SubOp = FI;
9021 }
9022
9023 if (AddOp) {
9024 Value *OtherAddOp = 0;
9025 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9026 OtherAddOp = AddOp->getOperand(1);
9027 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9028 OtherAddOp = AddOp->getOperand(0);
9029 }
9030
9031 if (OtherAddOp) {
9032 // So at this point we know we have (Y -> OtherAddOp):
9033 // select C, (add X, Y), (sub X, Z)
9034 Value *NegVal; // Compute -Z
9035 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
9036 NegVal = ConstantExpr::getNeg(C);
9037 } else {
9038 NegVal = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00009039 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009040 }
9041
9042 Value *NewTrueOp = OtherAddOp;
9043 Value *NewFalseOp = NegVal;
9044 if (AddOp != TI)
9045 std::swap(NewTrueOp, NewFalseOp);
9046 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009047 SelectInst::Create(CondVal, NewTrueOp,
9048 NewFalseOp, SI.getName() + ".p");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009049
9050 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009051 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009052 }
9053 }
9054 }
9055
9056 // See if we can fold the select into one of our operands.
9057 if (SI.getType()->isInteger()) {
9058 // See the comment above GetSelectFoldableOperands for a description of the
9059 // transformation we are doing here.
9060 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal))
9061 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9062 !isa<Constant>(FalseVal))
9063 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9064 unsigned OpToFold = 0;
9065 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9066 OpToFold = 1;
9067 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9068 OpToFold = 2;
9069 }
9070
9071 if (OpToFold) {
9072 Constant *C = GetSelectFoldableConstant(TVI);
9073 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009074 SelectInst::Create(SI.getCondition(),
9075 TVI->getOperand(2-OpToFold), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009076 InsertNewInstBefore(NewSel, SI);
9077 NewSel->takeName(TVI);
9078 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
Gabor Greifa645dd32008-05-16 19:29:10 +00009079 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009080 else {
9081 assert(0 && "Unknown instruction!!");
9082 }
9083 }
9084 }
9085
9086 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal))
9087 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9088 !isa<Constant>(TrueVal))
9089 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9090 unsigned OpToFold = 0;
9091 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9092 OpToFold = 1;
9093 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9094 OpToFold = 2;
9095 }
9096
9097 if (OpToFold) {
9098 Constant *C = GetSelectFoldableConstant(FVI);
9099 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009100 SelectInst::Create(SI.getCondition(), C,
9101 FVI->getOperand(2-OpToFold));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009102 InsertNewInstBefore(NewSel, SI);
9103 NewSel->takeName(FVI);
9104 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
Gabor Greifa645dd32008-05-16 19:29:10 +00009105 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009106 else
9107 assert(0 && "Unknown instruction!!");
9108 }
9109 }
9110 }
9111
9112 if (BinaryOperator::isNot(CondVal)) {
9113 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9114 SI.setOperand(1, FalseVal);
9115 SI.setOperand(2, TrueVal);
9116 return &SI;
9117 }
9118
9119 return 0;
9120}
9121
Dan Gohman2d648bb2008-04-10 18:43:06 +00009122/// EnforceKnownAlignment - If the specified pointer points to an object that
9123/// we control, modify the object's alignment to PrefAlign. This isn't
9124/// often possible though. If alignment is important, a more reliable approach
9125/// is to simply align all global variables and allocation instructions to
9126/// their preferred alignment from the beginning.
9127///
9128static unsigned EnforceKnownAlignment(Value *V,
9129 unsigned Align, unsigned PrefAlign) {
Chris Lattner47cf3452007-08-09 19:05:49 +00009130
Dan Gohman2d648bb2008-04-10 18:43:06 +00009131 User *U = dyn_cast<User>(V);
9132 if (!U) return Align;
9133
9134 switch (getOpcode(U)) {
9135 default: break;
9136 case Instruction::BitCast:
9137 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9138 case Instruction::GetElementPtr: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009139 // If all indexes are zero, it is just the alignment of the base pointer.
9140 bool AllZeroOperands = true;
Gabor Greife92fbe22008-06-12 21:51:29 +00009141 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif17396002008-06-12 21:37:33 +00009142 if (!isa<Constant>(*i) ||
9143 !cast<Constant>(*i)->isNullValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009144 AllZeroOperands = false;
9145 break;
9146 }
Chris Lattner47cf3452007-08-09 19:05:49 +00009147
9148 if (AllZeroOperands) {
9149 // Treat this like a bitcast.
Dan Gohman2d648bb2008-04-10 18:43:06 +00009150 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattner47cf3452007-08-09 19:05:49 +00009151 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009152 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009153 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009154 }
9155
9156 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9157 // If there is a large requested alignment and we can, bump up the alignment
9158 // of the global.
9159 if (!GV->isDeclaration()) {
9160 GV->setAlignment(PrefAlign);
9161 Align = PrefAlign;
9162 }
9163 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9164 // If there is a requested alignment and if this is an alloca, round up. We
9165 // don't do this for malloc, because some systems can't respect the request.
9166 if (isa<AllocaInst>(AI)) {
9167 AI->setAlignment(PrefAlign);
9168 Align = PrefAlign;
9169 }
9170 }
9171
9172 return Align;
9173}
9174
9175/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9176/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9177/// and it is more than the alignment of the ultimate object, see if we can
9178/// increase the alignment of the ultimate object, making this check succeed.
9179unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9180 unsigned PrefAlign) {
9181 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9182 sizeof(PrefAlign) * CHAR_BIT;
9183 APInt Mask = APInt::getAllOnesValue(BitWidth);
9184 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9185 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9186 unsigned TrailZ = KnownZero.countTrailingOnes();
9187 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9188
9189 if (PrefAlign > Align)
9190 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9191
9192 // We don't need to make any adjustment.
9193 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009194}
9195
Chris Lattner00ae5132008-01-13 23:50:23 +00009196Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00009197 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
9198 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattner00ae5132008-01-13 23:50:23 +00009199 unsigned MinAlign = std::min(DstAlign, SrcAlign);
9200 unsigned CopyAlign = MI->getAlignment()->getZExtValue();
9201
9202 if (CopyAlign < MinAlign) {
9203 MI->setAlignment(ConstantInt::get(Type::Int32Ty, MinAlign));
9204 return MI;
9205 }
9206
9207 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9208 // load/store.
9209 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9210 if (MemOpLength == 0) return 0;
9211
Chris Lattnerc669fb62008-01-14 00:28:35 +00009212 // Source and destination pointer types are always "i8*" for intrinsic. See
9213 // if the size is something we can handle with a single primitive load/store.
9214 // A single load+store correctly handles overlapping memory in the memmove
9215 // case.
Chris Lattner00ae5132008-01-13 23:50:23 +00009216 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner5af8a912008-04-30 06:39:11 +00009217 if (Size == 0) return MI; // Delete this mem transfer.
9218
9219 if (Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +00009220 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +00009221
Chris Lattnerc669fb62008-01-14 00:28:35 +00009222 // Use an integer load+store unless we can find something better.
Chris Lattner00ae5132008-01-13 23:50:23 +00009223 Type *NewPtrTy = PointerType::getUnqual(IntegerType::get(Size<<3));
Chris Lattnerc669fb62008-01-14 00:28:35 +00009224
9225 // Memcpy forces the use of i8* for the source and destination. That means
9226 // that if you're using memcpy to move one double around, you'll get a cast
9227 // from double* to i8*. We'd much rather use a double load+store rather than
9228 // an i64 load+store, here because this improves the odds that the source or
9229 // dest address will be promotable. See if we can find a better type than the
9230 // integer datatype.
9231 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9232 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9233 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9234 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9235 // down through these levels if so.
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009236 while (!SrcETy->isSingleValueType()) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00009237 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9238 if (STy->getNumElements() == 1)
9239 SrcETy = STy->getElementType(0);
9240 else
9241 break;
9242 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9243 if (ATy->getNumElements() == 1)
9244 SrcETy = ATy->getElementType();
9245 else
9246 break;
9247 } else
9248 break;
9249 }
9250
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009251 if (SrcETy->isSingleValueType())
Chris Lattnerc669fb62008-01-14 00:28:35 +00009252 NewPtrTy = PointerType::getUnqual(SrcETy);
9253 }
9254 }
9255
9256
Chris Lattner00ae5132008-01-13 23:50:23 +00009257 // If the memcpy/memmove provides better alignment info than we can
9258 // infer, use it.
9259 SrcAlign = std::max(SrcAlign, CopyAlign);
9260 DstAlign = std::max(DstAlign, CopyAlign);
9261
9262 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9263 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattnerc669fb62008-01-14 00:28:35 +00009264 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9265 InsertNewInstBefore(L, *MI);
9266 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9267
9268 // Set the size of the copy to 0, it will be deleted on the next iteration.
9269 MI->setOperand(3, Constant::getNullValue(MemOpLength->getType()));
9270 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +00009271}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009272
Chris Lattner5af8a912008-04-30 06:39:11 +00009273Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9274 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
9275 if (MI->getAlignment()->getZExtValue() < Alignment) {
9276 MI->setAlignment(ConstantInt::get(Type::Int32Ty, Alignment));
9277 return MI;
9278 }
9279
9280 // Extract the length and alignment and fill if they are constant.
9281 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9282 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9283 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9284 return 0;
9285 uint64_t Len = LenC->getZExtValue();
9286 Alignment = MI->getAlignment()->getZExtValue();
9287
9288 // If the length is zero, this is a no-op
9289 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9290
9291 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9292 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
9293 const Type *ITy = IntegerType::get(Len*8); // n=1 -> i8.
9294
9295 Value *Dest = MI->getDest();
9296 Dest = InsertBitCastBefore(Dest, PointerType::getUnqual(ITy), *MI);
9297
9298 // Alignment 0 is identity for alignment 1 for memset, but not store.
9299 if (Alignment == 0) Alignment = 1;
9300
9301 // Extract the fill value and store.
9302 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
9303 InsertNewInstBefore(new StoreInst(ConstantInt::get(ITy, Fill), Dest, false,
9304 Alignment), *MI);
9305
9306 // Set the size of the copy to 0, it will be deleted on the next iteration.
9307 MI->setLength(Constant::getNullValue(LenC->getType()));
9308 return MI;
9309 }
9310
9311 return 0;
9312}
9313
9314
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009315/// visitCallInst - CallInst simplification. This mostly only handles folding
9316/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9317/// the heavy lifting.
9318///
9319Instruction *InstCombiner::visitCallInst(CallInst &CI) {
9320 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9321 if (!II) return visitCallSite(&CI);
9322
9323 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9324 // visitCallSite.
9325 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9326 bool Changed = false;
9327
9328 // memmove/cpy/set of zero bytes is a noop.
9329 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9330 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9331
9332 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9333 if (CI->getZExtValue() == 1) {
9334 // Replace the instruction with just byte operations. We would
9335 // transform other cases to loads/stores, but we don't know if
9336 // alignment is sufficient.
9337 }
9338 }
9339
9340 // If we have a memmove and the source operation is a constant global,
9341 // then the source and dest pointers can't alias, so we can change this
9342 // into a call to memcpy.
Chris Lattner00ae5132008-01-13 23:50:23 +00009343 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009344 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9345 if (GVSrc->isConstant()) {
9346 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner82c2e432008-11-21 16:42:48 +00009347 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9348 const Type *Tys[1];
9349 Tys[0] = CI.getOperand(3)->getType();
9350 CI.setOperand(0,
9351 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009352 Changed = true;
9353 }
Chris Lattner59b27d92008-05-28 05:30:41 +00009354
9355 // memmove(x,x,size) -> noop.
9356 if (MMI->getSource() == MMI->getDest())
9357 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009358 }
9359
9360 // If we can determine a pointer alignment that is bigger than currently
9361 // set, update the alignment.
9362 if (isa<MemCpyInst>(MI) || isa<MemMoveInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +00009363 if (Instruction *I = SimplifyMemTransfer(MI))
9364 return I;
Chris Lattner5af8a912008-04-30 06:39:11 +00009365 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9366 if (Instruction *I = SimplifyMemSet(MSI))
9367 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009368 }
9369
9370 if (Changed) return II;
Chris Lattner989ba312008-06-18 04:33:20 +00009371 }
9372
9373 switch (II->getIntrinsicID()) {
9374 default: break;
9375 case Intrinsic::bswap:
9376 // bswap(bswap(x)) -> x
9377 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9378 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9379 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9380 break;
9381 case Intrinsic::ppc_altivec_lvx:
9382 case Intrinsic::ppc_altivec_lvxl:
9383 case Intrinsic::x86_sse_loadu_ps:
9384 case Intrinsic::x86_sse2_loadu_pd:
9385 case Intrinsic::x86_sse2_loadu_dq:
9386 // Turn PPC lvx -> load if the pointer is known aligned.
9387 // Turn X86 loadups -> load if the pointer is known aligned.
9388 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9389 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
9390 PointerType::getUnqual(II->getType()),
9391 CI);
9392 return new LoadInst(Ptr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009393 }
Chris Lattner989ba312008-06-18 04:33:20 +00009394 break;
9395 case Intrinsic::ppc_altivec_stvx:
9396 case Intrinsic::ppc_altivec_stvxl:
9397 // Turn stvx -> store if the pointer is known aligned.
9398 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9399 const Type *OpPtrTy =
9400 PointerType::getUnqual(II->getOperand(1)->getType());
9401 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9402 return new StoreInst(II->getOperand(1), Ptr);
9403 }
9404 break;
9405 case Intrinsic::x86_sse_storeu_ps:
9406 case Intrinsic::x86_sse2_storeu_pd:
9407 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner989ba312008-06-18 04:33:20 +00009408 // Turn X86 storeu -> store if the pointer is known aligned.
9409 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9410 const Type *OpPtrTy =
9411 PointerType::getUnqual(II->getOperand(2)->getType());
9412 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9413 return new StoreInst(II->getOperand(2), Ptr);
9414 }
9415 break;
9416
9417 case Intrinsic::x86_sse_cvttss2si: {
9418 // These intrinsics only demands the 0th element of its input vector. If
9419 // we can simplify the input based on that, do so now.
9420 uint64_t UndefElts;
9421 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), 1,
9422 UndefElts)) {
9423 II->setOperand(1, V);
9424 return II;
9425 }
9426 break;
9427 }
9428
9429 case Intrinsic::ppc_altivec_vperm:
9430 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9431 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9432 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009433
Chris Lattner989ba312008-06-18 04:33:20 +00009434 // Check that all of the elements are integer constants or undefs.
9435 bool AllEltsOk = true;
9436 for (unsigned i = 0; i != 16; ++i) {
9437 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9438 !isa<UndefValue>(Mask->getOperand(i))) {
9439 AllEltsOk = false;
9440 break;
9441 }
9442 }
9443
9444 if (AllEltsOk) {
9445 // Cast the input vectors to byte vectors.
9446 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9447 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
9448 Value *Result = UndefValue::get(Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009449
Chris Lattner989ba312008-06-18 04:33:20 +00009450 // Only extract each element once.
9451 Value *ExtractedElts[32];
9452 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9453
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009454 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner989ba312008-06-18 04:33:20 +00009455 if (isa<UndefValue>(Mask->getOperand(i)))
9456 continue;
9457 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
9458 Idx &= 31; // Match the hardware behavior.
9459
9460 if (ExtractedElts[Idx] == 0) {
9461 Instruction *Elt =
9462 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
9463 InsertNewInstBefore(Elt, CI);
9464 ExtractedElts[Idx] = Elt;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009465 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009466
Chris Lattner989ba312008-06-18 04:33:20 +00009467 // Insert this value into the result vector.
9468 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
9469 i, "tmp");
9470 InsertNewInstBefore(cast<Instruction>(Result), CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009471 }
Chris Lattner989ba312008-06-18 04:33:20 +00009472 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009473 }
Chris Lattner989ba312008-06-18 04:33:20 +00009474 }
9475 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009476
Chris Lattner989ba312008-06-18 04:33:20 +00009477 case Intrinsic::stackrestore: {
9478 // If the save is right next to the restore, remove the restore. This can
9479 // happen when variable allocas are DCE'd.
9480 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
9481 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
9482 BasicBlock::iterator BI = SS;
9483 if (&*++BI == II)
9484 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009485 }
Chris Lattner989ba312008-06-18 04:33:20 +00009486 }
9487
9488 // Scan down this block to see if there is another stack restore in the
9489 // same block without an intervening call/alloca.
9490 BasicBlock::iterator BI = II;
9491 TerminatorInst *TI = II->getParent()->getTerminator();
9492 bool CannotRemove = false;
9493 for (++BI; &*BI != TI; ++BI) {
9494 if (isa<AllocaInst>(BI)) {
9495 CannotRemove = true;
9496 break;
9497 }
Chris Lattnera6b477c2008-06-25 05:59:28 +00009498 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
9499 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
9500 // If there is a stackrestore below this one, remove this one.
9501 if (II->getIntrinsicID() == Intrinsic::stackrestore)
9502 return EraseInstFromFunction(CI);
9503 // Otherwise, ignore the intrinsic.
9504 } else {
9505 // If we found a non-intrinsic call, we can't remove the stack
9506 // restore.
Chris Lattner416d91c2008-02-18 06:12:38 +00009507 CannotRemove = true;
9508 break;
9509 }
Chris Lattner989ba312008-06-18 04:33:20 +00009510 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009511 }
Chris Lattner989ba312008-06-18 04:33:20 +00009512
9513 // If the stack restore is in a return/unwind block and if there are no
9514 // allocas or calls between the restore and the return, nuke the restore.
9515 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
9516 return EraseInstFromFunction(CI);
9517 break;
9518 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009519 }
9520
9521 return visitCallSite(II);
9522}
9523
9524// InvokeInst simplification
9525//
9526Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
9527 return visitCallSite(&II);
9528}
9529
Dale Johannesen96021832008-04-25 21:16:07 +00009530/// isSafeToEliminateVarargsCast - If this cast does not affect the value
9531/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen35615462008-04-23 18:34:37 +00009532static bool isSafeToEliminateVarargsCast(const CallSite CS,
9533 const CastInst * const CI,
9534 const TargetData * const TD,
9535 const int ix) {
9536 if (!CI->isLosslessCast())
9537 return false;
9538
9539 // The size of ByVal arguments is derived from the type, so we
9540 // can't change to a type with a different size. If the size were
9541 // passed explicitly we could avoid this check.
Devang Pateld222f862008-09-25 21:00:45 +00009542 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen35615462008-04-23 18:34:37 +00009543 return true;
9544
9545 const Type* SrcTy =
9546 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
9547 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
9548 if (!SrcTy->isSized() || !DstTy->isSized())
9549 return false;
Duncan Sandsd68f13b2009-01-12 20:38:59 +00009550 if (TD->getTypePaddedSize(SrcTy) != TD->getTypePaddedSize(DstTy))
Dale Johannesen35615462008-04-23 18:34:37 +00009551 return false;
9552 return true;
9553}
9554
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009555// visitCallSite - Improvements for call and invoke instructions.
9556//
9557Instruction *InstCombiner::visitCallSite(CallSite CS) {
9558 bool Changed = false;
9559
9560 // If the callee is a constexpr cast of a function, attempt to move the cast
9561 // to the arguments of the call/invoke.
9562 if (transformConstExprCastCall(CS)) return 0;
9563
9564 Value *Callee = CS.getCalledValue();
9565
9566 if (Function *CalleeF = dyn_cast<Function>(Callee))
9567 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
9568 Instruction *OldCall = CS.getInstruction();
9569 // If the call and callee calling conventions don't match, this call must
9570 // be unreachable, as the call is undefined.
9571 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00009572 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
9573 OldCall);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009574 if (!OldCall->use_empty())
9575 OldCall->replaceAllUsesWith(UndefValue::get(OldCall->getType()));
9576 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
9577 return EraseInstFromFunction(*OldCall);
9578 return 0;
9579 }
9580
9581 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
9582 // This instruction is not reachable, just remove it. We insert a store to
9583 // undef so that we know that this code is not reachable, despite the fact
9584 // that we can't modify the CFG here.
9585 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +00009586 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009587 CS.getInstruction());
9588
9589 if (!CS.getInstruction()->use_empty())
9590 CS.getInstruction()->
9591 replaceAllUsesWith(UndefValue::get(CS.getInstruction()->getType()));
9592
9593 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
9594 // Don't break the CFG, insert a dummy cond branch.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009595 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
9596 ConstantInt::getTrue(), II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009597 }
9598 return EraseInstFromFunction(*CS.getInstruction());
9599 }
9600
Duncan Sands74833f22007-09-17 10:26:40 +00009601 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
9602 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
9603 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
9604 return transformCallThroughTrampoline(CS);
9605
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009606 const PointerType *PTy = cast<PointerType>(Callee->getType());
9607 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
9608 if (FTy->isVarArg()) {
Dale Johannesen502336c2008-04-23 01:03:05 +00009609 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009610 // See if we can optimize any arguments passed through the varargs area of
9611 // the call.
9612 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen35615462008-04-23 18:34:37 +00009613 E = CS.arg_end(); I != E; ++I, ++ix) {
9614 CastInst *CI = dyn_cast<CastInst>(*I);
9615 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
9616 *I = CI->getOperand(0);
9617 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009618 }
Dale Johannesen35615462008-04-23 18:34:37 +00009619 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009620 }
9621
Duncan Sands2937e352007-12-19 21:13:37 +00009622 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +00009623 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +00009624 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +00009625 Changed = true;
9626 }
9627
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009628 return Changed ? CS.getInstruction() : 0;
9629}
9630
9631// transformConstExprCastCall - If the callee is a constexpr cast of a function,
9632// attempt to move the cast to the arguments of the call/invoke.
9633//
9634bool InstCombiner::transformConstExprCastCall(CallSite CS) {
9635 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
9636 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
9637 if (CE->getOpcode() != Instruction::BitCast ||
9638 !isa<Function>(CE->getOperand(0)))
9639 return false;
9640 Function *Callee = cast<Function>(CE->getOperand(0));
9641 Instruction *Caller = CS.getInstruction();
Devang Pateld222f862008-09-25 21:00:45 +00009642 const AttrListPtr &CallerPAL = CS.getAttributes();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009643
9644 // Okay, this is a cast from a function to a different type. Unless doing so
9645 // would cause a type conversion of one of our arguments, change this call to
9646 // be a direct call with arguments casted to the appropriate types.
9647 //
9648 const FunctionType *FT = Callee->getFunctionType();
9649 const Type *OldRetTy = Caller->getType();
Duncan Sands7901ce12008-06-01 07:38:42 +00009650 const Type *NewRetTy = FT->getReturnType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009651
Duncan Sands7901ce12008-06-01 07:38:42 +00009652 if (isa<StructType>(NewRetTy))
Devang Pateld091d322008-03-11 18:04:06 +00009653 return false; // TODO: Handle multiple return values.
9654
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009655 // Check to see if we are changing the return type...
Duncan Sands7901ce12008-06-01 07:38:42 +00009656 if (OldRetTy != NewRetTy) {
Bill Wendlingd9644a42008-05-14 22:45:20 +00009657 if (Callee->isDeclaration() &&
Duncan Sands7901ce12008-06-01 07:38:42 +00009658 // Conversion is ok if changing from one pointer type to another or from
9659 // a pointer to an integer of the same size.
9660 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
Duncan Sands886cadb2008-06-17 15:55:30 +00009661 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009662 return false; // Cannot transform this return value.
9663
Duncan Sands5c489582008-01-06 10:12:28 +00009664 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +00009665 // void -> non-void is handled specially
Duncan Sands7901ce12008-06-01 07:38:42 +00009666 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +00009667 return false; // Cannot transform this return value.
9668
Chris Lattner1c8733e2008-03-12 17:45:29 +00009669 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patelf2a4a922008-09-26 22:53:05 +00009670 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Pateld222f862008-09-25 21:00:45 +00009671 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sandsdbe97dc2008-01-07 17:16:06 +00009672 return false; // Attribute not compatible with transformed value.
9673 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009674
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009675 // If the callsite is an invoke instruction, and the return value is used by
9676 // a PHI node in a successor, we cannot change the return type of the call
9677 // because there is no place to put the cast instruction (without breaking
9678 // the critical edge). Bail out in this case.
9679 if (!Caller->use_empty())
9680 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
9681 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
9682 UI != E; ++UI)
9683 if (PHINode *PN = dyn_cast<PHINode>(*UI))
9684 if (PN->getParent() == II->getNormalDest() ||
9685 PN->getParent() == II->getUnwindDest())
9686 return false;
9687 }
9688
9689 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
9690 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
9691
9692 CallSite::arg_iterator AI = CS.arg_begin();
9693 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
9694 const Type *ParamTy = FT->getParamType(i);
9695 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +00009696
9697 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +00009698 return false; // Cannot transform this parameter value.
9699
Devang Patelf2a4a922008-09-26 22:53:05 +00009700 if (CallerPAL.getParamAttributes(i + 1)
9701 & Attribute::typeIncompatible(ParamTy))
Chris Lattner1c8733e2008-03-12 17:45:29 +00009702 return false; // Attribute not compatible with transformed value.
Duncan Sands5c489582008-01-06 10:12:28 +00009703
Duncan Sands7901ce12008-06-01 07:38:42 +00009704 // Converting from one pointer type to another or between a pointer and an
9705 // integer of the same size is safe even if we do not have a body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009706 bool isConvertible = ActTy == ParamTy ||
Duncan Sands7901ce12008-06-01 07:38:42 +00009707 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
9708 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009709 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009710 }
9711
9712 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
9713 Callee->isDeclaration())
Chris Lattner1c8733e2008-03-12 17:45:29 +00009714 return false; // Do not delete arguments unless we have a function body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009715
Chris Lattner1c8733e2008-03-12 17:45:29 +00009716 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
9717 !CallerPAL.isEmpty())
Duncan Sandsc849e662008-01-06 18:27:01 +00009718 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +00009719 // won't be dropping them. Check that these extra arguments have attributes
9720 // that are compatible with being a vararg call argument.
Chris Lattner1c8733e2008-03-12 17:45:29 +00009721 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
9722 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands4ced1f82008-01-13 08:02:44 +00009723 break;
Devang Patele480dfa2008-09-23 23:03:40 +00009724 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Pateld222f862008-09-25 21:00:45 +00009725 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sands4ced1f82008-01-13 08:02:44 +00009726 return false;
9727 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009728
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009729 // Okay, we decided that this is a safe thing to do: go ahead and start
9730 // inserting cast instructions as necessary...
9731 std::vector<Value*> Args;
9732 Args.reserve(NumActualArgs);
Devang Pateld222f862008-09-25 21:00:45 +00009733 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsc849e662008-01-06 18:27:01 +00009734 attrVec.reserve(NumCommonArgs);
9735
9736 // Get any return attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +00009737 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsc849e662008-01-06 18:27:01 +00009738
9739 // If the return value is not being used, the type may not be compatible
9740 // with the existing attributes. Wipe out any problematic attributes.
Devang Pateld222f862008-09-25 21:00:45 +00009741 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsc849e662008-01-06 18:27:01 +00009742
9743 // Add the new return attributes.
9744 if (RAttrs)
Devang Pateld222f862008-09-25 21:00:45 +00009745 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009746
9747 AI = CS.arg_begin();
9748 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
9749 const Type *ParamTy = FT->getParamType(i);
9750 if ((*AI)->getType() == ParamTy) {
9751 Args.push_back(*AI);
9752 } else {
9753 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
9754 false, ParamTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00009755 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009756 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
9757 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009758
9759 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +00009760 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +00009761 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009762 }
9763
9764 // If the function takes more arguments than the call was taking, add them
9765 // now...
9766 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
9767 Args.push_back(Constant::getNullValue(FT->getParamType(i)));
9768
9769 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009770 if (FT->getNumParams() < NumActualArgs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009771 if (!FT->isVarArg()) {
9772 cerr << "WARNING: While resolving call to function '"
9773 << Callee->getName() << "' arguments were dropped!\n";
9774 } else {
9775 // Add all of the arguments in their promoted form to the arg list...
9776 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
9777 const Type *PTy = getPromotedType((*AI)->getType());
9778 if (PTy != (*AI)->getType()) {
9779 // Must promote to pass through va_arg area!
9780 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
9781 PTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00009782 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009783 InsertNewInstBefore(Cast, *Caller);
9784 Args.push_back(Cast);
9785 } else {
9786 Args.push_back(*AI);
9787 }
Duncan Sandsc849e662008-01-06 18:27:01 +00009788
Duncan Sands4ced1f82008-01-13 08:02:44 +00009789 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +00009790 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +00009791 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sands4ced1f82008-01-13 08:02:44 +00009792 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009793 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00009794 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009795
Devang Patelf2a4a922008-09-26 22:53:05 +00009796 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
9797 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
9798
Duncan Sands7901ce12008-06-01 07:38:42 +00009799 if (NewRetTy == Type::VoidTy)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009800 Caller->setName(""); // Void type should not have a name.
9801
Devang Pateld222f862008-09-25 21:00:45 +00009802 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsc849e662008-01-06 18:27:01 +00009803
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009804 Instruction *NC;
9805 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009806 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009807 Args.begin(), Args.end(),
9808 Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +00009809 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +00009810 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009811 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009812 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
9813 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009814 CallInst *CI = cast<CallInst>(Caller);
9815 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009816 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009817 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +00009818 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009819 }
9820
9821 // Insert a cast of the return type as necessary.
9822 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +00009823 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009824 if (NV->getType() != Type::VoidTy) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009825 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +00009826 OldRetTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +00009827 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009828
9829 // If this is an invoke instruction, we should insert it after the first
9830 // non-phi, instruction in the normal successor block.
9831 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman514277c2008-05-23 21:05:58 +00009832 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009833 InsertNewInstBefore(NC, *I);
9834 } else {
9835 // Otherwise, it's a call, just insert cast right after the call instr
9836 InsertNewInstBefore(NC, *Caller);
9837 }
9838 AddUsersToWorkList(*Caller);
9839 } else {
9840 NV = UndefValue::get(Caller->getType());
9841 }
9842 }
9843
9844 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9845 Caller->replaceAllUsesWith(NV);
9846 Caller->eraseFromParent();
9847 RemoveFromWorkList(Caller);
9848 return true;
9849}
9850
Duncan Sands74833f22007-09-17 10:26:40 +00009851// transformCallThroughTrampoline - Turn a call to a function created by the
9852// init_trampoline intrinsic into a direct call to the underlying function.
9853//
9854Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
9855 Value *Callee = CS.getCalledValue();
9856 const PointerType *PTy = cast<PointerType>(Callee->getType());
9857 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Pateld222f862008-09-25 21:00:45 +00009858 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sands48b81112008-01-14 19:52:09 +00009859
9860 // If the call already has the 'nest' attribute somewhere then give up -
9861 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Pateld222f862008-09-25 21:00:45 +00009862 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sands48b81112008-01-14 19:52:09 +00009863 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +00009864
9865 IntrinsicInst *Tramp =
9866 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
9867
Anton Korobeynikov48fc88f2008-05-07 22:54:15 +00009868 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sands74833f22007-09-17 10:26:40 +00009869 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
9870 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
9871
Devang Pateld222f862008-09-25 21:00:45 +00009872 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner1c8733e2008-03-12 17:45:29 +00009873 if (!NestAttrs.isEmpty()) {
Duncan Sands74833f22007-09-17 10:26:40 +00009874 unsigned NestIdx = 1;
9875 const Type *NestTy = 0;
Devang Pateld222f862008-09-25 21:00:45 +00009876 Attributes NestAttr = Attribute::None;
Duncan Sands74833f22007-09-17 10:26:40 +00009877
9878 // Look for a parameter marked with the 'nest' attribute.
9879 for (FunctionType::param_iterator I = NestFTy->param_begin(),
9880 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Pateld222f862008-09-25 21:00:45 +00009881 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sands74833f22007-09-17 10:26:40 +00009882 // Record the parameter type and any other attributes.
9883 NestTy = *I;
Devang Patelf2a4a922008-09-26 22:53:05 +00009884 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sands74833f22007-09-17 10:26:40 +00009885 break;
9886 }
9887
9888 if (NestTy) {
9889 Instruction *Caller = CS.getInstruction();
9890 std::vector<Value*> NewArgs;
9891 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
9892
Devang Pateld222f862008-09-25 21:00:45 +00009893 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner1c8733e2008-03-12 17:45:29 +00009894 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sands48b81112008-01-14 19:52:09 +00009895
Duncan Sands74833f22007-09-17 10:26:40 +00009896 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +00009897 // mean appending it. Likewise for attributes.
9898
Devang Patelf2a4a922008-09-26 22:53:05 +00009899 // Add any result attributes.
9900 if (Attributes Attr = Attrs.getRetAttributes())
Devang Pateld222f862008-09-25 21:00:45 +00009901 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sands48b81112008-01-14 19:52:09 +00009902
Duncan Sands74833f22007-09-17 10:26:40 +00009903 {
9904 unsigned Idx = 1;
9905 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
9906 do {
9907 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +00009908 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00009909 Value *NestVal = Tramp->getOperand(3);
9910 if (NestVal->getType() != NestTy)
9911 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
9912 NewArgs.push_back(NestVal);
Devang Pateld222f862008-09-25 21:00:45 +00009913 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +00009914 }
9915
9916 if (I == E)
9917 break;
9918
Duncan Sands48b81112008-01-14 19:52:09 +00009919 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +00009920 NewArgs.push_back(*I);
Devang Patelf2a4a922008-09-26 22:53:05 +00009921 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sands48b81112008-01-14 19:52:09 +00009922 NewAttrs.push_back
Devang Pateld222f862008-09-25 21:00:45 +00009923 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +00009924
9925 ++Idx, ++I;
9926 } while (1);
9927 }
9928
Devang Patelf2a4a922008-09-26 22:53:05 +00009929 // Add any function attributes.
9930 if (Attributes Attr = Attrs.getFnAttributes())
9931 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
9932
Duncan Sands74833f22007-09-17 10:26:40 +00009933 // The trampoline may have been bitcast to a bogus type (FTy).
9934 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +00009935 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +00009936
Duncan Sands74833f22007-09-17 10:26:40 +00009937 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +00009938 NewTypes.reserve(FTy->getNumParams()+1);
9939
Duncan Sands74833f22007-09-17 10:26:40 +00009940 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +00009941 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +00009942 {
9943 unsigned Idx = 1;
9944 FunctionType::param_iterator I = FTy->param_begin(),
9945 E = FTy->param_end();
9946
9947 do {
Duncan Sands48b81112008-01-14 19:52:09 +00009948 if (Idx == NestIdx)
9949 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +00009950 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +00009951
9952 if (I == E)
9953 break;
9954
Duncan Sands48b81112008-01-14 19:52:09 +00009955 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +00009956 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +00009957
9958 ++Idx, ++I;
9959 } while (1);
9960 }
9961
9962 // Replace the trampoline call with a direct call. Let the generic
9963 // code sort out any function type mismatches.
9964 FunctionType *NewFTy =
Duncan Sandsf5588dc2007-11-27 13:23:08 +00009965 FunctionType::get(FTy->getReturnType(), NewTypes, FTy->isVarArg());
Christopher Lambbb2f2222007-12-17 01:12:55 +00009966 Constant *NewCallee = NestF->getType() == PointerType::getUnqual(NewFTy) ?
9967 NestF : ConstantExpr::getBitCast(NestF, PointerType::getUnqual(NewFTy));
Devang Pateld222f862008-09-25 21:00:45 +00009968 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sands74833f22007-09-17 10:26:40 +00009969
9970 Instruction *NewCaller;
9971 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009972 NewCaller = InvokeInst::Create(NewCallee,
9973 II->getNormalDest(), II->getUnwindDest(),
9974 NewArgs.begin(), NewArgs.end(),
9975 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +00009976 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +00009977 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00009978 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +00009979 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
9980 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +00009981 if (cast<CallInst>(Caller)->isTailCall())
9982 cast<CallInst>(NewCaller)->setTailCall();
9983 cast<CallInst>(NewCaller)->
9984 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +00009985 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +00009986 }
9987 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
9988 Caller->replaceAllUsesWith(NewCaller);
9989 Caller->eraseFromParent();
9990 RemoveFromWorkList(Caller);
9991 return 0;
9992 }
9993 }
9994
9995 // Replace the trampoline call with a direct call. Since there is no 'nest'
9996 // parameter, there is no need to adjust the argument list. Let the generic
9997 // code sort out any function type mismatches.
9998 Constant *NewCallee =
9999 NestF->getType() == PTy ? NestF : ConstantExpr::getBitCast(NestF, PTy);
10000 CS.setCalledFunction(NewCallee);
10001 return CS.getInstruction();
10002}
10003
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010004/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10005/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10006/// and a single binop.
10007Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10008 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner30078012008-12-01 03:42:51 +000010009 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010010 unsigned Opc = FirstInst->getOpcode();
10011 Value *LHSVal = FirstInst->getOperand(0);
10012 Value *RHSVal = FirstInst->getOperand(1);
10013
10014 const Type *LHSType = LHSVal->getType();
10015 const Type *RHSType = RHSVal->getType();
10016
10017 // Scan to see if all operands are the same opcode, all have one use, and all
10018 // kill their operands (i.e. the operands have one use).
Chris Lattner9e1916e2008-12-01 02:34:36 +000010019 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010020 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10021 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10022 // Verify type of the LHS matches so we don't fold cmp's of different
10023 // types or GEP's with different index types.
10024 I->getOperand(0)->getType() != LHSType ||
10025 I->getOperand(1)->getType() != RHSType)
10026 return 0;
10027
10028 // If they are CmpInst instructions, check their predicates
10029 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10030 if (cast<CmpInst>(I)->getPredicate() !=
10031 cast<CmpInst>(FirstInst)->getPredicate())
10032 return 0;
10033
10034 // Keep track of which operand needs a phi node.
10035 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10036 if (I->getOperand(1) != RHSVal) RHSVal = 0;
10037 }
10038
Chris Lattner30078012008-12-01 03:42:51 +000010039 // Otherwise, this is safe to transform!
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010040
10041 Value *InLHS = FirstInst->getOperand(0);
10042 Value *InRHS = FirstInst->getOperand(1);
10043 PHINode *NewLHS = 0, *NewRHS = 0;
10044 if (LHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010045 NewLHS = PHINode::Create(LHSType,
10046 FirstInst->getOperand(0)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010047 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10048 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10049 InsertNewInstBefore(NewLHS, PN);
10050 LHSVal = NewLHS;
10051 }
10052
10053 if (RHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010054 NewRHS = PHINode::Create(RHSType,
10055 FirstInst->getOperand(1)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010056 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10057 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10058 InsertNewInstBefore(NewRHS, PN);
10059 RHSVal = NewRHS;
10060 }
10061
10062 // Add all operands to the new PHIs.
Chris Lattner9e1916e2008-12-01 02:34:36 +000010063 if (NewLHS || NewRHS) {
10064 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10065 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10066 if (NewLHS) {
10067 Value *NewInLHS = InInst->getOperand(0);
10068 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10069 }
10070 if (NewRHS) {
10071 Value *NewInRHS = InInst->getOperand(1);
10072 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10073 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010074 }
10075 }
10076
10077 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010078 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner30078012008-12-01 03:42:51 +000010079 CmpInst *CIOp = cast<CmpInst>(FirstInst);
10080 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(), LHSVal,
10081 RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010082}
10083
Chris Lattner9e1916e2008-12-01 02:34:36 +000010084Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10085 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10086
10087 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10088 FirstInst->op_end());
10089
10090 // Scan to see if all operands are the same opcode, all have one use, and all
10091 // kill their operands (i.e. the operands have one use).
10092 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10093 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10094 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10095 GEP->getNumOperands() != FirstInst->getNumOperands())
10096 return 0;
10097
10098 // Compare the operand lists.
10099 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10100 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10101 continue;
10102
10103 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10104 // if one of the PHIs has a constant for the index. The index may be
10105 // substantially cheaper to compute for the constants, so making it a
10106 // variable index could pessimize the path. This also handles the case
10107 // for struct indices, which must always be constant.
10108 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10109 isa<ConstantInt>(GEP->getOperand(op)))
10110 return 0;
10111
10112 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10113 return 0;
10114 FixedOperands[op] = 0; // Needs a PHI.
10115 }
10116 }
10117
10118 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10119 // that is variable.
10120 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10121
10122 bool HasAnyPHIs = false;
10123 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10124 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10125 Value *FirstOp = FirstInst->getOperand(i);
10126 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10127 FirstOp->getName()+".pn");
10128 InsertNewInstBefore(NewPN, PN);
10129
10130 NewPN->reserveOperandSpace(e);
10131 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10132 OperandPhis[i] = NewPN;
10133 FixedOperands[i] = NewPN;
10134 HasAnyPHIs = true;
10135 }
10136
10137
10138 // Add all operands to the new PHIs.
10139 if (HasAnyPHIs) {
10140 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10141 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10142 BasicBlock *InBB = PN.getIncomingBlock(i);
10143
10144 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10145 if (PHINode *OpPhi = OperandPhis[op])
10146 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10147 }
10148 }
10149
10150 Value *Base = FixedOperands[0];
10151 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10152 FixedOperands.end());
10153}
10154
10155
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010156/// isSafeToSinkLoad - Return true if we know that it is safe sink the load out
10157/// of the block that defines it. This means that it must be obvious the value
10158/// of the load is not changed from the point of the load to the end of the
10159/// block it is in.
10160///
10161/// Finally, it is safe, but not profitable, to sink a load targetting a
10162/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10163/// to a register.
10164static bool isSafeToSinkLoad(LoadInst *L) {
10165 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10166
10167 for (++BBI; BBI != E; ++BBI)
10168 if (BBI->mayWriteToMemory())
10169 return false;
10170
10171 // Check for non-address taken alloca. If not address-taken already, it isn't
10172 // profitable to do this xform.
10173 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10174 bool isAddressTaken = false;
10175 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10176 UI != E; ++UI) {
10177 if (isa<LoadInst>(UI)) continue;
10178 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10179 // If storing TO the alloca, then the address isn't taken.
10180 if (SI->getOperand(1) == AI) continue;
10181 }
10182 isAddressTaken = true;
10183 break;
10184 }
10185
10186 if (!isAddressTaken)
10187 return false;
10188 }
10189
10190 return true;
10191}
10192
10193
10194// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10195// operator and they all are only used by the PHI, PHI together their
10196// inputs, and do the operation once, to the result of the PHI.
10197Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10198 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10199
10200 // Scan the instruction, looking for input operations that can be folded away.
10201 // If all input operands to the phi are the same instruction (e.g. a cast from
10202 // the same type or "+42") we can pull the operation through the PHI, reducing
10203 // code size and simplifying code.
10204 Constant *ConstantOp = 0;
10205 const Type *CastSrcTy = 0;
10206 bool isVolatile = false;
10207 if (isa<CastInst>(FirstInst)) {
10208 CastSrcTy = FirstInst->getOperand(0)->getType();
10209 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10210 // Can fold binop, compare or shift here if the RHS is a constant,
10211 // otherwise call FoldPHIArgBinOpIntoPHI.
10212 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10213 if (ConstantOp == 0)
10214 return FoldPHIArgBinOpIntoPHI(PN);
10215 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10216 isVolatile = LI->isVolatile();
10217 // We can't sink the load if the loaded value could be modified between the
10218 // load and the PHI.
10219 if (LI->getParent() != PN.getIncomingBlock(0) ||
10220 !isSafeToSinkLoad(LI))
10221 return 0;
Chris Lattner2d9fdd82008-07-08 17:18:32 +000010222
10223 // If the PHI is of volatile loads and the load block has multiple
10224 // successors, sinking it would remove a load of the volatile value from
10225 // the path through the other successor.
10226 if (isVolatile &&
10227 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10228 return 0;
10229
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010230 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner9e1916e2008-12-01 02:34:36 +000010231 return FoldPHIArgGEPIntoPHI(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010232 } else {
10233 return 0; // Cannot fold this operation.
10234 }
10235
10236 // Check to see if all arguments are the same operation.
10237 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10238 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10239 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10240 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10241 return 0;
10242 if (CastSrcTy) {
10243 if (I->getOperand(0)->getType() != CastSrcTy)
10244 return 0; // Cast operation must match.
10245 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10246 // We can't sink the load if the loaded value could be modified between
10247 // the load and the PHI.
10248 if (LI->isVolatile() != isVolatile ||
10249 LI->getParent() != PN.getIncomingBlock(i) ||
10250 !isSafeToSinkLoad(LI))
10251 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +000010252
Chris Lattner2d9fdd82008-07-08 17:18:32 +000010253 // If the PHI is of volatile loads and the load block has multiple
10254 // successors, sinking it would remove a load of the volatile value from
10255 // the path through the other successor.
Chris Lattnerf7867012008-04-29 17:28:22 +000010256 if (isVolatile &&
10257 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10258 return 0;
10259
10260
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010261 } else if (I->getOperand(1) != ConstantOp) {
10262 return 0;
10263 }
10264 }
10265
10266 // Okay, they are all the same operation. Create a new PHI node of the
10267 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greifd6da1d02008-04-06 20:25:17 +000010268 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10269 PN.getName()+".in");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010270 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10271
10272 Value *InVal = FirstInst->getOperand(0);
10273 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10274
10275 // Add all operands to the new PHI.
10276 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10277 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10278 if (NewInVal != InVal)
10279 InVal = 0;
10280 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10281 }
10282
10283 Value *PhiVal;
10284 if (InVal) {
10285 // The new PHI unions all of the same values together. This is really
10286 // common, so we handle it intelligently here for compile-time speed.
10287 PhiVal = InVal;
10288 delete NewPN;
10289 } else {
10290 InsertNewInstBefore(NewPN, PN);
10291 PhiVal = NewPN;
10292 }
10293
10294 // Insert and return the new operation.
10295 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010296 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnerfc984e92008-04-29 17:13:43 +000010297 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010298 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +000010299 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010300 return CmpInst::Create(CIOp->getOpcode(), CIOp->getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010301 PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +000010302 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10303
10304 // If this was a volatile load that we are merging, make sure to loop through
10305 // and mark all the input loads as non-volatile. If we don't do this, we will
10306 // insert a new volatile load and the old ones will not be deletable.
10307 if (isVolatile)
10308 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10309 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10310
10311 return new LoadInst(PhiVal, "", isVolatile);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010312}
10313
10314/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10315/// that is dead.
10316static bool DeadPHICycle(PHINode *PN,
10317 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10318 if (PN->use_empty()) return true;
10319 if (!PN->hasOneUse()) return false;
10320
10321 // Remember this node, and if we find the cycle, return.
10322 if (!PotentiallyDeadPHIs.insert(PN))
10323 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +000010324
10325 // Don't scan crazily complex things.
10326 if (PotentiallyDeadPHIs.size() == 16)
10327 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010328
10329 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10330 return DeadPHICycle(PU, PotentiallyDeadPHIs);
10331
10332 return false;
10333}
10334
Chris Lattner27b695d2007-11-06 21:52:06 +000010335/// PHIsEqualValue - Return true if this phi node is always equal to
10336/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10337/// z = some value; x = phi (y, z); y = phi (x, z)
10338static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10339 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10340 // See if we already saw this PHI node.
10341 if (!ValueEqualPHIs.insert(PN))
10342 return true;
10343
10344 // Don't scan crazily complex things.
10345 if (ValueEqualPHIs.size() == 16)
10346 return false;
10347
10348 // Scan the operands to see if they are either phi nodes or are equal to
10349 // the value.
10350 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10351 Value *Op = PN->getIncomingValue(i);
10352 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10353 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10354 return false;
10355 } else if (Op != NonPhiInVal)
10356 return false;
10357 }
10358
10359 return true;
10360}
10361
10362
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010363// PHINode simplification
10364//
10365Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10366 // If LCSSA is around, don't mess with Phi nodes
10367 if (MustPreserveLCSSA) return 0;
10368
10369 if (Value *V = PN.hasConstantValue())
10370 return ReplaceInstUsesWith(PN, V);
10371
10372 // If all PHI operands are the same operation, pull them through the PHI,
10373 // reducing code size.
10374 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner9e1916e2008-12-01 02:34:36 +000010375 isa<Instruction>(PN.getIncomingValue(1)) &&
10376 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10377 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10378 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10379 // than themselves more than once.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010380 PN.getIncomingValue(0)->hasOneUse())
10381 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10382 return Result;
10383
10384 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10385 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10386 // PHI)... break the cycle.
10387 if (PN.hasOneUse()) {
10388 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10389 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10390 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10391 PotentiallyDeadPHIs.insert(&PN);
10392 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
10393 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10394 }
10395
10396 // If this phi has a single use, and if that use just computes a value for
10397 // the next iteration of a loop, delete the phi. This occurs with unused
10398 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10399 // common case here is good because the only other things that catch this
10400 // are induction variable analysis (sometimes) and ADCE, which is only run
10401 // late.
10402 if (PHIUser->hasOneUse() &&
10403 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10404 PHIUser->use_back() == &PN) {
10405 return ReplaceInstUsesWith(PN, UndefValue::get(PN.getType()));
10406 }
10407 }
10408
Chris Lattner27b695d2007-11-06 21:52:06 +000010409 // We sometimes end up with phi cycles that non-obviously end up being the
10410 // same value, for example:
10411 // z = some value; x = phi (y, z); y = phi (x, z)
10412 // where the phi nodes don't necessarily need to be in the same block. Do a
10413 // quick check to see if the PHI node only contains a single non-phi value, if
10414 // so, scan to see if the phi cycle is actually equal to that value.
10415 {
10416 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10417 // Scan for the first non-phi operand.
10418 while (InValNo != NumOperandVals &&
10419 isa<PHINode>(PN.getIncomingValue(InValNo)))
10420 ++InValNo;
10421
10422 if (InValNo != NumOperandVals) {
10423 Value *NonPhiInVal = PN.getOperand(InValNo);
10424
10425 // Scan the rest of the operands to see if there are any conflicts, if so
10426 // there is no need to recursively scan other phis.
10427 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
10428 Value *OpVal = PN.getIncomingValue(InValNo);
10429 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
10430 break;
10431 }
10432
10433 // If we scanned over all operands, then we have one unique value plus
10434 // phi values. Scan PHI nodes to see if they all merge in each other or
10435 // the value.
10436 if (InValNo == NumOperandVals) {
10437 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
10438 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
10439 return ReplaceInstUsesWith(PN, NonPhiInVal);
10440 }
10441 }
10442 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010443 return 0;
10444}
10445
10446static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
10447 Instruction *InsertPoint,
10448 InstCombiner *IC) {
10449 unsigned PtrSize = DTy->getPrimitiveSizeInBits();
10450 unsigned VTySize = V->getType()->getPrimitiveSizeInBits();
10451 // We must cast correctly to the pointer type. Ensure that we
10452 // sign extend the integer value if it is smaller as this is
10453 // used for address computation.
10454 Instruction::CastOps opcode =
10455 (VTySize < PtrSize ? Instruction::SExt :
10456 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
10457 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
10458}
10459
10460
10461Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
10462 Value *PtrOp = GEP.getOperand(0);
10463 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
10464 // If so, eliminate the noop.
10465 if (GEP.getNumOperands() == 1)
10466 return ReplaceInstUsesWith(GEP, PtrOp);
10467
10468 if (isa<UndefValue>(GEP.getOperand(0)))
10469 return ReplaceInstUsesWith(GEP, UndefValue::get(GEP.getType()));
10470
10471 bool HasZeroPointerIndex = false;
10472 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
10473 HasZeroPointerIndex = C->isNullValue();
10474
10475 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
10476 return ReplaceInstUsesWith(GEP, PtrOp);
10477
10478 // Eliminate unneeded casts for indices.
10479 bool MadeChange = false;
10480
10481 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif17396002008-06-12 21:37:33 +000010482 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
10483 i != e; ++i, ++GTI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010484 if (isa<SequentialType>(*GTI)) {
Gabor Greif17396002008-06-12 21:37:33 +000010485 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010486 if (CI->getOpcode() == Instruction::ZExt ||
10487 CI->getOpcode() == Instruction::SExt) {
10488 const Type *SrcTy = CI->getOperand(0)->getType();
10489 // We can eliminate a cast from i32 to i64 iff the target
10490 // is a 32-bit pointer target.
10491 if (SrcTy->getPrimitiveSizeInBits() >= TD->getPointerSizeInBits()) {
10492 MadeChange = true;
Gabor Greif17396002008-06-12 21:37:33 +000010493 *i = CI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010494 }
10495 }
10496 }
10497 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman5d639ed2008-09-11 23:06:38 +000010498 // to what we need. If narrower, sign-extend it to what we need.
10499 // If the incoming value needs a cast instruction,
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010500 // insert it. This explicit cast can make subsequent optimizations more
10501 // obvious.
Gabor Greif17396002008-06-12 21:37:33 +000010502 Value *Op = *i;
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010503 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010504 if (Constant *C = dyn_cast<Constant>(Op)) {
Gabor Greif17396002008-06-12 21:37:33 +000010505 *i = ConstantExpr::getTrunc(C, TD->getIntPtrType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010506 MadeChange = true;
10507 } else {
10508 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
10509 GEP);
Gabor Greif17396002008-06-12 21:37:33 +000010510 *i = Op;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010511 MadeChange = true;
10512 }
Dan Gohman5d639ed2008-09-11 23:06:38 +000010513 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
10514 if (Constant *C = dyn_cast<Constant>(Op)) {
10515 *i = ConstantExpr::getSExt(C, TD->getIntPtrType());
10516 MadeChange = true;
10517 } else {
10518 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
10519 GEP);
10520 *i = Op;
10521 MadeChange = true;
10522 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010523 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010524 }
10525 }
10526 if (MadeChange) return &GEP;
10527
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010528 // Combine Indices - If the source pointer to this getelementptr instruction
10529 // is a getelementptr instruction, combine the indices of the two
10530 // getelementptr instructions into a single instruction.
10531 //
10532 SmallVector<Value*, 8> SrcGEPOperands;
10533 if (User *Src = dyn_castGetElementPtr(PtrOp))
10534 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
10535
10536 if (!SrcGEPOperands.empty()) {
10537 // Note that if our source is a gep chain itself that we wait for that
10538 // chain to be resolved before we perform this transformation. This
10539 // avoids us creating a TON of code in some cases.
10540 //
10541 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
10542 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
10543 return 0; // Wait until our source is folded to completion.
10544
10545 SmallVector<Value*, 8> Indices;
10546
10547 // Find out whether the last index in the source GEP is a sequential idx.
10548 bool EndsWithSequential = false;
10549 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
10550 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
10551 EndsWithSequential = !isa<StructType>(*I);
10552
10553 // Can we combine the two pointer arithmetics offsets?
10554 if (EndsWithSequential) {
10555 // Replace: gep (gep %P, long B), long A, ...
10556 // With: T = long A+B; gep %P, T, ...
10557 //
10558 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
10559 if (SO1 == Constant::getNullValue(SO1->getType())) {
10560 Sum = GO1;
10561 } else if (GO1 == Constant::getNullValue(GO1->getType())) {
10562 Sum = SO1;
10563 } else {
10564 // If they aren't the same type, convert both to an integer of the
10565 // target's pointer size.
10566 if (SO1->getType() != GO1->getType()) {
10567 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
10568 SO1 = ConstantExpr::getIntegerCast(SO1C, GO1->getType(), true);
10569 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
10570 GO1 = ConstantExpr::getIntegerCast(GO1C, SO1->getType(), true);
10571 } else {
Duncan Sandsf99fdc62007-11-01 20:53:16 +000010572 unsigned PS = TD->getPointerSizeInBits();
10573 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010574 // Convert GO1 to SO1's type.
10575 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
10576
Duncan Sandsf99fdc62007-11-01 20:53:16 +000010577 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010578 // Convert SO1 to GO1's type.
10579 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
10580 } else {
10581 const Type *PT = TD->getIntPtrType();
10582 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
10583 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
10584 }
10585 }
10586 }
10587 if (isa<Constant>(SO1) && isa<Constant>(GO1))
10588 Sum = ConstantExpr::getAdd(cast<Constant>(SO1), cast<Constant>(GO1));
10589 else {
Gabor Greifa645dd32008-05-16 19:29:10 +000010590 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010591 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
10592 }
10593 }
10594
10595 // Recycle the GEP we already have if possible.
10596 if (SrcGEPOperands.size() == 2) {
10597 GEP.setOperand(0, SrcGEPOperands[0]);
10598 GEP.setOperand(1, Sum);
10599 return &GEP;
10600 } else {
10601 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10602 SrcGEPOperands.end()-1);
10603 Indices.push_back(Sum);
10604 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
10605 }
10606 } else if (isa<Constant>(*GEP.idx_begin()) &&
10607 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
10608 SrcGEPOperands.size() != 1) {
10609 // Otherwise we can do the fold if the first index of the GEP is a zero
10610 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
10611 SrcGEPOperands.end());
10612 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
10613 }
10614
10615 if (!Indices.empty())
Gabor Greifd6da1d02008-04-06 20:25:17 +000010616 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
10617 Indices.end(), GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010618
10619 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
10620 // GEP of global variable. If all of the indices for this GEP are
10621 // constants, we can promote this to a constexpr instead of an instruction.
10622
10623 // Scan for nonconstants...
10624 SmallVector<Constant*, 8> Indices;
10625 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
10626 for (; I != E && isa<Constant>(*I); ++I)
10627 Indices.push_back(cast<Constant>(*I));
10628
10629 if (I == E) { // If they are all constants...
10630 Constant *CE = ConstantExpr::getGetElementPtr(GV,
10631 &Indices[0],Indices.size());
10632
10633 // Replace all uses of the GEP with the new constexpr...
10634 return ReplaceInstUsesWith(GEP, CE);
10635 }
10636 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
10637 if (!isa<PointerType>(X->getType())) {
10638 // Not interesting. Source pointer must be a cast from pointer.
10639 } else if (HasZeroPointerIndex) {
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010640 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
10641 // into : GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010642 //
10643 // This occurs when the program declares an array extern like "int X[];"
10644 //
10645 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
10646 const PointerType *XTy = cast<PointerType>(X->getType());
10647 if (const ArrayType *XATy =
10648 dyn_cast<ArrayType>(XTy->getElementType()))
10649 if (const ArrayType *CATy =
10650 dyn_cast<ArrayType>(CPTy->getElementType()))
10651 if (CATy->getElementType() == XATy->getElementType()) {
10652 // At this point, we know that the cast source type is a pointer
10653 // to an array of the same type as the destination pointer
10654 // array. Because the array type is never stepped over (there
10655 // is a leading zero) we can fold the cast into this GEP.
10656 GEP.setOperand(0, X);
10657 return &GEP;
10658 }
10659 } else if (GEP.getNumOperands() == 2) {
10660 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010661 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
10662 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010663 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
10664 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
10665 if (isa<ArrayType>(SrcElTy) &&
Duncan Sandsd68f13b2009-01-12 20:38:59 +000010666 TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
10667 TD->getTypePaddedSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +000010668 Value *Idx[2];
10669 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10670 Idx[1] = GEP.getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010671 Value *V = InsertNewInstBefore(
Gabor Greifd6da1d02008-04-06 20:25:17 +000010672 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010673 // V and GEP are both pointer types --> BitCast
10674 return new BitCastInst(V, GEP.getType());
10675 }
10676
10677 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010678 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010679 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010680 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010681
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010682 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010683 uint64_t ArrayEltSize =
Duncan Sandsd68f13b2009-01-12 20:38:59 +000010684 TD->getTypePaddedSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010685
10686 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
10687 // allow either a mul, shift, or constant here.
10688 Value *NewIdx = 0;
10689 ConstantInt *Scale = 0;
10690 if (ArrayEltSize == 1) {
10691 NewIdx = GEP.getOperand(1);
10692 Scale = ConstantInt::get(NewIdx->getType(), 1);
10693 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
10694 NewIdx = ConstantInt::get(CI->getType(), 1);
10695 Scale = CI;
10696 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
10697 if (Inst->getOpcode() == Instruction::Shl &&
10698 isa<ConstantInt>(Inst->getOperand(1))) {
10699 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
10700 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
10701 Scale = ConstantInt::get(Inst->getType(), 1ULL << ShAmtVal);
10702 NewIdx = Inst->getOperand(0);
10703 } else if (Inst->getOpcode() == Instruction::Mul &&
10704 isa<ConstantInt>(Inst->getOperand(1))) {
10705 Scale = cast<ConstantInt>(Inst->getOperand(1));
10706 NewIdx = Inst->getOperand(0);
10707 }
10708 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010709
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010710 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010711 // out, perform the transformation. Note, we don't know whether Scale is
10712 // signed or not. We'll use unsigned version of division/modulo
10713 // operation after making sure Scale doesn't have the sign bit set.
10714 if (Scale && Scale->getSExtValue() >= 0LL &&
10715 Scale->getZExtValue() % ArrayEltSize == 0) {
10716 Scale = ConstantInt::get(Scale->getType(),
10717 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010718 if (Scale->getZExtValue() != 1) {
10719 Constant *C = ConstantExpr::getIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000010720 false /*ZExt*/);
Gabor Greifa645dd32008-05-16 19:29:10 +000010721 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010722 NewIdx = InsertNewInstBefore(Sc, GEP);
10723 }
10724
10725 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +000010726 Value *Idx[2];
10727 Idx[0] = Constant::getNullValue(Type::Int32Ty);
10728 Idx[1] = NewIdx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010729 Instruction *NewGEP =
Gabor Greifd6da1d02008-04-06 20:25:17 +000010730 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010731 NewGEP = InsertNewInstBefore(NewGEP, GEP);
10732 // The NewGEP must be pointer typed, so must the old one -> BitCast
10733 return new BitCastInst(NewGEP, GEP.getType());
10734 }
10735 }
10736 }
10737 }
Chris Lattner111ea772009-01-09 04:53:57 +000010738
Chris Lattner94ccd5f2009-01-09 05:44:56 +000010739 /// See if we can simplify:
10740 /// X = bitcast A to B*
10741 /// Y = gep X, <...constant indices...>
10742 /// into a gep of the original struct. This is important for SROA and alias
10743 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner111ea772009-01-09 04:53:57 +000010744 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +000010745 if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
10746 // Determine how much the GEP moves the pointer. We are guaranteed to get
10747 // a constant back from EmitGEPOffset.
10748 ConstantInt *OffsetV = cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
10749 int64_t Offset = OffsetV->getSExtValue();
10750
10751 // If this GEP instruction doesn't move the pointer, just replace the GEP
10752 // with a bitcast of the real input to the dest type.
10753 if (Offset == 0) {
10754 // If the bitcast is of an allocation, and the allocation will be
10755 // converted to match the type of the cast, don't touch this.
10756 if (isa<AllocationInst>(BCI->getOperand(0))) {
10757 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
10758 if (Instruction *I = visitBitCast(*BCI)) {
10759 if (I != BCI) {
10760 I->takeName(BCI);
10761 BCI->getParent()->getInstList().insert(BCI, I);
10762 ReplaceInstUsesWith(*BCI, I);
10763 }
10764 return &GEP;
Chris Lattner111ea772009-01-09 04:53:57 +000010765 }
Chris Lattner111ea772009-01-09 04:53:57 +000010766 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000010767 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner111ea772009-01-09 04:53:57 +000010768 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000010769
10770 // Otherwise, if the offset is non-zero, we need to find out if there is a
10771 // field at Offset in 'A's type. If so, we can pull the cast through the
10772 // GEP.
10773 SmallVector<Value*, 8> NewIndices;
10774 const Type *InTy =
10775 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
10776 if (FindElementAtOffset(InTy, Offset, NewIndices, TD)) {
10777 Instruction *NGEP =
10778 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
10779 NewIndices.end());
10780 if (NGEP->getType() == GEP.getType()) return NGEP;
10781 InsertNewInstBefore(NGEP, GEP);
10782 NGEP->takeName(&GEP);
10783 return new BitCastInst(NGEP, GEP.getType());
10784 }
Chris Lattner111ea772009-01-09 04:53:57 +000010785 }
10786 }
10787
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010788 return 0;
10789}
10790
10791Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
10792 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010793 if (AI.isArrayAllocation()) { // Check C != 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010794 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
10795 const Type *NewTy =
10796 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
10797 AllocationInst *New = 0;
10798
10799 // Create and insert the replacement instruction...
10800 if (isa<MallocInst>(AI))
10801 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
10802 else {
10803 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
10804 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
10805 }
10806
10807 InsertNewInstBefore(New, AI);
10808
10809 // Scan to the end of the allocation instructions, to skip over a block of
10810 // allocas if possible...
10811 //
10812 BasicBlock::iterator It = New;
10813 while (isa<AllocationInst>(*It)) ++It;
10814
10815 // Now that I is pointing to the first non-allocation-inst in the block,
10816 // insert our getelementptr instruction...
10817 //
10818 Value *NullIdx = Constant::getNullValue(Type::Int32Ty);
David Greene393be882007-09-04 15:46:09 +000010819 Value *Idx[2];
10820 Idx[0] = NullIdx;
10821 Idx[1] = NullIdx;
Gabor Greifd6da1d02008-04-06 20:25:17 +000010822 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
10823 New->getName()+".sub", It);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010824
10825 // Now make everything use the getelementptr instead of the original
10826 // allocation.
10827 return ReplaceInstUsesWith(AI, V);
10828 } else if (isa<UndefValue>(AI.getArraySize())) {
10829 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10830 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010831 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010832
Dan Gohman28e78f02009-01-13 20:18:38 +000010833 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
10834 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
10835 // Note that we only do this for alloca's, because malloc should allocate and
10836 // return a unique pointer, even for a zero byte allocation.
10837 if (TD->getTypePaddedSize(AI.getAllocatedType()) == 0)
10838 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
10839
10840 // If the alignment is 0 (unspecified), assign it the preferred alignment.
10841 if (AI.getAlignment() == 0)
10842 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
10843 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010844
10845 return 0;
10846}
10847
10848Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
10849 Value *Op = FI.getOperand(0);
10850
10851 // free undef -> unreachable.
10852 if (isa<UndefValue>(Op)) {
10853 // Insert a new store to null because we cannot modify the CFG here.
10854 new StoreInst(ConstantInt::getTrue(),
Christopher Lambbb2f2222007-12-17 01:12:55 +000010855 UndefValue::get(PointerType::getUnqual(Type::Int1Ty)), &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010856 return EraseInstFromFunction(FI);
10857 }
10858
10859 // If we have 'free null' delete the instruction. This can happen in stl code
10860 // when lots of inlining happens.
10861 if (isa<ConstantPointerNull>(Op))
10862 return EraseInstFromFunction(FI);
10863
10864 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
10865 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
10866 FI.setOperand(0, CI->getOperand(0));
10867 return &FI;
10868 }
10869
10870 // Change free (gep X, 0,0,0,0) into free(X)
10871 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
10872 if (GEPI->hasAllZeroIndices()) {
10873 AddToWorkList(GEPI);
10874 FI.setOperand(0, GEPI->getOperand(0));
10875 return &FI;
10876 }
10877 }
10878
10879 // Change free(malloc) into nothing, if the malloc has a single use.
10880 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
10881 if (MI->hasOneUse()) {
10882 EraseInstFromFunction(FI);
10883 return EraseInstFromFunction(*MI);
10884 }
10885
10886 return 0;
10887}
10888
10889
10890/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patela0f8ea82007-10-18 19:52:32 +000010891static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling44a36ea2008-02-26 10:53:30 +000010892 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010893 User *CI = cast<User>(LI.getOperand(0));
10894 Value *CastOp = CI->getOperand(0);
10895
Devang Patela0f8ea82007-10-18 19:52:32 +000010896 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
10897 // Instead of loading constant c string, use corresponding integer value
10898 // directly if string length is small enough.
Evan Cheng833501d2008-06-30 07:31:25 +000010899 std::string Str;
10900 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
Devang Patela0f8ea82007-10-18 19:52:32 +000010901 unsigned len = Str.length();
10902 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
10903 unsigned numBits = Ty->getPrimitiveSizeInBits();
10904 // Replace LI with immediate integer store.
10905 if ((numBits >> 3) == len + 1) {
Bill Wendling44a36ea2008-02-26 10:53:30 +000010906 APInt StrVal(numBits, 0);
10907 APInt SingleChar(numBits, 0);
10908 if (TD->isLittleEndian()) {
10909 for (signed i = len-1; i >= 0; i--) {
10910 SingleChar = (uint64_t) Str[i];
10911 StrVal = (StrVal << 8) | SingleChar;
10912 }
10913 } else {
10914 for (unsigned i = 0; i < len; i++) {
10915 SingleChar = (uint64_t) Str[i];
10916 StrVal = (StrVal << 8) | SingleChar;
10917 }
10918 // Append NULL at the end.
10919 SingleChar = 0;
10920 StrVal = (StrVal << 8) | SingleChar;
10921 }
10922 Value *NL = ConstantInt::get(StrVal);
10923 return IC.ReplaceInstUsesWith(LI, NL);
Devang Patela0f8ea82007-10-18 19:52:32 +000010924 }
10925 }
10926 }
10927
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010928 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
10929 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
10930 const Type *SrcPTy = SrcTy->getElementType();
10931
10932 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
10933 isa<VectorType>(DestPTy)) {
10934 // If the source is an array, the code below will not succeed. Check to
10935 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
10936 // constants.
10937 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
10938 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
10939 if (ASrcTy->getNumElements() != 0) {
10940 Value *Idxs[2];
10941 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
10942 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
10943 SrcTy = cast<PointerType>(CastOp->getType());
10944 SrcPTy = SrcTy->getElementType();
10945 }
10946
10947 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
10948 isa<VectorType>(SrcPTy)) &&
10949 // Do not allow turning this into a load of an integer, which is then
10950 // casted to a pointer, this pessimizes pointer analysis a lot.
10951 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
10952 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
10953 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
10954
10955 // Okay, we are casting from one integer or pointer type to another of
10956 // the same size. Instead of casting the pointer before the load, cast
10957 // the result of the loaded value.
10958 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
10959 CI->getName(),
10960 LI.isVolatile()),LI);
10961 // Now cast the result of the load.
10962 return new BitCastInst(NewLoad, LI.getType());
10963 }
10964 }
10965 }
10966 return 0;
10967}
10968
10969/// isSafeToLoadUnconditionally - Return true if we know that executing a load
10970/// from this value cannot trap. If it is not obviously safe to load from the
10971/// specified pointer, we do a quick local scan of the basic block containing
10972/// ScanFrom, to determine if the address is already accessed.
10973static bool isSafeToLoadUnconditionally(Value *V, Instruction *ScanFrom) {
Duncan Sands9b27dbe2007-09-19 10:10:31 +000010974 // If it is an alloca it is always safe to load from.
10975 if (isa<AllocaInst>(V)) return true;
10976
Duncan Sandse40a94a2007-09-19 10:25:38 +000010977 // If it is a global variable it is mostly safe to load from.
Duncan Sands9b27dbe2007-09-19 10:10:31 +000010978 if (const GlobalValue *GV = dyn_cast<GlobalVariable>(V))
Duncan Sandse40a94a2007-09-19 10:25:38 +000010979 // Don't try to evaluate aliases. External weak GV can be null.
Duncan Sands9b27dbe2007-09-19 10:10:31 +000010980 return !isa<GlobalAlias>(GV) && !GV->hasExternalWeakLinkage();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010981
10982 // Otherwise, be a little bit agressive by scanning the local block where we
10983 // want to check to see if the pointer is already being loaded or stored
10984 // from/to. If so, the previous load or store would have already trapped,
10985 // so there is no harm doing an extra load (also, CSE will later eliminate
10986 // the load entirely).
10987 BasicBlock::iterator BBI = ScanFrom, E = ScanFrom->getParent()->begin();
10988
10989 while (BBI != E) {
10990 --BBI;
10991
Chris Lattner476983a2008-06-20 05:12:56 +000010992 // If we see a free or a call (which might do a free) the pointer could be
10993 // marked invalid.
10994 if (isa<FreeInst>(BBI) || isa<CallInst>(BBI))
10995 return false;
10996
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010997 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
10998 if (LI->getOperand(0) == V) return true;
Chris Lattner476983a2008-06-20 05:12:56 +000010999 } else if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011000 if (SI->getOperand(1) == V) return true;
Chris Lattner476983a2008-06-20 05:12:56 +000011001 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011002
11003 }
11004 return false;
11005}
11006
11007Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11008 Value *Op = LI.getOperand(0);
11009
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011010 // Attempt to improve the alignment.
Dan Gohman2d648bb2008-04-10 18:43:06 +000011011 unsigned KnownAlign = GetOrEnforceKnownAlignment(Op);
11012 if (KnownAlign >
11013 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11014 LI.getAlignment()))
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011015 LI.setAlignment(KnownAlign);
11016
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011017 // load (cast X) --> cast (load X) iff safe
11018 if (isa<CastInst>(Op))
Devang Patela0f8ea82007-10-18 19:52:32 +000011019 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011020 return Res;
11021
11022 // None of the following transforms are legal for volatile loads.
11023 if (LI.isVolatile()) return 0;
11024
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000011025 // Do really simple store-to-load forwarding and load CSE, to catch cases
11026 // where there are several consequtive memory accesses to the same location,
11027 // separated by a few arithmetic operations.
11028 BasicBlock::iterator BBI = &LI;
Chris Lattner6fd8c802008-11-27 08:56:30 +000011029 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11030 return ReplaceInstUsesWith(LI, AvailableVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011031
Christopher Lamb2c175392007-12-29 07:56:53 +000011032 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11033 const Value *GEPI0 = GEPI->getOperand(0);
11034 // TODO: Consider a target hook for valid address spaces for this xform.
11035 if (isa<ConstantPointerNull>(GEPI0) &&
11036 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011037 // Insert a new store to null instruction before the load to indicate
11038 // that this code is not reachable. We do this instead of inserting
11039 // an unreachable instruction directly because we cannot modify the
11040 // CFG.
11041 new StoreInst(UndefValue::get(LI.getType()),
11042 Constant::getNullValue(Op->getType()), &LI);
11043 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11044 }
Christopher Lamb2c175392007-12-29 07:56:53 +000011045 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011046
11047 if (Constant *C = dyn_cast<Constant>(Op)) {
11048 // load null/undef -> undef
Christopher Lamb2c175392007-12-29 07:56:53 +000011049 // TODO: Consider a target hook for valid address spaces for this xform.
11050 if (isa<UndefValue>(C) || (C->isNullValue() &&
11051 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011052 // Insert a new store to null instruction before the load to indicate that
11053 // this code is not reachable. We do this instead of inserting an
11054 // unreachable instruction directly because we cannot modify the CFG.
11055 new StoreInst(UndefValue::get(LI.getType()),
11056 Constant::getNullValue(Op->getType()), &LI);
11057 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11058 }
11059
11060 // Instcombine load (constant global) into the value loaded.
11061 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
11062 if (GV->isConstant() && !GV->isDeclaration())
11063 return ReplaceInstUsesWith(LI, GV->getInitializer());
11064
11065 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011066 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011067 if (CE->getOpcode() == Instruction::GetElementPtr) {
11068 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
11069 if (GV->isConstant() && !GV->isDeclaration())
11070 if (Constant *V =
11071 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE))
11072 return ReplaceInstUsesWith(LI, V);
11073 if (CE->getOperand(0)->isNullValue()) {
11074 // Insert a new store to null instruction before the load to indicate
11075 // that this code is not reachable. We do this instead of inserting
11076 // an unreachable instruction directly because we cannot modify the
11077 // CFG.
11078 new StoreInst(UndefValue::get(LI.getType()),
11079 Constant::getNullValue(Op->getType()), &LI);
11080 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11081 }
11082
11083 } else if (CE->isCast()) {
Devang Patela0f8ea82007-10-18 19:52:32 +000011084 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011085 return Res;
11086 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011087 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011088 }
Chris Lattner0270a112007-08-11 18:48:48 +000011089
11090 // If this load comes from anywhere in a constant global, and if the global
11091 // is all undef or zero, we know what it loads.
Duncan Sands52fb8732008-10-01 15:25:41 +000011092 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Chris Lattner0270a112007-08-11 18:48:48 +000011093 if (GV->isConstant() && GV->hasInitializer()) {
11094 if (GV->getInitializer()->isNullValue())
11095 return ReplaceInstUsesWith(LI, Constant::getNullValue(LI.getType()));
11096 else if (isa<UndefValue>(GV->getInitializer()))
11097 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
11098 }
11099 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011100
11101 if (Op->hasOneUse()) {
11102 // Change select and PHI nodes to select values instead of addresses: this
11103 // helps alias analysis out a lot, allows many others simplifications, and
11104 // exposes redundancy in the code.
11105 //
11106 // Note that we cannot do the transformation unless we know that the
11107 // introduced loads cannot trap! Something like this is valid as long as
11108 // the condition is always false: load (select bool %C, int* null, int* %G),
11109 // but it would not be valid if we transformed it to load from null
11110 // unconditionally.
11111 //
11112 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11113 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
11114 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11115 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11116 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11117 SI->getOperand(1)->getName()+".val"), LI);
11118 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11119 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greifd6da1d02008-04-06 20:25:17 +000011120 return SelectInst::Create(SI->getCondition(), V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011121 }
11122
11123 // load (select (cond, null, P)) -> load P
11124 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11125 if (C->isNullValue()) {
11126 LI.setOperand(0, SI->getOperand(2));
11127 return &LI;
11128 }
11129
11130 // load (select (cond, P, null)) -> load P
11131 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11132 if (C->isNullValue()) {
11133 LI.setOperand(0, SI->getOperand(1));
11134 return &LI;
11135 }
11136 }
11137 }
11138 return 0;
11139}
11140
11141/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
11142/// when possible.
11143static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11144 User *CI = cast<User>(SI.getOperand(1));
11145 Value *CastOp = CI->getOperand(0);
11146
11147 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
11148 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
11149 const Type *SrcPTy = SrcTy->getElementType();
11150
11151 if (DestPTy->isInteger() || isa<PointerType>(DestPTy)) {
11152 // If the source is an array, the code below will not succeed. Check to
11153 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11154 // constants.
11155 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11156 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11157 if (ASrcTy->getNumElements() != 0) {
11158 Value* Idxs[2];
11159 Idxs[0] = Idxs[1] = Constant::getNullValue(Type::Int32Ty);
11160 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs, 2);
11161 SrcTy = cast<PointerType>(CastOp->getType());
11162 SrcPTy = SrcTy->getElementType();
11163 }
11164
11165 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy)) &&
11166 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11167 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
11168
11169 // Okay, we are casting from one integer or pointer type to another of
11170 // the same size. Instead of casting the pointer before
11171 // the store, cast the value to be stored.
11172 Value *NewCast;
11173 Value *SIOp0 = SI.getOperand(0);
11174 Instruction::CastOps opcode = Instruction::BitCast;
11175 const Type* CastSrcTy = SIOp0->getType();
11176 const Type* CastDstTy = SrcPTy;
11177 if (isa<PointerType>(CastDstTy)) {
11178 if (CastSrcTy->isInteger())
11179 opcode = Instruction::IntToPtr;
11180 } else if (isa<IntegerType>(CastDstTy)) {
11181 if (isa<PointerType>(SIOp0->getType()))
11182 opcode = Instruction::PtrToInt;
11183 }
11184 if (Constant *C = dyn_cast<Constant>(SIOp0))
11185 NewCast = ConstantExpr::getCast(opcode, C, CastDstTy);
11186 else
11187 NewCast = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +000011188 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011189 SI);
11190 return new StoreInst(NewCast, CastOp);
11191 }
11192 }
11193 }
11194 return 0;
11195}
11196
Chris Lattner6fd8c802008-11-27 08:56:30 +000011197/// equivalentAddressValues - Test if A and B will obviously have the same
11198/// value. This includes recognizing that %t0 and %t1 will have the same
11199/// value in code like this:
11200/// %t0 = getelementptr @a, 0, 3
11201/// store i32 0, i32* %t0
11202/// %t1 = getelementptr @a, 0, 3
11203/// %t2 = load i32* %t1
11204///
11205static bool equivalentAddressValues(Value *A, Value *B) {
11206 // Test if the values are trivially equivalent.
11207 if (A == B) return true;
11208
11209 // Test if the values come form identical arithmetic instructions.
11210 if (isa<BinaryOperator>(A) ||
11211 isa<CastInst>(A) ||
11212 isa<PHINode>(A) ||
11213 isa<GetElementPtrInst>(A))
11214 if (Instruction *BI = dyn_cast<Instruction>(B))
11215 if (cast<Instruction>(A)->isIdenticalTo(BI))
11216 return true;
11217
11218 // Otherwise they may not be equivalent.
11219 return false;
11220}
11221
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011222Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11223 Value *Val = SI.getOperand(0);
11224 Value *Ptr = SI.getOperand(1);
11225
11226 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
11227 EraseInstFromFunction(SI);
11228 ++NumCombined;
11229 return 0;
11230 }
11231
11232 // If the RHS is an alloca with a single use, zapify the store, making the
11233 // alloca dead.
Chris Lattnera02bacc2008-04-29 04:58:38 +000011234 if (Ptr->hasOneUse() && !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011235 if (isa<AllocaInst>(Ptr)) {
11236 EraseInstFromFunction(SI);
11237 ++NumCombined;
11238 return 0;
11239 }
11240
11241 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
11242 if (isa<AllocaInst>(GEP->getOperand(0)) &&
11243 GEP->getOperand(0)->hasOneUse()) {
11244 EraseInstFromFunction(SI);
11245 ++NumCombined;
11246 return 0;
11247 }
11248 }
11249
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011250 // Attempt to improve the alignment.
Dan Gohman2d648bb2008-04-10 18:43:06 +000011251 unsigned KnownAlign = GetOrEnforceKnownAlignment(Ptr);
11252 if (KnownAlign >
11253 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11254 SI.getAlignment()))
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011255 SI.setAlignment(KnownAlign);
11256
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011257 // Do really simple DSE, to catch cases where there are several consequtive
11258 // stores to the same location, separated by a few arithmetic operations. This
11259 // situation often occurs with bitfield accesses.
11260 BasicBlock::iterator BBI = &SI;
11261 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11262 --ScanInsts) {
11263 --BBI;
11264
11265 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11266 // Prev store isn't volatile, and stores to the same location?
Chris Lattner6fd8c802008-11-27 08:56:30 +000011267 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11268 SI.getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011269 ++NumDeadStore;
11270 ++BBI;
11271 EraseInstFromFunction(*PrevSI);
11272 continue;
11273 }
11274 break;
11275 }
11276
11277 // If this is a load, we have to stop. However, if the loaded value is from
11278 // the pointer we're loading and is producing the pointer we're storing,
11279 // then *this* store is dead (X = load P; store X -> P).
11280 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000011281 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11282 !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011283 EraseInstFromFunction(SI);
11284 ++NumCombined;
11285 return 0;
11286 }
11287 // Otherwise, this is a load from some other location. Stores before it
11288 // may not be dead.
11289 break;
11290 }
11291
11292 // Don't skip over loads or things that can modify memory.
Chris Lattner84504282008-05-08 17:20:30 +000011293 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011294 break;
11295 }
11296
11297
11298 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
11299
11300 // store X, null -> turns into 'unreachable' in SimplifyCFG
11301 if (isa<ConstantPointerNull>(Ptr)) {
11302 if (!isa<UndefValue>(Val)) {
11303 SI.setOperand(0, UndefValue::get(Val->getType()));
11304 if (Instruction *U = dyn_cast<Instruction>(Val))
11305 AddToWorkList(U); // Dropped a use.
11306 ++NumCombined;
11307 }
11308 return 0; // Do not modify these!
11309 }
11310
11311 // store undef, Ptr -> noop
11312 if (isa<UndefValue>(Val)) {
11313 EraseInstFromFunction(SI);
11314 ++NumCombined;
11315 return 0;
11316 }
11317
11318 // If the pointer destination is a cast, see if we can fold the cast into the
11319 // source instead.
11320 if (isa<CastInst>(Ptr))
11321 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11322 return Res;
11323 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11324 if (CE->isCast())
11325 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11326 return Res;
11327
11328
11329 // If this store is the last instruction in the basic block, and if the block
11330 // ends with an unconditional branch, try to move it to the successor block.
11331 BBI = &SI; ++BBI;
11332 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11333 if (BI->isUnconditional())
11334 if (SimplifyStoreAtEndOfBlock(SI))
11335 return 0; // xform done!
11336
11337 return 0;
11338}
11339
11340/// SimplifyStoreAtEndOfBlock - Turn things like:
11341/// if () { *P = v1; } else { *P = v2 }
11342/// into a phi node with a store in the successor.
11343///
11344/// Simplify things like:
11345/// *P = v1; if () { *P = v2; }
11346/// into a phi node with a store in the successor.
11347///
11348bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
11349 BasicBlock *StoreBB = SI.getParent();
11350
11351 // Check to see if the successor block has exactly two incoming edges. If
11352 // so, see if the other predecessor contains a store to the same location.
11353 // if so, insert a PHI node (if needed) and move the stores down.
11354 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
11355
11356 // Determine whether Dest has exactly two predecessors and, if so, compute
11357 // the other predecessor.
11358 pred_iterator PI = pred_begin(DestBB);
11359 BasicBlock *OtherBB = 0;
11360 if (*PI != StoreBB)
11361 OtherBB = *PI;
11362 ++PI;
11363 if (PI == pred_end(DestBB))
11364 return false;
11365
11366 if (*PI != StoreBB) {
11367 if (OtherBB)
11368 return false;
11369 OtherBB = *PI;
11370 }
11371 if (++PI != pred_end(DestBB))
11372 return false;
Eli Friedmanab39f9a2008-06-13 21:17:49 +000011373
11374 // Bail out if all the relevant blocks aren't distinct (this can happen,
11375 // for example, if SI is in an infinite loop)
11376 if (StoreBB == DestBB || OtherBB == DestBB)
11377 return false;
11378
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011379 // Verify that the other block ends in a branch and is not otherwise empty.
11380 BasicBlock::iterator BBI = OtherBB->getTerminator();
11381 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
11382 if (!OtherBr || BBI == OtherBB->begin())
11383 return false;
11384
11385 // If the other block ends in an unconditional branch, check for the 'if then
11386 // else' case. there is an instruction before the branch.
11387 StoreInst *OtherStore = 0;
11388 if (OtherBr->isUnconditional()) {
11389 // If this isn't a store, or isn't a store to the same location, bail out.
11390 --BBI;
11391 OtherStore = dyn_cast<StoreInst>(BBI);
11392 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
11393 return false;
11394 } else {
11395 // Otherwise, the other block ended with a conditional branch. If one of the
11396 // destinations is StoreBB, then we have the if/then case.
11397 if (OtherBr->getSuccessor(0) != StoreBB &&
11398 OtherBr->getSuccessor(1) != StoreBB)
11399 return false;
11400
11401 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
11402 // if/then triangle. See if there is a store to the same ptr as SI that
11403 // lives in OtherBB.
11404 for (;; --BBI) {
11405 // Check to see if we find the matching store.
11406 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
11407 if (OtherStore->getOperand(1) != SI.getOperand(1))
11408 return false;
11409 break;
11410 }
Eli Friedman3a311d52008-06-13 22:02:12 +000011411 // If we find something that may be using or overwriting the stored
11412 // value, or if we run out of instructions, we can't do the xform.
11413 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011414 BBI == OtherBB->begin())
11415 return false;
11416 }
11417
11418 // In order to eliminate the store in OtherBr, we have to
Eli Friedman3a311d52008-06-13 22:02:12 +000011419 // make sure nothing reads or overwrites the stored value in
11420 // StoreBB.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011421 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
11422 // FIXME: This should really be AA driven.
Eli Friedman3a311d52008-06-13 22:02:12 +000011423 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011424 return false;
11425 }
11426 }
11427
11428 // Insert a PHI node now if we need it.
11429 Value *MergedVal = OtherStore->getOperand(0);
11430 if (MergedVal != SI.getOperand(0)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000011431 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011432 PN->reserveOperandSpace(2);
11433 PN->addIncoming(SI.getOperand(0), SI.getParent());
11434 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
11435 MergedVal = InsertNewInstBefore(PN, DestBB->front());
11436 }
11437
11438 // Advance to a place where it is safe to insert the new store and
11439 // insert it.
Dan Gohman514277c2008-05-23 21:05:58 +000011440 BBI = DestBB->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011441 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
11442 OtherStore->isVolatile()), *BBI);
11443
11444 // Nuke the old stores.
11445 EraseInstFromFunction(SI);
11446 EraseInstFromFunction(*OtherStore);
11447 ++NumCombined;
11448 return true;
11449}
11450
11451
11452Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
11453 // Change br (not X), label True, label False to: br X, label False, True
11454 Value *X = 0;
11455 BasicBlock *TrueDest;
11456 BasicBlock *FalseDest;
11457 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest)) &&
11458 !isa<Constant>(X)) {
11459 // Swap Destinations and condition...
11460 BI.setCondition(X);
11461 BI.setSuccessor(0, FalseDest);
11462 BI.setSuccessor(1, TrueDest);
11463 return &BI;
11464 }
11465
11466 // Cannonicalize fcmp_one -> fcmp_oeq
11467 FCmpInst::Predicate FPred; Value *Y;
11468 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
11469 TrueDest, FalseDest)))
11470 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
11471 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
11472 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
11473 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
11474 Instruction *NewSCC = new FCmpInst(NewPred, X, Y, "", I);
11475 NewSCC->takeName(I);
11476 // Swap Destinations and condition...
11477 BI.setCondition(NewSCC);
11478 BI.setSuccessor(0, FalseDest);
11479 BI.setSuccessor(1, TrueDest);
11480 RemoveFromWorkList(I);
11481 I->eraseFromParent();
11482 AddToWorkList(NewSCC);
11483 return &BI;
11484 }
11485
11486 // Cannonicalize icmp_ne -> icmp_eq
11487 ICmpInst::Predicate IPred;
11488 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
11489 TrueDest, FalseDest)))
11490 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
11491 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
11492 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
11493 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
11494 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
11495 Instruction *NewSCC = new ICmpInst(NewPred, X, Y, "", I);
11496 NewSCC->takeName(I);
11497 // Swap Destinations and condition...
11498 BI.setCondition(NewSCC);
11499 BI.setSuccessor(0, FalseDest);
11500 BI.setSuccessor(1, TrueDest);
11501 RemoveFromWorkList(I);
11502 I->eraseFromParent();;
11503 AddToWorkList(NewSCC);
11504 return &BI;
11505 }
11506
11507 return 0;
11508}
11509
11510Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
11511 Value *Cond = SI.getCondition();
11512 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
11513 if (I->getOpcode() == Instruction::Add)
11514 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
11515 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
11516 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
11517 SI.setOperand(i,ConstantExpr::getSub(cast<Constant>(SI.getOperand(i)),
11518 AddRHS));
11519 SI.setOperand(0, I->getOperand(0));
11520 AddToWorkList(I);
11521 return &SI;
11522 }
11523 }
11524 return 0;
11525}
11526
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000011527Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000011528 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000011529
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000011530 if (!EV.hasIndices())
11531 return ReplaceInstUsesWith(EV, Agg);
11532
11533 if (Constant *C = dyn_cast<Constant>(Agg)) {
11534 if (isa<UndefValue>(C))
11535 return ReplaceInstUsesWith(EV, UndefValue::get(EV.getType()));
11536
11537 if (isa<ConstantAggregateZero>(C))
11538 return ReplaceInstUsesWith(EV, Constant::getNullValue(EV.getType()));
11539
11540 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
11541 // Extract the element indexed by the first index out of the constant
11542 Value *V = C->getOperand(*EV.idx_begin());
11543 if (EV.getNumIndices() > 1)
11544 // Extract the remaining indices out of the constant indexed by the
11545 // first index
11546 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
11547 else
11548 return ReplaceInstUsesWith(EV, V);
11549 }
11550 return 0; // Can't handle other constants
11551 }
11552 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
11553 // We're extracting from an insertvalue instruction, compare the indices
11554 const unsigned *exti, *exte, *insi, *inse;
11555 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
11556 exte = EV.idx_end(), inse = IV->idx_end();
11557 exti != exte && insi != inse;
11558 ++exti, ++insi) {
11559 if (*insi != *exti)
11560 // The insert and extract both reference distinctly different elements.
11561 // This means the extract is not influenced by the insert, and we can
11562 // replace the aggregate operand of the extract with the aggregate
11563 // operand of the insert. i.e., replace
11564 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11565 // %E = extractvalue { i32, { i32 } } %I, 0
11566 // with
11567 // %E = extractvalue { i32, { i32 } } %A, 0
11568 return ExtractValueInst::Create(IV->getAggregateOperand(),
11569 EV.idx_begin(), EV.idx_end());
11570 }
11571 if (exti == exte && insi == inse)
11572 // Both iterators are at the end: Index lists are identical. Replace
11573 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11574 // %C = extractvalue { i32, { i32 } } %B, 1, 0
11575 // with "i32 42"
11576 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
11577 if (exti == exte) {
11578 // The extract list is a prefix of the insert list. i.e. replace
11579 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
11580 // %E = extractvalue { i32, { i32 } } %I, 1
11581 // with
11582 // %X = extractvalue { i32, { i32 } } %A, 1
11583 // %E = insertvalue { i32 } %X, i32 42, 0
11584 // by switching the order of the insert and extract (though the
11585 // insertvalue should be left in, since it may have other uses).
11586 Value *NewEV = InsertNewInstBefore(
11587 ExtractValueInst::Create(IV->getAggregateOperand(),
11588 EV.idx_begin(), EV.idx_end()),
11589 EV);
11590 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
11591 insi, inse);
11592 }
11593 if (insi == inse)
11594 // The insert list is a prefix of the extract list
11595 // We can simply remove the common indices from the extract and make it
11596 // operate on the inserted value instead of the insertvalue result.
11597 // i.e., replace
11598 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
11599 // %E = extractvalue { i32, { i32 } } %I, 1, 0
11600 // with
11601 // %E extractvalue { i32 } { i32 42 }, 0
11602 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
11603 exti, exte);
11604 }
11605 // Can't simplify extracts from other values. Note that nested extracts are
11606 // already simplified implicitely by the above (extract ( extract (insert) )
11607 // will be translated into extract ( insert ( extract ) ) first and then just
11608 // the value inserted, if appropriate).
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000011609 return 0;
11610}
11611
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011612/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
11613/// is to leave as a vector operation.
11614static bool CheapToScalarize(Value *V, bool isConstant) {
11615 if (isa<ConstantAggregateZero>(V))
11616 return true;
11617 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
11618 if (isConstant) return true;
11619 // If all elts are the same, we can extract.
11620 Constant *Op0 = C->getOperand(0);
11621 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11622 if (C->getOperand(i) != Op0)
11623 return false;
11624 return true;
11625 }
11626 Instruction *I = dyn_cast<Instruction>(V);
11627 if (!I) return false;
11628
11629 // Insert element gets simplified to the inserted element or is deleted if
11630 // this is constant idx extract element and its a constant idx insertelt.
11631 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
11632 isa<ConstantInt>(I->getOperand(2)))
11633 return true;
11634 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
11635 return true;
11636 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
11637 if (BO->hasOneUse() &&
11638 (CheapToScalarize(BO->getOperand(0), isConstant) ||
11639 CheapToScalarize(BO->getOperand(1), isConstant)))
11640 return true;
11641 if (CmpInst *CI = dyn_cast<CmpInst>(I))
11642 if (CI->hasOneUse() &&
11643 (CheapToScalarize(CI->getOperand(0), isConstant) ||
11644 CheapToScalarize(CI->getOperand(1), isConstant)))
11645 return true;
11646
11647 return false;
11648}
11649
11650/// Read and decode a shufflevector mask.
11651///
11652/// It turns undef elements into values that are larger than the number of
11653/// elements in the input.
11654static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
11655 unsigned NElts = SVI->getType()->getNumElements();
11656 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
11657 return std::vector<unsigned>(NElts, 0);
11658 if (isa<UndefValue>(SVI->getOperand(2)))
11659 return std::vector<unsigned>(NElts, 2*NElts);
11660
11661 std::vector<unsigned> Result;
11662 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif17396002008-06-12 21:37:33 +000011663 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
11664 if (isa<UndefValue>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011665 Result.push_back(NElts*2); // undef -> 8
11666 else
Gabor Greif17396002008-06-12 21:37:33 +000011667 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011668 return Result;
11669}
11670
11671/// FindScalarElement - Given a vector and an element number, see if the scalar
11672/// value is already around as a register, for example if it were inserted then
11673/// extracted from the vector.
11674static Value *FindScalarElement(Value *V, unsigned EltNo) {
11675 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
11676 const VectorType *PTy = cast<VectorType>(V->getType());
11677 unsigned Width = PTy->getNumElements();
11678 if (EltNo >= Width) // Out of range access.
11679 return UndefValue::get(PTy->getElementType());
11680
11681 if (isa<UndefValue>(V))
11682 return UndefValue::get(PTy->getElementType());
11683 else if (isa<ConstantAggregateZero>(V))
11684 return Constant::getNullValue(PTy->getElementType());
11685 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
11686 return CP->getOperand(EltNo);
11687 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
11688 // If this is an insert to a variable element, we don't know what it is.
11689 if (!isa<ConstantInt>(III->getOperand(2)))
11690 return 0;
11691 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
11692
11693 // If this is an insert to the element we are looking for, return the
11694 // inserted value.
11695 if (EltNo == IIElt)
11696 return III->getOperand(1);
11697
11698 // Otherwise, the insertelement doesn't modify the value, recurse on its
11699 // vector input.
11700 return FindScalarElement(III->getOperand(0), EltNo);
11701 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +000011702 unsigned LHSWidth =
11703 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011704 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangbff5d9c2008-11-10 04:46:22 +000011705 if (InEl < LHSWidth)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011706 return FindScalarElement(SVI->getOperand(0), InEl);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000011707 else if (InEl < LHSWidth*2)
11708 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011709 else
11710 return UndefValue::get(PTy->getElementType());
11711 }
11712
11713 // Otherwise, we don't know.
11714 return 0;
11715}
11716
11717Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011718 // If vector val is undef, replace extract with scalar undef.
11719 if (isa<UndefValue>(EI.getOperand(0)))
11720 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11721
11722 // If vector val is constant 0, replace extract with scalar 0.
11723 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
11724 return ReplaceInstUsesWith(EI, Constant::getNullValue(EI.getType()));
11725
11726 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmandd3425f2008-06-11 09:00:12 +000011727 // If vector val is constant with all elements the same, replace EI with
11728 // that element. When the elements are not identical, we cannot replace yet
11729 // (we do that below, but only when the index is constant).
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011730 Constant *op0 = C->getOperand(0);
11731 for (unsigned i = 1; i < C->getNumOperands(); ++i)
11732 if (C->getOperand(i) != op0) {
11733 op0 = 0;
11734 break;
11735 }
11736 if (op0)
11737 return ReplaceInstUsesWith(EI, op0);
11738 }
11739
11740 // If extracting a specified index from the vector, see if we can recursively
11741 // find a previously computed scalar that was inserted into the vector.
11742 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11743 unsigned IndexVal = IdxC->getZExtValue();
11744 unsigned VectorWidth =
11745 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
11746
11747 // If this is extracting an invalid index, turn this into undef, to avoid
11748 // crashing the code below.
11749 if (IndexVal >= VectorWidth)
11750 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11751
11752 // This instruction only demands the single element from the input vector.
11753 // If the input vector has a single use, simplify it based on this use
11754 // property.
11755 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
11756 uint64_t UndefElts;
11757 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
11758 1 << IndexVal,
11759 UndefElts)) {
11760 EI.setOperand(0, V);
11761 return &EI;
11762 }
11763 }
11764
11765 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal))
11766 return ReplaceInstUsesWith(EI, Elt);
11767
11768 // If the this extractelement is directly using a bitcast from a vector of
11769 // the same number of elements, see if we can find the source element from
11770 // it. In this case, we will end up needing to bitcast the scalars.
11771 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
11772 if (const VectorType *VT =
11773 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
11774 if (VT->getNumElements() == VectorWidth)
11775 if (Value *Elt = FindScalarElement(BCI->getOperand(0), IndexVal))
11776 return new BitCastInst(Elt, EI.getType());
11777 }
11778 }
11779
11780 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
11781 if (I->hasOneUse()) {
11782 // Push extractelement into predecessor operation if legal and
11783 // profitable to do so
11784 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
11785 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
11786 if (CheapToScalarize(BO, isConstantElt)) {
11787 ExtractElementInst *newEI0 =
11788 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
11789 EI.getName()+".lhs");
11790 ExtractElementInst *newEI1 =
11791 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
11792 EI.getName()+".rhs");
11793 InsertNewInstBefore(newEI0, EI);
11794 InsertNewInstBefore(newEI1, EI);
Gabor Greifa645dd32008-05-16 19:29:10 +000011795 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011796 }
11797 } else if (isa<LoadInst>(I)) {
Christopher Lambbb2f2222007-12-17 01:12:55 +000011798 unsigned AS =
11799 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +000011800 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
11801 PointerType::get(EI.getType(), AS),EI);
Gabor Greifb91ea9d2008-05-15 10:04:30 +000011802 GetElementPtrInst *GEP =
11803 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011804 InsertNewInstBefore(GEP, EI);
11805 return new LoadInst(GEP);
11806 }
11807 }
11808 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
11809 // Extracting the inserted element?
11810 if (IE->getOperand(2) == EI.getOperand(1))
11811 return ReplaceInstUsesWith(EI, IE->getOperand(1));
11812 // If the inserted and extracted elements are constants, they must not
11813 // be the same value, extract from the pre-inserted value instead.
11814 if (isa<Constant>(IE->getOperand(2)) &&
11815 isa<Constant>(EI.getOperand(1))) {
11816 AddUsesToWorkList(EI);
11817 EI.setOperand(0, IE->getOperand(0));
11818 return &EI;
11819 }
11820 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
11821 // If this is extracting an element from a shufflevector, figure out where
11822 // it came from and extract from the appropriate input element instead.
11823 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
11824 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
11825 Value *Src;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000011826 unsigned LHSWidth =
11827 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
11828
11829 if (SrcIdx < LHSWidth)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011830 Src = SVI->getOperand(0);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000011831 else if (SrcIdx < LHSWidth*2) {
11832 SrcIdx -= LHSWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011833 Src = SVI->getOperand(1);
11834 } else {
11835 return ReplaceInstUsesWith(EI, UndefValue::get(EI.getType()));
11836 }
11837 return new ExtractElementInst(Src, SrcIdx);
11838 }
11839 }
11840 }
11841 return 0;
11842}
11843
11844/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
11845/// elements from either LHS or RHS, return the shuffle mask and true.
11846/// Otherwise, return false.
11847static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
11848 std::vector<Constant*> &Mask) {
11849 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
11850 "Invalid CollectSingleShuffleElements");
11851 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11852
11853 if (isa<UndefValue>(V)) {
11854 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11855 return true;
11856 } else if (V == LHS) {
11857 for (unsigned i = 0; i != NumElts; ++i)
11858 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11859 return true;
11860 } else if (V == RHS) {
11861 for (unsigned i = 0; i != NumElts; ++i)
11862 Mask.push_back(ConstantInt::get(Type::Int32Ty, i+NumElts));
11863 return true;
11864 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11865 // If this is an insert of an extract from some other vector, include it.
11866 Value *VecOp = IEI->getOperand(0);
11867 Value *ScalarOp = IEI->getOperand(1);
11868 Value *IdxOp = IEI->getOperand(2);
11869
11870 if (!isa<ConstantInt>(IdxOp))
11871 return false;
11872 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11873
11874 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
11875 // Okay, we can handle this if the vector we are insertinting into is
11876 // transitively ok.
11877 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11878 // If so, update the mask to reflect the inserted undef.
11879 Mask[InsertedIdx] = UndefValue::get(Type::Int32Ty);
11880 return true;
11881 }
11882 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
11883 if (isa<ConstantInt>(EI->getOperand(1)) &&
11884 EI->getOperand(0)->getType() == V->getType()) {
11885 unsigned ExtractedIdx =
11886 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11887
11888 // This must be extracting from either LHS or RHS.
11889 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
11890 // Okay, we can handle this if the vector we are insertinting into is
11891 // transitively ok.
11892 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask)) {
11893 // If so, update the mask to reflect the inserted value.
11894 if (EI->getOperand(0) == LHS) {
Mon P Wang6bf3c592008-08-20 02:23:25 +000011895 Mask[InsertedIdx % NumElts] =
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011896 ConstantInt::get(Type::Int32Ty, ExtractedIdx);
11897 } else {
11898 assert(EI->getOperand(0) == RHS);
Mon P Wang6bf3c592008-08-20 02:23:25 +000011899 Mask[InsertedIdx % NumElts] =
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011900 ConstantInt::get(Type::Int32Ty, ExtractedIdx+NumElts);
11901
11902 }
11903 return true;
11904 }
11905 }
11906 }
11907 }
11908 }
11909 // TODO: Handle shufflevector here!
11910
11911 return false;
11912}
11913
11914/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
11915/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
11916/// that computes V and the LHS value of the shuffle.
11917static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
11918 Value *&RHS) {
11919 assert(isa<VectorType>(V->getType()) &&
11920 (RHS == 0 || V->getType() == RHS->getType()) &&
11921 "Invalid shuffle!");
11922 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
11923
11924 if (isa<UndefValue>(V)) {
11925 Mask.assign(NumElts, UndefValue::get(Type::Int32Ty));
11926 return V;
11927 } else if (isa<ConstantAggregateZero>(V)) {
11928 Mask.assign(NumElts, ConstantInt::get(Type::Int32Ty, 0));
11929 return V;
11930 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
11931 // If this is an insert of an extract from some other vector, include it.
11932 Value *VecOp = IEI->getOperand(0);
11933 Value *ScalarOp = IEI->getOperand(1);
11934 Value *IdxOp = IEI->getOperand(2);
11935
11936 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11937 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11938 EI->getOperand(0)->getType() == V->getType()) {
11939 unsigned ExtractedIdx =
11940 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11941 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11942
11943 // Either the extracted from or inserted into vector must be RHSVec,
11944 // otherwise we'd end up with a shuffle of three inputs.
11945 if (EI->getOperand(0) == RHS || RHS == 0) {
11946 RHS = EI->getOperand(0);
11947 Value *V = CollectShuffleElements(VecOp, Mask, RHS);
Mon P Wang6bf3c592008-08-20 02:23:25 +000011948 Mask[InsertedIdx % NumElts] =
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011949 ConstantInt::get(Type::Int32Ty, NumElts+ExtractedIdx);
11950 return V;
11951 }
11952
11953 if (VecOp == RHS) {
11954 Value *V = CollectShuffleElements(EI->getOperand(0), Mask, RHS);
11955 // Everything but the extracted element is replaced with the RHS.
11956 for (unsigned i = 0; i != NumElts; ++i) {
11957 if (i != InsertedIdx)
11958 Mask[i] = ConstantInt::get(Type::Int32Ty, NumElts+i);
11959 }
11960 return V;
11961 }
11962
11963 // If this insertelement is a chain that comes from exactly these two
11964 // vectors, return the vector and the effective shuffle.
11965 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask))
11966 return EI->getOperand(0);
11967
11968 }
11969 }
11970 }
11971 // TODO: Handle shufflevector here!
11972
11973 // Otherwise, can't do anything fancy. Return an identity vector.
11974 for (unsigned i = 0; i != NumElts; ++i)
11975 Mask.push_back(ConstantInt::get(Type::Int32Ty, i));
11976 return V;
11977}
11978
11979Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
11980 Value *VecOp = IE.getOperand(0);
11981 Value *ScalarOp = IE.getOperand(1);
11982 Value *IdxOp = IE.getOperand(2);
11983
11984 // Inserting an undef or into an undefined place, remove this.
11985 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
11986 ReplaceInstUsesWith(IE, VecOp);
11987
11988 // If the inserted element was extracted from some other vector, and if the
11989 // indexes are constant, try to turn this into a shufflevector operation.
11990 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
11991 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
11992 EI->getOperand(0)->getType() == IE.getType()) {
11993 unsigned NumVectorElts = IE.getType()->getNumElements();
11994 unsigned ExtractedIdx =
11995 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
11996 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
11997
11998 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
11999 return ReplaceInstUsesWith(IE, VecOp);
12000
12001 if (InsertedIdx >= NumVectorElts) // Out of range insert.
12002 return ReplaceInstUsesWith(IE, UndefValue::get(IE.getType()));
12003
12004 // If we are extracting a value from a vector, then inserting it right
12005 // back into the same place, just use the input vector.
12006 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12007 return ReplaceInstUsesWith(IE, VecOp);
12008
12009 // We could theoretically do this for ANY input. However, doing so could
12010 // turn chains of insertelement instructions into a chain of shufflevector
12011 // instructions, and right now we do not merge shufflevectors. As such,
12012 // only do this in a situation where it is clear that there is benefit.
12013 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12014 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12015 // the values of VecOp, except then one read from EIOp0.
12016 // Build a new shuffle mask.
12017 std::vector<Constant*> Mask;
12018 if (isa<UndefValue>(VecOp))
12019 Mask.assign(NumVectorElts, UndefValue::get(Type::Int32Ty));
12020 else {
12021 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
12022 Mask.assign(NumVectorElts, ConstantInt::get(Type::Int32Ty,
12023 NumVectorElts));
12024 }
12025 Mask[InsertedIdx] = ConstantInt::get(Type::Int32Ty, ExtractedIdx);
12026 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
12027 ConstantVector::get(Mask));
12028 }
12029
12030 // If this insertelement isn't used by some other insertelement, turn it
12031 // (and any insertelements it points to), into one big shuffle.
12032 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12033 std::vector<Constant*> Mask;
12034 Value *RHS = 0;
12035 Value *LHS = CollectShuffleElements(&IE, Mask, RHS);
12036 if (RHS == 0) RHS = UndefValue::get(LHS->getType());
12037 // We now have a shuffle of LHS, RHS, Mask.
12038 return new ShuffleVectorInst(LHS, RHS, ConstantVector::get(Mask));
12039 }
12040 }
12041 }
12042
12043 return 0;
12044}
12045
12046
12047Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12048 Value *LHS = SVI.getOperand(0);
12049 Value *RHS = SVI.getOperand(1);
12050 std::vector<unsigned> Mask = getShuffleMask(&SVI);
12051
12052 bool MadeChange = false;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012053
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012054 // Undefined shuffle mask -> undefined value.
12055 if (isa<UndefValue>(SVI.getOperand(2)))
12056 return ReplaceInstUsesWith(SVI, UndefValue::get(SVI.getType()));
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012057
12058 uint64_t UndefElts;
12059 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012060
12061 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12062 return 0;
12063
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012064 uint64_t AllOnesEltMask = ~0ULL >> (64-VWidth);
12065 if (VWidth <= 64 &&
Dan Gohman83b702d2008-09-11 22:47:57 +000012066 SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
12067 LHS = SVI.getOperand(0);
12068 RHS = SVI.getOperand(1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012069 MadeChange = true;
Dan Gohman83b702d2008-09-11 22:47:57 +000012070 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012071
12072 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12073 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12074 if (LHS == RHS || isa<UndefValue>(LHS)) {
12075 if (isa<UndefValue>(LHS) && LHS == RHS) {
12076 // shuffle(undef,undef,mask) -> undef.
12077 return ReplaceInstUsesWith(SVI, LHS);
12078 }
12079
12080 // Remap any references to RHS to use LHS.
12081 std::vector<Constant*> Elts;
12082 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12083 if (Mask[i] >= 2*e)
12084 Elts.push_back(UndefValue::get(Type::Int32Ty));
12085 else {
12086 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohmanbba96b92008-08-06 18:17:32 +000012087 (Mask[i] < e && isa<UndefValue>(LHS))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012088 Mask[i] = 2*e; // Turn into undef.
Dan Gohmanbba96b92008-08-06 18:17:32 +000012089 Elts.push_back(UndefValue::get(Type::Int32Ty));
12090 } else {
Mon P Wang6bf3c592008-08-20 02:23:25 +000012091 Mask[i] = Mask[i] % e; // Force to LHS.
Dan Gohmanbba96b92008-08-06 18:17:32 +000012092 Elts.push_back(ConstantInt::get(Type::Int32Ty, Mask[i]));
12093 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012094 }
12095 }
12096 SVI.setOperand(0, SVI.getOperand(1));
12097 SVI.setOperand(1, UndefValue::get(RHS->getType()));
12098 SVI.setOperand(2, ConstantVector::get(Elts));
12099 LHS = SVI.getOperand(0);
12100 RHS = SVI.getOperand(1);
12101 MadeChange = true;
12102 }
12103
12104 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12105 bool isLHSID = true, isRHSID = true;
12106
12107 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12108 if (Mask[i] >= e*2) continue; // Ignore undef values.
12109 // Is this an identity shuffle of the LHS value?
12110 isLHSID &= (Mask[i] == i);
12111
12112 // Is this an identity shuffle of the RHS value?
12113 isRHSID &= (Mask[i]-e == i);
12114 }
12115
12116 // Eliminate identity shuffles.
12117 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12118 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12119
12120 // If the LHS is a shufflevector itself, see if we can combine it with this
12121 // one without producing an unusual shuffle. Here we are really conservative:
12122 // we are absolutely afraid of producing a shuffle mask not in the input
12123 // program, because the code gen may not be smart enough to turn a merged
12124 // shuffle into two specific shuffles: it may produce worse code. As such,
12125 // we only merge two shuffles if the result is one of the two input shuffle
12126 // masks. In this case, merging the shuffles just removes one instruction,
12127 // which we know is safe. This is good for things like turning:
12128 // (splat(splat)) -> splat.
12129 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12130 if (isa<UndefValue>(RHS)) {
12131 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12132
12133 std::vector<unsigned> NewMask;
12134 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12135 if (Mask[i] >= 2*e)
12136 NewMask.push_back(2*e);
12137 else
12138 NewMask.push_back(LHSMask[Mask[i]]);
12139
12140 // If the result mask is equal to the src shuffle or this shuffle mask, do
12141 // the replacement.
12142 if (NewMask == LHSMask || NewMask == Mask) {
12143 std::vector<Constant*> Elts;
12144 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
12145 if (NewMask[i] >= e*2) {
12146 Elts.push_back(UndefValue::get(Type::Int32Ty));
12147 } else {
12148 Elts.push_back(ConstantInt::get(Type::Int32Ty, NewMask[i]));
12149 }
12150 }
12151 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12152 LHSSVI->getOperand(1),
12153 ConstantVector::get(Elts));
12154 }
12155 }
12156 }
12157
12158 return MadeChange ? &SVI : 0;
12159}
12160
12161
12162
12163
12164/// TryToSinkInstruction - Try to move the specified instruction from its
12165/// current block into the beginning of DestBlock, which can only happen if it's
12166/// safe to move the instruction past all of the instructions between it and the
12167/// end of its block.
12168static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12169 assert(I->hasOneUse() && "Invariants didn't hold!");
12170
12171 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Chris Lattnercb19a1c2008-05-09 15:07:33 +000012172 if (isa<PHINode>(I) || I->mayWriteToMemory() || isa<TerminatorInst>(I))
12173 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012174
12175 // Do not sink alloca instructions out of the entry block.
12176 if (isa<AllocaInst>(I) && I->getParent() ==
12177 &DestBlock->getParent()->getEntryBlock())
12178 return false;
12179
12180 // We can only sink load instructions if there is nothing between the load and
12181 // the end of block that could change the value.
Chris Lattner0db40a62008-05-08 17:37:37 +000012182 if (I->mayReadFromMemory()) {
12183 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012184 Scan != E; ++Scan)
12185 if (Scan->mayWriteToMemory())
12186 return false;
12187 }
12188
Dan Gohman514277c2008-05-23 21:05:58 +000012189 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012190
12191 I->moveBefore(InsertPos);
12192 ++NumSunkInst;
12193 return true;
12194}
12195
12196
12197/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12198/// all reachable code to the worklist.
12199///
12200/// This has a couple of tricks to make the code faster and more powerful. In
12201/// particular, we constant fold and DCE instructions as we go, to avoid adding
12202/// them to the worklist (this significantly speeds up instcombine on code where
12203/// many instructions are dead or constant). Additionally, if we find a branch
12204/// whose condition is a known constant, we only visit the reachable successors.
12205///
12206static void AddReachableCodeToWorklist(BasicBlock *BB,
12207 SmallPtrSet<BasicBlock*, 64> &Visited,
12208 InstCombiner &IC,
12209 const TargetData *TD) {
Chris Lattnera06291a2008-08-15 04:03:01 +000012210 SmallVector<BasicBlock*, 256> Worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012211 Worklist.push_back(BB);
12212
12213 while (!Worklist.empty()) {
12214 BB = Worklist.back();
12215 Worklist.pop_back();
12216
12217 // We have now visited this block! If we've already been here, ignore it.
12218 if (!Visited.insert(BB)) continue;
Devang Patel794140c2008-11-19 18:56:50 +000012219
12220 DbgInfoIntrinsic *DBI_Prev = NULL;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012221 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12222 Instruction *Inst = BBI++;
12223
12224 // DCE instruction if trivially dead.
12225 if (isInstructionTriviallyDead(Inst)) {
12226 ++NumDeadInst;
12227 DOUT << "IC: DCE: " << *Inst;
12228 Inst->eraseFromParent();
12229 continue;
12230 }
12231
12232 // ConstantProp instruction if trivially constant.
12233 if (Constant *C = ConstantFoldInstruction(Inst, TD)) {
12234 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12235 Inst->replaceAllUsesWith(C);
12236 ++NumConstProp;
12237 Inst->eraseFromParent();
12238 continue;
12239 }
Chris Lattnere0f462d2007-07-20 22:06:41 +000012240
Devang Patel794140c2008-11-19 18:56:50 +000012241 // If there are two consecutive llvm.dbg.stoppoint calls then
12242 // it is likely that the optimizer deleted code in between these
12243 // two intrinsics.
12244 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12245 if (DBI_Next) {
12246 if (DBI_Prev
12247 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12248 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12249 IC.RemoveFromWorkList(DBI_Prev);
12250 DBI_Prev->eraseFromParent();
12251 }
12252 DBI_Prev = DBI_Next;
12253 }
12254
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012255 IC.AddToWorkList(Inst);
12256 }
12257
12258 // Recursively visit successors. If this is a branch or switch on a
12259 // constant, only visit the reachable successor.
12260 TerminatorInst *TI = BB->getTerminator();
12261 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12262 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12263 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewyckyd551cf12008-03-09 08:50:23 +000012264 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000012265 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012266 continue;
12267 }
12268 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12269 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12270 // See if this is an explicit destination.
12271 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12272 if (SI->getCaseValue(i) == Cond) {
Nick Lewyckyd551cf12008-03-09 08:50:23 +000012273 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000012274 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012275 continue;
12276 }
12277
12278 // Otherwise it is the default destination.
12279 Worklist.push_back(SI->getSuccessor(0));
12280 continue;
12281 }
12282 }
12283
12284 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12285 Worklist.push_back(TI->getSuccessor(i));
12286 }
12287}
12288
12289bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12290 bool Changed = false;
12291 TD = &getAnalysis<TargetData>();
12292
12293 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12294 << F.getNameStr() << "\n");
12295
12296 {
12297 // Do a depth-first traversal of the function, populate the worklist with
12298 // the reachable instructions. Ignore blocks that are not reachable. Keep
12299 // track of which blocks we visit.
12300 SmallPtrSet<BasicBlock*, 64> Visited;
12301 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12302
12303 // Do a quick scan over the function. If we find any blocks that are
12304 // unreachable, remove any instructions inside of them. This prevents
12305 // the instcombine code from having to deal with some bad special cases.
12306 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12307 if (!Visited.count(BB)) {
12308 Instruction *Term = BB->getTerminator();
12309 while (Term != BB->begin()) { // Remove instrs bottom-up
12310 BasicBlock::iterator I = Term; --I;
12311
12312 DOUT << "IC: DCE: " << *I;
12313 ++NumDeadInst;
12314
12315 if (!I->use_empty())
12316 I->replaceAllUsesWith(UndefValue::get(I->getType()));
12317 I->eraseFromParent();
12318 }
12319 }
12320 }
12321
12322 while (!Worklist.empty()) {
12323 Instruction *I = RemoveOneFromWorkList();
12324 if (I == 0) continue; // skip null values.
12325
12326 // Check to see if we can DCE the instruction.
12327 if (isInstructionTriviallyDead(I)) {
12328 // Add operands to the worklist.
12329 if (I->getNumOperands() < 4)
12330 AddUsesToWorkList(*I);
12331 ++NumDeadInst;
12332
12333 DOUT << "IC: DCE: " << *I;
12334
12335 I->eraseFromParent();
12336 RemoveFromWorkList(I);
12337 continue;
12338 }
12339
12340 // Instruction isn't dead, see if we can constant propagate it.
12341 if (Constant *C = ConstantFoldInstruction(I, TD)) {
12342 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
12343
12344 // Add operands to the worklist.
12345 AddUsesToWorkList(*I);
12346 ReplaceInstUsesWith(*I, C);
12347
12348 ++NumConstProp;
12349 I->eraseFromParent();
12350 RemoveFromWorkList(I);
12351 continue;
12352 }
12353
Nick Lewyckyadb67922008-05-25 20:56:15 +000012354 if (TD && I->getType()->getTypeID() == Type::VoidTyID) {
12355 // See if we can constant fold its operands.
12356 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
12357 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i)) {
12358 if (Constant *NewC = ConstantFoldConstantExpression(CE, TD))
12359 i->set(NewC);
12360 }
12361 }
12362 }
12363
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012364 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohman29474e92008-07-23 00:34:11 +000012365 if (I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012366 BasicBlock *BB = I->getParent();
12367 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
12368 if (UserParent != BB) {
12369 bool UserIsSuccessor = false;
12370 // See if the user is one of our successors.
12371 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
12372 if (*SI == UserParent) {
12373 UserIsSuccessor = true;
12374 break;
12375 }
12376
12377 // If the user is one of our immediate successors, and if that successor
12378 // only has us as a predecessors (we'd have to split the critical edge
12379 // otherwise), we can keep going.
12380 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
12381 next(pred_begin(UserParent)) == pred_end(UserParent))
12382 // Okay, the CFG is simple enough, try to sink this instruction.
12383 Changed |= TryToSinkInstruction(I, UserParent);
12384 }
12385 }
12386
12387 // Now that we have an instruction, try combining it to simplify it...
12388#ifndef NDEBUG
12389 std::string OrigI;
12390#endif
12391 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
12392 if (Instruction *Result = visit(*I)) {
12393 ++NumCombined;
12394 // Should we replace the old instruction with a new one?
12395 if (Result != I) {
12396 DOUT << "IC: Old = " << *I
12397 << " New = " << *Result;
12398
12399 // Everything uses the new instruction now.
12400 I->replaceAllUsesWith(Result);
12401
12402 // Push the new instruction and any users onto the worklist.
12403 AddToWorkList(Result);
12404 AddUsersToWorkList(*Result);
12405
12406 // Move the name to the new instruction first.
12407 Result->takeName(I);
12408
12409 // Insert the new instruction into the basic block...
12410 BasicBlock *InstParent = I->getParent();
12411 BasicBlock::iterator InsertPos = I;
12412
12413 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
12414 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
12415 ++InsertPos;
12416
12417 InstParent->getInstList().insert(InsertPos, Result);
12418
12419 // Make sure that we reprocess all operands now that we reduced their
12420 // use counts.
12421 AddUsesToWorkList(*I);
12422
12423 // Instructions can end up on the worklist more than once. Make sure
12424 // we do not process an instruction that has been deleted.
12425 RemoveFromWorkList(I);
12426
12427 // Erase the old instruction.
12428 InstParent->getInstList().erase(I);
12429 } else {
12430#ifndef NDEBUG
12431 DOUT << "IC: Mod = " << OrigI
12432 << " New = " << *I;
12433#endif
12434
12435 // If the instruction was modified, it's possible that it is now dead.
12436 // if so, remove it.
12437 if (isInstructionTriviallyDead(I)) {
12438 // Make sure we process all operands now that we are reducing their
12439 // use counts.
12440 AddUsesToWorkList(*I);
12441
12442 // Instructions may end up in the worklist more than once. Erase all
12443 // occurrences of this instruction.
12444 RemoveFromWorkList(I);
12445 I->eraseFromParent();
12446 } else {
12447 AddToWorkList(I);
12448 AddUsersToWorkList(*I);
12449 }
12450 }
12451 Changed = true;
12452 }
12453 }
12454
12455 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnerb933ea62007-08-05 08:47:58 +000012456
12457 // Do an explicit clear, this shrinks the map if needed.
12458 WorklistMap.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012459 return Changed;
12460}
12461
12462
12463bool InstCombiner::runOnFunction(Function &F) {
12464 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
12465
12466 bool EverMadeChange = false;
12467
12468 // Iterate while there is work to do.
12469 unsigned Iteration = 0;
Bill Wendlingd9644a42008-05-14 22:45:20 +000012470 while (DoOneIteration(F, Iteration++))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012471 EverMadeChange = true;
12472 return EverMadeChange;
12473}
12474
12475FunctionPass *llvm::createInstructionCombiningPass() {
12476 return new InstCombiner();
12477}