blob: 89881f739fbb332a70f562279f1ae915b28d7bc4 [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"
Owen Anderson24be4c12009-07-03 00:17:18 +000039#include "llvm/LLVMContext.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000040#include "llvm/Pass.h"
41#include "llvm/DerivedTypes.h"
42#include "llvm/GlobalVariable.h"
43#include "llvm/Analysis/ConstantFolding.h"
Chris Lattnera432bc72008-06-02 01:18:21 +000044#include "llvm/Analysis/ValueTracking.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000045#include "llvm/Target/TargetData.h"
46#include "llvm/Transforms/Utils/BasicBlockUtils.h"
47#include "llvm/Transforms/Utils/Local.h"
48#include "llvm/Support/CallSite.h"
Nick Lewycky0185bbf2008-02-03 16:33:09 +000049#include "llvm/Support/ConstantRange.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000050#include "llvm/Support/Debug.h"
Edwin Törökced9ff82009-07-11 13:10:19 +000051#include "llvm/Support/ErrorHandling.h"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000052#include "llvm/Support/GetElementPtrTypeIterator.h"
53#include "llvm/Support/InstVisitor.h"
54#include "llvm/Support/MathExtras.h"
55#include "llvm/Support/PatternMatch.h"
56#include "llvm/Support/Compiler.h"
57#include "llvm/ADT/DenseMap.h"
58#include "llvm/ADT/SmallVector.h"
59#include "llvm/ADT/SmallPtrSet.h"
60#include "llvm/ADT/Statistic.h"
61#include "llvm/ADT/STLExtras.h"
62#include <algorithm>
Edwin Töröka0e6fce2008-04-20 08:33:11 +000063#include <climits>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000064#include <sstream>
65using namespace llvm;
66using namespace llvm::PatternMatch;
67
68STATISTIC(NumCombined , "Number of insts combined");
69STATISTIC(NumConstProp, "Number of constant folds");
70STATISTIC(NumDeadInst , "Number of dead inst eliminated");
71STATISTIC(NumDeadStore, "Number of dead stores eliminated");
72STATISTIC(NumSunkInst , "Number of instructions sunk");
73
74namespace {
75 class VISIBILITY_HIDDEN InstCombiner
76 : public FunctionPass,
77 public InstVisitor<InstCombiner, Instruction*> {
78 // Worklist of all of the instructions that need to be simplified.
Chris Lattnera06291a2008-08-15 04:03:01 +000079 SmallVector<Instruction*, 256> Worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000080 DenseMap<Instruction*, unsigned> WorklistMap;
81 TargetData *TD;
82 bool MustPreserveLCSSA;
83 public:
84 static char ID; // Pass identification, replacement for typeid
Dan Gohman26f8c272008-09-04 17:05:41 +000085 InstCombiner() : FunctionPass(&ID) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +000086
Owen Anderson5349f052009-07-06 23:00:19 +000087 LLVMContext *getContext() { return Context; }
Owen Anderson24be4c12009-07-03 00:17:18 +000088
Dan Gohmanf17a25c2007-07-18 16:29:46 +000089 /// AddToWorkList - Add the specified instruction to the worklist if it
90 /// isn't already in it.
91 void AddToWorkList(Instruction *I) {
Dan Gohman55d19662008-07-07 17:46:23 +000092 if (WorklistMap.insert(std::make_pair(I, Worklist.size())).second)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000093 Worklist.push_back(I);
94 }
95
96 // RemoveFromWorkList - remove I from the worklist if it exists.
97 void RemoveFromWorkList(Instruction *I) {
98 DenseMap<Instruction*, unsigned>::iterator It = WorklistMap.find(I);
99 if (It == WorklistMap.end()) return; // Not in worklist.
100
101 // Don't bother moving everything down, just null out the slot.
102 Worklist[It->second] = 0;
103
104 WorklistMap.erase(It);
105 }
106
107 Instruction *RemoveOneFromWorkList() {
108 Instruction *I = Worklist.back();
109 Worklist.pop_back();
110 WorklistMap.erase(I);
111 return I;
112 }
113
114
115 /// AddUsersToWorkList - When an instruction is simplified, add all users of
116 /// the instruction to the work lists because they might get more simplified
117 /// now.
118 ///
119 void AddUsersToWorkList(Value &I) {
120 for (Value::use_iterator UI = I.use_begin(), UE = I.use_end();
121 UI != UE; ++UI)
122 AddToWorkList(cast<Instruction>(*UI));
123 }
124
125 /// AddUsesToWorkList - When an instruction is simplified, add operands to
126 /// the work lists because they might get more simplified now.
127 ///
128 void AddUsesToWorkList(Instruction &I) {
Gabor Greif17396002008-06-12 21:37:33 +0000129 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
130 if (Instruction *Op = dyn_cast<Instruction>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000131 AddToWorkList(Op);
132 }
133
134 /// AddSoonDeadInstToWorklist - The specified instruction is about to become
135 /// dead. Add all of its operands to the worklist, turning them into
136 /// undef's to reduce the number of uses of those instructions.
137 ///
138 /// Return the specified operand before it is turned into an undef.
139 ///
140 Value *AddSoonDeadInstToWorklist(Instruction &I, unsigned op) {
141 Value *R = I.getOperand(op);
142
Gabor Greif17396002008-06-12 21:37:33 +0000143 for (User::op_iterator i = I.op_begin(), e = I.op_end(); i != e; ++i)
144 if (Instruction *Op = dyn_cast<Instruction>(*i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000145 AddToWorkList(Op);
146 // Set the operand to undef to drop the use.
Owen Anderson24be4c12009-07-03 00:17:18 +0000147 *i = Context->getUndef(Op->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000148 }
149
150 return R;
151 }
152
153 public:
154 virtual bool runOnFunction(Function &F);
155
156 bool DoOneIteration(Function &F, unsigned ItNum);
157
158 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
159 AU.addRequired<TargetData>();
160 AU.addPreservedID(LCSSAID);
161 AU.setPreservesCFG();
162 }
163
164 TargetData &getTargetData() const { return *TD; }
165
166 // Visitation implementation - Implement instruction combining for different
167 // instruction types. The semantics are as follows:
168 // Return Value:
169 // null - No change was made
170 // I - Change was made, I is still valid, I may be dead though
171 // otherwise - Change was made, replace I with returned instruction
172 //
173 Instruction *visitAdd(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000174 Instruction *visitFAdd(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000175 Instruction *visitSub(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000176 Instruction *visitFSub(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000177 Instruction *visitMul(BinaryOperator &I);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000178 Instruction *visitFMul(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000179 Instruction *visitURem(BinaryOperator &I);
180 Instruction *visitSRem(BinaryOperator &I);
181 Instruction *visitFRem(BinaryOperator &I);
Chris Lattner76972db2008-07-14 00:15:52 +0000182 bool SimplifyDivRemOfSelect(BinaryOperator &I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000183 Instruction *commonRemTransforms(BinaryOperator &I);
184 Instruction *commonIRemTransforms(BinaryOperator &I);
185 Instruction *commonDivTransforms(BinaryOperator &I);
186 Instruction *commonIDivTransforms(BinaryOperator &I);
187 Instruction *visitUDiv(BinaryOperator &I);
188 Instruction *visitSDiv(BinaryOperator &I);
189 Instruction *visitFDiv(BinaryOperator &I);
Chris Lattner0631ea72008-11-16 05:06:21 +0000190 Instruction *FoldAndOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000191 Instruction *visitAnd(BinaryOperator &I);
Chris Lattner0c678e52008-11-16 05:20:07 +0000192 Instruction *FoldOrOfICmps(Instruction &I, ICmpInst *LHS, ICmpInst *RHS);
Bill Wendling9912f712008-12-01 08:32:40 +0000193 Instruction *FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +0000194 Value *A, Value *B, Value *C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000195 Instruction *visitOr (BinaryOperator &I);
196 Instruction *visitXor(BinaryOperator &I);
197 Instruction *visitShl(BinaryOperator &I);
198 Instruction *visitAShr(BinaryOperator &I);
199 Instruction *visitLShr(BinaryOperator &I);
200 Instruction *commonShiftTransforms(BinaryOperator &I);
Chris Lattnere6b62d92008-05-19 20:18:56 +0000201 Instruction *FoldFCmp_IntToFP_Cst(FCmpInst &I, Instruction *LHSI,
202 Constant *RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000203 Instruction *visitFCmpInst(FCmpInst &I);
204 Instruction *visitICmpInst(ICmpInst &I);
205 Instruction *visitICmpInstWithCastAndCast(ICmpInst &ICI);
206 Instruction *visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
207 Instruction *LHS,
208 ConstantInt *RHS);
209 Instruction *FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
210 ConstantInt *DivRHS);
211
212 Instruction *FoldGEPICmp(User *GEPLHS, Value *RHS,
213 ICmpInst::Predicate Cond, Instruction &I);
214 Instruction *FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
215 BinaryOperator &I);
216 Instruction *commonCastTransforms(CastInst &CI);
217 Instruction *commonIntCastTransforms(CastInst &CI);
218 Instruction *commonPointerCastTransforms(CastInst &CI);
219 Instruction *visitTrunc(TruncInst &CI);
220 Instruction *visitZExt(ZExtInst &CI);
221 Instruction *visitSExt(SExtInst &CI);
Chris Lattnerdf7e8402008-01-27 05:29:54 +0000222 Instruction *visitFPTrunc(FPTruncInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000223 Instruction *visitFPExt(CastInst &CI);
Chris Lattnerdeef1a72008-05-19 20:25:04 +0000224 Instruction *visitFPToUI(FPToUIInst &FI);
225 Instruction *visitFPToSI(FPToSIInst &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000226 Instruction *visitUIToFP(CastInst &CI);
227 Instruction *visitSIToFP(CastInst &CI);
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000228 Instruction *visitPtrToInt(PtrToIntInst &CI);
Chris Lattner7c1626482008-01-08 07:23:51 +0000229 Instruction *visitIntToPtr(IntToPtrInst &CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000230 Instruction *visitBitCast(BitCastInst &CI);
231 Instruction *FoldSelectOpOp(SelectInst &SI, Instruction *TI,
232 Instruction *FI);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +0000233 Instruction *FoldSelectIntoOp(SelectInst &SI, Value*, Value*);
Dan Gohman58c09632008-09-16 18:46:06 +0000234 Instruction *visitSelectInst(SelectInst &SI);
235 Instruction *visitSelectInstWithICmp(SelectInst &SI, ICmpInst *ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000236 Instruction *visitCallInst(CallInst &CI);
237 Instruction *visitInvokeInst(InvokeInst &II);
238 Instruction *visitPHINode(PHINode &PN);
239 Instruction *visitGetElementPtrInst(GetElementPtrInst &GEP);
240 Instruction *visitAllocationInst(AllocationInst &AI);
241 Instruction *visitFreeInst(FreeInst &FI);
242 Instruction *visitLoadInst(LoadInst &LI);
243 Instruction *visitStoreInst(StoreInst &SI);
244 Instruction *visitBranchInst(BranchInst &BI);
245 Instruction *visitSwitchInst(SwitchInst &SI);
246 Instruction *visitInsertElementInst(InsertElementInst &IE);
247 Instruction *visitExtractElementInst(ExtractElementInst &EI);
248 Instruction *visitShuffleVectorInst(ShuffleVectorInst &SVI);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000249 Instruction *visitExtractValueInst(ExtractValueInst &EV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000250
251 // visitInstruction - Specify what to return for unhandled instructions...
252 Instruction *visitInstruction(Instruction &I) { return 0; }
253
254 private:
255 Instruction *visitCallSite(CallSite CS);
256 bool transformConstExprCastCall(CallSite CS);
Duncan Sands74833f22007-09-17 10:26:40 +0000257 Instruction *transformCallThroughTrampoline(CallSite CS);
Evan Chenge3779cf2008-03-24 00:21:34 +0000258 Instruction *transformZExtICmp(ICmpInst *ICI, Instruction &CI,
259 bool DoXform = true);
Chris Lattner3554f972008-05-20 05:46:13 +0000260 bool WillNotOverflowSignedAdd(Value *LHS, Value *RHS);
Dale Johannesen2c11fe22009-03-03 21:26:39 +0000261 DbgDeclareInst *hasOneUsePlusDeclare(Value *V);
262
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000263
264 public:
265 // InsertNewInstBefore - insert an instruction New before instruction Old
266 // in the program. Add the new instruction to the worklist.
267 //
268 Instruction *InsertNewInstBefore(Instruction *New, Instruction &Old) {
269 assert(New && New->getParent() == 0 &&
270 "New instruction already inserted into a basic block!");
271 BasicBlock *BB = Old.getParent();
272 BB->getInstList().insert(&Old, New); // Insert inst
273 AddToWorkList(New);
274 return New;
275 }
276
277 /// InsertCastBefore - Insert a cast of V to TY before the instruction POS.
278 /// This also adds the cast to the worklist. Finally, this returns the
279 /// cast.
280 Value *InsertCastBefore(Instruction::CastOps opc, Value *V, const Type *Ty,
281 Instruction &Pos) {
282 if (V->getType() == Ty) return V;
283
284 if (Constant *CV = dyn_cast<Constant>(V))
Owen Anderson24be4c12009-07-03 00:17:18 +0000285 return Context->getConstantExprCast(opc, CV, Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000286
Gabor Greifa645dd32008-05-16 19:29:10 +0000287 Instruction *C = CastInst::Create(opc, V, Ty, V->getName(), &Pos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000288 AddToWorkList(C);
289 return C;
290 }
Chris Lattner13c2d6e2008-01-13 22:23:22 +0000291
292 Value *InsertBitCastBefore(Value *V, const Type *Ty, Instruction &Pos) {
293 return InsertCastBefore(Instruction::BitCast, V, Ty, Pos);
294 }
295
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000296
297 // ReplaceInstUsesWith - This method is to be used when an instruction is
298 // found to be dead, replacable with another preexisting expression. Here
299 // we add all uses of I to the worklist, replace all uses of I with the new
300 // value, then return I, so that the inst combiner will know that I was
301 // modified.
302 //
303 Instruction *ReplaceInstUsesWith(Instruction &I, Value *V) {
304 AddUsersToWorkList(I); // Add all modified instrs to worklist
305 if (&I != V) {
306 I.replaceAllUsesWith(V);
307 return &I;
308 } else {
309 // If we are replacing the instruction with itself, this must be in a
310 // segment of unreachable code, so just clobber the instruction.
Owen Anderson24be4c12009-07-03 00:17:18 +0000311 I.replaceAllUsesWith(Context->getUndef(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000312 return &I;
313 }
314 }
315
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000316 // EraseInstFromFunction - When dealing with an instruction that has side
317 // effects or produces a void value, we can't rely on DCE to delete the
318 // instruction. Instead, visit methods should return the value returned by
319 // this function.
320 Instruction *EraseInstFromFunction(Instruction &I) {
321 assert(I.use_empty() && "Cannot erase instruction that is used!");
322 AddUsesToWorkList(I);
323 RemoveFromWorkList(&I);
324 I.eraseFromParent();
325 return 0; // Don't do anything with FI
326 }
Chris Lattnera432bc72008-06-02 01:18:21 +0000327
328 void ComputeMaskedBits(Value *V, const APInt &Mask, APInt &KnownZero,
329 APInt &KnownOne, unsigned Depth = 0) const {
330 return llvm::ComputeMaskedBits(V, Mask, KnownZero, KnownOne, TD, Depth);
331 }
332
333 bool MaskedValueIsZero(Value *V, const APInt &Mask,
334 unsigned Depth = 0) const {
335 return llvm::MaskedValueIsZero(V, Mask, TD, Depth);
336 }
337 unsigned ComputeNumSignBits(Value *Op, unsigned Depth = 0) const {
338 return llvm::ComputeNumSignBits(Op, TD, Depth);
339 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000340
341 private:
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000342
343 /// SimplifyCommutative - This performs a few simplifications for
344 /// commutative operators.
345 bool SimplifyCommutative(BinaryOperator &I);
346
347 /// SimplifyCompare - This reorders the operands of a CmpInst to get them in
348 /// most-complex to least-complex order.
349 bool SimplifyCompare(CmpInst &I);
350
Chris Lattner676c78e2009-01-31 08:15:18 +0000351 /// SimplifyDemandedUseBits - Attempts to replace V with a simpler value
352 /// based on the demanded bits.
353 Value *SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
354 APInt& KnownZero, APInt& KnownOne,
355 unsigned Depth);
356 bool SimplifyDemandedBits(Use &U, APInt DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000357 APInt& KnownZero, APInt& KnownOne,
Chris Lattner676c78e2009-01-31 08:15:18 +0000358 unsigned Depth=0);
359
360 /// SimplifyDemandedInstructionBits - Inst is an integer instruction that
361 /// SimplifyDemandedBits knows about. See if the instruction has any
362 /// properties that allow us to simplify its operands.
363 bool SimplifyDemandedInstructionBits(Instruction &Inst);
364
Evan Cheng63295ab2009-02-03 10:05:09 +0000365 Value *SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
366 APInt& UndefElts, unsigned Depth = 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000367
368 // FoldOpIntoPhi - Given a binary operator or cast instruction which has a
369 // PHI node as operand #0, see if we can fold the instruction into the PHI
370 // (which is only possible if all operands to the PHI are constants).
371 Instruction *FoldOpIntoPhi(Instruction &I);
372
373 // FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
374 // operator and they all are only used by the PHI, PHI together their
375 // inputs, and do the operation once, to the result of the PHI.
376 Instruction *FoldPHIArgOpIntoPHI(PHINode &PN);
377 Instruction *FoldPHIArgBinOpIntoPHI(PHINode &PN);
Chris Lattner9e1916e2008-12-01 02:34:36 +0000378 Instruction *FoldPHIArgGEPIntoPHI(PHINode &PN);
379
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000380
381 Instruction *OptAndOp(Instruction *Op, ConstantInt *OpRHS,
382 ConstantInt *AndRHS, BinaryOperator &TheAnd);
383
384 Value *FoldLogicalPlusAnd(Value *LHS, Value *RHS, ConstantInt *Mask,
385 bool isSub, Instruction &I);
386 Instruction *InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
387 bool isSigned, bool Inside, Instruction &IB);
388 Instruction *PromoteCastOfAllocation(BitCastInst &CI, AllocationInst &AI);
389 Instruction *MatchBSwap(BinaryOperator &I);
390 bool SimplifyStoreAtEndOfBlock(StoreInst &SI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000391 Instruction *SimplifyMemTransfer(MemIntrinsic *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +0000392 Instruction *SimplifyMemSet(MemSetInst *MI);
Chris Lattner00ae5132008-01-13 23:50:23 +0000393
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000394
395 Value *EvaluateInDifferentType(Value *V, const Type *Ty, bool isSigned);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000396
Dan Gohman8fd520a2009-06-15 22:12:54 +0000397 bool CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +0000398 unsigned CastOpc, int &NumCastsRemoved);
Dan Gohman2d648bb2008-04-10 18:43:06 +0000399 unsigned GetOrEnforceKnownAlignment(Value *V,
400 unsigned PrefAlign = 0);
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +0000401
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000402 };
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000403}
404
Dan Gohman089efff2008-05-13 00:00:25 +0000405char InstCombiner::ID = 0;
406static RegisterPass<InstCombiner>
407X("instcombine", "Combine redundant instructions");
408
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000409// getComplexity: Assign a complexity or rank value to LLVM Values...
410// 0 -> undef, 1 -> Const, 2 -> Other, 3 -> Arg, 3 -> Unary, 4 -> OtherInst
411static unsigned getComplexity(Value *V) {
412 if (isa<Instruction>(V)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +0000413 if (BinaryOperator::isNeg(V) || BinaryOperator::isFNeg(V) ||
414 BinaryOperator::isNot(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000415 return 3;
416 return 4;
417 }
418 if (isa<Argument>(V)) return 3;
419 return isa<Constant>(V) ? (isa<UndefValue>(V) ? 0 : 1) : 2;
420}
421
422// isOnlyUse - Return true if this instruction will be deleted if we stop using
423// it.
424static bool isOnlyUse(Value *V) {
425 return V->hasOneUse() || isa<Constant>(V);
426}
427
428// getPromotedType - Return the specified type promoted as it would be to pass
429// though a va_arg area...
430static const Type *getPromotedType(const Type *Ty) {
431 if (const IntegerType* ITy = dyn_cast<IntegerType>(Ty)) {
432 if (ITy->getBitWidth() < 32)
433 return Type::Int32Ty;
434 }
435 return Ty;
436}
437
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000438/// getBitCastOperand - If the specified operand is a CastInst, a constant
439/// expression bitcast, or a GetElementPtrInst with all zero indices, return the
440/// operand value, otherwise return null.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000441static Value *getBitCastOperand(Value *V) {
442 if (BitCastInst *I = dyn_cast<BitCastInst>(V))
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000443 // BitCastInst?
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000444 return I->getOperand(0);
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000445 else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(V)) {
446 // GetElementPtrInst?
447 if (GEP->hasAllZeroIndices())
448 return GEP->getOperand(0);
449 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000450 if (CE->getOpcode() == Instruction::BitCast)
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000451 // BitCast ConstantExp?
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000452 return CE->getOperand(0);
Matthijs Kooijman5e2a3182008-10-13 15:17:01 +0000453 else if (CE->getOpcode() == Instruction::GetElementPtr) {
454 // GetElementPtr ConstantExp?
455 for (User::op_iterator I = CE->op_begin() + 1, E = CE->op_end();
456 I != E; ++I) {
457 ConstantInt *CI = dyn_cast<ConstantInt>(I);
458 if (!CI || !CI->isZero())
459 // Any non-zero indices? Not cast-like.
460 return 0;
461 }
462 // All-zero indices? This is just like casting.
463 return CE->getOperand(0);
464 }
465 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000466 return 0;
467}
468
469/// This function is a wrapper around CastInst::isEliminableCastPair. It
470/// simply extracts arguments and returns what that function returns.
471static Instruction::CastOps
472isEliminableCastPair(
473 const CastInst *CI, ///< The first cast instruction
474 unsigned opcode, ///< The opcode of the second cast instruction
475 const Type *DstTy, ///< The target type for the second cast instruction
476 TargetData *TD ///< The target data for pointer size
477) {
478
479 const Type *SrcTy = CI->getOperand(0)->getType(); // A from above
480 const Type *MidTy = CI->getType(); // B from above
481
482 // Get the opcodes of the two Cast instructions
483 Instruction::CastOps firstOp = Instruction::CastOps(CI->getOpcode());
484 Instruction::CastOps secondOp = Instruction::CastOps(opcode);
485
Chris Lattner3e10f8d2009-03-24 18:35:40 +0000486 unsigned Res = CastInst::isEliminableCastPair(firstOp, secondOp, SrcTy, MidTy,
487 DstTy, TD->getIntPtrType());
488
489 // We don't want to form an inttoptr or ptrtoint that converts to an integer
490 // type that differs from the pointer size.
491 if ((Res == Instruction::IntToPtr && SrcTy != TD->getIntPtrType()) ||
492 (Res == Instruction::PtrToInt && DstTy != TD->getIntPtrType()))
493 Res = 0;
494
495 return Instruction::CastOps(Res);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000496}
497
498/// ValueRequiresCast - Return true if the cast from "V to Ty" actually results
499/// in any code being generated. It does not require codegen if V is simple
500/// enough or if the cast can be folded into other casts.
501static bool ValueRequiresCast(Instruction::CastOps opcode, const Value *V,
502 const Type *Ty, TargetData *TD) {
503 if (V->getType() == Ty || isa<Constant>(V)) return false;
504
505 // If this is another cast that can be eliminated, it isn't codegen either.
506 if (const CastInst *CI = dyn_cast<CastInst>(V))
507 if (isEliminableCastPair(CI, opcode, Ty, TD))
508 return false;
509 return true;
510}
511
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000512// SimplifyCommutative - This performs a few simplifications for commutative
513// operators:
514//
515// 1. Order operands such that they are listed from right (least complex) to
516// left (most complex). This puts constants before unary operators before
517// binary operators.
518//
519// 2. Transform: (op (op V, C1), C2) ==> (op V, (op C1, C2))
520// 3. Transform: (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
521//
522bool InstCombiner::SimplifyCommutative(BinaryOperator &I) {
523 bool Changed = false;
524 if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1)))
525 Changed = !I.swapOperands();
526
527 if (!I.isAssociative()) return Changed;
528 Instruction::BinaryOps Opcode = I.getOpcode();
529 if (BinaryOperator *Op = dyn_cast<BinaryOperator>(I.getOperand(0)))
530 if (Op->getOpcode() == Opcode && isa<Constant>(Op->getOperand(1))) {
531 if (isa<Constant>(I.getOperand(1))) {
Owen Anderson24be4c12009-07-03 00:17:18 +0000532 Constant *Folded = Context->getConstantExpr(I.getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000533 cast<Constant>(I.getOperand(1)),
534 cast<Constant>(Op->getOperand(1)));
535 I.setOperand(0, Op->getOperand(0));
536 I.setOperand(1, Folded);
537 return true;
538 } else if (BinaryOperator *Op1=dyn_cast<BinaryOperator>(I.getOperand(1)))
539 if (Op1->getOpcode() == Opcode && isa<Constant>(Op1->getOperand(1)) &&
540 isOnlyUse(Op) && isOnlyUse(Op1)) {
541 Constant *C1 = cast<Constant>(Op->getOperand(1));
542 Constant *C2 = cast<Constant>(Op1->getOperand(1));
543
544 // Fold (op (op V1, C1), (op V2, C2)) ==> (op (op V1, V2), (op C1,C2))
Owen Anderson24be4c12009-07-03 00:17:18 +0000545 Constant *Folded = Context->getConstantExpr(I.getOpcode(), C1, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +0000546 Instruction *New = BinaryOperator::Create(Opcode, Op->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000547 Op1->getOperand(0),
548 Op1->getName(), &I);
549 AddToWorkList(New);
550 I.setOperand(0, New);
551 I.setOperand(1, Folded);
552 return true;
553 }
554 }
555 return Changed;
556}
557
558/// SimplifyCompare - For a CmpInst this function just orders the operands
559/// so that theyare listed from right (least complex) to left (most complex).
560/// This puts constants before unary operators before binary operators.
561bool InstCombiner::SimplifyCompare(CmpInst &I) {
562 if (getComplexity(I.getOperand(0)) >= getComplexity(I.getOperand(1)))
563 return false;
564 I.swapOperands();
565 // Compare instructions are not associative so there's nothing else we can do.
566 return true;
567}
568
569// dyn_castNegVal - Given a 'sub' instruction, return the RHS of the instruction
570// if the LHS is a constant zero (which is the 'negate' form).
571//
Owen Anderson5349f052009-07-06 23:00:19 +0000572static inline Value *dyn_castNegVal(Value *V, LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000573 if (BinaryOperator::isNeg(V))
574 return BinaryOperator::getNegArgument(V);
575
576 // Constants can be considered to be negated values if they can be folded.
577 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Anderson24be4c12009-07-03 00:17:18 +0000578 return Context->getConstantExprNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000579
580 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
581 if (C->getType()->getElementType()->isInteger())
Owen Anderson24be4c12009-07-03 00:17:18 +0000582 return Context->getConstantExprNeg(C);
Nick Lewycky58867bc2008-05-23 04:54:45 +0000583
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000584 return 0;
585}
586
Dan Gohman7ce405e2009-06-04 22:49:04 +0000587// dyn_castFNegVal - Given a 'fsub' instruction, return the RHS of the
588// instruction if the LHS is a constant negative zero (which is the 'negate'
589// form).
590//
Owen Anderson5349f052009-07-06 23:00:19 +0000591static inline Value *dyn_castFNegVal(Value *V, LLVMContext *Context) {
Dan Gohman7ce405e2009-06-04 22:49:04 +0000592 if (BinaryOperator::isFNeg(V))
593 return BinaryOperator::getFNegArgument(V);
594
595 // Constants can be considered to be negated values if they can be folded.
596 if (ConstantFP *C = dyn_cast<ConstantFP>(V))
Owen Anderson24be4c12009-07-03 00:17:18 +0000597 return Context->getConstantExprFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000598
599 if (ConstantVector *C = dyn_cast<ConstantVector>(V))
600 if (C->getType()->getElementType()->isFloatingPoint())
Owen Anderson24be4c12009-07-03 00:17:18 +0000601 return Context->getConstantExprFNeg(C);
Dan Gohman7ce405e2009-06-04 22:49:04 +0000602
603 return 0;
604}
605
Owen Anderson5349f052009-07-06 23:00:19 +0000606static inline Value *dyn_castNotVal(Value *V, LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000607 if (BinaryOperator::isNot(V))
608 return BinaryOperator::getNotArgument(V);
609
610 // Constants can be considered to be not'ed values...
611 if (ConstantInt *C = dyn_cast<ConstantInt>(V))
Owen Anderson24be4c12009-07-03 00:17:18 +0000612 return Context->getConstantInt(~C->getValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000613 return 0;
614}
615
616// dyn_castFoldableMul - If this value is a multiply that can be folded into
617// other computations (because it has a constant operand), return the
618// non-constant operand of the multiply, and set CST to point to the multiplier.
619// Otherwise, return null.
620//
Owen Anderson24be4c12009-07-03 00:17:18 +0000621static inline Value *dyn_castFoldableMul(Value *V, ConstantInt *&CST,
Owen Anderson5349f052009-07-06 23:00:19 +0000622 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000623 if (V->hasOneUse() && V->getType()->isInteger())
624 if (Instruction *I = dyn_cast<Instruction>(V)) {
625 if (I->getOpcode() == Instruction::Mul)
626 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1))))
627 return I->getOperand(0);
628 if (I->getOpcode() == Instruction::Shl)
629 if ((CST = dyn_cast<ConstantInt>(I->getOperand(1)))) {
630 // The multiplier is really 1 << CST.
631 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
632 uint32_t CSTVal = CST->getLimitedValue(BitWidth);
Owen Anderson24be4c12009-07-03 00:17:18 +0000633 CST = Context->getConstantInt(APInt(BitWidth, 1).shl(CSTVal));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000634 return I->getOperand(0);
635 }
636 }
637 return 0;
638}
639
640/// dyn_castGetElementPtr - If this is a getelementptr instruction or constant
641/// expression, return it.
642static User *dyn_castGetElementPtr(Value *V) {
643 if (isa<GetElementPtrInst>(V)) return cast<User>(V);
644 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
645 if (CE->getOpcode() == Instruction::GetElementPtr)
646 return cast<User>(V);
647 return false;
648}
649
Dan Gohman2d648bb2008-04-10 18:43:06 +0000650/// getOpcode - If this is an Instruction or a ConstantExpr, return the
651/// opcode value. Otherwise return UserOp1.
Dan Gohman8c397862008-05-29 19:53:46 +0000652static unsigned getOpcode(const Value *V) {
653 if (const Instruction *I = dyn_cast<Instruction>(V))
Dan Gohman2d648bb2008-04-10 18:43:06 +0000654 return I->getOpcode();
Dan Gohman8c397862008-05-29 19:53:46 +0000655 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
Dan Gohman2d648bb2008-04-10 18:43:06 +0000656 return CE->getOpcode();
657 // Use UserOp1 to mean there's no opcode.
658 return Instruction::UserOp1;
659}
660
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000661/// AddOne - Add one to a ConstantInt
Owen Anderson5349f052009-07-06 23:00:19 +0000662static Constant *AddOne(Constant *C, LLVMContext *Context) {
Owen Anderson24be4c12009-07-03 00:17:18 +0000663 return Context->getConstantExprAdd(C,
664 Context->getConstantInt(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000665}
666/// SubOne - Subtract one from a ConstantInt
Owen Anderson5349f052009-07-06 23:00:19 +0000667static Constant *SubOne(ConstantInt *C, LLVMContext *Context) {
Owen Anderson24be4c12009-07-03 00:17:18 +0000668 return Context->getConstantExprSub(C,
669 Context->getConstantInt(C->getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000670}
Nick Lewycky9d798f92008-02-18 22:48:05 +0000671/// MultiplyOverflows - True if the multiply can not be expressed in an int
672/// this size.
Owen Anderson24be4c12009-07-03 00:17:18 +0000673static bool MultiplyOverflows(ConstantInt *C1, ConstantInt *C2, bool sign,
Owen Anderson5349f052009-07-06 23:00:19 +0000674 LLVMContext *Context) {
Nick Lewycky9d798f92008-02-18 22:48:05 +0000675 uint32_t W = C1->getBitWidth();
676 APInt LHSExt = C1->getValue(), RHSExt = C2->getValue();
677 if (sign) {
678 LHSExt.sext(W * 2);
679 RHSExt.sext(W * 2);
680 } else {
681 LHSExt.zext(W * 2);
682 RHSExt.zext(W * 2);
683 }
684
685 APInt MulExt = LHSExt * RHSExt;
686
687 if (sign) {
688 APInt Min = APInt::getSignedMinValue(W).sext(W * 2);
689 APInt Max = APInt::getSignedMaxValue(W).sext(W * 2);
690 return MulExt.slt(Min) || MulExt.sgt(Max);
691 } else
692 return MulExt.ugt(APInt::getLowBitsSet(W * 2, W));
693}
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000694
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000695
696/// ShrinkDemandedConstant - Check to see if the specified operand of the
697/// specified instruction is a constant integer. If so, check to see if there
698/// are any bits set in the constant that are not demanded. If so, shrink the
699/// constant and return true.
700static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
Owen Anderson5349f052009-07-06 23:00:19 +0000701 APInt Demanded, LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000702 assert(I && "No instruction?");
703 assert(OpNo < I->getNumOperands() && "Operand index too large");
704
705 // If the operand is not a constant integer, nothing to do.
706 ConstantInt *OpC = dyn_cast<ConstantInt>(I->getOperand(OpNo));
707 if (!OpC) return false;
708
709 // If there are no bits set that aren't demanded, nothing to do.
710 Demanded.zextOrTrunc(OpC->getValue().getBitWidth());
711 if ((~Demanded & OpC->getValue()) == 0)
712 return false;
713
714 // This instruction is producing bits that are not demanded. Shrink the RHS.
715 Demanded &= OpC->getValue();
Owen Anderson24be4c12009-07-03 00:17:18 +0000716 I->setOperand(OpNo, Context->getConstantInt(Demanded));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000717 return true;
718}
719
720// ComputeSignedMinMaxValuesFromKnownBits - Given a signed integer type and a
721// set of known zero and one bits, compute the maximum and minimum values that
722// could have the specified known zero and known one bits, returning them in
723// min/max.
Dan Gohman7934d592009-04-25 17:12:48 +0000724static void ComputeSignedMinMaxValuesFromKnownBits(const APInt& KnownZero,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000725 const APInt& KnownOne,
726 APInt& Min, APInt& Max) {
Dan Gohman7934d592009-04-25 17:12:48 +0000727 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
728 KnownZero.getBitWidth() == Min.getBitWidth() &&
729 KnownZero.getBitWidth() == Max.getBitWidth() &&
730 "KnownZero, KnownOne and Min, Max must have equal bitwidth.");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000731 APInt UnknownBits = ~(KnownZero|KnownOne);
732
733 // The minimum value is when all unknown bits are zeros, EXCEPT for the sign
734 // bit if it is unknown.
735 Min = KnownOne;
736 Max = KnownOne|UnknownBits;
737
Dan Gohman7934d592009-04-25 17:12:48 +0000738 if (UnknownBits.isNegative()) { // Sign bit is unknown
739 Min.set(Min.getBitWidth()-1);
740 Max.clear(Max.getBitWidth()-1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000741 }
742}
743
744// ComputeUnsignedMinMaxValuesFromKnownBits - Given an unsigned integer type and
745// a set of known zero and one bits, compute the maximum and minimum values that
746// could have the specified known zero and known one bits, returning them in
747// min/max.
Dan Gohman7934d592009-04-25 17:12:48 +0000748static void ComputeUnsignedMinMaxValuesFromKnownBits(const APInt &KnownZero,
Chris Lattnerb933ea62007-08-05 08:47:58 +0000749 const APInt &KnownOne,
750 APInt &Min, APInt &Max) {
Dan Gohman7934d592009-04-25 17:12:48 +0000751 assert(KnownZero.getBitWidth() == KnownOne.getBitWidth() &&
752 KnownZero.getBitWidth() == Min.getBitWidth() &&
753 KnownZero.getBitWidth() == Max.getBitWidth() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000754 "Ty, KnownZero, KnownOne and Min, Max must have equal bitwidth.");
755 APInt UnknownBits = ~(KnownZero|KnownOne);
756
757 // The minimum value is when the unknown bits are all zeros.
758 Min = KnownOne;
759 // The maximum value is when the unknown bits are all ones.
760 Max = KnownOne|UnknownBits;
761}
762
Chris Lattner676c78e2009-01-31 08:15:18 +0000763/// SimplifyDemandedInstructionBits - Inst is an integer instruction that
764/// SimplifyDemandedBits knows about. See if the instruction has any
765/// properties that allow us to simplify its operands.
766bool InstCombiner::SimplifyDemandedInstructionBits(Instruction &Inst) {
Dan Gohman8fd520a2009-06-15 22:12:54 +0000767 unsigned BitWidth = Inst.getType()->getScalarSizeInBits();
Chris Lattner676c78e2009-01-31 08:15:18 +0000768 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
769 APInt DemandedMask(APInt::getAllOnesValue(BitWidth));
770
771 Value *V = SimplifyDemandedUseBits(&Inst, DemandedMask,
772 KnownZero, KnownOne, 0);
773 if (V == 0) return false;
774 if (V == &Inst) return true;
775 ReplaceInstUsesWith(Inst, V);
776 return true;
777}
778
779/// SimplifyDemandedBits - This form of SimplifyDemandedBits simplifies the
780/// specified instruction operand if possible, updating it in place. It returns
781/// true if it made any change and false otherwise.
782bool InstCombiner::SimplifyDemandedBits(Use &U, APInt DemandedMask,
783 APInt &KnownZero, APInt &KnownOne,
784 unsigned Depth) {
785 Value *NewVal = SimplifyDemandedUseBits(U.get(), DemandedMask,
786 KnownZero, KnownOne, Depth);
787 if (NewVal == 0) return false;
788 U.set(NewVal);
789 return true;
790}
791
792
793/// SimplifyDemandedUseBits - This function attempts to replace V with a simpler
794/// value based on the demanded bits. When this function is called, it is known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000795/// that only the bits set in DemandedMask of the result of V are ever used
796/// downstream. Consequently, depending on the mask and V, it may be possible
797/// to replace V with a constant or one of its operands. In such cases, this
798/// function does the replacement and returns true. In all other cases, it
799/// returns false after analyzing the expression and setting KnownOne and known
Chris Lattner676c78e2009-01-31 08:15:18 +0000800/// to be one in the expression. KnownZero contains all the bits that are known
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000801/// to be zero in the expression. These are provided to potentially allow the
802/// caller (which might recursively be SimplifyDemandedBits itself) to simplify
803/// the expression. KnownOne and KnownZero always follow the invariant that
804/// KnownOne & KnownZero == 0. That is, a bit can't be both 1 and 0. Note that
805/// the bits in KnownOne and KnownZero may only be accurate for those bits set
806/// in DemandedMask. Note also that the bitwidth of V, DemandedMask, KnownZero
807/// and KnownOne must all be the same.
Chris Lattner676c78e2009-01-31 08:15:18 +0000808///
809/// This returns null if it did not change anything and it permits no
810/// simplification. This returns V itself if it did some simplification of V's
811/// operands based on the information about what bits are demanded. This returns
812/// some other non-null value if it found out that V is equal to another value
813/// in the context where the specified bits are demanded, but not for all users.
814Value *InstCombiner::SimplifyDemandedUseBits(Value *V, APInt DemandedMask,
815 APInt &KnownZero, APInt &KnownOne,
816 unsigned Depth) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000817 assert(V != 0 && "Null pointer of Value???");
818 assert(Depth <= 6 && "Limit Search Depth");
819 uint32_t BitWidth = DemandedMask.getBitWidth();
Dan Gohman7934d592009-04-25 17:12:48 +0000820 const Type *VTy = V->getType();
821 assert((TD || !isa<PointerType>(VTy)) &&
822 "SimplifyDemandedBits needs to know bit widths!");
Dan Gohman8fd520a2009-06-15 22:12:54 +0000823 assert((!TD || TD->getTypeSizeInBits(VTy->getScalarType()) == BitWidth) &&
824 (!VTy->isIntOrIntVector() ||
825 VTy->getScalarSizeInBits() == BitWidth) &&
Dan Gohman7934d592009-04-25 17:12:48 +0000826 KnownZero.getBitWidth() == BitWidth &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000827 KnownOne.getBitWidth() == BitWidth &&
Dan Gohman8fd520a2009-06-15 22:12:54 +0000828 "Value *V, DemandedMask, KnownZero and KnownOne "
829 "must have same BitWidth");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000830 if (ConstantInt *CI = dyn_cast<ConstantInt>(V)) {
831 // We know all of the bits for a constant!
832 KnownOne = CI->getValue() & DemandedMask;
833 KnownZero = ~KnownOne & DemandedMask;
Chris Lattner676c78e2009-01-31 08:15:18 +0000834 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000835 }
Dan Gohman7934d592009-04-25 17:12:48 +0000836 if (isa<ConstantPointerNull>(V)) {
837 // We know all of the bits for a constant!
838 KnownOne.clear();
839 KnownZero = DemandedMask;
840 return 0;
841 }
842
Chris Lattnerc5d7e4e2009-01-31 07:26:06 +0000843 KnownZero.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000844 KnownOne.clear();
Chris Lattner676c78e2009-01-31 08:15:18 +0000845 if (DemandedMask == 0) { // Not demanding any bits from V.
846 if (isa<UndefValue>(V))
847 return 0;
Owen Anderson24be4c12009-07-03 00:17:18 +0000848 return Context->getUndef(VTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000849 }
850
Chris Lattner08817332009-01-31 08:24:16 +0000851 if (Depth == 6) // Limit search depth.
852 return 0;
853
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000854 APInt LHSKnownZero(BitWidth, 0), LHSKnownOne(BitWidth, 0);
855 APInt &RHSKnownZero = KnownZero, &RHSKnownOne = KnownOne;
856
Dan Gohman7934d592009-04-25 17:12:48 +0000857 Instruction *I = dyn_cast<Instruction>(V);
858 if (!I) {
859 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
860 return 0; // Only analyze instructions.
861 }
862
Chris Lattner08817332009-01-31 08:24:16 +0000863 // If there are multiple uses of this value and we aren't at the root, then
864 // we can't do any simplifications of the operands, because DemandedMask
865 // only reflects the bits demanded by *one* of the users.
866 if (Depth != 0 && !I->hasOneUse()) {
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000867 // Despite the fact that we can't simplify this instruction in all User's
868 // context, we can at least compute the knownzero/knownone bits, and we can
869 // do simplifications that apply to *just* the one user if we know that
870 // this instruction has a simpler value in that context.
871 if (I->getOpcode() == Instruction::And) {
872 // If either the LHS or the RHS are Zero, the result is zero.
873 ComputeMaskedBits(I->getOperand(1), DemandedMask,
874 RHSKnownZero, RHSKnownOne, Depth+1);
875 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownZero,
876 LHSKnownZero, LHSKnownOne, Depth+1);
877
878 // If all of the demanded bits are known 1 on one side, return the other.
879 // These bits cannot contribute to the result of the 'and' in this
880 // context.
881 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
882 (DemandedMask & ~LHSKnownZero))
883 return I->getOperand(0);
884 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
885 (DemandedMask & ~RHSKnownZero))
886 return I->getOperand(1);
887
888 // If all of the demanded bits in the inputs are known zeros, return zero.
889 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Anderson24be4c12009-07-03 00:17:18 +0000890 return Context->getNullValue(VTy);
Chris Lattnercd8d44c2009-01-31 08:40:03 +0000891
892 } else if (I->getOpcode() == Instruction::Or) {
893 // We can simplify (X|Y) -> X or Y in the user's context if we know that
894 // only bits from X or Y are demanded.
895
896 // If either the LHS or the RHS are One, the result is One.
897 ComputeMaskedBits(I->getOperand(1), DemandedMask,
898 RHSKnownZero, RHSKnownOne, Depth+1);
899 ComputeMaskedBits(I->getOperand(0), DemandedMask & ~RHSKnownOne,
900 LHSKnownZero, LHSKnownOne, Depth+1);
901
902 // If all of the demanded bits are known zero on one side, return the
903 // other. These bits cannot contribute to the result of the 'or' in this
904 // context.
905 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
906 (DemandedMask & ~LHSKnownOne))
907 return I->getOperand(0);
908 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
909 (DemandedMask & ~RHSKnownOne))
910 return I->getOperand(1);
911
912 // If all of the potentially set bits on one side are known to be set on
913 // the other side, just use the 'other' side.
914 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
915 (DemandedMask & (~RHSKnownZero)))
916 return I->getOperand(0);
917 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
918 (DemandedMask & (~LHSKnownZero)))
919 return I->getOperand(1);
920 }
921
Chris Lattner08817332009-01-31 08:24:16 +0000922 // Compute the KnownZero/KnownOne bits to simplify things downstream.
923 ComputeMaskedBits(I, DemandedMask, KnownZero, KnownOne, Depth);
924 return 0;
925 }
926
927 // If this is the root being simplified, allow it to have multiple uses,
928 // just set the DemandedMask to all bits so that we can try to simplify the
929 // operands. This allows visitTruncInst (for example) to simplify the
930 // operand of a trunc without duplicating all the logic below.
931 if (Depth == 0 && !V->hasOneUse())
932 DemandedMask = APInt::getAllOnesValue(BitWidth);
933
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000934 switch (I->getOpcode()) {
Dan Gohmanbec16052008-04-28 17:02:21 +0000935 default:
Chris Lattner676c78e2009-01-31 08:15:18 +0000936 ComputeMaskedBits(I, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanbec16052008-04-28 17:02:21 +0000937 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000938 case Instruction::And:
939 // If either the LHS or the RHS are Zero, the result is zero.
Chris Lattner676c78e2009-01-31 08:15:18 +0000940 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
941 RHSKnownZero, RHSKnownOne, Depth+1) ||
942 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownZero,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000943 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000944 return I;
945 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
946 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000947
948 // If all of the demanded bits are known 1 on one side, return the other.
949 // These bits cannot contribute to the result of the 'and'.
950 if ((DemandedMask & ~LHSKnownZero & RHSKnownOne) ==
951 (DemandedMask & ~LHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000952 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000953 if ((DemandedMask & ~RHSKnownZero & LHSKnownOne) ==
954 (DemandedMask & ~RHSKnownZero))
Chris Lattner676c78e2009-01-31 08:15:18 +0000955 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000956
957 // If all of the demanded bits in the inputs are known zeros, return zero.
958 if ((DemandedMask & (RHSKnownZero|LHSKnownZero)) == DemandedMask)
Owen Anderson24be4c12009-07-03 00:17:18 +0000959 return Context->getNullValue(VTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000960
961 // If the RHS is a constant, see if we can simplify it.
Owen Anderson24be4c12009-07-03 00:17:18 +0000962 if (ShrinkDemandedConstant(I, 1, DemandedMask & ~LHSKnownZero, Context))
Chris Lattner676c78e2009-01-31 08:15:18 +0000963 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000964
965 // Output known-1 bits are only known if set in both the LHS & RHS.
966 RHSKnownOne &= LHSKnownOne;
967 // Output known-0 are known to be clear if zero in either the LHS | RHS.
968 RHSKnownZero |= LHSKnownZero;
969 break;
970 case Instruction::Or:
971 // If either the LHS or the RHS are One, the result is One.
Chris Lattner676c78e2009-01-31 08:15:18 +0000972 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
973 RHSKnownZero, RHSKnownOne, Depth+1) ||
974 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask & ~RHSKnownOne,
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000975 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +0000976 return I;
977 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
978 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000979
980 // If all of the demanded bits are known zero on one side, return the other.
981 // These bits cannot contribute to the result of the 'or'.
982 if ((DemandedMask & ~LHSKnownOne & RHSKnownZero) ==
983 (DemandedMask & ~LHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +0000984 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000985 if ((DemandedMask & ~RHSKnownOne & LHSKnownZero) ==
986 (DemandedMask & ~RHSKnownOne))
Chris Lattner676c78e2009-01-31 08:15:18 +0000987 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000988
989 // If all of the potentially set bits on one side are known to be set on
990 // the other side, just use the 'other' side.
991 if ((DemandedMask & (~RHSKnownZero) & LHSKnownOne) ==
992 (DemandedMask & (~RHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +0000993 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000994 if ((DemandedMask & (~LHSKnownZero) & RHSKnownOne) ==
995 (DemandedMask & (~LHSKnownZero)))
Chris Lattner676c78e2009-01-31 08:15:18 +0000996 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000997
998 // If the RHS is a constant, see if we can simplify it.
Owen Anderson24be4c12009-07-03 00:17:18 +0000999 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
Chris Lattner676c78e2009-01-31 08:15:18 +00001000 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001001
1002 // Output known-0 bits are only known if clear in both the LHS & RHS.
1003 RHSKnownZero &= LHSKnownZero;
1004 // Output known-1 are known to be set if set in either the LHS | RHS.
1005 RHSKnownOne |= LHSKnownOne;
1006 break;
1007 case Instruction::Xor: {
Chris Lattner676c78e2009-01-31 08:15:18 +00001008 if (SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
1009 RHSKnownZero, RHSKnownOne, Depth+1) ||
1010 SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001011 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001012 return I;
1013 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1014 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001015
1016 // If all of the demanded bits are known zero on one side, return the other.
1017 // These bits cannot contribute to the result of the 'xor'.
1018 if ((DemandedMask & RHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +00001019 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001020 if ((DemandedMask & LHSKnownZero) == DemandedMask)
Chris Lattner676c78e2009-01-31 08:15:18 +00001021 return I->getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001022
1023 // Output known-0 bits are known if clear or set in both the LHS & RHS.
1024 APInt KnownZeroOut = (RHSKnownZero & LHSKnownZero) |
1025 (RHSKnownOne & LHSKnownOne);
1026 // Output known-1 are known to be set if set in only one of the LHS, RHS.
1027 APInt KnownOneOut = (RHSKnownZero & LHSKnownOne) |
1028 (RHSKnownOne & LHSKnownZero);
1029
1030 // If all of the demanded bits are known to be zero on one side or the
1031 // other, turn this into an *inclusive* or.
1032 // e.g. (A & C1)^(B & C2) -> (A & C1)|(B & C2) iff C1&C2 == 0
1033 if ((DemandedMask & ~RHSKnownZero & ~LHSKnownZero) == 0) {
1034 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001035 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001036 I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001037 return InsertNewInstBefore(Or, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001038 }
1039
1040 // If all of the demanded bits on one side are known, and all of the set
1041 // bits on that side are also known to be set on the other side, turn this
1042 // into an AND, as we know the bits will be cleared.
1043 // e.g. (X | C1) ^ C2 --> (X | C1) & ~C2 iff (C1&C2) == C2
1044 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
1045 // all known
1046 if ((RHSKnownOne & LHSKnownOne) == RHSKnownOne) {
Owen Anderson24be4c12009-07-03 00:17:18 +00001047 Constant *AndC = Context->getConstantInt(~RHSKnownOne & DemandedMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001048 Instruction *And =
Gabor Greifa645dd32008-05-16 19:29:10 +00001049 BinaryOperator::CreateAnd(I->getOperand(0), AndC, "tmp");
Chris Lattner676c78e2009-01-31 08:15:18 +00001050 return InsertNewInstBefore(And, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001051 }
1052 }
1053
1054 // If the RHS is a constant, see if we can simplify it.
1055 // FIXME: for XOR, we prefer to force bits to 1 if they will make a -1.
Owen Anderson24be4c12009-07-03 00:17:18 +00001056 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context))
Chris Lattner676c78e2009-01-31 08:15:18 +00001057 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001058
1059 RHSKnownZero = KnownZeroOut;
1060 RHSKnownOne = KnownOneOut;
1061 break;
1062 }
1063 case Instruction::Select:
Chris Lattner676c78e2009-01-31 08:15:18 +00001064 if (SimplifyDemandedBits(I->getOperandUse(2), DemandedMask,
1065 RHSKnownZero, RHSKnownOne, Depth+1) ||
1066 SimplifyDemandedBits(I->getOperandUse(1), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001067 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001068 return I;
1069 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
1070 assert(!(LHSKnownZero & LHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001071
1072 // If the operands are constants, see if we can simplify them.
Owen Anderson24be4c12009-07-03 00:17:18 +00001073 if (ShrinkDemandedConstant(I, 1, DemandedMask, Context) ||
1074 ShrinkDemandedConstant(I, 2, DemandedMask, Context))
Chris Lattner676c78e2009-01-31 08:15:18 +00001075 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001076
1077 // Only known if known in both the LHS and RHS.
1078 RHSKnownOne &= LHSKnownOne;
1079 RHSKnownZero &= LHSKnownZero;
1080 break;
1081 case Instruction::Trunc: {
Dan Gohman8fd520a2009-06-15 22:12:54 +00001082 unsigned truncBf = I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001083 DemandedMask.zext(truncBf);
1084 RHSKnownZero.zext(truncBf);
1085 RHSKnownOne.zext(truncBf);
Chris Lattner676c78e2009-01-31 08:15:18 +00001086 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001087 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001088 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001089 DemandedMask.trunc(BitWidth);
1090 RHSKnownZero.trunc(BitWidth);
1091 RHSKnownOne.trunc(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001092 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001093 break;
1094 }
1095 case Instruction::BitCast:
Dan Gohman72d5fbb2009-07-01 21:38:46 +00001096 if (!I->getOperand(0)->getType()->isIntOrIntVector())
Chris Lattner676c78e2009-01-31 08:15:18 +00001097 return false; // vector->int or fp->int?
Dan Gohman72d5fbb2009-07-01 21:38:46 +00001098
1099 if (const VectorType *DstVTy = dyn_cast<VectorType>(I->getType())) {
1100 if (const VectorType *SrcVTy =
1101 dyn_cast<VectorType>(I->getOperand(0)->getType())) {
1102 if (DstVTy->getNumElements() != SrcVTy->getNumElements())
1103 // Don't touch a bitcast between vectors of different element counts.
1104 return false;
1105 } else
1106 // Don't touch a scalar-to-vector bitcast.
1107 return false;
1108 } else if (isa<VectorType>(I->getOperand(0)->getType()))
1109 // Don't touch a vector-to-scalar bitcast.
1110 return false;
1111
Chris Lattner676c78e2009-01-31 08:15:18 +00001112 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001113 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001114 return I;
1115 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001116 break;
1117 case Instruction::ZExt: {
1118 // Compute the bits in the result that are not present in the input.
Dan Gohman8fd520a2009-06-15 22:12:54 +00001119 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001120
1121 DemandedMask.trunc(SrcBitWidth);
1122 RHSKnownZero.trunc(SrcBitWidth);
1123 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001124 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMask,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001125 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001126 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001127 DemandedMask.zext(BitWidth);
1128 RHSKnownZero.zext(BitWidth);
1129 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001130 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001131 // The top bits are known to be zero.
1132 RHSKnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth);
1133 break;
1134 }
1135 case Instruction::SExt: {
1136 // Compute the bits in the result that are not present in the input.
Dan Gohman8fd520a2009-06-15 22:12:54 +00001137 unsigned SrcBitWidth =I->getOperand(0)->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001138
1139 APInt InputDemandedBits = DemandedMask &
1140 APInt::getLowBitsSet(BitWidth, SrcBitWidth);
1141
1142 APInt NewBits(APInt::getHighBitsSet(BitWidth, BitWidth - SrcBitWidth));
1143 // If any of the sign extended bits are demanded, we know that the sign
1144 // bit is demanded.
1145 if ((NewBits & DemandedMask) != 0)
1146 InputDemandedBits.set(SrcBitWidth-1);
1147
1148 InputDemandedBits.trunc(SrcBitWidth);
1149 RHSKnownZero.trunc(SrcBitWidth);
1150 RHSKnownOne.trunc(SrcBitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001151 if (SimplifyDemandedBits(I->getOperandUse(0), InputDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001152 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001153 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001154 InputDemandedBits.zext(BitWidth);
1155 RHSKnownZero.zext(BitWidth);
1156 RHSKnownOne.zext(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001157 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001158
1159 // If the sign bit of the input is known set or clear, then we know the
1160 // top bits of the result.
1161
1162 // If the input sign bit is known zero, or if the NewBits are not demanded
1163 // convert this into a zero extension.
Chris Lattner676c78e2009-01-31 08:15:18 +00001164 if (RHSKnownZero[SrcBitWidth-1] || (NewBits & ~DemandedMask) == NewBits) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001165 // Convert to ZExt cast
Chris Lattner676c78e2009-01-31 08:15:18 +00001166 CastInst *NewCast = new ZExtInst(I->getOperand(0), VTy, I->getName());
1167 return InsertNewInstBefore(NewCast, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001168 } else if (RHSKnownOne[SrcBitWidth-1]) { // Input sign bit known set
1169 RHSKnownOne |= NewBits;
1170 }
1171 break;
1172 }
1173 case Instruction::Add: {
1174 // Figure out what the input bits are. If the top bits of the and result
1175 // are not demanded, then the add doesn't demand them from its input
1176 // either.
Chris Lattner676c78e2009-01-31 08:15:18 +00001177 unsigned NLZ = DemandedMask.countLeadingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001178
1179 // If there is a constant on the RHS, there are a variety of xformations
1180 // we can do.
1181 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
1182 // If null, this should be simplified elsewhere. Some of the xforms here
1183 // won't work if the RHS is zero.
1184 if (RHS->isZero())
1185 break;
1186
1187 // If the top bit of the output is demanded, demand everything from the
1188 // input. Otherwise, we demand all the input bits except NLZ top bits.
1189 APInt InDemandedBits(APInt::getLowBitsSet(BitWidth, BitWidth - NLZ));
1190
1191 // Find information about known zero/one bits in the input.
Chris Lattner676c78e2009-01-31 08:15:18 +00001192 if (SimplifyDemandedBits(I->getOperandUse(0), InDemandedBits,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001193 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001194 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001195
1196 // If the RHS of the add has bits set that can't affect the input, reduce
1197 // the constant.
Owen Anderson24be4c12009-07-03 00:17:18 +00001198 if (ShrinkDemandedConstant(I, 1, InDemandedBits, Context))
Chris Lattner676c78e2009-01-31 08:15:18 +00001199 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001200
1201 // Avoid excess work.
1202 if (LHSKnownZero == 0 && LHSKnownOne == 0)
1203 break;
1204
1205 // Turn it into OR if input bits are zero.
1206 if ((LHSKnownZero & RHS->getValue()) == RHS->getValue()) {
1207 Instruction *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00001208 BinaryOperator::CreateOr(I->getOperand(0), I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001209 I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001210 return InsertNewInstBefore(Or, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001211 }
1212
1213 // We can say something about the output known-zero and known-one bits,
1214 // depending on potential carries from the input constant and the
1215 // unknowns. For example if the LHS is known to have at most the 0x0F0F0
1216 // bits set and the RHS constant is 0x01001, then we know we have a known
1217 // one mask of 0x00001 and a known zero mask of 0xE0F0E.
1218
1219 // To compute this, we first compute the potential carry bits. These are
1220 // the bits which may be modified. I'm not aware of a better way to do
1221 // this scan.
Chris Lattner676c78e2009-01-31 08:15:18 +00001222 const APInt &RHSVal = RHS->getValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001223 APInt CarryBits((~LHSKnownZero + RHSVal) ^ (~LHSKnownZero ^ RHSVal));
1224
1225 // Now that we know which bits have carries, compute the known-1/0 sets.
1226
1227 // Bits are known one if they are known zero in one operand and one in the
1228 // other, and there is no input carry.
1229 RHSKnownOne = ((LHSKnownZero & RHSVal) |
1230 (LHSKnownOne & ~RHSVal)) & ~CarryBits;
1231
1232 // Bits are known zero if they are known zero in both operands and there
1233 // is no input carry.
1234 RHSKnownZero = LHSKnownZero & ~RHSVal & ~CarryBits;
1235 } else {
1236 // If the high-bits of this ADD are not demanded, then it does not demand
1237 // the high bits of its LHS or RHS.
1238 if (DemandedMask[BitWidth-1] == 0) {
1239 // Right fill the mask of bits for this ADD to demand the most
1240 // significant bit and all those below it.
1241 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001242 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1243 LHSKnownZero, LHSKnownOne, Depth+1) ||
1244 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001245 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001246 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001247 }
1248 }
1249 break;
1250 }
1251 case Instruction::Sub:
1252 // If the high-bits of this SUB are not demanded, then it does not demand
1253 // the high bits of its LHS or RHS.
1254 if (DemandedMask[BitWidth-1] == 0) {
1255 // Right fill the mask of bits for this SUB to demand the most
1256 // significant bit and all those below it.
1257 uint32_t NLZ = DemandedMask.countLeadingZeros();
1258 APInt DemandedFromOps(APInt::getLowBitsSet(BitWidth, BitWidth-NLZ));
Chris Lattner676c78e2009-01-31 08:15:18 +00001259 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedFromOps,
1260 LHSKnownZero, LHSKnownOne, Depth+1) ||
1261 SimplifyDemandedBits(I->getOperandUse(1), DemandedFromOps,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001262 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001263 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001264 }
Dan Gohmanbec16052008-04-28 17:02:21 +00001265 // Otherwise just hand the sub off to ComputeMaskedBits to fill in
1266 // the known zeros and ones.
1267 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001268 break;
1269 case Instruction::Shl:
1270 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1271 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1272 APInt DemandedMaskIn(DemandedMask.lshr(ShiftAmt));
Chris Lattner676c78e2009-01-31 08:15:18 +00001273 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001274 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001275 return I;
1276 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001277 RHSKnownZero <<= ShiftAmt;
1278 RHSKnownOne <<= ShiftAmt;
1279 // low bits known zero.
1280 if (ShiftAmt)
1281 RHSKnownZero |= APInt::getLowBitsSet(BitWidth, ShiftAmt);
1282 }
1283 break;
1284 case Instruction::LShr:
1285 // For a logical shift right
1286 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1287 uint64_t ShiftAmt = SA->getLimitedValue(BitWidth);
1288
1289 // Unsigned shift right.
1290 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
Chris Lattner676c78e2009-01-31 08:15:18 +00001291 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001292 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001293 return I;
1294 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001295 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1296 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1297 if (ShiftAmt) {
1298 // Compute the new bits that are at the top now.
1299 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1300 RHSKnownZero |= HighBits; // high bits known zero.
1301 }
1302 }
1303 break;
1304 case Instruction::AShr:
1305 // If this is an arithmetic shift right and only the low-bit is set, we can
1306 // always convert this into a logical shr, even if the shift amount is
1307 // variable. The low bit of the shift cannot be an input sign bit unless
1308 // the shift amount is >= the size of the datatype, which is undefined.
1309 if (DemandedMask == 1) {
1310 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001311 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001312 I->getOperand(0), I->getOperand(1), I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001313 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001314 }
1315
1316 // If the sign bit is the only bit demanded by this ashr, then there is no
1317 // need to do it, the shift doesn't change the high bit.
1318 if (DemandedMask.isSignBit())
Chris Lattner676c78e2009-01-31 08:15:18 +00001319 return I->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001320
1321 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1322 uint32_t ShiftAmt = SA->getLimitedValue(BitWidth);
1323
1324 // Signed shift right.
1325 APInt DemandedMaskIn(DemandedMask.shl(ShiftAmt));
1326 // If any of the "high bits" are demanded, we should set the sign bit as
1327 // demanded.
1328 if (DemandedMask.countLeadingZeros() <= ShiftAmt)
1329 DemandedMaskIn.set(BitWidth-1);
Chris Lattner676c78e2009-01-31 08:15:18 +00001330 if (SimplifyDemandedBits(I->getOperandUse(0), DemandedMaskIn,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001331 RHSKnownZero, RHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001332 return I;
1333 assert(!(RHSKnownZero & RHSKnownOne) && "Bits known to be one AND zero?");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001334 // Compute the new bits that are at the top now.
1335 APInt HighBits(APInt::getHighBitsSet(BitWidth, ShiftAmt));
1336 RHSKnownZero = APIntOps::lshr(RHSKnownZero, ShiftAmt);
1337 RHSKnownOne = APIntOps::lshr(RHSKnownOne, ShiftAmt);
1338
1339 // Handle the sign bits.
1340 APInt SignBit(APInt::getSignBit(BitWidth));
1341 // Adjust to where it is now in the mask.
1342 SignBit = APIntOps::lshr(SignBit, ShiftAmt);
1343
1344 // If the input sign bit is known to be zero, or if none of the top bits
1345 // are demanded, turn this into an unsigned shift right.
Zhou Sheng533604e2008-06-06 08:32:05 +00001346 if (BitWidth <= ShiftAmt || RHSKnownZero[BitWidth-ShiftAmt-1] ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001347 (HighBits & ~DemandedMask) == HighBits) {
1348 // Perform the logical shift right.
Chris Lattner676c78e2009-01-31 08:15:18 +00001349 Instruction *NewVal = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001350 I->getOperand(0), SA, I->getName());
Chris Lattner676c78e2009-01-31 08:15:18 +00001351 return InsertNewInstBefore(NewVal, *I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001352 } else if ((RHSKnownOne & SignBit) != 0) { // New bits are known one.
1353 RHSKnownOne |= HighBits;
1354 }
1355 }
1356 break;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001357 case Instruction::SRem:
1358 if (ConstantInt *Rem = dyn_cast<ConstantInt>(I->getOperand(1))) {
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001359 APInt RA = Rem->getValue().abs();
1360 if (RA.isPowerOf2()) {
Eli Friedman579c5722009-06-17 02:57:36 +00001361 if (DemandedMask.ult(RA)) // srem won't affect demanded bits
Chris Lattner676c78e2009-01-31 08:15:18 +00001362 return I->getOperand(0);
Nick Lewycky245de422008-07-12 05:04:38 +00001363
Nick Lewyckycfaaece2008-11-02 02:41:50 +00001364 APInt LowBits = RA - 1;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001365 APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001366 if (SimplifyDemandedBits(I->getOperandUse(0), Mask2,
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001367 LHSKnownZero, LHSKnownOne, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001368 return I;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001369
1370 if (LHSKnownZero[BitWidth-1] || ((LHSKnownZero & LowBits) == LowBits))
1371 LHSKnownZero |= ~LowBits;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001372
1373 KnownZero |= LHSKnownZero & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001374
Chris Lattner676c78e2009-01-31 08:15:18 +00001375 assert(!(KnownZero & KnownOne) && "Bits known to be one AND zero?");
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001376 }
1377 }
1378 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001379 case Instruction::URem: {
Dan Gohmanbec16052008-04-28 17:02:21 +00001380 APInt KnownZero2(BitWidth, 0), KnownOne2(BitWidth, 0);
1381 APInt AllOnes = APInt::getAllOnesValue(BitWidth);
Chris Lattner676c78e2009-01-31 08:15:18 +00001382 if (SimplifyDemandedBits(I->getOperandUse(0), AllOnes,
1383 KnownZero2, KnownOne2, Depth+1) ||
1384 SimplifyDemandedBits(I->getOperandUse(1), AllOnes,
Dan Gohman23ea06d2008-05-01 19:13:24 +00001385 KnownZero2, KnownOne2, Depth+1))
Chris Lattner676c78e2009-01-31 08:15:18 +00001386 return I;
Dan Gohman23ea06d2008-05-01 19:13:24 +00001387
Chris Lattneree5417c2009-01-21 18:09:24 +00001388 unsigned Leaders = KnownZero2.countLeadingOnes();
Dan Gohmanbec16052008-04-28 17:02:21 +00001389 Leaders = std::max(Leaders,
1390 KnownZero2.countLeadingOnes());
1391 KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & DemandedMask;
Nick Lewyckyc1372c82008-03-06 06:48:30 +00001392 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001393 }
Chris Lattner989ba312008-06-18 04:33:20 +00001394 case Instruction::Call:
1395 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
1396 switch (II->getIntrinsicID()) {
1397 default: break;
1398 case Intrinsic::bswap: {
1399 // If the only bits demanded come from one byte of the bswap result,
1400 // just shift the input byte into position to eliminate the bswap.
1401 unsigned NLZ = DemandedMask.countLeadingZeros();
1402 unsigned NTZ = DemandedMask.countTrailingZeros();
1403
1404 // Round NTZ down to the next byte. If we have 11 trailing zeros, then
1405 // we need all the bits down to bit 8. Likewise, round NLZ. If we
1406 // have 14 leading zeros, round to 8.
1407 NLZ &= ~7;
1408 NTZ &= ~7;
1409 // If we need exactly one byte, we can do this transformation.
1410 if (BitWidth-NLZ-NTZ == 8) {
1411 unsigned ResultBit = NTZ;
1412 unsigned InputBit = BitWidth-NTZ-8;
1413
1414 // Replace this with either a left or right shift to get the byte into
1415 // the right place.
1416 Instruction *NewVal;
1417 if (InputBit > ResultBit)
1418 NewVal = BinaryOperator::CreateLShr(I->getOperand(1),
Owen Anderson24be4c12009-07-03 00:17:18 +00001419 Context->getConstantInt(I->getType(), InputBit-ResultBit));
Chris Lattner989ba312008-06-18 04:33:20 +00001420 else
1421 NewVal = BinaryOperator::CreateShl(I->getOperand(1),
Owen Anderson24be4c12009-07-03 00:17:18 +00001422 Context->getConstantInt(I->getType(), ResultBit-InputBit));
Chris Lattner989ba312008-06-18 04:33:20 +00001423 NewVal->takeName(I);
Chris Lattner676c78e2009-01-31 08:15:18 +00001424 return InsertNewInstBefore(NewVal, *I);
Chris Lattner989ba312008-06-18 04:33:20 +00001425 }
1426
1427 // TODO: Could compute known zero/one bits based on the input.
1428 break;
1429 }
1430 }
1431 }
Chris Lattner4946e222008-06-18 18:11:55 +00001432 ComputeMaskedBits(V, DemandedMask, RHSKnownZero, RHSKnownOne, Depth);
Chris Lattner989ba312008-06-18 04:33:20 +00001433 break;
Dan Gohmanbec16052008-04-28 17:02:21 +00001434 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001435
1436 // If the client is only demanding bits that we know, return the known
1437 // constant.
Dan Gohman7934d592009-04-25 17:12:48 +00001438 if ((DemandedMask & (RHSKnownZero|RHSKnownOne)) == DemandedMask) {
Owen Anderson24be4c12009-07-03 00:17:18 +00001439 Constant *C = Context->getConstantInt(RHSKnownOne);
Dan Gohman7934d592009-04-25 17:12:48 +00001440 if (isa<PointerType>(V->getType()))
Owen Anderson24be4c12009-07-03 00:17:18 +00001441 C = Context->getConstantExprIntToPtr(C, V->getType());
Dan Gohman7934d592009-04-25 17:12:48 +00001442 return C;
1443 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001444 return false;
1445}
1446
1447
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001448/// SimplifyDemandedVectorElts - The specified value produces a vector with
Evan Cheng63295ab2009-02-03 10:05:09 +00001449/// any number of elements. DemandedElts contains the set of elements that are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001450/// actually used by the caller. This method analyzes which elements of the
1451/// operand are undef and returns that information in UndefElts.
1452///
1453/// If the information about demanded elements can be used to simplify the
1454/// operation, the operation is simplified, then the resultant value is
1455/// returned. This returns null if no change was made.
Evan Cheng63295ab2009-02-03 10:05:09 +00001456Value *InstCombiner::SimplifyDemandedVectorElts(Value *V, APInt DemandedElts,
1457 APInt& UndefElts,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001458 unsigned Depth) {
1459 unsigned VWidth = cast<VectorType>(V->getType())->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001460 APInt EltMask(APInt::getAllOnesValue(VWidth));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001461 assert((DemandedElts & ~EltMask) == 0 && "Invalid DemandedElts!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001462
1463 if (isa<UndefValue>(V)) {
1464 // If the entire vector is undefined, just return this info.
1465 UndefElts = EltMask;
1466 return 0;
1467 } else if (DemandedElts == 0) { // If nothing is demanded, provide undef.
1468 UndefElts = EltMask;
Owen Anderson24be4c12009-07-03 00:17:18 +00001469 return Context->getUndef(V->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001470 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001471
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001472 UndefElts = 0;
1473 if (ConstantVector *CP = dyn_cast<ConstantVector>(V)) {
1474 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson24be4c12009-07-03 00:17:18 +00001475 Constant *Undef = Context->getUndef(EltTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001476
1477 std::vector<Constant*> Elts;
1478 for (unsigned i = 0; i != VWidth; ++i)
Evan Cheng63295ab2009-02-03 10:05:09 +00001479 if (!DemandedElts[i]) { // If not demanded, set to undef.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001480 Elts.push_back(Undef);
Evan Cheng63295ab2009-02-03 10:05:09 +00001481 UndefElts.set(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001482 } else if (isa<UndefValue>(CP->getOperand(i))) { // Already undef.
1483 Elts.push_back(Undef);
Evan Cheng63295ab2009-02-03 10:05:09 +00001484 UndefElts.set(i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001485 } else { // Otherwise, defined.
1486 Elts.push_back(CP->getOperand(i));
1487 }
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001488
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001489 // If we changed the constant, return it.
Owen Anderson24be4c12009-07-03 00:17:18 +00001490 Constant *NewCP = Context->getConstantVector(Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001491 return NewCP != CP ? NewCP : 0;
1492 } else if (isa<ConstantAggregateZero>(V)) {
1493 // Simplify the CAZ to a ConstantVector where the non-demanded elements are
1494 // set to undef.
Mon P Wang927daf52008-11-06 22:52:21 +00001495
1496 // Check if this is identity. If so, return 0 since we are not simplifying
1497 // anything.
1498 if (DemandedElts == ((1ULL << VWidth) -1))
1499 return 0;
1500
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001501 const Type *EltTy = cast<VectorType>(V->getType())->getElementType();
Owen Anderson24be4c12009-07-03 00:17:18 +00001502 Constant *Zero = Context->getNullValue(EltTy);
1503 Constant *Undef = Context->getUndef(EltTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001504 std::vector<Constant*> Elts;
Evan Cheng63295ab2009-02-03 10:05:09 +00001505 for (unsigned i = 0; i != VWidth; ++i) {
1506 Constant *Elt = DemandedElts[i] ? Zero : Undef;
1507 Elts.push_back(Elt);
1508 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001509 UndefElts = DemandedElts ^ EltMask;
Owen Anderson24be4c12009-07-03 00:17:18 +00001510 return Context->getConstantVector(Elts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001511 }
1512
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001513 // Limit search depth.
1514 if (Depth == 10)
Dan Gohmand5f85af2009-04-25 17:28:45 +00001515 return 0;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001516
1517 // If multiple users are using the root value, procede with
1518 // simplification conservatively assuming that all elements
1519 // are needed.
1520 if (!V->hasOneUse()) {
1521 // Quit if we find multiple users of a non-root value though.
1522 // They'll be handled when it's their turn to be visited by
1523 // the main instcombine process.
1524 if (Depth != 0)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001525 // TODO: Just compute the UndefElts information recursively.
Dan Gohmand5f85af2009-04-25 17:28:45 +00001526 return 0;
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001527
1528 // Conservatively assume that all elements are needed.
1529 DemandedElts = EltMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001530 }
1531
1532 Instruction *I = dyn_cast<Instruction>(V);
Dan Gohmand5f85af2009-04-25 17:28:45 +00001533 if (!I) return 0; // Only analyze instructions.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001534
1535 bool MadeChange = false;
Evan Cheng63295ab2009-02-03 10:05:09 +00001536 APInt UndefElts2(VWidth, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001537 Value *TmpV;
1538 switch (I->getOpcode()) {
1539 default: break;
1540
1541 case Instruction::InsertElement: {
1542 // If this is a variable index, we don't know which element it overwrites.
1543 // demand exactly the same input as we produce.
1544 ConstantInt *Idx = dyn_cast<ConstantInt>(I->getOperand(2));
1545 if (Idx == 0) {
1546 // Note that we can't propagate undef elt info, because we don't know
1547 // which elt is getting updated.
1548 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1549 UndefElts2, Depth+1);
1550 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1551 break;
1552 }
1553
1554 // If this is inserting an element that isn't demanded, remove this
1555 // insertelement.
1556 unsigned IdxNo = Idx->getZExtValue();
Evan Cheng63295ab2009-02-03 10:05:09 +00001557 if (IdxNo >= VWidth || !DemandedElts[IdxNo])
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001558 return AddSoonDeadInstToWorklist(*I, 0);
1559
1560 // Otherwise, the element inserted overwrites whatever was there, so the
1561 // input demanded set is simpler than the output set.
Evan Cheng63295ab2009-02-03 10:05:09 +00001562 APInt DemandedElts2 = DemandedElts;
1563 DemandedElts2.clear(IdxNo);
1564 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts2,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001565 UndefElts, Depth+1);
1566 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1567
1568 // The inserted element is defined.
Evan Cheng63295ab2009-02-03 10:05:09 +00001569 UndefElts.clear(IdxNo);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001570 break;
1571 }
1572 case Instruction::ShuffleVector: {
1573 ShuffleVectorInst *Shuffle = cast<ShuffleVectorInst>(I);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001574 uint64_t LHSVWidth =
1575 cast<VectorType>(Shuffle->getOperand(0)->getType())->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001576 APInt LeftDemanded(LHSVWidth, 0), RightDemanded(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001577 for (unsigned i = 0; i < VWidth; i++) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001578 if (DemandedElts[i]) {
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001579 unsigned MaskVal = Shuffle->getMaskValue(i);
1580 if (MaskVal != -1u) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001581 assert(MaskVal < LHSVWidth * 2 &&
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001582 "shufflevector mask index out of range!");
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001583 if (MaskVal < LHSVWidth)
Evan Cheng63295ab2009-02-03 10:05:09 +00001584 LeftDemanded.set(MaskVal);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001585 else
Evan Cheng63295ab2009-02-03 10:05:09 +00001586 RightDemanded.set(MaskVal - LHSVWidth);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001587 }
1588 }
1589 }
1590
Nate Begemanb4d176f2009-02-11 22:36:25 +00001591 APInt UndefElts4(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001592 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), LeftDemanded,
Nate Begemanb4d176f2009-02-11 22:36:25 +00001593 UndefElts4, Depth+1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001594 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1595
Nate Begemanb4d176f2009-02-11 22:36:25 +00001596 APInt UndefElts3(LHSVWidth, 0);
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001597 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), RightDemanded,
1598 UndefElts3, Depth+1);
1599 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1600
1601 bool NewUndefElts = false;
1602 for (unsigned i = 0; i < VWidth; i++) {
1603 unsigned MaskVal = Shuffle->getMaskValue(i);
Dan Gohman24f6ee22008-09-10 01:09:32 +00001604 if (MaskVal == -1u) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001605 UndefElts.set(i);
Mon P Wangbff5d9c2008-11-10 04:46:22 +00001606 } else if (MaskVal < LHSVWidth) {
Nate Begemanb4d176f2009-02-11 22:36:25 +00001607 if (UndefElts4[MaskVal]) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001608 NewUndefElts = true;
1609 UndefElts.set(i);
1610 }
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001611 } else {
Evan Cheng63295ab2009-02-03 10:05:09 +00001612 if (UndefElts3[MaskVal - LHSVWidth]) {
1613 NewUndefElts = true;
1614 UndefElts.set(i);
1615 }
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001616 }
1617 }
1618
1619 if (NewUndefElts) {
1620 // Add additional discovered undefs.
1621 std::vector<Constant*> Elts;
1622 for (unsigned i = 0; i < VWidth; ++i) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001623 if (UndefElts[i])
Owen Anderson24be4c12009-07-03 00:17:18 +00001624 Elts.push_back(Context->getUndef(Type::Int32Ty));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001625 else
Owen Anderson24be4c12009-07-03 00:17:18 +00001626 Elts.push_back(Context->getConstantInt(Type::Int32Ty,
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001627 Shuffle->getMaskValue(i)));
1628 }
Owen Anderson24be4c12009-07-03 00:17:18 +00001629 I->setOperand(2, Context->getConstantVector(Elts));
Dan Gohmanda93bbe2008-09-09 18:11:14 +00001630 MadeChange = true;
1631 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001632 break;
1633 }
1634 case Instruction::BitCast: {
1635 // Vector->vector casts only.
1636 const VectorType *VTy = dyn_cast<VectorType>(I->getOperand(0)->getType());
1637 if (!VTy) break;
1638 unsigned InVWidth = VTy->getNumElements();
Evan Cheng63295ab2009-02-03 10:05:09 +00001639 APInt InputDemandedElts(InVWidth, 0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001640 unsigned Ratio;
1641
1642 if (VWidth == InVWidth) {
1643 // If we are converting from <4 x i32> -> <4 x f32>, we demand the same
1644 // elements as are demanded of us.
1645 Ratio = 1;
1646 InputDemandedElts = DemandedElts;
1647 } else if (VWidth > InVWidth) {
1648 // Untested so far.
1649 break;
1650
1651 // If there are more elements in the result than there are in the source,
1652 // then an input element is live if any of the corresponding output
1653 // elements are live.
1654 Ratio = VWidth/InVWidth;
1655 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx) {
Evan Cheng63295ab2009-02-03 10:05:09 +00001656 if (DemandedElts[OutIdx])
1657 InputDemandedElts.set(OutIdx/Ratio);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001658 }
1659 } else {
1660 // Untested so far.
1661 break;
1662
1663 // If there are more elements in the source than there are in the result,
1664 // then an input element is live if the corresponding output element is
1665 // live.
1666 Ratio = InVWidth/VWidth;
1667 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001668 if (DemandedElts[InIdx/Ratio])
1669 InputDemandedElts.set(InIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001670 }
1671
1672 // div/rem demand all inputs, because they don't want divide by zero.
1673 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), InputDemandedElts,
1674 UndefElts2, Depth+1);
1675 if (TmpV) {
1676 I->setOperand(0, TmpV);
1677 MadeChange = true;
1678 }
1679
1680 UndefElts = UndefElts2;
1681 if (VWidth > InVWidth) {
1682 assert(0 && "Unimp");
1683 // If there are more elements in the result than there are in the source,
1684 // then an output element is undef if the corresponding input element is
1685 // undef.
1686 for (unsigned OutIdx = 0; OutIdx != VWidth; ++OutIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001687 if (UndefElts2[OutIdx/Ratio])
1688 UndefElts.set(OutIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001689 } else if (VWidth < InVWidth) {
1690 assert(0 && "Unimp");
1691 // If there are more elements in the source than there are in the result,
1692 // then a result element is undef if all of the corresponding input
1693 // elements are undef.
1694 UndefElts = ~0ULL >> (64-VWidth); // Start out all undef.
1695 for (unsigned InIdx = 0; InIdx != InVWidth; ++InIdx)
Evan Cheng63295ab2009-02-03 10:05:09 +00001696 if (!UndefElts2[InIdx]) // Not undef?
1697 UndefElts.clear(InIdx/Ratio); // Clear undef bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001698 }
1699 break;
1700 }
1701 case Instruction::And:
1702 case Instruction::Or:
1703 case Instruction::Xor:
1704 case Instruction::Add:
1705 case Instruction::Sub:
1706 case Instruction::Mul:
1707 // div/rem demand all inputs, because they don't want divide by zero.
1708 TmpV = SimplifyDemandedVectorElts(I->getOperand(0), DemandedElts,
1709 UndefElts, Depth+1);
1710 if (TmpV) { I->setOperand(0, TmpV); MadeChange = true; }
1711 TmpV = SimplifyDemandedVectorElts(I->getOperand(1), DemandedElts,
1712 UndefElts2, Depth+1);
1713 if (TmpV) { I->setOperand(1, TmpV); MadeChange = true; }
1714
1715 // Output elements are undefined if both are undefined. Consider things
1716 // like undef&0. The result is known zero, not undef.
1717 UndefElts &= UndefElts2;
1718 break;
1719
1720 case Instruction::Call: {
1721 IntrinsicInst *II = dyn_cast<IntrinsicInst>(I);
1722 if (!II) break;
1723 switch (II->getIntrinsicID()) {
1724 default: break;
1725
1726 // Binary vector operations that work column-wise. A dest element is a
1727 // function of the corresponding input elements from the two inputs.
1728 case Intrinsic::x86_sse_sub_ss:
1729 case Intrinsic::x86_sse_mul_ss:
1730 case Intrinsic::x86_sse_min_ss:
1731 case Intrinsic::x86_sse_max_ss:
1732 case Intrinsic::x86_sse2_sub_sd:
1733 case Intrinsic::x86_sse2_mul_sd:
1734 case Intrinsic::x86_sse2_min_sd:
1735 case Intrinsic::x86_sse2_max_sd:
1736 TmpV = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
1737 UndefElts, Depth+1);
1738 if (TmpV) { II->setOperand(1, TmpV); MadeChange = true; }
1739 TmpV = SimplifyDemandedVectorElts(II->getOperand(2), DemandedElts,
1740 UndefElts2, Depth+1);
1741 if (TmpV) { II->setOperand(2, TmpV); MadeChange = true; }
1742
1743 // If only the low elt is demanded and this is a scalarizable intrinsic,
1744 // scalarize it now.
1745 if (DemandedElts == 1) {
1746 switch (II->getIntrinsicID()) {
1747 default: break;
1748 case Intrinsic::x86_sse_sub_ss:
1749 case Intrinsic::x86_sse_mul_ss:
1750 case Intrinsic::x86_sse2_sub_sd:
1751 case Intrinsic::x86_sse2_mul_sd:
1752 // TODO: Lower MIN/MAX/ABS/etc
1753 Value *LHS = II->getOperand(1);
1754 Value *RHS = II->getOperand(2);
1755 // Extract the element as scalars.
1756 LHS = InsertNewInstBefore(new ExtractElementInst(LHS, 0U,"tmp"), *II);
1757 RHS = InsertNewInstBefore(new ExtractElementInst(RHS, 0U,"tmp"), *II);
1758
1759 switch (II->getIntrinsicID()) {
1760 default: assert(0 && "Case stmts out of sync!");
1761 case Intrinsic::x86_sse_sub_ss:
1762 case Intrinsic::x86_sse2_sub_sd:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001763 TmpV = InsertNewInstBefore(BinaryOperator::CreateFSub(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001764 II->getName()), *II);
1765 break;
1766 case Intrinsic::x86_sse_mul_ss:
1767 case Intrinsic::x86_sse2_mul_sd:
Dan Gohman7ce405e2009-06-04 22:49:04 +00001768 TmpV = InsertNewInstBefore(BinaryOperator::CreateFMul(LHS, RHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001769 II->getName()), *II);
1770 break;
1771 }
1772
1773 Instruction *New =
Owen Anderson24be4c12009-07-03 00:17:18 +00001774 InsertElementInst::Create(
1775 Context->getUndef(II->getType()), TmpV, 0U, II->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001776 InsertNewInstBefore(New, *II);
1777 AddSoonDeadInstToWorklist(*II, 0);
1778 return New;
1779 }
1780 }
1781
1782 // Output elements are undefined if both are undefined. Consider things
1783 // like undef&0. The result is known zero, not undef.
1784 UndefElts &= UndefElts2;
1785 break;
1786 }
1787 break;
1788 }
1789 }
1790 return MadeChange ? I : 0;
1791}
1792
Dan Gohman5d56fd42008-05-19 22:14:15 +00001793
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001794/// AssociativeOpt - Perform an optimization on an associative operator. This
1795/// function is designed to check a chain of associative operators for a
1796/// potential to apply a certain optimization. Since the optimization may be
1797/// applicable if the expression was reassociated, this checks the chain, then
1798/// reassociates the expression as necessary to expose the optimization
1799/// opportunity. This makes use of a special Functor, which must define
1800/// 'shouldApply' and 'apply' methods.
1801///
1802template<typename Functor>
Owen Anderson24be4c12009-07-03 00:17:18 +00001803static Instruction *AssociativeOpt(BinaryOperator &Root, const Functor &F,
Owen Anderson5349f052009-07-06 23:00:19 +00001804 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001805 unsigned Opcode = Root.getOpcode();
1806 Value *LHS = Root.getOperand(0);
1807
1808 // Quick check, see if the immediate LHS matches...
1809 if (F.shouldApply(LHS))
1810 return F.apply(Root);
1811
1812 // Otherwise, if the LHS is not of the same opcode as the root, return.
1813 Instruction *LHSI = dyn_cast<Instruction>(LHS);
1814 while (LHSI && LHSI->getOpcode() == Opcode && LHSI->hasOneUse()) {
1815 // Should we apply this transform to the RHS?
1816 bool ShouldApply = F.shouldApply(LHSI->getOperand(1));
1817
1818 // If not to the RHS, check to see if we should apply to the LHS...
1819 if (!ShouldApply && F.shouldApply(LHSI->getOperand(0))) {
1820 cast<BinaryOperator>(LHSI)->swapOperands(); // Make the LHS the RHS
1821 ShouldApply = true;
1822 }
1823
1824 // If the functor wants to apply the optimization to the RHS of LHSI,
1825 // reassociate the expression from ((? op A) op B) to (? op (A op B))
1826 if (ShouldApply) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001827 // Now all of the instructions are in the current basic block, go ahead
1828 // and perform the reassociation.
1829 Instruction *TmpLHSI = cast<Instruction>(Root.getOperand(0));
1830
1831 // First move the selected RHS to the LHS of the root...
1832 Root.setOperand(0, LHSI->getOperand(1));
1833
1834 // Make what used to be the LHS of the root be the user of the root...
1835 Value *ExtraOperand = TmpLHSI->getOperand(1);
1836 if (&Root == TmpLHSI) {
Owen Anderson24be4c12009-07-03 00:17:18 +00001837 Root.replaceAllUsesWith(Context->getNullValue(TmpLHSI->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001838 return 0;
1839 }
1840 Root.replaceAllUsesWith(TmpLHSI); // Users now use TmpLHSI
1841 TmpLHSI->setOperand(1, &Root); // TmpLHSI now uses the root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001842 BasicBlock::iterator ARI = &Root; ++ARI;
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001843 TmpLHSI->moveBefore(ARI); // Move TmpLHSI to after Root
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001844 ARI = Root;
1845
1846 // Now propagate the ExtraOperand down the chain of instructions until we
1847 // get to LHSI.
1848 while (TmpLHSI != LHSI) {
1849 Instruction *NextLHSI = cast<Instruction>(TmpLHSI->getOperand(0));
1850 // Move the instruction to immediately before the chain we are
1851 // constructing to avoid breaking dominance properties.
Dan Gohman0bb9a3d2008-06-19 17:47:47 +00001852 NextLHSI->moveBefore(ARI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001853 ARI = NextLHSI;
1854
1855 Value *NextOp = NextLHSI->getOperand(1);
1856 NextLHSI->setOperand(1, ExtraOperand);
1857 TmpLHSI = NextLHSI;
1858 ExtraOperand = NextOp;
1859 }
1860
1861 // Now that the instructions are reassociated, have the functor perform
1862 // the transformation...
1863 return F.apply(Root);
1864 }
1865
1866 LHSI = dyn_cast<Instruction>(LHSI->getOperand(0));
1867 }
1868 return 0;
1869}
1870
Dan Gohman089efff2008-05-13 00:00:25 +00001871namespace {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001872
Nick Lewycky27f6c132008-05-23 04:34:58 +00001873// AddRHS - Implements: X + X --> X << 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001874struct AddRHS {
1875 Value *RHS;
Owen Anderson5349f052009-07-06 23:00:19 +00001876 LLVMContext *Context;
1877 AddRHS(Value *rhs, LLVMContext *C) : RHS(rhs), Context(C) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001878 bool shouldApply(Value *LHS) const { return LHS == RHS; }
1879 Instruction *apply(BinaryOperator &Add) const {
Nick Lewycky27f6c132008-05-23 04:34:58 +00001880 return BinaryOperator::CreateShl(Add.getOperand(0),
Owen Anderson24be4c12009-07-03 00:17:18 +00001881 Context->getConstantInt(Add.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001882 }
1883};
1884
1885// AddMaskingAnd - Implements (A & C1)+(B & C2) --> (A & C1)|(B & C2)
1886// iff C1&C2 == 0
1887struct AddMaskingAnd {
1888 Constant *C2;
Owen Anderson5349f052009-07-06 23:00:19 +00001889 LLVMContext *Context;
1890 AddMaskingAnd(Constant *c, LLVMContext *C) : C2(c), Context(C) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001891 bool shouldApply(Value *LHS) const {
1892 ConstantInt *C1;
Owen Andersona21eb582009-07-10 17:35:01 +00001893 return match(LHS, m_And(m_Value(), m_ConstantInt(C1)), *Context) &&
Owen Anderson24be4c12009-07-03 00:17:18 +00001894 Context->getConstantExprAnd(C1, C2)->isNullValue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001895 }
1896 Instruction *apply(BinaryOperator &Add) const {
Gabor Greifa645dd32008-05-16 19:29:10 +00001897 return BinaryOperator::CreateOr(Add.getOperand(0), Add.getOperand(1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001898 }
1899};
1900
Dan Gohman089efff2008-05-13 00:00:25 +00001901}
1902
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001903static Value *FoldOperationIntoSelectOperand(Instruction &I, Value *SO,
1904 InstCombiner *IC) {
Owen Anderson5349f052009-07-06 23:00:19 +00001905 LLVMContext *Context = IC->getContext();
Owen Anderson24be4c12009-07-03 00:17:18 +00001906
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001907 if (CastInst *CI = dyn_cast<CastInst>(&I)) {
Eli Friedman722b4792008-11-30 21:09:11 +00001908 return IC->InsertCastBefore(CI->getOpcode(), SO, I.getType(), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001909 }
1910
1911 // Figure out if the constant is the left or the right argument.
1912 bool ConstIsRHS = isa<Constant>(I.getOperand(1));
1913 Constant *ConstOperand = cast<Constant>(I.getOperand(ConstIsRHS));
1914
1915 if (Constant *SOC = dyn_cast<Constant>(SO)) {
1916 if (ConstIsRHS)
Owen Anderson24be4c12009-07-03 00:17:18 +00001917 return Context->getConstantExpr(I.getOpcode(), SOC, ConstOperand);
1918 return Context->getConstantExpr(I.getOpcode(), ConstOperand, SOC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001919 }
1920
1921 Value *Op0 = SO, *Op1 = ConstOperand;
1922 if (!ConstIsRHS)
1923 std::swap(Op0, Op1);
1924 Instruction *New;
1925 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00001926 New = BinaryOperator::Create(BO->getOpcode(), Op0, Op1,SO->getName()+".op");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001927 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson6601fcd2009-07-09 23:48:35 +00001928 New = CmpInst::Create(*Context, CI->getOpcode(), CI->getPredicate(),
1929 Op0, Op1, SO->getName()+".cmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001930 else {
Edwin Törökced9ff82009-07-11 13:10:19 +00001931 LLVM_UNREACHABLE("Unknown binary instruction type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001932 }
1933 return IC->InsertNewInstBefore(New, I);
1934}
1935
1936// FoldOpIntoSelect - Given an instruction with a select as one operand and a
1937// constant as the other operand, try to fold the binary operator into the
1938// select arguments. This also works for Cast instructions, which obviously do
1939// not have a second operand.
1940static Instruction *FoldOpIntoSelect(Instruction &Op, SelectInst *SI,
1941 InstCombiner *IC) {
1942 // Don't modify shared select instructions
1943 if (!SI->hasOneUse()) return 0;
1944 Value *TV = SI->getOperand(1);
1945 Value *FV = SI->getOperand(2);
1946
1947 if (isa<Constant>(TV) || isa<Constant>(FV)) {
1948 // Bool selects with constant operands can be folded to logical ops.
1949 if (SI->getType() == Type::Int1Ty) return 0;
1950
1951 Value *SelectTrueVal = FoldOperationIntoSelectOperand(Op, TV, IC);
1952 Value *SelectFalseVal = FoldOperationIntoSelectOperand(Op, FV, IC);
1953
Gabor Greifd6da1d02008-04-06 20:25:17 +00001954 return SelectInst::Create(SI->getCondition(), SelectTrueVal,
1955 SelectFalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001956 }
1957 return 0;
1958}
1959
1960
1961/// FoldOpIntoPhi - Given a binary operator or cast instruction which has a PHI
1962/// node as operand #0, see if we can fold the instruction into the PHI (which
1963/// is only possible if all operands to the PHI are constants).
1964Instruction *InstCombiner::FoldOpIntoPhi(Instruction &I) {
1965 PHINode *PN = cast<PHINode>(I.getOperand(0));
1966 unsigned NumPHIValues = PN->getNumIncomingValues();
1967 if (!PN->hasOneUse() || NumPHIValues == 0) return 0;
1968
1969 // Check to see if all of the operands of the PHI are constants. If there is
1970 // one non-constant value, remember the BB it is. If there is more than one
1971 // or if *it* is a PHI, bail out.
1972 BasicBlock *NonConstBB = 0;
1973 for (unsigned i = 0; i != NumPHIValues; ++i)
1974 if (!isa<Constant>(PN->getIncomingValue(i))) {
1975 if (NonConstBB) return 0; // More than one non-const value.
1976 if (isa<PHINode>(PN->getIncomingValue(i))) return 0; // Itself a phi.
1977 NonConstBB = PN->getIncomingBlock(i);
1978
1979 // If the incoming non-constant value is in I's block, we have an infinite
1980 // loop.
1981 if (NonConstBB == I.getParent())
1982 return 0;
1983 }
1984
1985 // If there is exactly one non-constant value, we can insert a copy of the
1986 // operation in that block. However, if this is a critical edge, we would be
1987 // inserting the computation one some other paths (e.g. inside a loop). Only
1988 // do this if the pred block is unconditionally branching into the phi block.
1989 if (NonConstBB) {
1990 BranchInst *BI = dyn_cast<BranchInst>(NonConstBB->getTerminator());
1991 if (!BI || !BI->isUnconditional()) return 0;
1992 }
1993
1994 // Okay, we can do the transformation: create the new PHI node.
Gabor Greifd6da1d02008-04-06 20:25:17 +00001995 PHINode *NewPN = PHINode::Create(I.getType(), "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001996 NewPN->reserveOperandSpace(PN->getNumOperands()/2);
1997 InsertNewInstBefore(NewPN, *PN);
1998 NewPN->takeName(PN);
1999
2000 // Next, add all of the operands to the PHI.
2001 if (I.getNumOperands() == 2) {
2002 Constant *C = cast<Constant>(I.getOperand(1));
2003 for (unsigned i = 0; i != NumPHIValues; ++i) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00002004 Value *InV = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002005 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
2006 if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson24be4c12009-07-03 00:17:18 +00002007 InV = Context->getConstantExprCompare(CI->getPredicate(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002008 else
Owen Anderson24be4c12009-07-03 00:17:18 +00002009 InV = Context->getConstantExpr(I.getOpcode(), InC, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002010 } else {
2011 assert(PN->getIncomingBlock(i) == NonConstBB);
2012 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(&I))
Gabor Greifa645dd32008-05-16 19:29:10 +00002013 InV = BinaryOperator::Create(BO->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002014 PN->getIncomingValue(i), C, "phitmp",
2015 NonConstBB->getTerminator());
2016 else if (CmpInst *CI = dyn_cast<CmpInst>(&I))
Owen Anderson6601fcd2009-07-09 23:48:35 +00002017 InV = CmpInst::Create(*Context, CI->getOpcode(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002018 CI->getPredicate(),
2019 PN->getIncomingValue(i), C, "phitmp",
2020 NonConstBB->getTerminator());
2021 else
2022 assert(0 && "Unknown binop!");
2023
2024 AddToWorkList(cast<Instruction>(InV));
2025 }
2026 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2027 }
2028 } else {
2029 CastInst *CI = cast<CastInst>(&I);
2030 const Type *RetTy = CI->getType();
2031 for (unsigned i = 0; i != NumPHIValues; ++i) {
2032 Value *InV;
2033 if (Constant *InC = dyn_cast<Constant>(PN->getIncomingValue(i))) {
Owen Anderson24be4c12009-07-03 00:17:18 +00002034 InV = Context->getConstantExprCast(CI->getOpcode(), InC, RetTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002035 } else {
2036 assert(PN->getIncomingBlock(i) == NonConstBB);
Gabor Greifa645dd32008-05-16 19:29:10 +00002037 InV = CastInst::Create(CI->getOpcode(), PN->getIncomingValue(i),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002038 I.getType(), "phitmp",
2039 NonConstBB->getTerminator());
2040 AddToWorkList(cast<Instruction>(InV));
2041 }
2042 NewPN->addIncoming(InV, PN->getIncomingBlock(i));
2043 }
2044 }
2045 return ReplaceInstUsesWith(I, NewPN);
2046}
2047
Chris Lattner55476162008-01-29 06:52:45 +00002048
Chris Lattner3554f972008-05-20 05:46:13 +00002049/// WillNotOverflowSignedAdd - Return true if we can prove that:
2050/// (sext (add LHS, RHS)) === (add (sext LHS), (sext RHS))
2051/// This basically requires proving that the add in the original type would not
2052/// overflow to change the sign bit or have a carry out.
2053bool InstCombiner::WillNotOverflowSignedAdd(Value *LHS, Value *RHS) {
2054 // There are different heuristics we can use for this. Here are some simple
2055 // ones.
2056
2057 // Add has the property that adding any two 2's complement numbers can only
2058 // have one carry bit which can change a sign. As such, if LHS and RHS each
2059 // have at least two sign bits, we know that the addition of the two values will
2060 // sign extend fine.
2061 if (ComputeNumSignBits(LHS) > 1 && ComputeNumSignBits(RHS) > 1)
2062 return true;
2063
2064
2065 // If one of the operands only has one non-zero bit, and if the other operand
2066 // has a known-zero bit in a more significant place than it (not including the
2067 // sign bit) the ripple may go up to and fill the zero, but won't change the
2068 // sign. For example, (X & ~4) + 1.
2069
2070 // TODO: Implement.
2071
2072 return false;
2073}
2074
Chris Lattner55476162008-01-29 06:52:45 +00002075
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002076Instruction *InstCombiner::visitAdd(BinaryOperator &I) {
2077 bool Changed = SimplifyCommutative(I);
2078 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2079
2080 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2081 // X + undef -> undef
2082 if (isa<UndefValue>(RHS))
2083 return ReplaceInstUsesWith(I, RHS);
2084
2085 // X + 0 --> X
Dan Gohman7ce405e2009-06-04 22:49:04 +00002086 if (RHSC->isNullValue())
2087 return ReplaceInstUsesWith(I, LHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002088
2089 if (ConstantInt *CI = dyn_cast<ConstantInt>(RHSC)) {
2090 // X + (signbit) --> X ^ signbit
2091 const APInt& Val = CI->getValue();
2092 uint32_t BitWidth = Val.getBitWidth();
2093 if (Val == APInt::getSignBit(BitWidth))
Gabor Greifa645dd32008-05-16 19:29:10 +00002094 return BinaryOperator::CreateXor(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002095
2096 // See if SimplifyDemandedBits can simplify this. This handles stuff like
2097 // (X & 254)+1 -> (X&254)|1
Dan Gohman8fd520a2009-06-15 22:12:54 +00002098 if (SimplifyDemandedInstructionBits(I))
Chris Lattner676c78e2009-01-31 08:15:18 +00002099 return &I;
Dan Gohman35b76162008-10-30 20:40:10 +00002100
2101 // zext(i1) - 1 -> select i1, 0, -1
2102 if (ZExtInst *ZI = dyn_cast<ZExtInst>(LHS))
2103 if (CI->isAllOnesValue() &&
2104 ZI->getOperand(0)->getType() == Type::Int1Ty)
2105 return SelectInst::Create(ZI->getOperand(0),
Owen Anderson24be4c12009-07-03 00:17:18 +00002106 Context->getNullValue(I.getType()),
2107 Context->getConstantIntAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002108 }
2109
2110 if (isa<PHINode>(LHS))
2111 if (Instruction *NV = FoldOpIntoPhi(I))
2112 return NV;
2113
2114 ConstantInt *XorRHS = 0;
2115 Value *XorLHS = 0;
2116 if (isa<ConstantInt>(RHSC) &&
Owen Andersona21eb582009-07-10 17:35:01 +00002117 match(LHS, m_Xor(m_Value(XorLHS), m_ConstantInt(XorRHS)), *Context)) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00002118 uint32_t TySizeBits = I.getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002119 const APInt& RHSVal = cast<ConstantInt>(RHSC)->getValue();
2120
2121 uint32_t Size = TySizeBits / 2;
2122 APInt C0080Val(APInt(TySizeBits, 1ULL).shl(Size - 1));
2123 APInt CFF80Val(-C0080Val);
2124 do {
2125 if (TySizeBits > Size) {
2126 // If we have ADD(XOR(AND(X, 0xFF), 0x80), 0xF..F80), it's a sext.
2127 // If we have ADD(XOR(AND(X, 0xFF), 0xF..F80), 0x80), it's a sext.
2128 if ((RHSVal == CFF80Val && XorRHS->getValue() == C0080Val) ||
2129 (RHSVal == C0080Val && XorRHS->getValue() == CFF80Val)) {
2130 // This is a sign extend if the top bits are known zero.
2131 if (!MaskedValueIsZero(XorLHS,
2132 APInt::getHighBitsSet(TySizeBits, TySizeBits - Size)))
2133 Size = 0; // Not a sign ext, but can't be any others either.
2134 break;
2135 }
2136 }
2137 Size >>= 1;
2138 C0080Val = APIntOps::lshr(C0080Val, Size);
2139 CFF80Val = APIntOps::ashr(CFF80Val, Size);
2140 } while (Size >= 1);
2141
2142 // FIXME: This shouldn't be necessary. When the backends can handle types
Chris Lattnerdeef1a72008-05-19 20:25:04 +00002143 // with funny bit widths then this switch statement should be removed. It
2144 // is just here to get the size of the "middle" type back up to something
2145 // that the back ends can handle.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002146 const Type *MiddleType = 0;
2147 switch (Size) {
2148 default: break;
2149 case 32: MiddleType = Type::Int32Ty; break;
2150 case 16: MiddleType = Type::Int16Ty; break;
2151 case 8: MiddleType = Type::Int8Ty; break;
2152 }
2153 if (MiddleType) {
2154 Instruction *NewTrunc = new TruncInst(XorLHS, MiddleType, "sext");
2155 InsertNewInstBefore(NewTrunc, I);
2156 return new SExtInst(NewTrunc, I.getType(), I.getName());
2157 }
2158 }
2159 }
2160
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002161 if (I.getType() == Type::Int1Ty)
2162 return BinaryOperator::CreateXor(LHS, RHS);
2163
Nick Lewycky4d474cd2008-05-23 04:39:38 +00002164 // X + X --> X << 1
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002165 if (I.getType()->isInteger()) {
Owen Anderson24be4c12009-07-03 00:17:18 +00002166 if (Instruction *Result = AssociativeOpt(I, AddRHS(RHS, Context), Context))
2167 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002168
2169 if (Instruction *RHSI = dyn_cast<Instruction>(RHS)) {
2170 if (RHSI->getOpcode() == Instruction::Sub)
2171 if (LHS == RHSI->getOperand(1)) // A + (B - A) --> B
2172 return ReplaceInstUsesWith(I, RHSI->getOperand(0));
2173 }
2174 if (Instruction *LHSI = dyn_cast<Instruction>(LHS)) {
2175 if (LHSI->getOpcode() == Instruction::Sub)
2176 if (RHS == LHSI->getOperand(1)) // (B - A) + A --> B
2177 return ReplaceInstUsesWith(I, LHSI->getOperand(0));
2178 }
2179 }
2180
2181 // -A + B --> B - A
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002182 // -A + -B --> -(A + B)
Owen Anderson24be4c12009-07-03 00:17:18 +00002183 if (Value *LHSV = dyn_castNegVal(LHS, Context)) {
Chris Lattner322a9192008-02-18 17:50:16 +00002184 if (LHS->getType()->isIntOrIntVector()) {
Owen Anderson24be4c12009-07-03 00:17:18 +00002185 if (Value *RHSV = dyn_castNegVal(RHS, Context)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002186 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSV, RHSV, "sum");
Chris Lattner322a9192008-02-18 17:50:16 +00002187 InsertNewInstBefore(NewAdd, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002188 return BinaryOperator::CreateNeg(NewAdd);
Chris Lattner322a9192008-02-18 17:50:16 +00002189 }
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002190 }
2191
Gabor Greifa645dd32008-05-16 19:29:10 +00002192 return BinaryOperator::CreateSub(RHS, LHSV);
Chris Lattner53c9fbf2008-02-17 21:03:36 +00002193 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002194
2195 // A + -B --> A - B
2196 if (!isa<Constant>(RHS))
Owen Anderson24be4c12009-07-03 00:17:18 +00002197 if (Value *V = dyn_castNegVal(RHS, Context))
Gabor Greifa645dd32008-05-16 19:29:10 +00002198 return BinaryOperator::CreateSub(LHS, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002199
2200
2201 ConstantInt *C2;
Owen Anderson24be4c12009-07-03 00:17:18 +00002202 if (Value *X = dyn_castFoldableMul(LHS, C2, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002203 if (X == RHS) // X*C + X --> X * (C+1)
Owen Anderson24be4c12009-07-03 00:17:18 +00002204 return BinaryOperator::CreateMul(RHS, AddOne(C2, Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002205
2206 // X*C1 + X*C2 --> X * (C1+C2)
2207 ConstantInt *C1;
Owen Anderson24be4c12009-07-03 00:17:18 +00002208 if (X == dyn_castFoldableMul(RHS, C1, Context))
2209 return BinaryOperator::CreateMul(X, Context->getConstantExprAdd(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002210 }
2211
2212 // X + X*C --> X * (C+1)
Owen Anderson24be4c12009-07-03 00:17:18 +00002213 if (dyn_castFoldableMul(RHS, C2, Context) == LHS)
2214 return BinaryOperator::CreateMul(LHS, AddOne(C2, Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002215
2216 // X + ~X --> -1 since ~X = -X-1
Owen Anderson24be4c12009-07-03 00:17:18 +00002217 if (dyn_castNotVal(LHS, Context) == RHS ||
2218 dyn_castNotVal(RHS, Context) == LHS)
2219 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002220
2221
2222 // (A & C1)+(B & C2) --> (A & C1)|(B & C2) iff C1&C2 == 0
Owen Andersona21eb582009-07-10 17:35:01 +00002223 if (match(RHS, m_And(m_Value(), m_ConstantInt(C2)), *Context))
Owen Anderson24be4c12009-07-03 00:17:18 +00002224 if (Instruction *R = AssociativeOpt(I, AddMaskingAnd(C2, Context), Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002225 return R;
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002226
2227 // A+B --> A|B iff A and B have no bits set in common.
2228 if (const IntegerType *IT = dyn_cast<IntegerType>(I.getType())) {
2229 APInt Mask = APInt::getAllOnesValue(IT->getBitWidth());
2230 APInt LHSKnownOne(IT->getBitWidth(), 0);
2231 APInt LHSKnownZero(IT->getBitWidth(), 0);
2232 ComputeMaskedBits(LHS, Mask, LHSKnownZero, LHSKnownOne);
2233 if (LHSKnownZero != 0) {
2234 APInt RHSKnownOne(IT->getBitWidth(), 0);
2235 APInt RHSKnownZero(IT->getBitWidth(), 0);
2236 ComputeMaskedBits(RHS, Mask, RHSKnownZero, RHSKnownOne);
2237
2238 // No bits in common -> bitwise or.
Chris Lattner130443c2008-05-19 20:03:53 +00002239 if ((LHSKnownZero|RHSKnownZero).isAllOnesValue())
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002240 return BinaryOperator::CreateOr(LHS, RHS);
Chris Lattnerc1575ce2008-05-19 20:01:56 +00002241 }
2242 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002243
Nick Lewycky83598a72008-02-03 07:42:09 +00002244 // W*X + Y*Z --> W * (X+Z) iff W == Y
Nick Lewycky5d03b512008-02-03 08:19:11 +00002245 if (I.getType()->isIntOrIntVector()) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002246 Value *W, *X, *Y, *Z;
Owen Andersona21eb582009-07-10 17:35:01 +00002247 if (match(LHS, m_Mul(m_Value(W), m_Value(X)), *Context) &&
2248 match(RHS, m_Mul(m_Value(Y), m_Value(Z)), *Context)) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002249 if (W != Y) {
2250 if (W == Z) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002251 std::swap(Y, Z);
Nick Lewycky83598a72008-02-03 07:42:09 +00002252 } else if (Y == X) {
Bill Wendling44a36ea2008-02-26 10:53:30 +00002253 std::swap(W, X);
2254 } else if (X == Z) {
Nick Lewycky83598a72008-02-03 07:42:09 +00002255 std::swap(Y, Z);
2256 std::swap(W, X);
2257 }
2258 }
2259
2260 if (W == Y) {
Gabor Greifa645dd32008-05-16 19:29:10 +00002261 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, Z,
Nick Lewycky83598a72008-02-03 07:42:09 +00002262 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002263 return BinaryOperator::CreateMul(W, NewAdd);
Nick Lewycky83598a72008-02-03 07:42:09 +00002264 }
2265 }
2266 }
2267
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002268 if (ConstantInt *CRHS = dyn_cast<ConstantInt>(RHS)) {
2269 Value *X = 0;
Owen Andersona21eb582009-07-10 17:35:01 +00002270 if (match(LHS, m_Not(m_Value(X)), *Context)) // ~X + C --> (C-1) - X
Owen Anderson24be4c12009-07-03 00:17:18 +00002271 return BinaryOperator::CreateSub(SubOne(CRHS, Context), X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002272
2273 // (X & FF00) + xx00 -> (X+xx00) & FF00
Owen Andersona21eb582009-07-10 17:35:01 +00002274 if (LHS->hasOneUse() &&
2275 match(LHS, m_And(m_Value(X), m_ConstantInt(C2)), *Context)) {
Owen Anderson24be4c12009-07-03 00:17:18 +00002276 Constant *Anded = Context->getConstantExprAnd(CRHS, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002277 if (Anded == CRHS) {
2278 // See if all bits from the first bit set in the Add RHS up are included
2279 // in the mask. First, get the rightmost bit.
2280 const APInt& AddRHSV = CRHS->getValue();
2281
2282 // Form a mask of all bits from the lowest bit added through the top.
2283 APInt AddRHSHighBits(~((AddRHSV & -AddRHSV)-1));
2284
2285 // See if the and mask includes all of these bits.
2286 APInt AddRHSHighBitsAnd(AddRHSHighBits & C2->getValue());
2287
2288 if (AddRHSHighBits == AddRHSHighBitsAnd) {
2289 // Okay, the xform is safe. Insert the new add pronto.
Gabor Greifa645dd32008-05-16 19:29:10 +00002290 Value *NewAdd = InsertNewInstBefore(BinaryOperator::CreateAdd(X, CRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002291 LHS->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00002292 return BinaryOperator::CreateAnd(NewAdd, C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002293 }
2294 }
2295 }
2296
2297 // Try to fold constant add into select arguments.
2298 if (SelectInst *SI = dyn_cast<SelectInst>(LHS))
2299 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2300 return R;
2301 }
2302
2303 // add (cast *A to intptrtype) B ->
Dan Gohman9e1657f2009-06-14 23:30:43 +00002304 // cast (GEP (cast *A to i8*) B) --> intptrtype
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002305 {
2306 CastInst *CI = dyn_cast<CastInst>(LHS);
2307 Value *Other = RHS;
2308 if (!CI) {
2309 CI = dyn_cast<CastInst>(RHS);
2310 Other = LHS;
2311 }
2312 if (CI && CI->getType()->isSized() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00002313 (CI->getType()->getScalarSizeInBits() ==
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002314 TD->getIntPtrType()->getPrimitiveSizeInBits())
2315 && isa<PointerType>(CI->getOperand(0)->getType())) {
Christopher Lambbb2f2222007-12-17 01:12:55 +00002316 unsigned AS =
2317 cast<PointerType>(CI->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +00002318 Value *I2 = InsertBitCastBefore(CI->getOperand(0),
Owen Anderson24be4c12009-07-03 00:17:18 +00002319 Context->getPointerType(Type::Int8Ty, AS), I);
Gabor Greifd6da1d02008-04-06 20:25:17 +00002320 I2 = InsertNewInstBefore(GetElementPtrInst::Create(I2, Other, "ctg2"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002321 return new PtrToIntInst(I2, CI->getType());
2322 }
2323 }
Christopher Lamb244ec282007-12-18 09:34:41 +00002324
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002325 // add (select X 0 (sub n A)) A --> select X A n
Christopher Lamb244ec282007-12-18 09:34:41 +00002326 {
2327 SelectInst *SI = dyn_cast<SelectInst>(LHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002328 Value *A = RHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002329 if (!SI) {
2330 SI = dyn_cast<SelectInst>(RHS);
Chris Lattner641ea462008-11-16 04:46:19 +00002331 A = LHS;
Christopher Lamb244ec282007-12-18 09:34:41 +00002332 }
Chris Lattnerbf0c5f32007-12-20 01:56:58 +00002333 if (SI && SI->hasOneUse()) {
Christopher Lamb244ec282007-12-18 09:34:41 +00002334 Value *TV = SI->getTrueValue();
2335 Value *FV = SI->getFalseValue();
Chris Lattner641ea462008-11-16 04:46:19 +00002336 Value *N;
Christopher Lamb244ec282007-12-18 09:34:41 +00002337
2338 // Can we fold the add into the argument of the select?
2339 // We check both true and false select arguments for a matching subtract.
Owen Andersona21eb582009-07-10 17:35:01 +00002340 if (match(FV, m_Zero(), *Context) &&
2341 match(TV, m_Sub(m_Value(N), m_Specific(A)), *Context))
Chris Lattner641ea462008-11-16 04:46:19 +00002342 // Fold the add into the true select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002343 return SelectInst::Create(SI->getCondition(), N, A);
Owen Andersona21eb582009-07-10 17:35:01 +00002344 if (match(TV, m_Zero(), *Context) &&
2345 match(FV, m_Sub(m_Value(N), m_Specific(A)), *Context))
Chris Lattner641ea462008-11-16 04:46:19 +00002346 // Fold the add into the false select value.
Gabor Greifd6da1d02008-04-06 20:25:17 +00002347 return SelectInst::Create(SI->getCondition(), A, N);
Christopher Lamb244ec282007-12-18 09:34:41 +00002348 }
2349 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002350
Chris Lattner3554f972008-05-20 05:46:13 +00002351 // Check for (add (sext x), y), see if we can merge this into an
2352 // integer add followed by a sext.
2353 if (SExtInst *LHSConv = dyn_cast<SExtInst>(LHS)) {
2354 // (add (sext x), cst) --> (sext (add x, cst'))
2355 if (ConstantInt *RHSC = dyn_cast<ConstantInt>(RHS)) {
2356 Constant *CI =
Owen Anderson24be4c12009-07-03 00:17:18 +00002357 Context->getConstantExprTrunc(RHSC, LHSConv->getOperand(0)->getType());
Chris Lattner3554f972008-05-20 05:46:13 +00002358 if (LHSConv->hasOneUse() &&
Owen Anderson24be4c12009-07-03 00:17:18 +00002359 Context->getConstantExprSExt(CI, I.getType()) == RHSC &&
Chris Lattner3554f972008-05-20 05:46:13 +00002360 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2361 // Insert the new, smaller add.
2362 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2363 CI, "addconv");
2364 InsertNewInstBefore(NewAdd, I);
2365 return new SExtInst(NewAdd, I.getType());
2366 }
2367 }
2368
2369 // (add (sext x), (sext y)) --> (sext (add int x, y))
2370 if (SExtInst *RHSConv = dyn_cast<SExtInst>(RHS)) {
2371 // Only do this if x/y have the same type, if at last one of them has a
2372 // single use (so we don't increase the number of sexts), and if the
2373 // integer add will not overflow.
2374 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2375 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2376 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2377 RHSConv->getOperand(0))) {
2378 // Insert the new integer add.
2379 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2380 RHSConv->getOperand(0),
2381 "addconv");
2382 InsertNewInstBefore(NewAdd, I);
2383 return new SExtInst(NewAdd, I.getType());
2384 }
2385 }
2386 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002387
2388 return Changed ? &I : 0;
2389}
2390
2391Instruction *InstCombiner::visitFAdd(BinaryOperator &I) {
2392 bool Changed = SimplifyCommutative(I);
2393 Value *LHS = I.getOperand(0), *RHS = I.getOperand(1);
2394
2395 if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
2396 // X + 0 --> X
2397 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
Owen Anderson24be4c12009-07-03 00:17:18 +00002398 if (CFP->isExactlyValue(Context->getConstantFPNegativeZero
Dan Gohman7ce405e2009-06-04 22:49:04 +00002399 (I.getType())->getValueAPF()))
2400 return ReplaceInstUsesWith(I, LHS);
2401 }
2402
2403 if (isa<PHINode>(LHS))
2404 if (Instruction *NV = FoldOpIntoPhi(I))
2405 return NV;
2406 }
2407
2408 // -A + B --> B - A
2409 // -A + -B --> -(A + B)
Owen Anderson24be4c12009-07-03 00:17:18 +00002410 if (Value *LHSV = dyn_castFNegVal(LHS, Context))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002411 return BinaryOperator::CreateFSub(RHS, LHSV);
2412
2413 // A + -B --> A - B
2414 if (!isa<Constant>(RHS))
Owen Anderson24be4c12009-07-03 00:17:18 +00002415 if (Value *V = dyn_castFNegVal(RHS, Context))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002416 return BinaryOperator::CreateFSub(LHS, V);
2417
2418 // Check for X+0.0. Simplify it to X if we know X is not -0.0.
2419 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS))
2420 if (CFP->getValueAPF().isPosZero() && CannotBeNegativeZero(LHS))
2421 return ReplaceInstUsesWith(I, LHS);
2422
Chris Lattner3554f972008-05-20 05:46:13 +00002423 // Check for (add double (sitofp x), y), see if we can merge this into an
2424 // integer add followed by a promotion.
2425 if (SIToFPInst *LHSConv = dyn_cast<SIToFPInst>(LHS)) {
2426 // (add double (sitofp x), fpcst) --> (sitofp (add int x, intcst))
2427 // ... if the constant fits in the integer value. This is useful for things
2428 // like (double)(x & 1234) + 4.0 -> (double)((X & 1234)+4) which no longer
2429 // requires a constant pool load, and generally allows the add to be better
2430 // instcombined.
2431 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHS)) {
2432 Constant *CI =
Owen Anderson24be4c12009-07-03 00:17:18 +00002433 Context->getConstantExprFPToSI(CFP, LHSConv->getOperand(0)->getType());
Chris Lattner3554f972008-05-20 05:46:13 +00002434 if (LHSConv->hasOneUse() &&
Owen Anderson24be4c12009-07-03 00:17:18 +00002435 Context->getConstantExprSIToFP(CI, I.getType()) == CFP &&
Chris Lattner3554f972008-05-20 05:46:13 +00002436 WillNotOverflowSignedAdd(LHSConv->getOperand(0), CI)) {
2437 // Insert the new integer add.
2438 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2439 CI, "addconv");
2440 InsertNewInstBefore(NewAdd, I);
2441 return new SIToFPInst(NewAdd, I.getType());
2442 }
2443 }
2444
2445 // (add double (sitofp x), (sitofp y)) --> (sitofp (add int x, y))
2446 if (SIToFPInst *RHSConv = dyn_cast<SIToFPInst>(RHS)) {
2447 // Only do this if x/y have the same type, if at last one of them has a
2448 // single use (so we don't increase the number of int->fp conversions),
2449 // and if the integer add will not overflow.
2450 if (LHSConv->getOperand(0)->getType()==RHSConv->getOperand(0)->getType()&&
2451 (LHSConv->hasOneUse() || RHSConv->hasOneUse()) &&
2452 WillNotOverflowSignedAdd(LHSConv->getOperand(0),
2453 RHSConv->getOperand(0))) {
2454 // Insert the new integer add.
2455 Instruction *NewAdd = BinaryOperator::CreateAdd(LHSConv->getOperand(0),
2456 RHSConv->getOperand(0),
2457 "addconv");
2458 InsertNewInstBefore(NewAdd, I);
2459 return new SIToFPInst(NewAdd, I.getType());
2460 }
2461 }
2462 }
2463
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002464 return Changed ? &I : 0;
2465}
2466
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002467Instruction *InstCombiner::visitSub(BinaryOperator &I) {
2468 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2469
Dan Gohman7ce405e2009-06-04 22:49:04 +00002470 if (Op0 == Op1) // sub X, X -> 0
Owen Anderson24be4c12009-07-03 00:17:18 +00002471 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002472
2473 // If this is a 'B = x-(-A)', change to B = x+A...
Owen Anderson24be4c12009-07-03 00:17:18 +00002474 if (Value *V = dyn_castNegVal(Op1, Context))
Gabor Greifa645dd32008-05-16 19:29:10 +00002475 return BinaryOperator::CreateAdd(Op0, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002476
2477 if (isa<UndefValue>(Op0))
2478 return ReplaceInstUsesWith(I, Op0); // undef - X -> undef
2479 if (isa<UndefValue>(Op1))
2480 return ReplaceInstUsesWith(I, Op1); // X - undef -> undef
2481
2482 if (ConstantInt *C = dyn_cast<ConstantInt>(Op0)) {
2483 // Replace (-1 - A) with (~A)...
2484 if (C->isAllOnesValue())
Gabor Greifa645dd32008-05-16 19:29:10 +00002485 return BinaryOperator::CreateNot(Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002486
2487 // C - ~X == X + (1+C)
2488 Value *X = 0;
Owen Andersona21eb582009-07-10 17:35:01 +00002489 if (match(Op1, m_Not(m_Value(X)), *Context))
Owen Anderson24be4c12009-07-03 00:17:18 +00002490 return BinaryOperator::CreateAdd(X, AddOne(C, Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002491
2492 // -(X >>u 31) -> (X >>s 31)
2493 // -(X >>s 31) -> (X >>u 31)
2494 if (C->isZero()) {
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002495 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002496 if (SI->getOpcode() == Instruction::LShr) {
2497 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2498 // Check to see if we are shifting out everything but the sign bit.
2499 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2500 SI->getType()->getPrimitiveSizeInBits()-1) {
2501 // Ok, the transformation is safe. Insert AShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002502 return BinaryOperator::Create(Instruction::AShr,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002503 SI->getOperand(0), CU, SI->getName());
2504 }
2505 }
2506 }
2507 else if (SI->getOpcode() == Instruction::AShr) {
2508 if (ConstantInt *CU = dyn_cast<ConstantInt>(SI->getOperand(1))) {
2509 // Check to see if we are shifting out everything but the sign bit.
2510 if (CU->getLimitedValue(SI->getType()->getPrimitiveSizeInBits()) ==
2511 SI->getType()->getPrimitiveSizeInBits()-1) {
2512 // Ok, the transformation is safe. Insert LShr.
Gabor Greifa645dd32008-05-16 19:29:10 +00002513 return BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002514 SI->getOperand(0), CU, SI->getName());
2515 }
2516 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002517 }
2518 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002519 }
2520
2521 // Try to fold constant sub into select arguments.
2522 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
2523 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2524 return R;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002525 }
2526
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002527 if (I.getType() == Type::Int1Ty)
2528 return BinaryOperator::CreateXor(Op0, Op1);
2529
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002530 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Dan Gohman7ce405e2009-06-04 22:49:04 +00002531 if (Op1I->getOpcode() == Instruction::Add) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002532 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002533 return BinaryOperator::CreateNeg(Op1I->getOperand(1), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002534 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
Gabor Greifa645dd32008-05-16 19:29:10 +00002535 return BinaryOperator::CreateNeg(Op1I->getOperand(0), I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002536 else if (ConstantInt *CI1 = dyn_cast<ConstantInt>(I.getOperand(0))) {
2537 if (ConstantInt *CI2 = dyn_cast<ConstantInt>(Op1I->getOperand(1)))
2538 // C1-(X+C2) --> (C1-C2)-X
Owen Anderson24be4c12009-07-03 00:17:18 +00002539 return BinaryOperator::CreateSub(
2540 Context->getConstantExprSub(CI1, CI2), Op1I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002541 }
2542 }
2543
2544 if (Op1I->hasOneUse()) {
2545 // Replace (x - (y - z)) with (x + (z - y)) if the (y - z) subexpression
2546 // is not used by anyone else...
2547 //
Dan Gohman7ce405e2009-06-04 22:49:04 +00002548 if (Op1I->getOpcode() == Instruction::Sub) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002549 // Swap the two operands of the subexpr...
2550 Value *IIOp0 = Op1I->getOperand(0), *IIOp1 = Op1I->getOperand(1);
2551 Op1I->setOperand(0, IIOp1);
2552 Op1I->setOperand(1, IIOp0);
2553
2554 // Create the new top level add instruction...
Gabor Greifa645dd32008-05-16 19:29:10 +00002555 return BinaryOperator::CreateAdd(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002556 }
2557
2558 // Replace (A - (A & B)) with (A & ~B) if this is the only use of (A&B)...
2559 //
2560 if (Op1I->getOpcode() == Instruction::And &&
2561 (Op1I->getOperand(0) == Op0 || Op1I->getOperand(1) == Op0)) {
2562 Value *OtherOp = Op1I->getOperand(Op1I->getOperand(0) == Op0);
2563
2564 Value *NewNot =
Gabor Greifa645dd32008-05-16 19:29:10 +00002565 InsertNewInstBefore(BinaryOperator::CreateNot(OtherOp, "B.not"), I);
2566 return BinaryOperator::CreateAnd(Op0, NewNot);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002567 }
2568
2569 // 0 - (X sdiv C) -> (X sdiv -C)
2570 if (Op1I->getOpcode() == Instruction::SDiv)
2571 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
2572 if (CSI->isZero())
2573 if (Constant *DivRHS = dyn_cast<Constant>(Op1I->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002574 return BinaryOperator::CreateSDiv(Op1I->getOperand(0),
Owen Anderson24be4c12009-07-03 00:17:18 +00002575 Context->getConstantExprNeg(DivRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002576
2577 // X - X*C --> X * (1-C)
2578 ConstantInt *C2 = 0;
Owen Anderson24be4c12009-07-03 00:17:18 +00002579 if (dyn_castFoldableMul(Op1I, C2, Context) == Op0) {
2580 Constant *CP1 =
2581 Context->getConstantExprSub(Context->getConstantInt(I.getType(), 1),
Dan Gohman8fd520a2009-06-15 22:12:54 +00002582 C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00002583 return BinaryOperator::CreateMul(Op0, CP1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002584 }
2585 }
2586 }
2587
Dan Gohman7ce405e2009-06-04 22:49:04 +00002588 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
2589 if (Op0I->getOpcode() == Instruction::Add) {
2590 if (Op0I->getOperand(0) == Op1) // (Y+X)-Y == X
2591 return ReplaceInstUsesWith(I, Op0I->getOperand(1));
2592 else if (Op0I->getOperand(1) == Op1) // (X+Y)-Y == X
2593 return ReplaceInstUsesWith(I, Op0I->getOperand(0));
2594 } else if (Op0I->getOpcode() == Instruction::Sub) {
2595 if (Op0I->getOperand(0) == Op1) // (X-Y)-X == -Y
2596 return BinaryOperator::CreateNeg(Op0I->getOperand(1), I.getName());
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00002597 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002598 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002599
2600 ConstantInt *C1;
Owen Anderson24be4c12009-07-03 00:17:18 +00002601 if (Value *X = dyn_castFoldableMul(Op0, C1, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002602 if (X == Op1) // X*C - X --> X * (C-1)
Owen Anderson24be4c12009-07-03 00:17:18 +00002603 return BinaryOperator::CreateMul(Op1, SubOne(C1, Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002604
2605 ConstantInt *C2; // X*C1 - X*C2 -> X * (C1-C2)
Owen Anderson24be4c12009-07-03 00:17:18 +00002606 if (X == dyn_castFoldableMul(Op1, C2, Context))
2607 return BinaryOperator::CreateMul(X, Context->getConstantExprSub(C1, C2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002608 }
2609 return 0;
2610}
2611
Dan Gohman7ce405e2009-06-04 22:49:04 +00002612Instruction *InstCombiner::visitFSub(BinaryOperator &I) {
2613 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2614
2615 // If this is a 'B = x-(-A)', change to B = x+A...
Owen Anderson24be4c12009-07-03 00:17:18 +00002616 if (Value *V = dyn_castFNegVal(Op1, Context))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002617 return BinaryOperator::CreateFAdd(Op0, V);
2618
2619 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
2620 if (Op1I->getOpcode() == Instruction::FAdd) {
2621 if (Op1I->getOperand(0) == Op0) // X-(X+Y) == -Y
2622 return BinaryOperator::CreateFNeg(Op1I->getOperand(1), I.getName());
2623 else if (Op1I->getOperand(1) == Op0) // X-(Y+X) == -Y
2624 return BinaryOperator::CreateFNeg(Op1I->getOperand(0), I.getName());
2625 }
Dan Gohman7ce405e2009-06-04 22:49:04 +00002626 }
2627
2628 return 0;
2629}
2630
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002631/// isSignBitCheck - Given an exploded icmp instruction, return true if the
2632/// comparison only checks the sign bit. If it only checks the sign bit, set
2633/// TrueIfSigned if the result of the comparison is true when the input value is
2634/// signed.
2635static bool isSignBitCheck(ICmpInst::Predicate pred, ConstantInt *RHS,
2636 bool &TrueIfSigned) {
2637 switch (pred) {
2638 case ICmpInst::ICMP_SLT: // True if LHS s< 0
2639 TrueIfSigned = true;
2640 return RHS->isZero();
2641 case ICmpInst::ICMP_SLE: // True if LHS s<= RHS and RHS == -1
2642 TrueIfSigned = true;
2643 return RHS->isAllOnesValue();
2644 case ICmpInst::ICMP_SGT: // True if LHS s> -1
2645 TrueIfSigned = false;
2646 return RHS->isAllOnesValue();
2647 case ICmpInst::ICMP_UGT:
2648 // True if LHS u> RHS and RHS == high-bit-mask - 1
2649 TrueIfSigned = true;
2650 return RHS->getValue() ==
2651 APInt::getSignedMaxValue(RHS->getType()->getPrimitiveSizeInBits());
2652 case ICmpInst::ICMP_UGE:
2653 // True if LHS u>= RHS and RHS == high-bit-mask (2^7, 2^15, 2^31, etc)
2654 TrueIfSigned = true;
Chris Lattner60813c22008-06-02 01:29:46 +00002655 return RHS->getValue().isSignBit();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002656 default:
2657 return false;
2658 }
2659}
2660
2661Instruction *InstCombiner::visitMul(BinaryOperator &I) {
2662 bool Changed = SimplifyCommutative(I);
2663 Value *Op0 = I.getOperand(0);
2664
Dan Gohmana22a8402009-06-04 17:12:12 +00002665 // TODO: If Op1 is undef and Op0 is finite, return zero.
2666 if (!I.getType()->isFPOrFPVector() &&
2667 isa<UndefValue>(I.getOperand(1))) // undef * X -> 0
Owen Anderson24be4c12009-07-03 00:17:18 +00002668 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002669
2670 // Simplify mul instructions with a constant RHS...
2671 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2672 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
2673
2674 // ((X << C1)*C2) == (X * (C2 << C1))
2675 if (BinaryOperator *SI = dyn_cast<BinaryOperator>(Op0))
2676 if (SI->getOpcode() == Instruction::Shl)
2677 if (Constant *ShOp = dyn_cast<Constant>(SI->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00002678 return BinaryOperator::CreateMul(SI->getOperand(0),
Owen Anderson24be4c12009-07-03 00:17:18 +00002679 Context->getConstantExprShl(CI, ShOp));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002680
2681 if (CI->isZero())
2682 return ReplaceInstUsesWith(I, Op1); // X * 0 == 0
2683 if (CI->equalsInt(1)) // X * 1 == X
2684 return ReplaceInstUsesWith(I, Op0);
2685 if (CI->isAllOnesValue()) // X * -1 == 0 - X
Gabor Greifa645dd32008-05-16 19:29:10 +00002686 return BinaryOperator::CreateNeg(Op0, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002687
2688 const APInt& Val = cast<ConstantInt>(CI)->getValue();
2689 if (Val.isPowerOf2()) { // Replace X*(2^C) with X << C
Gabor Greifa645dd32008-05-16 19:29:10 +00002690 return BinaryOperator::CreateShl(Op0,
Owen Anderson24be4c12009-07-03 00:17:18 +00002691 Context->getConstantInt(Op0->getType(), Val.logBase2()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002692 }
Chris Lattner6297fc72008-08-11 22:06:05 +00002693 } else if (isa<VectorType>(Op1->getType())) {
Dan Gohmana22a8402009-06-04 17:12:12 +00002694 // TODO: If Op1 is all zeros and Op0 is all finite, return all zeros.
Nick Lewycky94418732008-11-27 20:21:08 +00002695
2696 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2697 if (Op1V->isAllOnesValue()) // X * -1 == 0 - X
2698 return BinaryOperator::CreateNeg(Op0, I.getName());
2699
2700 // As above, vector X*splat(1.0) -> X in all defined cases.
2701 if (Constant *Splat = Op1V->getSplatValue()) {
Nick Lewycky94418732008-11-27 20:21:08 +00002702 if (ConstantInt *CI = dyn_cast<ConstantInt>(Splat))
2703 if (CI->equalsInt(1))
2704 return ReplaceInstUsesWith(I, Op0);
2705 }
2706 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002707 }
2708
2709 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0))
2710 if (Op0I->getOpcode() == Instruction::Add && Op0I->hasOneUse() &&
Chris Lattner58194082008-05-18 04:11:26 +00002711 isa<ConstantInt>(Op0I->getOperand(1)) && isa<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002712 // Canonicalize (X+C1)*C2 -> X*C2+C1*C2.
Gabor Greifa645dd32008-05-16 19:29:10 +00002713 Instruction *Add = BinaryOperator::CreateMul(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002714 Op1, "tmp");
2715 InsertNewInstBefore(Add, I);
Owen Anderson24be4c12009-07-03 00:17:18 +00002716 Value *C1C2 = Context->getConstantExprMul(Op1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002717 cast<Constant>(Op0I->getOperand(1)));
Gabor Greifa645dd32008-05-16 19:29:10 +00002718 return BinaryOperator::CreateAdd(Add, C1C2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002719
2720 }
2721
2722 // Try to fold constant mul into select arguments.
2723 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2724 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2725 return R;
2726
2727 if (isa<PHINode>(Op0))
2728 if (Instruction *NV = FoldOpIntoPhi(I))
2729 return NV;
2730 }
2731
Owen Anderson24be4c12009-07-03 00:17:18 +00002732 if (Value *Op0v = dyn_castNegVal(Op0, Context)) // -X * -Y = X*Y
2733 if (Value *Op1v = dyn_castNegVal(I.getOperand(1), Context))
Gabor Greifa645dd32008-05-16 19:29:10 +00002734 return BinaryOperator::CreateMul(Op0v, Op1v);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002735
Nick Lewycky1c246402008-11-21 07:33:58 +00002736 // (X / Y) * Y = X - (X % Y)
2737 // (X / Y) * -Y = (X % Y) - X
2738 {
2739 Value *Op1 = I.getOperand(1);
2740 BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0);
2741 if (!BO ||
2742 (BO->getOpcode() != Instruction::UDiv &&
2743 BO->getOpcode() != Instruction::SDiv)) {
2744 Op1 = Op0;
2745 BO = dyn_cast<BinaryOperator>(I.getOperand(1));
2746 }
Owen Anderson24be4c12009-07-03 00:17:18 +00002747 Value *Neg = dyn_castNegVal(Op1, Context);
Nick Lewycky1c246402008-11-21 07:33:58 +00002748 if (BO && BO->hasOneUse() &&
2749 (BO->getOperand(1) == Op1 || BO->getOperand(1) == Neg) &&
2750 (BO->getOpcode() == Instruction::UDiv ||
2751 BO->getOpcode() == Instruction::SDiv)) {
2752 Value *Op0BO = BO->getOperand(0), *Op1BO = BO->getOperand(1);
2753
2754 Instruction *Rem;
2755 if (BO->getOpcode() == Instruction::UDiv)
2756 Rem = BinaryOperator::CreateURem(Op0BO, Op1BO);
2757 else
2758 Rem = BinaryOperator::CreateSRem(Op0BO, Op1BO);
2759
2760 InsertNewInstBefore(Rem, I);
2761 Rem->takeName(BO);
2762
2763 if (Op1BO == Op1)
2764 return BinaryOperator::CreateSub(Op0BO, Rem);
2765 else
2766 return BinaryOperator::CreateSub(Rem, Op0BO);
2767 }
2768 }
2769
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002770 if (I.getType() == Type::Int1Ty)
2771 return BinaryOperator::CreateAnd(Op0, I.getOperand(1));
2772
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002773 // If one of the operands of the multiply is a cast from a boolean value, then
2774 // we know the bool is either zero or one, so this is a 'masking' multiply.
2775 // See if we can simplify things based on how the boolean was originally
2776 // formed.
2777 CastInst *BoolCast = 0;
Nick Lewyckyd4b63672008-05-31 17:59:52 +00002778 if (ZExtInst *CI = dyn_cast<ZExtInst>(Op0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002779 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2780 BoolCast = CI;
2781 if (!BoolCast)
2782 if (ZExtInst *CI = dyn_cast<ZExtInst>(I.getOperand(1)))
2783 if (CI->getOperand(0)->getType() == Type::Int1Ty)
2784 BoolCast = CI;
2785 if (BoolCast) {
2786 if (ICmpInst *SCI = dyn_cast<ICmpInst>(BoolCast->getOperand(0))) {
2787 Value *SCIOp0 = SCI->getOperand(0), *SCIOp1 = SCI->getOperand(1);
2788 const Type *SCOpTy = SCIOp0->getType();
2789 bool TIS = false;
2790
2791 // If the icmp is true iff the sign bit of X is set, then convert this
2792 // multiply into a shift/and combination.
2793 if (isa<ConstantInt>(SCIOp1) &&
2794 isSignBitCheck(SCI->getPredicate(), cast<ConstantInt>(SCIOp1), TIS) &&
2795 TIS) {
2796 // Shift the X value right to turn it into "all signbits".
Owen Anderson24be4c12009-07-03 00:17:18 +00002797 Constant *Amt = Context->getConstantInt(SCIOp0->getType(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002798 SCOpTy->getPrimitiveSizeInBits()-1);
2799 Value *V =
2800 InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00002801 BinaryOperator::Create(Instruction::AShr, SCIOp0, Amt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002802 BoolCast->getOperand(0)->getName()+
2803 ".mask"), I);
2804
2805 // If the multiply type is not the same as the source type, sign extend
2806 // or truncate to the multiply type.
2807 if (I.getType() != V->getType()) {
2808 uint32_t SrcBits = V->getType()->getPrimitiveSizeInBits();
2809 uint32_t DstBits = I.getType()->getPrimitiveSizeInBits();
2810 Instruction::CastOps opcode =
2811 (SrcBits == DstBits ? Instruction::BitCast :
2812 (SrcBits < DstBits ? Instruction::SExt : Instruction::Trunc));
2813 V = InsertCastBefore(opcode, V, I.getType(), I);
2814 }
2815
2816 Value *OtherOp = Op0 == BoolCast ? I.getOperand(1) : Op0;
Gabor Greifa645dd32008-05-16 19:29:10 +00002817 return BinaryOperator::CreateAnd(V, OtherOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002818 }
2819 }
2820 }
2821
2822 return Changed ? &I : 0;
2823}
2824
Dan Gohman7ce405e2009-06-04 22:49:04 +00002825Instruction *InstCombiner::visitFMul(BinaryOperator &I) {
2826 bool Changed = SimplifyCommutative(I);
2827 Value *Op0 = I.getOperand(0);
2828
2829 // Simplify mul instructions with a constant RHS...
2830 if (Constant *Op1 = dyn_cast<Constant>(I.getOperand(1))) {
2831 if (ConstantFP *Op1F = dyn_cast<ConstantFP>(Op1)) {
2832 // "In IEEE floating point, x*1 is not equivalent to x for nans. However,
2833 // ANSI says we can drop signals, so we can do this anyway." (from GCC)
2834 if (Op1F->isExactlyValue(1.0))
2835 return ReplaceInstUsesWith(I, Op0); // Eliminate 'mul double %X, 1.0'
2836 } else if (isa<VectorType>(Op1->getType())) {
2837 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
2838 // As above, vector X*splat(1.0) -> X in all defined cases.
2839 if (Constant *Splat = Op1V->getSplatValue()) {
2840 if (ConstantFP *F = dyn_cast<ConstantFP>(Splat))
2841 if (F->isExactlyValue(1.0))
2842 return ReplaceInstUsesWith(I, Op0);
2843 }
2844 }
2845 }
2846
2847 // Try to fold constant mul into select arguments.
2848 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
2849 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
2850 return R;
2851
2852 if (isa<PHINode>(Op0))
2853 if (Instruction *NV = FoldOpIntoPhi(I))
2854 return NV;
2855 }
2856
Owen Anderson24be4c12009-07-03 00:17:18 +00002857 if (Value *Op0v = dyn_castFNegVal(Op0, Context)) // -X * -Y = X*Y
2858 if (Value *Op1v = dyn_castFNegVal(I.getOperand(1), Context))
Dan Gohman7ce405e2009-06-04 22:49:04 +00002859 return BinaryOperator::CreateFMul(Op0v, Op1v);
2860
2861 return Changed ? &I : 0;
2862}
2863
Chris Lattner76972db2008-07-14 00:15:52 +00002864/// SimplifyDivRemOfSelect - Try to fold a divide or remainder of a select
2865/// instruction.
2866bool InstCombiner::SimplifyDivRemOfSelect(BinaryOperator &I) {
2867 SelectInst *SI = cast<SelectInst>(I.getOperand(1));
2868
2869 // div/rem X, (Cond ? 0 : Y) -> div/rem X, Y
2870 int NonNullOperand = -1;
2871 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(1)))
2872 if (ST->isNullValue())
2873 NonNullOperand = 2;
2874 // div/rem X, (Cond ? Y : 0) -> div/rem X, Y
2875 if (Constant *ST = dyn_cast<Constant>(SI->getOperand(2)))
2876 if (ST->isNullValue())
2877 NonNullOperand = 1;
2878
2879 if (NonNullOperand == -1)
2880 return false;
2881
2882 Value *SelectCond = SI->getOperand(0);
2883
2884 // Change the div/rem to use 'Y' instead of the select.
2885 I.setOperand(1, SI->getOperand(NonNullOperand));
2886
2887 // Okay, we know we replace the operand of the div/rem with 'Y' with no
2888 // problem. However, the select, or the condition of the select may have
2889 // multiple uses. Based on our knowledge that the operand must be non-zero,
2890 // propagate the known value for the select into other uses of it, and
2891 // propagate a known value of the condition into its other users.
2892
2893 // If the select and condition only have a single use, don't bother with this,
2894 // early exit.
2895 if (SI->use_empty() && SelectCond->hasOneUse())
2896 return true;
2897
2898 // Scan the current block backward, looking for other uses of SI.
2899 BasicBlock::iterator BBI = &I, BBFront = I.getParent()->begin();
2900
2901 while (BBI != BBFront) {
2902 --BBI;
2903 // If we found a call to a function, we can't assume it will return, so
2904 // information from below it cannot be propagated above it.
2905 if (isa<CallInst>(BBI) && !isa<IntrinsicInst>(BBI))
2906 break;
2907
2908 // Replace uses of the select or its condition with the known values.
2909 for (Instruction::op_iterator I = BBI->op_begin(), E = BBI->op_end();
2910 I != E; ++I) {
2911 if (*I == SI) {
2912 *I = SI->getOperand(NonNullOperand);
2913 AddToWorkList(BBI);
2914 } else if (*I == SelectCond) {
Owen Anderson24be4c12009-07-03 00:17:18 +00002915 *I = NonNullOperand == 1 ? Context->getConstantIntTrue() :
2916 Context->getConstantIntFalse();
Chris Lattner76972db2008-07-14 00:15:52 +00002917 AddToWorkList(BBI);
2918 }
2919 }
2920
2921 // If we past the instruction, quit looking for it.
2922 if (&*BBI == SI)
2923 SI = 0;
2924 if (&*BBI == SelectCond)
2925 SelectCond = 0;
2926
2927 // If we ran out of things to eliminate, break out of the loop.
2928 if (SelectCond == 0 && SI == 0)
2929 break;
2930
2931 }
2932 return true;
2933}
2934
2935
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002936/// This function implements the transforms on div instructions that work
2937/// regardless of the kind of div instruction it is (udiv, sdiv, or fdiv). It is
2938/// used by the visitors to those instructions.
2939/// @brief Transforms common to all three div instructions
2940Instruction *InstCombiner::commonDivTransforms(BinaryOperator &I) {
2941 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2942
Chris Lattner653ef3c2008-02-19 06:12:18 +00002943 // undef / X -> 0 for integer.
2944 // undef / X -> undef for FP (the undef could be a snan).
2945 if (isa<UndefValue>(Op0)) {
2946 if (Op0->getType()->isFPOrFPVector())
2947 return ReplaceInstUsesWith(I, Op0);
Owen Anderson24be4c12009-07-03 00:17:18 +00002948 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00002949 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002950
2951 // X / undef -> undef
2952 if (isa<UndefValue>(Op1))
2953 return ReplaceInstUsesWith(I, Op1);
2954
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002955 return 0;
2956}
2957
2958/// This function implements the transforms common to both integer division
2959/// instructions (udiv and sdiv). It is called by the visitors to those integer
2960/// division instructions.
2961/// @brief Common integer divide transforms
2962Instruction *InstCombiner::commonIDivTransforms(BinaryOperator &I) {
2963 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
2964
Chris Lattnercefb36c2008-05-16 02:59:42 +00002965 // (sdiv X, X) --> 1 (udiv X, X) --> 1
Nick Lewycky386c0132008-05-23 03:26:47 +00002966 if (Op0 == Op1) {
2967 if (const VectorType *Ty = dyn_cast<VectorType>(I.getType())) {
Owen Anderson24be4c12009-07-03 00:17:18 +00002968 Constant *CI = Context->getConstantInt(Ty->getElementType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00002969 std::vector<Constant*> Elts(Ty->getNumElements(), CI);
Owen Anderson24be4c12009-07-03 00:17:18 +00002970 return ReplaceInstUsesWith(I, Context->getConstantVector(Elts));
Nick Lewycky386c0132008-05-23 03:26:47 +00002971 }
2972
Owen Anderson24be4c12009-07-03 00:17:18 +00002973 Constant *CI = Context->getConstantInt(I.getType(), 1);
Nick Lewycky386c0132008-05-23 03:26:47 +00002974 return ReplaceInstUsesWith(I, CI);
2975 }
Chris Lattnercefb36c2008-05-16 02:59:42 +00002976
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002977 if (Instruction *Common = commonDivTransforms(I))
2978 return Common;
Chris Lattner76972db2008-07-14 00:15:52 +00002979
2980 // Handle cases involving: [su]div X, (select Cond, Y, Z)
2981 // This does not apply for fdiv.
2982 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
2983 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002984
2985 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
2986 // div X, 1 == X
2987 if (RHS->equalsInt(1))
2988 return ReplaceInstUsesWith(I, Op0);
2989
2990 // (X / C1) / C2 -> X / (C1*C2)
2991 if (Instruction *LHS = dyn_cast<Instruction>(Op0))
2992 if (Instruction::BinaryOps(LHS->getOpcode()) == I.getOpcode())
2993 if (ConstantInt *LHSRHS = dyn_cast<ConstantInt>(LHS->getOperand(1))) {
Owen Anderson24be4c12009-07-03 00:17:18 +00002994 if (MultiplyOverflows(RHS, LHSRHS,
2995 I.getOpcode()==Instruction::SDiv, Context))
2996 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Nick Lewycky9d798f92008-02-18 22:48:05 +00002997 else
Gabor Greifa645dd32008-05-16 19:29:10 +00002998 return BinaryOperator::Create(I.getOpcode(), LHS->getOperand(0),
Owen Anderson24be4c12009-07-03 00:17:18 +00002999 Context->getConstantExprMul(RHS, LHSRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003000 }
3001
3002 if (!RHS->isZero()) { // avoid X udiv 0
3003 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
3004 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3005 return R;
3006 if (isa<PHINode>(Op0))
3007 if (Instruction *NV = FoldOpIntoPhi(I))
3008 return NV;
3009 }
3010 }
3011
3012 // 0 / X == 0, we don't need to preserve faults!
3013 if (ConstantInt *LHS = dyn_cast<ConstantInt>(Op0))
3014 if (LHS->equalsInt(0))
Owen Anderson24be4c12009-07-03 00:17:18 +00003015 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003016
Nick Lewyckyd4b63672008-05-31 17:59:52 +00003017 // It can't be division by zero, hence it must be division by one.
3018 if (I.getType() == Type::Int1Ty)
3019 return ReplaceInstUsesWith(I, Op0);
3020
Nick Lewycky94418732008-11-27 20:21:08 +00003021 if (ConstantVector *Op1V = dyn_cast<ConstantVector>(Op1)) {
3022 if (ConstantInt *X = cast_or_null<ConstantInt>(Op1V->getSplatValue()))
3023 // div X, 1 == X
3024 if (X->isOne())
3025 return ReplaceInstUsesWith(I, Op0);
3026 }
3027
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003028 return 0;
3029}
3030
3031Instruction *InstCombiner::visitUDiv(BinaryOperator &I) {
3032 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3033
3034 // Handle the integer div common cases
3035 if (Instruction *Common = commonIDivTransforms(I))
3036 return Common;
3037
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003038 if (ConstantInt *C = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky240182a2008-11-27 22:41:10 +00003039 // X udiv C^2 -> X >> C
3040 // Check to see if this is an unsigned division with an exact power of 2,
3041 // if so, convert to a right shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003042 if (C->getValue().isPowerOf2()) // 0 not included in isPowerOf2
Gabor Greifa645dd32008-05-16 19:29:10 +00003043 return BinaryOperator::CreateLShr(Op0,
Owen Anderson24be4c12009-07-03 00:17:18 +00003044 Context->getConstantInt(Op0->getType(), C->getValue().logBase2()));
Nick Lewycky240182a2008-11-27 22:41:10 +00003045
3046 // X udiv C, where C >= signbit
3047 if (C->getValue().isNegative()) {
Owen Anderson6601fcd2009-07-09 23:48:35 +00003048 Value *IC = InsertNewInstBefore(new ICmpInst(*Context,
3049 ICmpInst::ICMP_ULT, Op0, C),
Nick Lewycky240182a2008-11-27 22:41:10 +00003050 I);
Owen Anderson24be4c12009-07-03 00:17:18 +00003051 return SelectInst::Create(IC, Context->getNullValue(I.getType()),
3052 Context->getConstantInt(I.getType(), 1));
Nick Lewycky240182a2008-11-27 22:41:10 +00003053 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003054 }
3055
3056 // X udiv (C1 << N), where C1 is "1<<C2" --> X >> (N+C2)
3057 if (BinaryOperator *RHSI = dyn_cast<BinaryOperator>(I.getOperand(1))) {
3058 if (RHSI->getOpcode() == Instruction::Shl &&
3059 isa<ConstantInt>(RHSI->getOperand(0))) {
3060 const APInt& C1 = cast<ConstantInt>(RHSI->getOperand(0))->getValue();
3061 if (C1.isPowerOf2()) {
3062 Value *N = RHSI->getOperand(1);
3063 const Type *NTy = N->getType();
3064 if (uint32_t C2 = C1.logBase2()) {
Owen Anderson24be4c12009-07-03 00:17:18 +00003065 Constant *C2V = Context->getConstantInt(NTy, C2);
Gabor Greifa645dd32008-05-16 19:29:10 +00003066 N = InsertNewInstBefore(BinaryOperator::CreateAdd(N, C2V, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003067 }
Gabor Greifa645dd32008-05-16 19:29:10 +00003068 return BinaryOperator::CreateLShr(Op0, N);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003069 }
3070 }
3071 }
3072
3073 // udiv X, (Select Cond, C1, C2) --> Select Cond, (shr X, C1), (shr X, C2)
3074 // where C1&C2 are powers of two.
3075 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
3076 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3077 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3078 const APInt &TVA = STO->getValue(), &FVA = SFO->getValue();
3079 if (TVA.isPowerOf2() && FVA.isPowerOf2()) {
3080 // Compute the shift amounts
3081 uint32_t TSA = TVA.logBase2(), FSA = FVA.logBase2();
3082 // Construct the "on true" case of the select
Owen Anderson24be4c12009-07-03 00:17:18 +00003083 Constant *TC = Context->getConstantInt(Op0->getType(), TSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00003084 Instruction *TSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003085 Op0, TC, SI->getName()+".t");
3086 TSI = InsertNewInstBefore(TSI, I);
3087
3088 // Construct the "on false" case of the select
Owen Anderson24be4c12009-07-03 00:17:18 +00003089 Constant *FC = Context->getConstantInt(Op0->getType(), FSA);
Gabor Greifa645dd32008-05-16 19:29:10 +00003090 Instruction *FSI = BinaryOperator::CreateLShr(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003091 Op0, FC, SI->getName()+".f");
3092 FSI = InsertNewInstBefore(FSI, I);
3093
3094 // construct the select instruction and return it.
Gabor Greifd6da1d02008-04-06 20:25:17 +00003095 return SelectInst::Create(SI->getOperand(0), TSI, FSI, SI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003096 }
3097 }
3098 return 0;
3099}
3100
3101Instruction *InstCombiner::visitSDiv(BinaryOperator &I) {
3102 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3103
3104 // Handle the integer div common cases
3105 if (Instruction *Common = commonIDivTransforms(I))
3106 return Common;
3107
3108 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3109 // sdiv X, -1 == -X
3110 if (RHS->isAllOnesValue())
Gabor Greifa645dd32008-05-16 19:29:10 +00003111 return BinaryOperator::CreateNeg(Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003112 }
3113
3114 // If the sign bits of both operands are zero (i.e. we can prove they are
3115 // unsigned inputs), turn this into a udiv.
3116 if (I.getType()->isInteger()) {
3117 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3118 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
Dan Gohmandb3dd962007-11-05 23:16:33 +00003119 // X sdiv Y -> X udiv Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00003120 return BinaryOperator::CreateUDiv(Op0, Op1, I.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003121 }
3122 }
3123
3124 return 0;
3125}
3126
3127Instruction *InstCombiner::visitFDiv(BinaryOperator &I) {
3128 return commonDivTransforms(I);
3129}
3130
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003131/// This function implements the transforms on rem instructions that work
3132/// regardless of the kind of rem instruction it is (urem, srem, or frem). It
3133/// is used by the visitors to those instructions.
3134/// @brief Transforms common to all three rem instructions
3135Instruction *InstCombiner::commonRemTransforms(BinaryOperator &I) {
3136 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3137
Chris Lattner653ef3c2008-02-19 06:12:18 +00003138 if (isa<UndefValue>(Op0)) { // undef % X -> 0
3139 if (I.getType()->isFPOrFPVector())
3140 return ReplaceInstUsesWith(I, Op0); // X % undef -> undef (could be SNaN)
Owen Anderson24be4c12009-07-03 00:17:18 +00003141 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattner653ef3c2008-02-19 06:12:18 +00003142 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003143 if (isa<UndefValue>(Op1))
3144 return ReplaceInstUsesWith(I, Op1); // X % undef -> undef
3145
3146 // Handle cases involving: rem X, (select Cond, Y, Z)
Chris Lattner76972db2008-07-14 00:15:52 +00003147 if (isa<SelectInst>(Op1) && SimplifyDivRemOfSelect(I))
3148 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003149
3150 return 0;
3151}
3152
3153/// This function implements the transforms common to both integer remainder
3154/// instructions (urem and srem). It is called by the visitors to those integer
3155/// remainder instructions.
3156/// @brief Common integer remainder transforms
3157Instruction *InstCombiner::commonIRemTransforms(BinaryOperator &I) {
3158 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3159
3160 if (Instruction *common = commonRemTransforms(I))
3161 return common;
3162
Dale Johannesena51f7372009-01-21 00:35:19 +00003163 // 0 % X == 0 for integer, we don't need to preserve faults!
3164 if (Constant *LHS = dyn_cast<Constant>(Op0))
3165 if (LHS->isNullValue())
Owen Anderson24be4c12009-07-03 00:17:18 +00003166 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Dale Johannesena51f7372009-01-21 00:35:19 +00003167
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003168 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3169 // X % 0 == undef, we don't need to preserve faults!
3170 if (RHS->equalsInt(0))
Owen Anderson24be4c12009-07-03 00:17:18 +00003171 return ReplaceInstUsesWith(I, Context->getUndef(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003172
3173 if (RHS->equalsInt(1)) // X % 1 == 0
Owen Anderson24be4c12009-07-03 00:17:18 +00003174 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003175
3176 if (Instruction *Op0I = dyn_cast<Instruction>(Op0)) {
3177 if (SelectInst *SI = dyn_cast<SelectInst>(Op0I)) {
3178 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
3179 return R;
3180 } else if (isa<PHINode>(Op0I)) {
3181 if (Instruction *NV = FoldOpIntoPhi(I))
3182 return NV;
3183 }
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003184
3185 // See if we can fold away this rem instruction.
Chris Lattner676c78e2009-01-31 08:15:18 +00003186 if (SimplifyDemandedInstructionBits(I))
Nick Lewyckyc1372c82008-03-06 06:48:30 +00003187 return &I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003188 }
3189 }
3190
3191 return 0;
3192}
3193
3194Instruction *InstCombiner::visitURem(BinaryOperator &I) {
3195 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3196
3197 if (Instruction *common = commonIRemTransforms(I))
3198 return common;
3199
3200 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
3201 // X urem C^2 -> X and C
3202 // Check to see if this is an unsigned remainder with an exact power of 2,
3203 // if so, convert to a bitwise and.
3204 if (ConstantInt *C = dyn_cast<ConstantInt>(RHS))
3205 if (C->getValue().isPowerOf2())
Owen Anderson24be4c12009-07-03 00:17:18 +00003206 return BinaryOperator::CreateAnd(Op0, SubOne(C, Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003207 }
3208
3209 if (Instruction *RHSI = dyn_cast<Instruction>(I.getOperand(1))) {
3210 // Turn A % (C << N), where C is 2^k, into A & ((C << N)-1)
3211 if (RHSI->getOpcode() == Instruction::Shl &&
3212 isa<ConstantInt>(RHSI->getOperand(0))) {
3213 if (cast<ConstantInt>(RHSI->getOperand(0))->getValue().isPowerOf2()) {
Owen Anderson24be4c12009-07-03 00:17:18 +00003214 Constant *N1 = Context->getConstantIntAllOnesValue(I.getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00003215 Value *Add = InsertNewInstBefore(BinaryOperator::CreateAdd(RHSI, N1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003216 "tmp"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00003217 return BinaryOperator::CreateAnd(Op0, Add);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003218 }
3219 }
3220 }
3221
3222 // urem X, (select Cond, 2^C1, 2^C2) --> select Cond, (and X, C1), (and X, C2)
3223 // where C1&C2 are powers of two.
3224 if (SelectInst *SI = dyn_cast<SelectInst>(Op1)) {
3225 if (ConstantInt *STO = dyn_cast<ConstantInt>(SI->getOperand(1)))
3226 if (ConstantInt *SFO = dyn_cast<ConstantInt>(SI->getOperand(2))) {
3227 // STO == 0 and SFO == 0 handled above.
3228 if ((STO->getValue().isPowerOf2()) &&
3229 (SFO->getValue().isPowerOf2())) {
3230 Value *TrueAnd = InsertNewInstBefore(
Owen Anderson24be4c12009-07-03 00:17:18 +00003231 BinaryOperator::CreateAnd(Op0, SubOne(STO, Context),
3232 SI->getName()+".t"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003233 Value *FalseAnd = InsertNewInstBefore(
Owen Anderson24be4c12009-07-03 00:17:18 +00003234 BinaryOperator::CreateAnd(Op0, SubOne(SFO, Context),
3235 SI->getName()+".f"), I);
Gabor Greifd6da1d02008-04-06 20:25:17 +00003236 return SelectInst::Create(SI->getOperand(0), TrueAnd, FalseAnd);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003237 }
3238 }
3239 }
3240
3241 return 0;
3242}
3243
3244Instruction *InstCombiner::visitSRem(BinaryOperator &I) {
3245 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3246
Dan Gohmandb3dd962007-11-05 23:16:33 +00003247 // Handle the integer rem common cases
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003248 if (Instruction *common = commonIRemTransforms(I))
3249 return common;
3250
Owen Anderson24be4c12009-07-03 00:17:18 +00003251 if (Value *RHSNeg = dyn_castNegVal(Op1, Context))
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00003252 if (!isa<Constant>(RHSNeg) ||
3253 (isa<ConstantInt>(RHSNeg) &&
3254 cast<ConstantInt>(RHSNeg)->getValue().isStrictlyPositive())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003255 // X % -Y -> X % Y
3256 AddUsesToWorkList(I);
3257 I.setOperand(1, RHSNeg);
3258 return &I;
3259 }
Nick Lewycky5515c7a2008-09-30 06:08:34 +00003260
Dan Gohmandb3dd962007-11-05 23:16:33 +00003261 // If the sign bits of both operands are zero (i.e. we can prove they are
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003262 // unsigned inputs), turn this into a urem.
Dan Gohmandb3dd962007-11-05 23:16:33 +00003263 if (I.getType()->isInteger()) {
3264 APInt Mask(APInt::getSignBit(I.getType()->getPrimitiveSizeInBits()));
3265 if (MaskedValueIsZero(Op1, Mask) && MaskedValueIsZero(Op0, Mask)) {
3266 // X srem Y -> X urem Y, iff X and Y don't have sign bit set
Gabor Greifa645dd32008-05-16 19:29:10 +00003267 return BinaryOperator::CreateURem(Op0, Op1, I.getName());
Dan Gohmandb3dd962007-11-05 23:16:33 +00003268 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003269 }
3270
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003271 // If it's a constant vector, flip any negative values positive.
Nick Lewyckyfd746832008-12-20 16:48:00 +00003272 if (ConstantVector *RHSV = dyn_cast<ConstantVector>(Op1)) {
3273 unsigned VWidth = RHSV->getNumOperands();
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003274
Nick Lewyckyfd746832008-12-20 16:48:00 +00003275 bool hasNegative = false;
3276 for (unsigned i = 0; !hasNegative && i != VWidth; ++i)
3277 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i)))
3278 if (RHS->getValue().isNegative())
3279 hasNegative = true;
3280
3281 if (hasNegative) {
3282 std::vector<Constant *> Elts(VWidth);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003283 for (unsigned i = 0; i != VWidth; ++i) {
3284 if (ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV->getOperand(i))) {
3285 if (RHS->getValue().isNegative())
Owen Anderson24be4c12009-07-03 00:17:18 +00003286 Elts[i] = cast<ConstantInt>(Context->getConstantExprNeg(RHS));
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003287 else
3288 Elts[i] = RHS;
3289 }
3290 }
3291
Owen Anderson24be4c12009-07-03 00:17:18 +00003292 Constant *NewRHSV = Context->getConstantVector(Elts);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003293 if (NewRHSV != RHSV) {
Nick Lewycky338ecd52008-12-18 06:42:28 +00003294 AddUsesToWorkList(I);
Nick Lewyckyda9fa432008-12-18 06:31:11 +00003295 I.setOperand(1, NewRHSV);
3296 return &I;
3297 }
3298 }
3299 }
3300
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003301 return 0;
3302}
3303
3304Instruction *InstCombiner::visitFRem(BinaryOperator &I) {
3305 return commonRemTransforms(I);
3306}
3307
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003308// isOneBitSet - Return true if there is exactly one bit set in the specified
3309// constant.
3310static bool isOneBitSet(const ConstantInt *CI) {
3311 return CI->getValue().isPowerOf2();
3312}
3313
3314// isHighOnes - Return true if the constant is of the form 1+0+.
3315// This is the same as lowones(~X).
3316static bool isHighOnes(const ConstantInt *CI) {
3317 return (~CI->getValue() + 1).isPowerOf2();
3318}
3319
3320/// getICmpCode - Encode a icmp predicate into a three bit mask. These bits
3321/// are carefully arranged to allow folding of expressions such as:
3322///
3323/// (A < B) | (A > B) --> (A != B)
3324///
3325/// Note that this is only valid if the first and second predicates have the
3326/// same sign. Is illegal to do: (A u< B) | (A s> B)
3327///
3328/// Three bits are used to represent the condition, as follows:
3329/// 0 A > B
3330/// 1 A == B
3331/// 2 A < B
3332///
3333/// <=> Value Definition
3334/// 000 0 Always false
3335/// 001 1 A > B
3336/// 010 2 A == B
3337/// 011 3 A >= B
3338/// 100 4 A < B
3339/// 101 5 A != B
3340/// 110 6 A <= B
3341/// 111 7 Always true
3342///
3343static unsigned getICmpCode(const ICmpInst *ICI) {
3344 switch (ICI->getPredicate()) {
3345 // False -> 0
3346 case ICmpInst::ICMP_UGT: return 1; // 001
3347 case ICmpInst::ICMP_SGT: return 1; // 001
3348 case ICmpInst::ICMP_EQ: return 2; // 010
3349 case ICmpInst::ICMP_UGE: return 3; // 011
3350 case ICmpInst::ICMP_SGE: return 3; // 011
3351 case ICmpInst::ICMP_ULT: return 4; // 100
3352 case ICmpInst::ICMP_SLT: return 4; // 100
3353 case ICmpInst::ICMP_NE: return 5; // 101
3354 case ICmpInst::ICMP_ULE: return 6; // 110
3355 case ICmpInst::ICMP_SLE: return 6; // 110
3356 // True -> 7
3357 default:
3358 assert(0 && "Invalid ICmp predicate!");
3359 return 0;
3360 }
3361}
3362
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003363/// getFCmpCode - Similar to getICmpCode but for FCmpInst. This encodes a fcmp
3364/// predicate into a three bit mask. It also returns whether it is an ordered
3365/// predicate by reference.
3366static unsigned getFCmpCode(FCmpInst::Predicate CC, bool &isOrdered) {
3367 isOrdered = false;
3368 switch (CC) {
3369 case FCmpInst::FCMP_ORD: isOrdered = true; return 0; // 000
3370 case FCmpInst::FCMP_UNO: return 0; // 000
Evan Chengf1f2cea2008-10-14 18:13:38 +00003371 case FCmpInst::FCMP_OGT: isOrdered = true; return 1; // 001
3372 case FCmpInst::FCMP_UGT: return 1; // 001
3373 case FCmpInst::FCMP_OEQ: isOrdered = true; return 2; // 010
3374 case FCmpInst::FCMP_UEQ: return 2; // 010
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003375 case FCmpInst::FCMP_OGE: isOrdered = true; return 3; // 011
3376 case FCmpInst::FCMP_UGE: return 3; // 011
3377 case FCmpInst::FCMP_OLT: isOrdered = true; return 4; // 100
3378 case FCmpInst::FCMP_ULT: return 4; // 100
Evan Chengf1f2cea2008-10-14 18:13:38 +00003379 case FCmpInst::FCMP_ONE: isOrdered = true; return 5; // 101
3380 case FCmpInst::FCMP_UNE: return 5; // 101
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003381 case FCmpInst::FCMP_OLE: isOrdered = true; return 6; // 110
3382 case FCmpInst::FCMP_ULE: return 6; // 110
Evan Cheng72988052008-10-14 18:44:08 +00003383 // True -> 7
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003384 default:
3385 // Not expecting FCMP_FALSE and FCMP_TRUE;
3386 assert(0 && "Unexpected FCmp predicate!");
3387 return 0;
3388 }
3389}
3390
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003391/// getICmpValue - This is the complement of getICmpCode, which turns an
3392/// opcode and two operands into either a constant true or false, or a brand
Dan Gohmanda338742007-09-17 17:31:57 +00003393/// new ICmp instruction. The sign is passed in to determine which kind
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003394/// of predicate to use in the new icmp instruction.
Owen Anderson24be4c12009-07-03 00:17:18 +00003395static Value *getICmpValue(bool sign, unsigned code, Value *LHS, Value *RHS,
Owen Anderson5349f052009-07-06 23:00:19 +00003396 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003397 switch (code) {
3398 default: assert(0 && "Illegal ICmp code!");
Owen Anderson24be4c12009-07-03 00:17:18 +00003399 case 0: return Context->getConstantIntFalse();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003400 case 1:
3401 if (sign)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003402 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003403 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003404 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, LHS, RHS);
3405 case 2: return new ICmpInst(*Context, ICmpInst::ICMP_EQ, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003406 case 3:
3407 if (sign)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003408 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003409 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003410 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003411 case 4:
3412 if (sign)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003413 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003414 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003415 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHS, RHS);
3416 case 5: return new ICmpInst(*Context, ICmpInst::ICMP_NE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003417 case 6:
3418 if (sign)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003419 return new ICmpInst(*Context, ICmpInst::ICMP_SLE, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003420 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003421 return new ICmpInst(*Context, ICmpInst::ICMP_ULE, LHS, RHS);
Owen Anderson24be4c12009-07-03 00:17:18 +00003422 case 7: return Context->getConstantIntTrue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003423 }
3424}
3425
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003426/// getFCmpValue - This is the complement of getFCmpCode, which turns an
3427/// opcode and two operands into either a FCmp instruction. isordered is passed
3428/// in to determine which kind of predicate to use in the new fcmp instruction.
3429static Value *getFCmpValue(bool isordered, unsigned code,
Owen Anderson5349f052009-07-06 23:00:19 +00003430 Value *LHS, Value *RHS, LLVMContext *Context) {
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003431 switch (code) {
Evan Chengf1f2cea2008-10-14 18:13:38 +00003432 default: assert(0 && "Illegal FCmp code!");
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003433 case 0:
3434 if (isordered)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003435 return new FCmpInst(*Context, FCmpInst::FCMP_ORD, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003436 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003437 return new FCmpInst(*Context, FCmpInst::FCMP_UNO, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003438 case 1:
3439 if (isordered)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003440 return new FCmpInst(*Context, FCmpInst::FCMP_OGT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003441 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003442 return new FCmpInst(*Context, FCmpInst::FCMP_UGT, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003443 case 2:
3444 if (isordered)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003445 return new FCmpInst(*Context, FCmpInst::FCMP_OEQ, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003446 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003447 return new FCmpInst(*Context, FCmpInst::FCMP_UEQ, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003448 case 3:
3449 if (isordered)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003450 return new FCmpInst(*Context, FCmpInst::FCMP_OGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003451 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003452 return new FCmpInst(*Context, FCmpInst::FCMP_UGE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003453 case 4:
3454 if (isordered)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003455 return new FCmpInst(*Context, FCmpInst::FCMP_OLT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003456 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003457 return new FCmpInst(*Context, FCmpInst::FCMP_ULT, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003458 case 5:
3459 if (isordered)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003460 return new FCmpInst(*Context, FCmpInst::FCMP_ONE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003461 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003462 return new FCmpInst(*Context, FCmpInst::FCMP_UNE, LHS, RHS);
Evan Chengf1f2cea2008-10-14 18:13:38 +00003463 case 6:
3464 if (isordered)
Owen Anderson6601fcd2009-07-09 23:48:35 +00003465 return new FCmpInst(*Context, FCmpInst::FCMP_OLE, LHS, RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003466 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00003467 return new FCmpInst(*Context, FCmpInst::FCMP_ULE, LHS, RHS);
Owen Anderson24be4c12009-07-03 00:17:18 +00003468 case 7: return Context->getConstantIntTrue();
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00003469 }
3470}
3471
Chris Lattner2972b822008-11-16 04:55:20 +00003472/// PredicatesFoldable - Return true if both predicates match sign or if at
3473/// least one of them is an equality comparison (which is signless).
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003474static bool PredicatesFoldable(ICmpInst::Predicate p1, ICmpInst::Predicate p2) {
3475 return (ICmpInst::isSignedPredicate(p1) == ICmpInst::isSignedPredicate(p2)) ||
Chris Lattner2972b822008-11-16 04:55:20 +00003476 (ICmpInst::isSignedPredicate(p1) && ICmpInst::isEquality(p2)) ||
3477 (ICmpInst::isSignedPredicate(p2) && ICmpInst::isEquality(p1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003478}
3479
3480namespace {
3481// FoldICmpLogical - Implements (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
3482struct FoldICmpLogical {
3483 InstCombiner &IC;
3484 Value *LHS, *RHS;
3485 ICmpInst::Predicate pred;
3486 FoldICmpLogical(InstCombiner &ic, ICmpInst *ICI)
3487 : IC(ic), LHS(ICI->getOperand(0)), RHS(ICI->getOperand(1)),
3488 pred(ICI->getPredicate()) {}
3489 bool shouldApply(Value *V) const {
3490 if (ICmpInst *ICI = dyn_cast<ICmpInst>(V))
3491 if (PredicatesFoldable(pred, ICI->getPredicate()))
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00003492 return ((ICI->getOperand(0) == LHS && ICI->getOperand(1) == RHS) ||
3493 (ICI->getOperand(0) == RHS && ICI->getOperand(1) == LHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003494 return false;
3495 }
3496 Instruction *apply(Instruction &Log) const {
3497 ICmpInst *ICI = cast<ICmpInst>(Log.getOperand(0));
3498 if (ICI->getOperand(0) != LHS) {
3499 assert(ICI->getOperand(1) == LHS);
3500 ICI->swapOperands(); // Swap the LHS and RHS of the ICmp
3501 }
3502
3503 ICmpInst *RHSICI = cast<ICmpInst>(Log.getOperand(1));
3504 unsigned LHSCode = getICmpCode(ICI);
3505 unsigned RHSCode = getICmpCode(RHSICI);
3506 unsigned Code;
3507 switch (Log.getOpcode()) {
3508 case Instruction::And: Code = LHSCode & RHSCode; break;
3509 case Instruction::Or: Code = LHSCode | RHSCode; break;
3510 case Instruction::Xor: Code = LHSCode ^ RHSCode; break;
3511 default: assert(0 && "Illegal logical opcode!"); return 0;
3512 }
3513
3514 bool isSigned = ICmpInst::isSignedPredicate(RHSICI->getPredicate()) ||
3515 ICmpInst::isSignedPredicate(ICI->getPredicate());
3516
Owen Anderson24be4c12009-07-03 00:17:18 +00003517 Value *RV = getICmpValue(isSigned, Code, LHS, RHS, IC.getContext());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003518 if (Instruction *I = dyn_cast<Instruction>(RV))
3519 return I;
3520 // Otherwise, it's a constant boolean value...
3521 return IC.ReplaceInstUsesWith(Log, RV);
3522 }
3523};
3524} // end anonymous namespace
3525
3526// OptAndOp - This handles expressions of the form ((val OP C1) & C2). Where
3527// the Op parameter is 'OP', OpRHS is 'C1', and AndRHS is 'C2'. Op is
3528// guaranteed to be a binary operator.
3529Instruction *InstCombiner::OptAndOp(Instruction *Op,
3530 ConstantInt *OpRHS,
3531 ConstantInt *AndRHS,
3532 BinaryOperator &TheAnd) {
3533 Value *X = Op->getOperand(0);
3534 Constant *Together = 0;
3535 if (!Op->isShift())
Owen Anderson24be4c12009-07-03 00:17:18 +00003536 Together = Context->getConstantExprAnd(AndRHS, OpRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003537
3538 switch (Op->getOpcode()) {
3539 case Instruction::Xor:
3540 if (Op->hasOneUse()) {
3541 // (X ^ C1) & C2 --> (X & C2) ^ (C1&C2)
Gabor Greifa645dd32008-05-16 19:29:10 +00003542 Instruction *And = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003543 InsertNewInstBefore(And, TheAnd);
3544 And->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003545 return BinaryOperator::CreateXor(And, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003546 }
3547 break;
3548 case Instruction::Or:
3549 if (Together == AndRHS) // (X | C) & C --> C
3550 return ReplaceInstUsesWith(TheAnd, AndRHS);
3551
3552 if (Op->hasOneUse() && Together != OpRHS) {
3553 // (X | C1) & C2 --> (X | (C1&C2)) & C2
Gabor Greifa645dd32008-05-16 19:29:10 +00003554 Instruction *Or = BinaryOperator::CreateOr(X, Together);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003555 InsertNewInstBefore(Or, TheAnd);
3556 Or->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003557 return BinaryOperator::CreateAnd(Or, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003558 }
3559 break;
3560 case Instruction::Add:
3561 if (Op->hasOneUse()) {
3562 // Adding a one to a single bit bit-field should be turned into an XOR
3563 // of the bit. First thing to check is to see if this AND is with a
3564 // single bit constant.
3565 const APInt& AndRHSV = cast<ConstantInt>(AndRHS)->getValue();
3566
3567 // If there is only one bit set...
3568 if (isOneBitSet(cast<ConstantInt>(AndRHS))) {
3569 // Ok, at this point, we know that we are masking the result of the
3570 // ADD down to exactly one bit. If the constant we are adding has
3571 // no bits set below this bit, then we can eliminate the ADD.
3572 const APInt& AddRHS = cast<ConstantInt>(OpRHS)->getValue();
3573
3574 // Check to see if any bits below the one bit set in AndRHSV are set.
3575 if ((AddRHS & (AndRHSV-1)) == 0) {
3576 // If not, the only thing that can effect the output of the AND is
3577 // the bit specified by AndRHSV. If that bit is set, the effect of
3578 // the XOR is to toggle the bit. If it is clear, then the ADD has
3579 // no effect.
3580 if ((AddRHS & AndRHSV) == 0) { // Bit is not set, noop
3581 TheAnd.setOperand(0, X);
3582 return &TheAnd;
3583 } else {
3584 // Pull the XOR out of the AND.
Gabor Greifa645dd32008-05-16 19:29:10 +00003585 Instruction *NewAnd = BinaryOperator::CreateAnd(X, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003586 InsertNewInstBefore(NewAnd, TheAnd);
3587 NewAnd->takeName(Op);
Gabor Greifa645dd32008-05-16 19:29:10 +00003588 return BinaryOperator::CreateXor(NewAnd, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003589 }
3590 }
3591 }
3592 }
3593 break;
3594
3595 case Instruction::Shl: {
3596 // We know that the AND will not produce any of the bits shifted in, so if
3597 // the anded constant includes them, clear them now!
3598 //
3599 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3600 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3601 APInt ShlMask(APInt::getHighBitsSet(BitWidth, BitWidth-OpRHSVal));
Owen Anderson24be4c12009-07-03 00:17:18 +00003602 ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShlMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003603
3604 if (CI->getValue() == ShlMask) {
3605 // Masking out bits that the shift already masks
3606 return ReplaceInstUsesWith(TheAnd, Op); // No need for the and.
3607 } else if (CI != AndRHS) { // Reducing bits set in and.
3608 TheAnd.setOperand(1, CI);
3609 return &TheAnd;
3610 }
3611 break;
3612 }
3613 case Instruction::LShr:
3614 {
3615 // We know that the AND will not produce any of the bits shifted in, so if
3616 // the anded constant includes them, clear them now! This only applies to
3617 // unsigned shifts, because a signed shr may bring in set bits!
3618 //
3619 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3620 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3621 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Anderson24be4c12009-07-03 00:17:18 +00003622 ConstantInt *CI = Context->getConstantInt(AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003623
3624 if (CI->getValue() == ShrMask) {
3625 // Masking out bits that the shift already masks.
3626 return ReplaceInstUsesWith(TheAnd, Op);
3627 } else if (CI != AndRHS) {
3628 TheAnd.setOperand(1, CI); // Reduce bits set in and cst.
3629 return &TheAnd;
3630 }
3631 break;
3632 }
3633 case Instruction::AShr:
3634 // Signed shr.
3635 // See if this is shifting in some sign extension, then masking it out
3636 // with an and.
3637 if (Op->hasOneUse()) {
3638 uint32_t BitWidth = AndRHS->getType()->getBitWidth();
3639 uint32_t OpRHSVal = OpRHS->getLimitedValue(BitWidth);
3640 APInt ShrMask(APInt::getLowBitsSet(BitWidth, BitWidth - OpRHSVal));
Owen Anderson24be4c12009-07-03 00:17:18 +00003641 Constant *C = Context->getConstantInt(AndRHS->getValue() & ShrMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003642 if (C == AndRHS) { // Masking out bits shifted in.
3643 // (Val ashr C1) & C2 -> (Val lshr C1) & C2
3644 // Make the argument unsigned.
3645 Value *ShVal = Op->getOperand(0);
3646 ShVal = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00003647 BinaryOperator::CreateLShr(ShVal, OpRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003648 Op->getName()), TheAnd);
Gabor Greifa645dd32008-05-16 19:29:10 +00003649 return BinaryOperator::CreateAnd(ShVal, AndRHS, TheAnd.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003650 }
3651 }
3652 break;
3653 }
3654 return 0;
3655}
3656
3657
3658/// InsertRangeTest - Emit a computation of: (V >= Lo && V < Hi) if Inside is
3659/// true, otherwise (V < Lo || V >= Hi). In pratice, we emit the more efficient
3660/// (V-Lo) <u Hi-Lo. This method expects that Lo <= Hi. isSigned indicates
3661/// whether to treat the V, Lo and HI as signed or not. IB is the location to
3662/// insert new instructions.
3663Instruction *InstCombiner::InsertRangeTest(Value *V, Constant *Lo, Constant *Hi,
3664 bool isSigned, bool Inside,
3665 Instruction &IB) {
Owen Anderson24be4c12009-07-03 00:17:18 +00003666 assert(cast<ConstantInt>(Context->getConstantExprICmp((isSigned ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003667 ICmpInst::ICMP_SLE:ICmpInst::ICMP_ULE), Lo, Hi))->getZExtValue() &&
3668 "Lo is not <= Hi in range emission code!");
3669
3670 if (Inside) {
3671 if (Lo == Hi) // Trivially false.
Owen Anderson6601fcd2009-07-09 23:48:35 +00003672 return new ICmpInst(*Context, ICmpInst::ICMP_NE, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003673
3674 // V >= Min && V < Hi --> V < Hi
3675 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3676 ICmpInst::Predicate pred = (isSigned ?
3677 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT);
Owen Anderson6601fcd2009-07-09 23:48:35 +00003678 return new ICmpInst(*Context, pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003679 }
3680
3681 // Emit V-Lo <u Hi-Lo
Owen Anderson24be4c12009-07-03 00:17:18 +00003682 Constant *NegLo = Context->getConstantExprNeg(Lo);
Gabor Greifa645dd32008-05-16 19:29:10 +00003683 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003684 InsertNewInstBefore(Add, IB);
Owen Anderson24be4c12009-07-03 00:17:18 +00003685 Constant *UpperBound = Context->getConstantExprAdd(NegLo, Hi);
Owen Anderson6601fcd2009-07-09 23:48:35 +00003686 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, UpperBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003687 }
3688
3689 if (Lo == Hi) // Trivially true.
Owen Anderson6601fcd2009-07-09 23:48:35 +00003690 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, V, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003691
3692 // V < Min || V >= Hi -> V > Hi-1
Owen Anderson24be4c12009-07-03 00:17:18 +00003693 Hi = SubOne(cast<ConstantInt>(Hi), Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003694 if (cast<ConstantInt>(Lo)->isMinValue(isSigned)) {
3695 ICmpInst::Predicate pred = (isSigned ?
3696 ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT);
Owen Anderson6601fcd2009-07-09 23:48:35 +00003697 return new ICmpInst(*Context, pred, V, Hi);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003698 }
3699
3700 // Emit V-Lo >u Hi-1-Lo
3701 // Note that Hi has already had one subtracted from it, above.
Owen Anderson24be4c12009-07-03 00:17:18 +00003702 ConstantInt *NegLo = cast<ConstantInt>(Context->getConstantExprNeg(Lo));
Gabor Greifa645dd32008-05-16 19:29:10 +00003703 Instruction *Add = BinaryOperator::CreateAdd(V, NegLo, V->getName()+".off");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003704 InsertNewInstBefore(Add, IB);
Owen Anderson24be4c12009-07-03 00:17:18 +00003705 Constant *LowerBound = Context->getConstantExprAdd(NegLo, Hi);
Owen Anderson6601fcd2009-07-09 23:48:35 +00003706 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add, LowerBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003707}
3708
3709// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
3710// any number of 0s on either side. The 1s are allowed to wrap from LSB to
3711// MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs. 0x0F0F0000 is
3712// not, since all 1s are not contiguous.
3713static bool isRunOfOnes(ConstantInt *Val, uint32_t &MB, uint32_t &ME) {
3714 const APInt& V = Val->getValue();
3715 uint32_t BitWidth = Val->getType()->getBitWidth();
3716 if (!APIntOps::isShiftedMask(BitWidth, V)) return false;
3717
3718 // look for the first zero bit after the run of ones
3719 MB = BitWidth - ((V - 1) ^ V).countLeadingZeros();
3720 // look for the first non-zero bit
3721 ME = V.getActiveBits();
3722 return true;
3723}
3724
3725/// FoldLogicalPlusAnd - This is part of an expression (LHS +/- RHS) & Mask,
3726/// where isSub determines whether the operator is a sub. If we can fold one of
3727/// the following xforms:
3728///
3729/// ((A & N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == Mask
3730/// ((A | N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3731/// ((A ^ N) +/- B) & Mask -> (A +/- B) & Mask iff N&Mask == 0
3732///
3733/// return (A +/- B).
3734///
3735Value *InstCombiner::FoldLogicalPlusAnd(Value *LHS, Value *RHS,
3736 ConstantInt *Mask, bool isSub,
3737 Instruction &I) {
3738 Instruction *LHSI = dyn_cast<Instruction>(LHS);
3739 if (!LHSI || LHSI->getNumOperands() != 2 ||
3740 !isa<ConstantInt>(LHSI->getOperand(1))) return 0;
3741
3742 ConstantInt *N = cast<ConstantInt>(LHSI->getOperand(1));
3743
3744 switch (LHSI->getOpcode()) {
3745 default: return 0;
3746 case Instruction::And:
Owen Anderson24be4c12009-07-03 00:17:18 +00003747 if (Context->getConstantExprAnd(N, Mask) == Mask) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003748 // If the AndRHS is a power of two minus one (0+1+), this is simple.
3749 if ((Mask->getValue().countLeadingZeros() +
3750 Mask->getValue().countPopulation()) ==
3751 Mask->getValue().getBitWidth())
3752 break;
3753
3754 // Otherwise, if Mask is 0+1+0+, and if B is known to have the low 0+
3755 // part, we don't need any explicit masks to take them out of A. If that
3756 // is all N is, ignore it.
3757 uint32_t MB = 0, ME = 0;
3758 if (isRunOfOnes(Mask, MB, ME)) { // begin/end bit of run, inclusive
3759 uint32_t BitWidth = cast<IntegerType>(RHS->getType())->getBitWidth();
3760 APInt Mask(APInt::getLowBitsSet(BitWidth, MB-1));
3761 if (MaskedValueIsZero(RHS, Mask))
3762 break;
3763 }
3764 }
3765 return 0;
3766 case Instruction::Or:
3767 case Instruction::Xor:
3768 // If the AndRHS is a power of two minus one (0+1+), and N&Mask == 0
3769 if ((Mask->getValue().countLeadingZeros() +
3770 Mask->getValue().countPopulation()) == Mask->getValue().getBitWidth()
Owen Anderson24be4c12009-07-03 00:17:18 +00003771 && Context->getConstantExprAnd(N, Mask)->isNullValue())
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003772 break;
3773 return 0;
3774 }
3775
3776 Instruction *New;
3777 if (isSub)
Gabor Greifa645dd32008-05-16 19:29:10 +00003778 New = BinaryOperator::CreateSub(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003779 else
Gabor Greifa645dd32008-05-16 19:29:10 +00003780 New = BinaryOperator::CreateAdd(LHSI->getOperand(0), RHS, "fold");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003781 return InsertNewInstBefore(New, I);
3782}
3783
Chris Lattner0631ea72008-11-16 05:06:21 +00003784/// FoldAndOfICmps - Fold (icmp)&(icmp) if possible.
3785Instruction *InstCombiner::FoldAndOfICmps(Instruction &I,
3786 ICmpInst *LHS, ICmpInst *RHS) {
Chris Lattnerf3803482008-11-16 05:10:52 +00003787 Value *Val, *Val2;
Chris Lattner0631ea72008-11-16 05:06:21 +00003788 ConstantInt *LHSCst, *RHSCst;
3789 ICmpInst::Predicate LHSCC, RHSCC;
3790
Chris Lattnerf3803482008-11-16 05:10:52 +00003791 // This only handles icmp of constants: (icmp1 A, C1) & (icmp2 B, C2).
Owen Andersona21eb582009-07-10 17:35:01 +00003792 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
3793 m_ConstantInt(LHSCst)), *Context) ||
3794 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
3795 m_ConstantInt(RHSCst)), *Context))
Chris Lattner0631ea72008-11-16 05:06:21 +00003796 return 0;
Chris Lattnerf3803482008-11-16 05:10:52 +00003797
3798 // (icmp ult A, C) & (icmp ult B, C) --> (icmp ult (A|B), C)
3799 // where C is a power of 2
3800 if (LHSCst == RHSCst && LHSCC == RHSCC && LHSCC == ICmpInst::ICMP_ULT &&
3801 LHSCst->getValue().isPowerOf2()) {
3802 Instruction *NewOr = BinaryOperator::CreateOr(Val, Val2);
3803 InsertNewInstBefore(NewOr, I);
Owen Anderson6601fcd2009-07-09 23:48:35 +00003804 return new ICmpInst(*Context, LHSCC, NewOr, LHSCst);
Chris Lattnerf3803482008-11-16 05:10:52 +00003805 }
3806
3807 // From here on, we only handle:
3808 // (icmp1 A, C1) & (icmp2 A, C2) --> something simpler.
3809 if (Val != Val2) return 0;
3810
Chris Lattner0631ea72008-11-16 05:06:21 +00003811 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
3812 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
3813 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
3814 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
3815 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
3816 return 0;
3817
3818 // We can't fold (ugt x, C) & (sgt x, C2).
3819 if (!PredicatesFoldable(LHSCC, RHSCC))
3820 return 0;
3821
3822 // Ensure that the larger constant is on the RHS.
Chris Lattner665298f2008-11-16 05:14:43 +00003823 bool ShouldSwap;
Chris Lattner0631ea72008-11-16 05:06:21 +00003824 if (ICmpInst::isSignedPredicate(LHSCC) ||
3825 (ICmpInst::isEquality(LHSCC) &&
3826 ICmpInst::isSignedPredicate(RHSCC)))
Chris Lattner665298f2008-11-16 05:14:43 +00003827 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
Chris Lattner0631ea72008-11-16 05:06:21 +00003828 else
Chris Lattner665298f2008-11-16 05:14:43 +00003829 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
3830
3831 if (ShouldSwap) {
Chris Lattner0631ea72008-11-16 05:06:21 +00003832 std::swap(LHS, RHS);
3833 std::swap(LHSCst, RHSCst);
3834 std::swap(LHSCC, RHSCC);
3835 }
3836
3837 // At this point, we know we have have two icmp instructions
3838 // comparing a value against two constants and and'ing the result
3839 // together. Because of the above check, we know that we only have
3840 // icmp eq, icmp ne, icmp [su]lt, and icmp [SU]gt here. We also know
3841 // (from the FoldICmpLogical check above), that the two constants
3842 // are not equal and that the larger constant is on the RHS
3843 assert(LHSCst != RHSCst && "Compares not folded above?");
3844
3845 switch (LHSCC) {
3846 default: assert(0 && "Unknown integer condition code!");
3847 case ICmpInst::ICMP_EQ:
3848 switch (RHSCC) {
3849 default: assert(0 && "Unknown integer condition code!");
3850 case ICmpInst::ICMP_EQ: // (X == 13 & X == 15) -> false
3851 case ICmpInst::ICMP_UGT: // (X == 13 & X > 15) -> false
3852 case ICmpInst::ICMP_SGT: // (X == 13 & X > 15) -> false
Owen Anderson24be4c12009-07-03 00:17:18 +00003853 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner0631ea72008-11-16 05:06:21 +00003854 case ICmpInst::ICMP_NE: // (X == 13 & X != 15) -> X == 13
3855 case ICmpInst::ICMP_ULT: // (X == 13 & X < 15) -> X == 13
3856 case ICmpInst::ICMP_SLT: // (X == 13 & X < 15) -> X == 13
3857 return ReplaceInstUsesWith(I, LHS);
3858 }
3859 case ICmpInst::ICMP_NE:
3860 switch (RHSCC) {
3861 default: assert(0 && "Unknown integer condition code!");
3862 case ICmpInst::ICMP_ULT:
Owen Anderson24be4c12009-07-03 00:17:18 +00003863 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X u< 14) -> X < 13
Owen Anderson6601fcd2009-07-09 23:48:35 +00003864 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Val, LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003865 break; // (X != 13 & X u< 15) -> no change
3866 case ICmpInst::ICMP_SLT:
Owen Anderson24be4c12009-07-03 00:17:18 +00003867 if (LHSCst == SubOne(RHSCst, Context)) // (X != 13 & X s< 14) -> X < 13
Owen Anderson6601fcd2009-07-09 23:48:35 +00003868 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Val, LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003869 break; // (X != 13 & X s< 15) -> no change
3870 case ICmpInst::ICMP_EQ: // (X != 13 & X == 15) -> X == 15
3871 case ICmpInst::ICMP_UGT: // (X != 13 & X u> 15) -> X u> 15
3872 case ICmpInst::ICMP_SGT: // (X != 13 & X s> 15) -> X s> 15
3873 return ReplaceInstUsesWith(I, RHS);
3874 case ICmpInst::ICMP_NE:
Owen Anderson24be4c12009-07-03 00:17:18 +00003875 if (LHSCst == SubOne(RHSCst, Context)){// (X != 13 & X != 14) -> X-13 >u 1
3876 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003877 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
3878 Val->getName()+".off");
3879 InsertNewInstBefore(Add, I);
Owen Anderson6601fcd2009-07-09 23:48:35 +00003880 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Add,
Owen Anderson24be4c12009-07-03 00:17:18 +00003881 Context->getConstantInt(Add->getType(), 1));
Chris Lattner0631ea72008-11-16 05:06:21 +00003882 }
3883 break; // (X != 13 & X != 15) -> no change
3884 }
3885 break;
3886 case ICmpInst::ICMP_ULT:
3887 switch (RHSCC) {
3888 default: assert(0 && "Unknown integer condition code!");
3889 case ICmpInst::ICMP_EQ: // (X u< 13 & X == 15) -> false
3890 case ICmpInst::ICMP_UGT: // (X u< 13 & X u> 15) -> false
Owen Anderson24be4c12009-07-03 00:17:18 +00003891 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner0631ea72008-11-16 05:06:21 +00003892 case ICmpInst::ICMP_SGT: // (X u< 13 & X s> 15) -> no change
3893 break;
3894 case ICmpInst::ICMP_NE: // (X u< 13 & X != 15) -> X u< 13
3895 case ICmpInst::ICMP_ULT: // (X u< 13 & X u< 15) -> X u< 13
3896 return ReplaceInstUsesWith(I, LHS);
3897 case ICmpInst::ICMP_SLT: // (X u< 13 & X s< 15) -> no change
3898 break;
3899 }
3900 break;
3901 case ICmpInst::ICMP_SLT:
3902 switch (RHSCC) {
3903 default: assert(0 && "Unknown integer condition code!");
3904 case ICmpInst::ICMP_EQ: // (X s< 13 & X == 15) -> false
3905 case ICmpInst::ICMP_SGT: // (X s< 13 & X s> 15) -> false
Owen Anderson24be4c12009-07-03 00:17:18 +00003906 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner0631ea72008-11-16 05:06:21 +00003907 case ICmpInst::ICMP_UGT: // (X s< 13 & X u> 15) -> no change
3908 break;
3909 case ICmpInst::ICMP_NE: // (X s< 13 & X != 15) -> X < 13
3910 case ICmpInst::ICMP_SLT: // (X s< 13 & X s< 15) -> X < 13
3911 return ReplaceInstUsesWith(I, LHS);
3912 case ICmpInst::ICMP_ULT: // (X s< 13 & X u< 15) -> no change
3913 break;
3914 }
3915 break;
3916 case ICmpInst::ICMP_UGT:
3917 switch (RHSCC) {
3918 default: assert(0 && "Unknown integer condition code!");
3919 case ICmpInst::ICMP_EQ: // (X u> 13 & X == 15) -> X == 15
3920 case ICmpInst::ICMP_UGT: // (X u> 13 & X u> 15) -> X u> 15
3921 return ReplaceInstUsesWith(I, RHS);
3922 case ICmpInst::ICMP_SGT: // (X u> 13 & X s> 15) -> no change
3923 break;
3924 case ICmpInst::ICMP_NE:
Owen Anderson24be4c12009-07-03 00:17:18 +00003925 if (RHSCst == AddOne(LHSCst, Context)) // (X u> 13 & X != 14) -> X u> 14
Owen Anderson6601fcd2009-07-09 23:48:35 +00003926 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003927 break; // (X u> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00003928 case ICmpInst::ICMP_ULT: // (X u> 13 & X u< 15) -> (X-14) <u 1
Owen Anderson24be4c12009-07-03 00:17:18 +00003929 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3930 RHSCst, false, true, I);
Chris Lattner0631ea72008-11-16 05:06:21 +00003931 case ICmpInst::ICMP_SLT: // (X u> 13 & X s< 15) -> no change
3932 break;
3933 }
3934 break;
3935 case ICmpInst::ICMP_SGT:
3936 switch (RHSCC) {
3937 default: assert(0 && "Unknown integer condition code!");
3938 case ICmpInst::ICMP_EQ: // (X s> 13 & X == 15) -> X == 15
3939 case ICmpInst::ICMP_SGT: // (X s> 13 & X s> 15) -> X s> 15
3940 return ReplaceInstUsesWith(I, RHS);
3941 case ICmpInst::ICMP_UGT: // (X s> 13 & X u> 15) -> no change
3942 break;
3943 case ICmpInst::ICMP_NE:
Owen Anderson24be4c12009-07-03 00:17:18 +00003944 if (RHSCst == AddOne(LHSCst, Context)) // (X s> 13 & X != 14) -> X s> 14
Owen Anderson6601fcd2009-07-09 23:48:35 +00003945 return new ICmpInst(*Context, LHSCC, Val, RHSCst);
Chris Lattner0631ea72008-11-16 05:06:21 +00003946 break; // (X s> 13 & X != 15) -> no change
Chris Lattner0c678e52008-11-16 05:20:07 +00003947 case ICmpInst::ICMP_SLT: // (X s> 13 & X s< 15) -> (X-14) s< 1
Owen Anderson24be4c12009-07-03 00:17:18 +00003948 return InsertRangeTest(Val, AddOne(LHSCst, Context),
3949 RHSCst, true, true, I);
Chris Lattner0631ea72008-11-16 05:06:21 +00003950 case ICmpInst::ICMP_ULT: // (X s> 13 & X u< 15) -> no change
3951 break;
3952 }
3953 break;
3954 }
Chris Lattner0631ea72008-11-16 05:06:21 +00003955
3956 return 0;
3957}
3958
3959
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003960Instruction *InstCombiner::visitAnd(BinaryOperator &I) {
3961 bool Changed = SimplifyCommutative(I);
3962 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
3963
3964 if (isa<UndefValue>(Op1)) // X & undef -> 0
Owen Anderson24be4c12009-07-03 00:17:18 +00003965 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003966
3967 // and X, X = X
3968 if (Op0 == Op1)
3969 return ReplaceInstUsesWith(I, Op1);
3970
3971 // See if we can simplify any instructions used by the instruction whose sole
3972 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00003973 if (SimplifyDemandedInstructionBits(I))
3974 return &I;
3975 if (isa<VectorType>(I.getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003976 if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
3977 if (CP->isAllOnesValue()) // X & <-1,-1> -> X
3978 return ReplaceInstUsesWith(I, I.getOperand(0));
3979 } else if (isa<ConstantAggregateZero>(Op1)) {
3980 return ReplaceInstUsesWith(I, Op1); // X & <0,0> -> <0,0>
3981 }
3982 }
Dan Gohman8fd520a2009-06-15 22:12:54 +00003983
Dan Gohmanf17a25c2007-07-18 16:29:46 +00003984 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(Op1)) {
3985 const APInt& AndRHSMask = AndRHS->getValue();
3986 APInt NotAndRHS(~AndRHSMask);
3987
3988 // Optimize a variety of ((val OP C1) & C2) combinations...
3989 if (isa<BinaryOperator>(Op0)) {
3990 Instruction *Op0I = cast<Instruction>(Op0);
3991 Value *Op0LHS = Op0I->getOperand(0);
3992 Value *Op0RHS = Op0I->getOperand(1);
3993 switch (Op0I->getOpcode()) {
3994 case Instruction::Xor:
3995 case Instruction::Or:
3996 // If the mask is only needed on one incoming arm, push it up.
3997 if (Op0I->hasOneUse()) {
3998 if (MaskedValueIsZero(Op0LHS, NotAndRHS)) {
3999 // Not masking anything out for the LHS, move to RHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00004000 Instruction *NewRHS = BinaryOperator::CreateAnd(Op0RHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004001 Op0RHS->getName()+".masked");
4002 InsertNewInstBefore(NewRHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004003 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004004 cast<BinaryOperator>(Op0I)->getOpcode(), Op0LHS, NewRHS);
4005 }
4006 if (!isa<Constant>(Op0RHS) &&
4007 MaskedValueIsZero(Op0RHS, NotAndRHS)) {
4008 // Not masking anything out for the RHS, move to LHS.
Gabor Greifa645dd32008-05-16 19:29:10 +00004009 Instruction *NewLHS = BinaryOperator::CreateAnd(Op0LHS, AndRHS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004010 Op0LHS->getName()+".masked");
4011 InsertNewInstBefore(NewLHS, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004012 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004013 cast<BinaryOperator>(Op0I)->getOpcode(), NewLHS, Op0RHS);
4014 }
4015 }
4016
4017 break;
4018 case Instruction::Add:
4019 // ((A & N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == AndRHS.
4020 // ((A | N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4021 // ((A ^ N) + B) & AndRHS -> (A + B) & AndRHS iff N&AndRHS == 0
4022 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004023 return BinaryOperator::CreateAnd(V, AndRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004024 if (Value *V = FoldLogicalPlusAnd(Op0RHS, Op0LHS, AndRHS, false, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004025 return BinaryOperator::CreateAnd(V, AndRHS); // Add commutes
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004026 break;
4027
4028 case Instruction::Sub:
4029 // ((A & N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == AndRHS.
4030 // ((A | N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4031 // ((A ^ N) - B) & AndRHS -> (A - B) & AndRHS iff N&AndRHS == 0
4032 if (Value *V = FoldLogicalPlusAnd(Op0LHS, Op0RHS, AndRHS, true, I))
Gabor Greifa645dd32008-05-16 19:29:10 +00004033 return BinaryOperator::CreateAnd(V, AndRHS);
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004034
Nick Lewyckya349ba42008-07-10 05:51:40 +00004035 // (A - N) & AndRHS -> -N & AndRHS iff A&AndRHS==0 and AndRHS
4036 // has 1's for all bits that the subtraction with A might affect.
4037 if (Op0I->hasOneUse()) {
4038 uint32_t BitWidth = AndRHSMask.getBitWidth();
4039 uint32_t Zeros = AndRHSMask.countLeadingZeros();
4040 APInt Mask = APInt::getLowBitsSet(BitWidth, BitWidth - Zeros);
4041
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004042 ConstantInt *A = dyn_cast<ConstantInt>(Op0LHS);
Nick Lewyckya349ba42008-07-10 05:51:40 +00004043 if (!(A && A->isZero()) && // avoid infinite recursion.
4044 MaskedValueIsZero(Op0LHS, Mask)) {
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004045 Instruction *NewNeg = BinaryOperator::CreateNeg(Op0RHS);
4046 InsertNewInstBefore(NewNeg, I);
4047 return BinaryOperator::CreateAnd(NewNeg, AndRHS);
4048 }
4049 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004050 break;
Nick Lewycky659ed4d2008-07-09 05:20:13 +00004051
4052 case Instruction::Shl:
4053 case Instruction::LShr:
4054 // (1 << x) & 1 --> zext(x == 0)
4055 // (1 >> x) & 1 --> zext(x == 0)
Nick Lewyckyf1b12222008-07-09 07:35:26 +00004056 if (AndRHSMask == 1 && Op0LHS == AndRHS) {
Owen Anderson6601fcd2009-07-09 23:48:35 +00004057 Instruction *NewICmp = new ICmpInst(*Context, ICmpInst::ICMP_EQ,
4058 Op0RHS, Context->getNullValue(I.getType()));
Nick Lewycky659ed4d2008-07-09 05:20:13 +00004059 InsertNewInstBefore(NewICmp, I);
4060 return new ZExtInst(NewICmp, I.getType());
4061 }
4062 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004063 }
4064
4065 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1)))
4066 if (Instruction *Res = OptAndOp(Op0I, Op0CI, AndRHS, I))
4067 return Res;
4068 } else if (CastInst *CI = dyn_cast<CastInst>(Op0)) {
4069 // If this is an integer truncation or change from signed-to-unsigned, and
4070 // if the source is an and/or with immediate, transform it. This
4071 // frequently occurs for bitfield accesses.
4072 if (Instruction *CastOp = dyn_cast<Instruction>(CI->getOperand(0))) {
4073 if ((isa<TruncInst>(CI) || isa<BitCastInst>(CI)) &&
4074 CastOp->getNumOperands() == 2)
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004075 if (ConstantInt *AndCI = dyn_cast<ConstantInt>(CastOp->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004076 if (CastOp->getOpcode() == Instruction::And) {
4077 // Change: and (cast (and X, C1) to T), C2
4078 // into : and (cast X to T), trunc_or_bitcast(C1)&C2
4079 // This will fold the two constants together, which may allow
4080 // other simplifications.
Gabor Greifa645dd32008-05-16 19:29:10 +00004081 Instruction *NewCast = CastInst::CreateTruncOrBitCast(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004082 CastOp->getOperand(0), I.getType(),
4083 CastOp->getName()+".shrunk");
4084 NewCast = InsertNewInstBefore(NewCast, I);
4085 // trunc_or_bitcast(C1)&C2
Owen Anderson24be4c12009-07-03 00:17:18 +00004086 Constant *C3 =
4087 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4088 C3 = Context->getConstantExprAnd(C3, AndRHS);
Gabor Greifa645dd32008-05-16 19:29:10 +00004089 return BinaryOperator::CreateAnd(NewCast, C3);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004090 } else if (CastOp->getOpcode() == Instruction::Or) {
4091 // Change: and (cast (or X, C1) to T), C2
4092 // into : trunc(C1)&C2 iff trunc(C1)&C2 == C2
Owen Anderson24be4c12009-07-03 00:17:18 +00004093 Constant *C3 =
4094 Context->getConstantExprTruncOrBitCast(AndCI,I.getType());
4095 if (Context->getConstantExprAnd(C3, AndRHS) == AndRHS)
4096 // trunc(C1)&C2
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004097 return ReplaceInstUsesWith(I, AndRHS);
4098 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00004099 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004100 }
4101 }
4102
4103 // Try to fold constant and into select arguments.
4104 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4105 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4106 return R;
4107 if (isa<PHINode>(Op0))
4108 if (Instruction *NV = FoldOpIntoPhi(I))
4109 return NV;
4110 }
4111
Owen Anderson24be4c12009-07-03 00:17:18 +00004112 Value *Op0NotVal = dyn_castNotVal(Op0, Context);
4113 Value *Op1NotVal = dyn_castNotVal(Op1, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004114
4115 if (Op0NotVal == Op1 || Op1NotVal == Op0) // A & ~A == ~A & A == 0
Owen Anderson24be4c12009-07-03 00:17:18 +00004116 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004117
4118 // (~A & ~B) == (~(A | B)) - De Morgan's Law
4119 if (Op0NotVal && Op1NotVal && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004120 Instruction *Or = BinaryOperator::CreateOr(Op0NotVal, Op1NotVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004121 I.getName()+".demorgan");
4122 InsertNewInstBefore(Or, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004123 return BinaryOperator::CreateNot(Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004124 }
4125
4126 {
4127 Value *A = 0, *B = 0, *C = 0, *D = 0;
Owen Andersona21eb582009-07-10 17:35:01 +00004128 if (match(Op0, m_Or(m_Value(A), m_Value(B)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004129 if (A == Op1 || B == Op1) // (A | ?) & A --> A
4130 return ReplaceInstUsesWith(I, Op1);
4131
4132 // (A|B) & ~(A&B) -> A^B
Owen Andersona21eb582009-07-10 17:35:01 +00004133 if (match(Op1, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004134 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004135 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004136 }
4137 }
4138
Owen Andersona21eb582009-07-10 17:35:01 +00004139 if (match(Op1, m_Or(m_Value(A), m_Value(B)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004140 if (A == Op0 || B == Op0) // A & (A | ?) --> A
4141 return ReplaceInstUsesWith(I, Op0);
4142
4143 // ~(A&B) & (A|B) -> A^B
Owen Andersona21eb582009-07-10 17:35:01 +00004144 if (match(Op0, m_Not(m_And(m_Value(C), m_Value(D))), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004145 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00004146 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004147 }
4148 }
4149
4150 if (Op0->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00004151 match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004152 if (A == Op1) { // (A^B)&A -> A&(A^B)
4153 I.swapOperands(); // Simplify below
4154 std::swap(Op0, Op1);
4155 } else if (B == Op1) { // (A^B)&B -> B&(B^A)
4156 cast<BinaryOperator>(Op0)->swapOperands();
4157 I.swapOperands(); // Simplify below
4158 std::swap(Op0, Op1);
4159 }
4160 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004161
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004162 if (Op1->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00004163 match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004164 if (B == Op0) { // B&(A^B) -> B&(B^A)
4165 cast<BinaryOperator>(Op1)->swapOperands();
4166 std::swap(A, B);
4167 }
4168 if (A == Op0) { // A&(A^B) -> A & ~B
Gabor Greifa645dd32008-05-16 19:29:10 +00004169 Instruction *NotB = BinaryOperator::CreateNot(B, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004170 InsertNewInstBefore(NotB, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004171 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004172 }
4173 }
Bill Wendlingce5e0af2008-11-30 13:08:13 +00004174
4175 // (A&((~A)|B)) -> A&B
Owen Andersona21eb582009-07-10 17:35:01 +00004176 if (match(Op0, m_Or(m_Not(m_Specific(Op1)), m_Value(A)), *Context) ||
4177 match(Op0, m_Or(m_Value(A), m_Not(m_Specific(Op1))), *Context))
Chris Lattner9db479f2008-12-01 05:16:26 +00004178 return BinaryOperator::CreateAnd(A, Op1);
Owen Andersona21eb582009-07-10 17:35:01 +00004179 if (match(Op1, m_Or(m_Not(m_Specific(Op0)), m_Value(A)), *Context) ||
4180 match(Op1, m_Or(m_Value(A), m_Not(m_Specific(Op0))), *Context))
Chris Lattner9db479f2008-12-01 05:16:26 +00004181 return BinaryOperator::CreateAnd(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004182 }
4183
4184 if (ICmpInst *RHS = dyn_cast<ICmpInst>(Op1)) {
4185 // (icmp1 A, B) & (icmp2 A, B) --> (icmp3 A, B)
Owen Anderson24be4c12009-07-03 00:17:18 +00004186 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004187 return R;
4188
Chris Lattner0631ea72008-11-16 05:06:21 +00004189 if (ICmpInst *LHS = dyn_cast<ICmpInst>(Op0))
4190 if (Instruction *Res = FoldAndOfICmps(I, LHS, RHS))
4191 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004192 }
4193
4194 // fold (and (cast A), (cast B)) -> (cast (and A, B))
4195 if (CastInst *Op0C = dyn_cast<CastInst>(Op0))
4196 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4197 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind ?
4198 const Type *SrcTy = Op0C->getOperand(0)->getType();
4199 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4200 // Only do this if the casts both really cause code to be generated.
4201 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4202 I.getType(), TD) &&
4203 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4204 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004205 Instruction *NewOp = BinaryOperator::CreateAnd(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004206 Op1C->getOperand(0),
4207 I.getName());
4208 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004209 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004210 }
4211 }
4212
4213 // (X >> Z) & (Y >> Z) -> (X&Y) >> Z for all shifts.
4214 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4215 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4216 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4217 SI0->getOperand(1) == SI1->getOperand(1) &&
4218 (SI0->hasOneUse() || SI1->hasOneUse())) {
4219 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004220 InsertNewInstBefore(BinaryOperator::CreateAnd(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004221 SI1->getOperand(0),
4222 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004223 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004224 SI1->getOperand(1));
4225 }
4226 }
4227
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004228 // If and'ing two fcmp, try combine them into one.
Chris Lattner91882432007-10-24 05:38:08 +00004229 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4230 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4231 if (LHS->getPredicate() == FCmpInst::FCMP_ORD &&
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004232 RHS->getPredicate() == FCmpInst::FCMP_ORD) {
4233 // (fcmp ord x, c) & (fcmp ord y, c) -> (fcmp ord x, y)
Chris Lattner91882432007-10-24 05:38:08 +00004234 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4235 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4236 // If either of the constants are nans, then the whole thing returns
4237 // false.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00004238 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson24be4c12009-07-03 00:17:18 +00004239 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Owen Anderson6601fcd2009-07-09 23:48:35 +00004240 return new FCmpInst(*Context, FCmpInst::FCMP_ORD,
4241 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner91882432007-10-24 05:38:08 +00004242 }
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004243 } else {
4244 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4245 FCmpInst::Predicate Op0CC, Op1CC;
Owen Andersona21eb582009-07-10 17:35:01 +00004246 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4247 m_Value(Op0RHS)), *Context) &&
4248 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4249 m_Value(Op1RHS)), *Context)) {
Evan Chengf1f2cea2008-10-14 18:13:38 +00004250 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4251 // Swap RHS operands to match LHS.
4252 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4253 std::swap(Op1LHS, Op1RHS);
4254 }
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004255 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4256 // Simplify (fcmp cc0 x, y) & (fcmp cc1 x, y).
4257 if (Op0CC == Op1CC)
Owen Anderson6601fcd2009-07-09 23:48:35 +00004258 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4259 Op0LHS, Op0RHS);
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004260 else if (Op0CC == FCmpInst::FCMP_FALSE ||
4261 Op1CC == FCmpInst::FCMP_FALSE)
Owen Anderson24be4c12009-07-03 00:17:18 +00004262 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004263 else if (Op0CC == FCmpInst::FCMP_TRUE)
4264 return ReplaceInstUsesWith(I, Op1);
4265 else if (Op1CC == FCmpInst::FCMP_TRUE)
4266 return ReplaceInstUsesWith(I, Op0);
4267 bool Op0Ordered;
4268 bool Op1Ordered;
4269 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4270 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4271 if (Op1Pred == 0) {
4272 std::swap(Op0, Op1);
4273 std::swap(Op0Pred, Op1Pred);
4274 std::swap(Op0Ordered, Op1Ordered);
4275 }
4276 if (Op0Pred == 0) {
4277 // uno && ueq -> uno && (uno || eq) -> ueq
4278 // ord && olt -> ord && (ord && lt) -> olt
4279 if (Op0Ordered == Op1Ordered)
4280 return ReplaceInstUsesWith(I, Op1);
4281 // uno && oeq -> uno && (ord && eq) -> false
4282 // uno && ord -> false
4283 if (!Op0Ordered)
Owen Anderson24be4c12009-07-03 00:17:18 +00004284 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004285 // ord && ueq -> ord && (uno || eq) -> oeq
4286 return cast<Instruction>(getFCmpValue(true, Op1Pred,
Owen Anderson24be4c12009-07-03 00:17:18 +00004287 Op0LHS, Op0RHS, Context));
Evan Cheng0ac3a4d2008-10-14 17:15:11 +00004288 }
4289 }
4290 }
4291 }
Chris Lattner91882432007-10-24 05:38:08 +00004292 }
4293 }
Nick Lewyckyffed71b2008-07-09 04:32:37 +00004294
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004295 return Changed ? &I : 0;
4296}
4297
Chris Lattner567f5112008-10-05 02:13:19 +00004298/// CollectBSwapParts - Analyze the specified subexpression and see if it is
4299/// capable of providing pieces of a bswap. The subexpression provides pieces
4300/// of a bswap if it is proven that each of the non-zero bytes in the output of
4301/// the expression came from the corresponding "byte swapped" byte in some other
4302/// value. For example, if the current subexpression is "(shl i32 %X, 24)" then
4303/// we know that the expression deposits the low byte of %X into the high byte
4304/// of the bswap result and that all other bytes are zero. This expression is
4305/// accepted, the high byte of ByteValues is set to X to indicate a correct
4306/// match.
4307///
4308/// This function returns true if the match was unsuccessful and false if so.
4309/// On entry to the function the "OverallLeftShift" is a signed integer value
4310/// indicating the number of bytes that the subexpression is later shifted. For
4311/// example, if the expression is later right shifted by 16 bits, the
4312/// OverallLeftShift value would be -2 on entry. This is used to specify which
4313/// byte of ByteValues is actually being set.
4314///
4315/// Similarly, ByteMask is a bitmask where a bit is clear if its corresponding
4316/// byte is masked to zero by a user. For example, in (X & 255), X will be
4317/// processed with a bytemask of 1. Because bytemask is 32-bits, this limits
4318/// this function to working on up to 32-byte (256 bit) values. ByteMask is
4319/// always in the local (OverallLeftShift) coordinate space.
4320///
4321static bool CollectBSwapParts(Value *V, int OverallLeftShift, uint32_t ByteMask,
4322 SmallVector<Value*, 8> &ByteValues) {
4323 if (Instruction *I = dyn_cast<Instruction>(V)) {
4324 // If this is an or instruction, it may be an inner node of the bswap.
4325 if (I->getOpcode() == Instruction::Or) {
4326 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4327 ByteValues) ||
4328 CollectBSwapParts(I->getOperand(1), OverallLeftShift, ByteMask,
4329 ByteValues);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004330 }
Chris Lattner567f5112008-10-05 02:13:19 +00004331
4332 // If this is a logical shift by a constant multiple of 8, recurse with
4333 // OverallLeftShift and ByteMask adjusted.
4334 if (I->isLogicalShift() && isa<ConstantInt>(I->getOperand(1))) {
4335 unsigned ShAmt =
4336 cast<ConstantInt>(I->getOperand(1))->getLimitedValue(~0U);
4337 // Ensure the shift amount is defined and of a byte value.
4338 if ((ShAmt & 7) || (ShAmt > 8*ByteValues.size()))
4339 return true;
4340
4341 unsigned ByteShift = ShAmt >> 3;
4342 if (I->getOpcode() == Instruction::Shl) {
4343 // X << 2 -> collect(X, +2)
4344 OverallLeftShift += ByteShift;
4345 ByteMask >>= ByteShift;
4346 } else {
4347 // X >>u 2 -> collect(X, -2)
4348 OverallLeftShift -= ByteShift;
4349 ByteMask <<= ByteShift;
Chris Lattner44448592008-10-08 06:42:28 +00004350 ByteMask &= (~0U >> (32-ByteValues.size()));
Chris Lattner567f5112008-10-05 02:13:19 +00004351 }
4352
4353 if (OverallLeftShift >= (int)ByteValues.size()) return true;
4354 if (OverallLeftShift <= -(int)ByteValues.size()) return true;
4355
4356 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4357 ByteValues);
4358 }
4359
4360 // If this is a logical 'and' with a mask that clears bytes, clear the
4361 // corresponding bytes in ByteMask.
4362 if (I->getOpcode() == Instruction::And &&
4363 isa<ConstantInt>(I->getOperand(1))) {
4364 // Scan every byte of the and mask, seeing if the byte is either 0 or 255.
4365 unsigned NumBytes = ByteValues.size();
4366 APInt Byte(I->getType()->getPrimitiveSizeInBits(), 255);
4367 const APInt &AndMask = cast<ConstantInt>(I->getOperand(1))->getValue();
4368
4369 for (unsigned i = 0; i != NumBytes; ++i, Byte <<= 8) {
4370 // If this byte is masked out by a later operation, we don't care what
4371 // the and mask is.
4372 if ((ByteMask & (1 << i)) == 0)
4373 continue;
4374
4375 // If the AndMask is all zeros for this byte, clear the bit.
4376 APInt MaskB = AndMask & Byte;
4377 if (MaskB == 0) {
4378 ByteMask &= ~(1U << i);
4379 continue;
4380 }
4381
4382 // If the AndMask is not all ones for this byte, it's not a bytezap.
4383 if (MaskB != Byte)
4384 return true;
4385
4386 // Otherwise, this byte is kept.
4387 }
4388
4389 return CollectBSwapParts(I->getOperand(0), OverallLeftShift, ByteMask,
4390 ByteValues);
4391 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004392 }
4393
Chris Lattner567f5112008-10-05 02:13:19 +00004394 // Okay, we got to something that isn't a shift, 'or' or 'and'. This must be
4395 // the input value to the bswap. Some observations: 1) if more than one byte
4396 // is demanded from this input, then it could not be successfully assembled
4397 // into a byteswap. At least one of the two bytes would not be aligned with
4398 // their ultimate destination.
4399 if (!isPowerOf2_32(ByteMask)) return true;
4400 unsigned InputByteNo = CountTrailingZeros_32(ByteMask);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004401
Chris Lattner567f5112008-10-05 02:13:19 +00004402 // 2) The input and ultimate destinations must line up: if byte 3 of an i32
4403 // is demanded, it needs to go into byte 0 of the result. This means that the
4404 // byte needs to be shifted until it lands in the right byte bucket. The
4405 // shift amount depends on the position: if the byte is coming from the high
4406 // part of the value (e.g. byte 3) then it must be shifted right. If from the
4407 // low part, it must be shifted left.
4408 unsigned DestByteNo = InputByteNo + OverallLeftShift;
4409 if (InputByteNo < ByteValues.size()/2) {
4410 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4411 return true;
4412 } else {
4413 if (ByteValues.size()-1-DestByteNo != InputByteNo)
4414 return true;
4415 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004416
4417 // If the destination byte value is already defined, the values are or'd
4418 // together, which isn't a bswap (unless it's an or of the same bits).
Chris Lattner567f5112008-10-05 02:13:19 +00004419 if (ByteValues[DestByteNo] && ByteValues[DestByteNo] != V)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004420 return true;
Chris Lattner567f5112008-10-05 02:13:19 +00004421 ByteValues[DestByteNo] = V;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004422 return false;
4423}
4424
4425/// MatchBSwap - Given an OR instruction, check to see if this is a bswap idiom.
4426/// If so, insert the new bswap intrinsic and return it.
4427Instruction *InstCombiner::MatchBSwap(BinaryOperator &I) {
4428 const IntegerType *ITy = dyn_cast<IntegerType>(I.getType());
Chris Lattner567f5112008-10-05 02:13:19 +00004429 if (!ITy || ITy->getBitWidth() % 16 ||
4430 // ByteMask only allows up to 32-byte values.
4431 ITy->getBitWidth() > 32*8)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004432 return 0; // Can only bswap pairs of bytes. Can't do vectors.
4433
4434 /// ByteValues - For each byte of the result, we keep track of which value
4435 /// defines each byte.
4436 SmallVector<Value*, 8> ByteValues;
4437 ByteValues.resize(ITy->getBitWidth()/8);
4438
4439 // Try to find all the pieces corresponding to the bswap.
Chris Lattner567f5112008-10-05 02:13:19 +00004440 uint32_t ByteMask = ~0U >> (32-ByteValues.size());
4441 if (CollectBSwapParts(&I, 0, ByteMask, ByteValues))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004442 return 0;
4443
4444 // Check to see if all of the bytes come from the same value.
4445 Value *V = ByteValues[0];
4446 if (V == 0) return 0; // Didn't find a byte? Must be zero.
4447
4448 // Check to make sure that all of the bytes come from the same value.
4449 for (unsigned i = 1, e = ByteValues.size(); i != e; ++i)
4450 if (ByteValues[i] != V)
4451 return 0;
Chandler Carrutha228e392007-08-04 01:51:18 +00004452 const Type *Tys[] = { ITy };
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004453 Module *M = I.getParent()->getParent()->getParent();
Chandler Carrutha228e392007-08-04 01:51:18 +00004454 Function *F = Intrinsic::getDeclaration(M, Intrinsic::bswap, Tys, 1);
Gabor Greifd6da1d02008-04-06 20:25:17 +00004455 return CallInst::Create(F, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004456}
4457
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004458/// MatchSelectFromAndOr - We have an expression of the form (A&C)|(B&D). Check
4459/// If A is (cond?-1:0) and either B or D is ~(cond?-1,0) or (cond?0,-1), then
4460/// we can simplify this expression to "cond ? C : D or B".
4461static Instruction *MatchSelectFromAndOr(Value *A, Value *B,
Owen Andersona21eb582009-07-10 17:35:01 +00004462 Value *C, Value *D,
4463 LLVMContext *Context) {
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004464 // If A is not a select of -1/0, this cannot match.
Chris Lattner641ea462008-11-16 04:46:19 +00004465 Value *Cond = 0;
Owen Andersona21eb582009-07-10 17:35:01 +00004466 if (!match(A, m_SelectCst<-1, 0>(m_Value(Cond)), *Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004467 return 0;
4468
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004469 // ((cond?-1:0)&C) | (B&(cond?0:-1)) -> cond ? C : B.
Owen Andersona21eb582009-07-10 17:35:01 +00004470 if (match(D, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004471 return SelectInst::Create(Cond, C, B);
Owen Andersona21eb582009-07-10 17:35:01 +00004472 if (match(D, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004473 return SelectInst::Create(Cond, C, B);
4474 // ((cond?-1:0)&C) | ((cond?0:-1)&D) -> cond ? C : D.
Owen Andersona21eb582009-07-10 17:35:01 +00004475 if (match(B, m_SelectCst<0, -1>(m_Specific(Cond)), *Context))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004476 return SelectInst::Create(Cond, C, D);
Owen Andersona21eb582009-07-10 17:35:01 +00004477 if (match(B, m_Not(m_SelectCst<-1, 0>(m_Specific(Cond))), *Context))
Chris Lattnerd09b5ba2008-11-16 04:26:55 +00004478 return SelectInst::Create(Cond, C, D);
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004479 return 0;
4480}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004481
Chris Lattner0c678e52008-11-16 05:20:07 +00004482/// FoldOrOfICmps - Fold (icmp)|(icmp) if possible.
4483Instruction *InstCombiner::FoldOrOfICmps(Instruction &I,
4484 ICmpInst *LHS, ICmpInst *RHS) {
4485 Value *Val, *Val2;
4486 ConstantInt *LHSCst, *RHSCst;
4487 ICmpInst::Predicate LHSCC, RHSCC;
4488
4489 // This only handles icmp of constants: (icmp1 A, C1) | (icmp2 B, C2).
Owen Andersona21eb582009-07-10 17:35:01 +00004490 if (!match(LHS, m_ICmp(LHSCC, m_Value(Val),
4491 m_ConstantInt(LHSCst)), *Context) ||
4492 !match(RHS, m_ICmp(RHSCC, m_Value(Val2),
4493 m_ConstantInt(RHSCst)), *Context))
Chris Lattner0c678e52008-11-16 05:20:07 +00004494 return 0;
4495
4496 // From here on, we only handle:
4497 // (icmp1 A, C1) | (icmp2 A, C2) --> something simpler.
4498 if (Val != Val2) return 0;
4499
4500 // ICMP_[US][GL]E X, CST is folded to ICMP_[US][GL]T elsewhere.
4501 if (LHSCC == ICmpInst::ICMP_UGE || LHSCC == ICmpInst::ICMP_ULE ||
4502 RHSCC == ICmpInst::ICMP_UGE || RHSCC == ICmpInst::ICMP_ULE ||
4503 LHSCC == ICmpInst::ICMP_SGE || LHSCC == ICmpInst::ICMP_SLE ||
4504 RHSCC == ICmpInst::ICMP_SGE || RHSCC == ICmpInst::ICMP_SLE)
4505 return 0;
4506
4507 // We can't fold (ugt x, C) | (sgt x, C2).
4508 if (!PredicatesFoldable(LHSCC, RHSCC))
4509 return 0;
4510
4511 // Ensure that the larger constant is on the RHS.
4512 bool ShouldSwap;
4513 if (ICmpInst::isSignedPredicate(LHSCC) ||
4514 (ICmpInst::isEquality(LHSCC) &&
4515 ICmpInst::isSignedPredicate(RHSCC)))
4516 ShouldSwap = LHSCst->getValue().sgt(RHSCst->getValue());
4517 else
4518 ShouldSwap = LHSCst->getValue().ugt(RHSCst->getValue());
4519
4520 if (ShouldSwap) {
4521 std::swap(LHS, RHS);
4522 std::swap(LHSCst, RHSCst);
4523 std::swap(LHSCC, RHSCC);
4524 }
4525
4526 // At this point, we know we have have two icmp instructions
4527 // comparing a value against two constants and or'ing the result
4528 // together. Because of the above check, we know that we only have
4529 // ICMP_EQ, ICMP_NE, ICMP_LT, and ICMP_GT here. We also know (from the
4530 // FoldICmpLogical check above), that the two constants are not
4531 // equal.
4532 assert(LHSCst != RHSCst && "Compares not folded above?");
4533
4534 switch (LHSCC) {
4535 default: assert(0 && "Unknown integer condition code!");
4536 case ICmpInst::ICMP_EQ:
4537 switch (RHSCC) {
4538 default: assert(0 && "Unknown integer condition code!");
4539 case ICmpInst::ICMP_EQ:
Owen Anderson24be4c12009-07-03 00:17:18 +00004540 if (LHSCst == SubOne(RHSCst, Context)) {
4541 // (X == 13 | X == 14) -> X-13 <u 2
4542 Constant *AddCST = Context->getConstantExprNeg(LHSCst);
Chris Lattner0c678e52008-11-16 05:20:07 +00004543 Instruction *Add = BinaryOperator::CreateAdd(Val, AddCST,
4544 Val->getName()+".off");
4545 InsertNewInstBefore(Add, I);
Owen Anderson24be4c12009-07-03 00:17:18 +00004546 AddCST = Context->getConstantExprSub(AddOne(RHSCst, Context), LHSCst);
Owen Anderson6601fcd2009-07-09 23:48:35 +00004547 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Add, AddCST);
Chris Lattner0c678e52008-11-16 05:20:07 +00004548 }
4549 break; // (X == 13 | X == 15) -> no change
4550 case ICmpInst::ICMP_UGT: // (X == 13 | X u> 14) -> no change
4551 case ICmpInst::ICMP_SGT: // (X == 13 | X s> 14) -> no change
4552 break;
4553 case ICmpInst::ICMP_NE: // (X == 13 | X != 15) -> X != 15
4554 case ICmpInst::ICMP_ULT: // (X == 13 | X u< 15) -> X u< 15
4555 case ICmpInst::ICMP_SLT: // (X == 13 | X s< 15) -> X s< 15
4556 return ReplaceInstUsesWith(I, RHS);
4557 }
4558 break;
4559 case ICmpInst::ICMP_NE:
4560 switch (RHSCC) {
4561 default: assert(0 && "Unknown integer condition code!");
4562 case ICmpInst::ICMP_EQ: // (X != 13 | X == 15) -> X != 13
4563 case ICmpInst::ICMP_UGT: // (X != 13 | X u> 15) -> X != 13
4564 case ICmpInst::ICMP_SGT: // (X != 13 | X s> 15) -> X != 13
4565 return ReplaceInstUsesWith(I, LHS);
4566 case ICmpInst::ICMP_NE: // (X != 13 | X != 15) -> true
4567 case ICmpInst::ICMP_ULT: // (X != 13 | X u< 15) -> true
4568 case ICmpInst::ICMP_SLT: // (X != 13 | X s< 15) -> true
Owen Anderson24be4c12009-07-03 00:17:18 +00004569 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner0c678e52008-11-16 05:20:07 +00004570 }
4571 break;
4572 case ICmpInst::ICMP_ULT:
4573 switch (RHSCC) {
4574 default: assert(0 && "Unknown integer condition code!");
4575 case ICmpInst::ICMP_EQ: // (X u< 13 | X == 14) -> no change
4576 break;
4577 case ICmpInst::ICMP_UGT: // (X u< 13 | X u> 15) -> (X-13) u> 2
4578 // If RHSCst is [us]MAXINT, it is always false. Not handling
4579 // this can cause overflow.
4580 if (RHSCst->isMaxValue(false))
4581 return ReplaceInstUsesWith(I, LHS);
Owen Anderson24be4c12009-07-03 00:17:18 +00004582 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4583 false, false, I);
Chris Lattner0c678e52008-11-16 05:20:07 +00004584 case ICmpInst::ICMP_SGT: // (X u< 13 | X s> 15) -> no change
4585 break;
4586 case ICmpInst::ICMP_NE: // (X u< 13 | X != 15) -> X != 15
4587 case ICmpInst::ICMP_ULT: // (X u< 13 | X u< 15) -> X u< 15
4588 return ReplaceInstUsesWith(I, RHS);
4589 case ICmpInst::ICMP_SLT: // (X u< 13 | X s< 15) -> no change
4590 break;
4591 }
4592 break;
4593 case ICmpInst::ICMP_SLT:
4594 switch (RHSCC) {
4595 default: assert(0 && "Unknown integer condition code!");
4596 case ICmpInst::ICMP_EQ: // (X s< 13 | X == 14) -> no change
4597 break;
4598 case ICmpInst::ICMP_SGT: // (X s< 13 | X s> 15) -> (X-13) s> 2
4599 // If RHSCst is [us]MAXINT, it is always false. Not handling
4600 // this can cause overflow.
4601 if (RHSCst->isMaxValue(true))
4602 return ReplaceInstUsesWith(I, LHS);
Owen Anderson24be4c12009-07-03 00:17:18 +00004603 return InsertRangeTest(Val, LHSCst, AddOne(RHSCst, Context),
4604 true, false, I);
Chris Lattner0c678e52008-11-16 05:20:07 +00004605 case ICmpInst::ICMP_UGT: // (X s< 13 | X u> 15) -> no change
4606 break;
4607 case ICmpInst::ICMP_NE: // (X s< 13 | X != 15) -> X != 15
4608 case ICmpInst::ICMP_SLT: // (X s< 13 | X s< 15) -> X s< 15
4609 return ReplaceInstUsesWith(I, RHS);
4610 case ICmpInst::ICMP_ULT: // (X s< 13 | X u< 15) -> no change
4611 break;
4612 }
4613 break;
4614 case ICmpInst::ICMP_UGT:
4615 switch (RHSCC) {
4616 default: assert(0 && "Unknown integer condition code!");
4617 case ICmpInst::ICMP_EQ: // (X u> 13 | X == 15) -> X u> 13
4618 case ICmpInst::ICMP_UGT: // (X u> 13 | X u> 15) -> X u> 13
4619 return ReplaceInstUsesWith(I, LHS);
4620 case ICmpInst::ICMP_SGT: // (X u> 13 | X s> 15) -> no change
4621 break;
4622 case ICmpInst::ICMP_NE: // (X u> 13 | X != 15) -> true
4623 case ICmpInst::ICMP_ULT: // (X u> 13 | X u< 15) -> true
Owen Anderson24be4c12009-07-03 00:17:18 +00004624 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner0c678e52008-11-16 05:20:07 +00004625 case ICmpInst::ICMP_SLT: // (X u> 13 | X s< 15) -> no change
4626 break;
4627 }
4628 break;
4629 case ICmpInst::ICMP_SGT:
4630 switch (RHSCC) {
4631 default: assert(0 && "Unknown integer condition code!");
4632 case ICmpInst::ICMP_EQ: // (X s> 13 | X == 15) -> X > 13
4633 case ICmpInst::ICMP_SGT: // (X s> 13 | X s> 15) -> X > 13
4634 return ReplaceInstUsesWith(I, LHS);
4635 case ICmpInst::ICMP_UGT: // (X s> 13 | X u> 15) -> no change
4636 break;
4637 case ICmpInst::ICMP_NE: // (X s> 13 | X != 15) -> true
4638 case ICmpInst::ICMP_SLT: // (X s> 13 | X s< 15) -> true
Owen Anderson24be4c12009-07-03 00:17:18 +00004639 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner0c678e52008-11-16 05:20:07 +00004640 case ICmpInst::ICMP_ULT: // (X s> 13 | X u< 15) -> no change
4641 break;
4642 }
4643 break;
4644 }
4645 return 0;
4646}
4647
Bill Wendlingdae376a2008-12-01 08:23:25 +00004648/// FoldOrWithConstants - This helper function folds:
4649///
Bill Wendling236a1192008-12-02 05:09:00 +00004650/// ((A | B) & C1) | (B & C2)
Bill Wendlingdae376a2008-12-01 08:23:25 +00004651///
4652/// into:
4653///
Bill Wendling236a1192008-12-02 05:09:00 +00004654/// (A & C1) | B
Bill Wendling9912f712008-12-01 08:32:40 +00004655///
Bill Wendling236a1192008-12-02 05:09:00 +00004656/// when the XOR of the two constants is "all ones" (-1).
Bill Wendling9912f712008-12-01 08:32:40 +00004657Instruction *InstCombiner::FoldOrWithConstants(BinaryOperator &I, Value *Op,
Bill Wendlingdae376a2008-12-01 08:23:25 +00004658 Value *A, Value *B, Value *C) {
Bill Wendlingfc5b8e62008-12-02 05:06:43 +00004659 ConstantInt *CI1 = dyn_cast<ConstantInt>(C);
4660 if (!CI1) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00004661
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00004662 Value *V1 = 0;
4663 ConstantInt *CI2 = 0;
Owen Andersona21eb582009-07-10 17:35:01 +00004664 if (!match(Op, m_And(m_Value(V1), m_ConstantInt(CI2)), *Context)) return 0;
Bill Wendlingdae376a2008-12-01 08:23:25 +00004665
Bill Wendling86ee3162008-12-02 06:18:11 +00004666 APInt Xor = CI1->getValue() ^ CI2->getValue();
4667 if (!Xor.isAllOnesValue()) return 0;
4668
Bill Wendling0a0dcaf2008-12-02 06:24:20 +00004669 if (V1 == A || V1 == B) {
Bill Wendling86ee3162008-12-02 06:18:11 +00004670 Instruction *NewOp =
Bill Wendling6c8ecbb2008-12-02 06:22:04 +00004671 InsertNewInstBefore(BinaryOperator::CreateAnd((V1 == A) ? B : A, CI1), I);
4672 return BinaryOperator::CreateOr(NewOp, V1);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004673 }
4674
4675 return 0;
4676}
4677
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004678Instruction *InstCombiner::visitOr(BinaryOperator &I) {
4679 bool Changed = SimplifyCommutative(I);
4680 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
4681
4682 if (isa<UndefValue>(Op1)) // X | undef -> -1
Owen Anderson24be4c12009-07-03 00:17:18 +00004683 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004684
4685 // or X, X = X
4686 if (Op0 == Op1)
4687 return ReplaceInstUsesWith(I, Op0);
4688
4689 // See if we can simplify any instructions used by the instruction whose sole
4690 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00004691 if (SimplifyDemandedInstructionBits(I))
4692 return &I;
4693 if (isa<VectorType>(I.getType())) {
4694 if (isa<ConstantAggregateZero>(Op1)) {
4695 return ReplaceInstUsesWith(I, Op0); // X | <0,0> -> X
4696 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Op1)) {
4697 if (CP->isAllOnesValue()) // X | <-1,-1> -> <-1,-1>
4698 return ReplaceInstUsesWith(I, I.getOperand(1));
4699 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004700 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004701
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004702 // or X, -1 == -1
4703 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
4704 ConstantInt *C1 = 0; Value *X = 0;
4705 // (X & C1) | C2 --> (X | C2) & (C1|C2)
Owen Andersona21eb582009-07-10 17:35:01 +00004706 if (match(Op0, m_And(m_Value(X), m_ConstantInt(C1)), *Context) &&
4707 isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004708 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004709 InsertNewInstBefore(Or, I);
4710 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004711 return BinaryOperator::CreateAnd(Or,
Owen Anderson24be4c12009-07-03 00:17:18 +00004712 Context->getConstantInt(RHS->getValue() | C1->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004713 }
4714
4715 // (X ^ C1) | C2 --> (X | C2) ^ (C1&~C2)
Owen Andersona21eb582009-07-10 17:35:01 +00004716 if (match(Op0, m_Xor(m_Value(X), m_ConstantInt(C1)), *Context) &&
4717 isOnlyUse(Op0)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004718 Instruction *Or = BinaryOperator::CreateOr(X, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004719 InsertNewInstBefore(Or, I);
4720 Or->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004721 return BinaryOperator::CreateXor(Or,
Owen Anderson24be4c12009-07-03 00:17:18 +00004722 Context->getConstantInt(C1->getValue() & ~RHS->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004723 }
4724
4725 // Try to fold constant and into select arguments.
4726 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
4727 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
4728 return R;
4729 if (isa<PHINode>(Op0))
4730 if (Instruction *NV = FoldOpIntoPhi(I))
4731 return NV;
4732 }
4733
4734 Value *A = 0, *B = 0;
4735 ConstantInt *C1 = 0, *C2 = 0;
4736
Owen Andersona21eb582009-07-10 17:35:01 +00004737 if (match(Op0, m_And(m_Value(A), m_Value(B)), *Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004738 if (A == Op1 || B == Op1) // (A & ?) | A --> A
4739 return ReplaceInstUsesWith(I, Op1);
Owen Andersona21eb582009-07-10 17:35:01 +00004740 if (match(Op1, m_And(m_Value(A), m_Value(B)), *Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004741 if (A == Op0 || B == Op0) // A | (A & ?) --> A
4742 return ReplaceInstUsesWith(I, Op0);
4743
4744 // (A | B) | C and A | (B | C) -> bswap if possible.
4745 // (A >> B) | (C << D) and (A << B) | (B >> C) -> bswap if possible.
Owen Andersona21eb582009-07-10 17:35:01 +00004746 if (match(Op0, m_Or(m_Value(), m_Value()), *Context) ||
4747 match(Op1, m_Or(m_Value(), m_Value()), *Context) ||
4748 (match(Op0, m_Shift(m_Value(), m_Value()), *Context) &&
4749 match(Op1, m_Shift(m_Value(), m_Value()), *Context))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004750 if (Instruction *BSwap = MatchBSwap(I))
4751 return BSwap;
4752 }
4753
4754 // (X^C)|Y -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00004755 if (Op0->hasOneUse() &&
4756 match(Op0, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004757 MaskedValueIsZero(Op1, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004758 Instruction *NOr = BinaryOperator::CreateOr(A, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004759 InsertNewInstBefore(NOr, I);
4760 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004761 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004762 }
4763
4764 // Y|(X^C) -> (X|Y)^C iff Y&C == 0
Owen Andersona21eb582009-07-10 17:35:01 +00004765 if (Op1->hasOneUse() &&
4766 match(Op1, m_Xor(m_Value(A), m_ConstantInt(C1)), *Context) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004767 MaskedValueIsZero(Op0, C1->getValue())) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004768 Instruction *NOr = BinaryOperator::CreateOr(A, Op0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004769 InsertNewInstBefore(NOr, I);
4770 NOr->takeName(Op0);
Gabor Greifa645dd32008-05-16 19:29:10 +00004771 return BinaryOperator::CreateXor(NOr, C1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004772 }
4773
4774 // (A & C)|(B & D)
4775 Value *C = 0, *D = 0;
Owen Andersona21eb582009-07-10 17:35:01 +00004776 if (match(Op0, m_And(m_Value(A), m_Value(C)), *Context) &&
4777 match(Op1, m_And(m_Value(B), m_Value(D)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004778 Value *V1 = 0, *V2 = 0, *V3 = 0;
4779 C1 = dyn_cast<ConstantInt>(C);
4780 C2 = dyn_cast<ConstantInt>(D);
4781 if (C1 && C2) { // (A & C1)|(B & C2)
4782 // If we have: ((V + N) & C1) | (V & C2)
4783 // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
4784 // replace with V+N.
4785 if (C1->getValue() == ~C2->getValue()) {
4786 if ((C2->getValue() & (C2->getValue()+1)) == 0 && // C2 == 0+1+
Owen Andersona21eb582009-07-10 17:35:01 +00004787 match(A, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004788 // Add commutes, try both ways.
4789 if (V1 == B && MaskedValueIsZero(V2, C2->getValue()))
4790 return ReplaceInstUsesWith(I, A);
4791 if (V2 == B && MaskedValueIsZero(V1, C2->getValue()))
4792 return ReplaceInstUsesWith(I, A);
4793 }
4794 // Or commutes, try both ways.
4795 if ((C1->getValue() & (C1->getValue()+1)) == 0 &&
Owen Andersona21eb582009-07-10 17:35:01 +00004796 match(B, m_Add(m_Value(V1), m_Value(V2)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004797 // Add commutes, try both ways.
4798 if (V1 == A && MaskedValueIsZero(V2, C1->getValue()))
4799 return ReplaceInstUsesWith(I, B);
4800 if (V2 == A && MaskedValueIsZero(V1, C1->getValue()))
4801 return ReplaceInstUsesWith(I, B);
4802 }
4803 }
4804 V1 = 0; V2 = 0; V3 = 0;
4805 }
4806
4807 // Check to see if we have any common things being and'ed. If so, find the
4808 // terms for V1 & (V2|V3).
4809 if (isOnlyUse(Op0) || isOnlyUse(Op1)) {
4810 if (A == B) // (A & C)|(A & D) == A & (C|D)
4811 V1 = A, V2 = C, V3 = D;
4812 else if (A == D) // (A & C)|(B & A) == A & (B|C)
4813 V1 = A, V2 = B, V3 = C;
4814 else if (C == B) // (A & C)|(C & D) == C & (A|D)
4815 V1 = C, V2 = A, V3 = D;
4816 else if (C == D) // (A & C)|(B & C) == C & (A|B)
4817 V1 = C, V2 = A, V3 = B;
4818
4819 if (V1) {
4820 Value *Or =
Gabor Greifa645dd32008-05-16 19:29:10 +00004821 InsertNewInstBefore(BinaryOperator::CreateOr(V2, V3, "tmp"), I);
4822 return BinaryOperator::CreateAnd(V1, Or);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004823 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004824 }
Dan Gohman279952c2008-10-28 22:38:57 +00004825
Dan Gohman35b76162008-10-30 20:40:10 +00004826 // (A & (C0?-1:0)) | (B & ~(C0?-1:0)) -> C0 ? A : B, and commuted variants
Owen Andersona21eb582009-07-10 17:35:01 +00004827 if (Instruction *Match = MatchSelectFromAndOr(A, B, C, D, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004828 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00004829 if (Instruction *Match = MatchSelectFromAndOr(B, A, D, C, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004830 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00004831 if (Instruction *Match = MatchSelectFromAndOr(C, B, A, D, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004832 return Match;
Owen Andersona21eb582009-07-10 17:35:01 +00004833 if (Instruction *Match = MatchSelectFromAndOr(D, A, B, C, Context))
Chris Lattnerdd7772b2008-11-16 04:24:12 +00004834 return Match;
Bill Wendling22ca8352008-11-30 13:52:49 +00004835
Bill Wendling22ca8352008-11-30 13:52:49 +00004836 // ((A&~B)|(~A&B)) -> A^B
Owen Andersona21eb582009-07-10 17:35:01 +00004837 if ((match(C, m_Not(m_Specific(D)), *Context) &&
4838 match(B, m_Not(m_Specific(A)), *Context)))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004839 return BinaryOperator::CreateXor(A, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00004840 // ((~B&A)|(~A&B)) -> A^B
Owen Andersona21eb582009-07-10 17:35:01 +00004841 if ((match(A, m_Not(m_Specific(D)), *Context) &&
4842 match(B, m_Not(m_Specific(C)), *Context)))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004843 return BinaryOperator::CreateXor(C, D);
Bill Wendling22ca8352008-11-30 13:52:49 +00004844 // ((A&~B)|(B&~A)) -> A^B
Owen Andersona21eb582009-07-10 17:35:01 +00004845 if ((match(C, m_Not(m_Specific(B)), *Context) &&
4846 match(D, m_Not(m_Specific(A)), *Context)))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004847 return BinaryOperator::CreateXor(A, B);
Bill Wendling22ca8352008-11-30 13:52:49 +00004848 // ((~B&A)|(B&~A)) -> A^B
Owen Andersona21eb582009-07-10 17:35:01 +00004849 if ((match(A, m_Not(m_Specific(B)), *Context) &&
4850 match(D, m_Not(m_Specific(C)), *Context)))
Bill Wendlingc1f31132008-12-01 08:09:47 +00004851 return BinaryOperator::CreateXor(C, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004852 }
4853
4854 // (X >> Z) | (Y >> Z) -> (X|Y) >> Z for all shifts.
4855 if (BinaryOperator *SI1 = dyn_cast<BinaryOperator>(Op1)) {
4856 if (BinaryOperator *SI0 = dyn_cast<BinaryOperator>(Op0))
4857 if (SI0->isShift() && SI0->getOpcode() == SI1->getOpcode() &&
4858 SI0->getOperand(1) == SI1->getOperand(1) &&
4859 (SI0->hasOneUse() || SI1->hasOneUse())) {
4860 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00004861 InsertNewInstBefore(BinaryOperator::CreateOr(SI0->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004862 SI1->getOperand(0),
4863 SI0->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004864 return BinaryOperator::Create(SI1->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004865 SI1->getOperand(1));
4866 }
4867 }
4868
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004869 // ((A|B)&1)|(B&-2) -> (A&1) | B
Owen Andersona21eb582009-07-10 17:35:01 +00004870 if (match(Op0, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4871 match(Op0, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
Bill Wendling9912f712008-12-01 08:32:40 +00004872 Instruction *Ret = FoldOrWithConstants(I, Op1, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004873 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004874 }
4875 // (B&-2)|((A|B)&1) -> (A&1) | B
Owen Andersona21eb582009-07-10 17:35:01 +00004876 if (match(Op1, m_And(m_Or(m_Value(A), m_Value(B)), m_Value(C)), *Context) ||
4877 match(Op1, m_And(m_Value(C), m_Or(m_Value(A), m_Value(B))), *Context)) {
Bill Wendling9912f712008-12-01 08:32:40 +00004878 Instruction *Ret = FoldOrWithConstants(I, Op0, A, B, C);
Bill Wendlingdae376a2008-12-01 08:23:25 +00004879 if (Ret) return Ret;
Bill Wendlingd8ce2372008-12-01 01:07:11 +00004880 }
4881
Owen Andersona21eb582009-07-10 17:35:01 +00004882 if (match(Op0, m_Not(m_Value(A)), *Context)) { // ~A | Op1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004883 if (A == Op1) // ~A | A == -1
Owen Anderson24be4c12009-07-03 00:17:18 +00004884 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004885 } else {
4886 A = 0;
4887 }
4888 // Note, A is still live here!
Owen Andersona21eb582009-07-10 17:35:01 +00004889 if (match(Op1, m_Not(m_Value(B)), *Context)) { // Op0 | ~B
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004890 if (Op0 == B)
Owen Anderson24be4c12009-07-03 00:17:18 +00004891 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004892
4893 // (~A | ~B) == (~(A & B)) - De Morgan's Law
4894 if (A && isOnlyUse(Op0) && isOnlyUse(Op1)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004895 Value *And = InsertNewInstBefore(BinaryOperator::CreateAnd(A, B,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004896 I.getName()+".demorgan"), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004897 return BinaryOperator::CreateNot(And);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004898 }
4899 }
4900
4901 // (icmp1 A, B) | (icmp2 A, B) --> (icmp3 A, B)
4902 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1))) {
Owen Anderson24be4c12009-07-03 00:17:18 +00004903 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004904 return R;
4905
Chris Lattner0c678e52008-11-16 05:20:07 +00004906 if (ICmpInst *LHS = dyn_cast<ICmpInst>(I.getOperand(0)))
4907 if (Instruction *Res = FoldOrOfICmps(I, LHS, RHS))
4908 return Res;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004909 }
4910
4911 // fold (or (cast A), (cast B)) -> (cast (or A, B))
Chris Lattner91882432007-10-24 05:38:08 +00004912 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004913 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
4914 if (Op0C->getOpcode() == Op1C->getOpcode()) {// same cast kind ?
Evan Chenge3779cf2008-03-24 00:21:34 +00004915 if (!isa<ICmpInst>(Op0C->getOperand(0)) ||
4916 !isa<ICmpInst>(Op1C->getOperand(0))) {
4917 const Type *SrcTy = Op0C->getOperand(0)->getType();
4918 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
4919 // Only do this if the casts both really cause code to be
4920 // generated.
4921 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
4922 I.getType(), TD) &&
4923 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
4924 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00004925 Instruction *NewOp = BinaryOperator::CreateOr(Op0C->getOperand(0),
Evan Chenge3779cf2008-03-24 00:21:34 +00004926 Op1C->getOperand(0),
4927 I.getName());
4928 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00004929 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00004930 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004931 }
4932 }
Chris Lattner91882432007-10-24 05:38:08 +00004933 }
4934
4935
4936 // (fcmp uno x, c) | (fcmp uno y, c) -> (fcmp uno x, y)
4937 if (FCmpInst *LHS = dyn_cast<FCmpInst>(I.getOperand(0))) {
4938 if (FCmpInst *RHS = dyn_cast<FCmpInst>(I.getOperand(1))) {
4939 if (LHS->getPredicate() == FCmpInst::FCMP_UNO &&
Chris Lattnerbe9e63e2008-02-29 06:09:11 +00004940 RHS->getPredicate() == FCmpInst::FCMP_UNO &&
Evan Cheng72988052008-10-14 18:44:08 +00004941 LHS->getOperand(0)->getType() == RHS->getOperand(0)->getType()) {
Chris Lattner91882432007-10-24 05:38:08 +00004942 if (ConstantFP *LHSC = dyn_cast<ConstantFP>(LHS->getOperand(1)))
4943 if (ConstantFP *RHSC = dyn_cast<ConstantFP>(RHS->getOperand(1))) {
4944 // If either of the constants are nans, then the whole thing returns
4945 // true.
Chris Lattnera6c7dce2007-10-24 18:54:45 +00004946 if (LHSC->getValueAPF().isNaN() || RHSC->getValueAPF().isNaN())
Owen Anderson24be4c12009-07-03 00:17:18 +00004947 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner91882432007-10-24 05:38:08 +00004948
4949 // Otherwise, no need to compare the two constants, compare the
4950 // rest.
Owen Anderson6601fcd2009-07-09 23:48:35 +00004951 return new FCmpInst(*Context, FCmpInst::FCMP_UNO,
4952 LHS->getOperand(0), RHS->getOperand(0));
Chris Lattner91882432007-10-24 05:38:08 +00004953 }
Evan Cheng72988052008-10-14 18:44:08 +00004954 } else {
4955 Value *Op0LHS, *Op0RHS, *Op1LHS, *Op1RHS;
4956 FCmpInst::Predicate Op0CC, Op1CC;
Owen Andersona21eb582009-07-10 17:35:01 +00004957 if (match(Op0, m_FCmp(Op0CC, m_Value(Op0LHS),
4958 m_Value(Op0RHS)), *Context) &&
4959 match(Op1, m_FCmp(Op1CC, m_Value(Op1LHS),
4960 m_Value(Op1RHS)), *Context)) {
Evan Cheng72988052008-10-14 18:44:08 +00004961 if (Op0LHS == Op1RHS && Op0RHS == Op1LHS) {
4962 // Swap RHS operands to match LHS.
4963 Op1CC = FCmpInst::getSwappedPredicate(Op1CC);
4964 std::swap(Op1LHS, Op1RHS);
4965 }
4966 if (Op0LHS == Op1LHS && Op0RHS == Op1RHS) {
4967 // Simplify (fcmp cc0 x, y) | (fcmp cc1 x, y).
4968 if (Op0CC == Op1CC)
Owen Anderson6601fcd2009-07-09 23:48:35 +00004969 return new FCmpInst(*Context, (FCmpInst::Predicate)Op0CC,
4970 Op0LHS, Op0RHS);
Evan Cheng72988052008-10-14 18:44:08 +00004971 else if (Op0CC == FCmpInst::FCMP_TRUE ||
4972 Op1CC == FCmpInst::FCMP_TRUE)
Owen Anderson24be4c12009-07-03 00:17:18 +00004973 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Evan Cheng72988052008-10-14 18:44:08 +00004974 else if (Op0CC == FCmpInst::FCMP_FALSE)
4975 return ReplaceInstUsesWith(I, Op1);
4976 else if (Op1CC == FCmpInst::FCMP_FALSE)
4977 return ReplaceInstUsesWith(I, Op0);
4978 bool Op0Ordered;
4979 bool Op1Ordered;
4980 unsigned Op0Pred = getFCmpCode(Op0CC, Op0Ordered);
4981 unsigned Op1Pred = getFCmpCode(Op1CC, Op1Ordered);
4982 if (Op0Ordered == Op1Ordered) {
4983 // If both are ordered or unordered, return a new fcmp with
4984 // or'ed predicates.
4985 Value *RV = getFCmpValue(Op0Ordered, Op0Pred|Op1Pred,
Owen Anderson24be4c12009-07-03 00:17:18 +00004986 Op0LHS, Op0RHS, Context);
Evan Cheng72988052008-10-14 18:44:08 +00004987 if (Instruction *I = dyn_cast<Instruction>(RV))
4988 return I;
4989 // Otherwise, it's a constant boolean value...
4990 return ReplaceInstUsesWith(I, RV);
4991 }
4992 }
4993 }
4994 }
Chris Lattner91882432007-10-24 05:38:08 +00004995 }
4996 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00004997
4998 return Changed ? &I : 0;
4999}
5000
Dan Gohman089efff2008-05-13 00:00:25 +00005001namespace {
5002
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005003// XorSelf - Implements: X ^ X --> 0
5004struct XorSelf {
5005 Value *RHS;
5006 XorSelf(Value *rhs) : RHS(rhs) {}
5007 bool shouldApply(Value *LHS) const { return LHS == RHS; }
5008 Instruction *apply(BinaryOperator &Xor) const {
5009 return &Xor;
5010 }
5011};
5012
Dan Gohman089efff2008-05-13 00:00:25 +00005013}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005014
5015Instruction *InstCombiner::visitXor(BinaryOperator &I) {
5016 bool Changed = SimplifyCommutative(I);
5017 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5018
Evan Chenge5cd8032008-03-25 20:07:13 +00005019 if (isa<UndefValue>(Op1)) {
5020 if (isa<UndefValue>(Op0))
5021 // Handle undef ^ undef -> 0 special case. This is a common
5022 // idiom (misuse).
Owen Anderson24be4c12009-07-03 00:17:18 +00005023 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005024 return ReplaceInstUsesWith(I, Op1); // X ^ undef -> undef
Evan Chenge5cd8032008-03-25 20:07:13 +00005025 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005026
5027 // xor X, X = 0, even if X is nested in a sequence of Xor's.
Owen Anderson24be4c12009-07-03 00:17:18 +00005028 if (Instruction *Result = AssociativeOpt(I, XorSelf(Op1), Context)) {
Chris Lattnerb933ea62007-08-05 08:47:58 +00005029 assert(Result == &I && "AssociativeOpt didn't work?"); Result=Result;
Owen Anderson24be4c12009-07-03 00:17:18 +00005030 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005031 }
5032
5033 // See if we can simplify any instructions used by the instruction whose sole
5034 // purpose is to compute bits we don't care about.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005035 if (SimplifyDemandedInstructionBits(I))
5036 return &I;
5037 if (isa<VectorType>(I.getType()))
5038 if (isa<ConstantAggregateZero>(Op1))
5039 return ReplaceInstUsesWith(I, Op0); // X ^ <0,0> -> X
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005040
5041 // Is this a ~ operation?
Owen Anderson24be4c12009-07-03 00:17:18 +00005042 if (Value *NotOp = dyn_castNotVal(&I, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005043 // ~(~X & Y) --> (X | ~Y) - De Morgan's Law
5044 // ~(~X | Y) === (X & ~Y) - De Morgan's Law
5045 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(NotOp)) {
5046 if (Op0I->getOpcode() == Instruction::And ||
5047 Op0I->getOpcode() == Instruction::Or) {
Owen Anderson24be4c12009-07-03 00:17:18 +00005048 if (dyn_castNotVal(Op0I->getOperand(1), Context)) Op0I->swapOperands();
5049 if (Value *Op0NotVal = dyn_castNotVal(Op0I->getOperand(0), Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005050 Instruction *NotY =
Gabor Greifa645dd32008-05-16 19:29:10 +00005051 BinaryOperator::CreateNot(Op0I->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005052 Op0I->getOperand(1)->getName()+".not");
5053 InsertNewInstBefore(NotY, I);
5054 if (Op0I->getOpcode() == Instruction::And)
Gabor Greifa645dd32008-05-16 19:29:10 +00005055 return BinaryOperator::CreateOr(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005056 else
Gabor Greifa645dd32008-05-16 19:29:10 +00005057 return BinaryOperator::CreateAnd(Op0NotVal, NotY);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005058 }
5059 }
5060 }
5061 }
5062
5063
5064 if (ConstantInt *RHS = dyn_cast<ConstantInt>(Op1)) {
Owen Anderson24be4c12009-07-03 00:17:18 +00005065 if (RHS == Context->getConstantIntTrue() && Op0->hasOneUse()) {
Bill Wendling61741952009-01-01 01:18:23 +00005066 // xor (cmp A, B), true = not (cmp A, B) = !cmp A, B
Nick Lewycky1405e922007-08-06 20:04:16 +00005067 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Op0))
Owen Anderson6601fcd2009-07-09 23:48:35 +00005068 return new ICmpInst(*Context, ICI->getInversePredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005069 ICI->getOperand(0), ICI->getOperand(1));
5070
Nick Lewycky1405e922007-08-06 20:04:16 +00005071 if (FCmpInst *FCI = dyn_cast<FCmpInst>(Op0))
Owen Anderson6601fcd2009-07-09 23:48:35 +00005072 return new FCmpInst(*Context, FCI->getInversePredicate(),
Nick Lewycky1405e922007-08-06 20:04:16 +00005073 FCI->getOperand(0), FCI->getOperand(1));
5074 }
5075
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005076 // fold (xor(zext(cmp)), 1) and (xor(sext(cmp)), -1) to ext(!cmp).
5077 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
5078 if (CmpInst *CI = dyn_cast<CmpInst>(Op0C->getOperand(0))) {
5079 if (CI->hasOneUse() && Op0C->hasOneUse()) {
5080 Instruction::CastOps Opcode = Op0C->getOpcode();
5081 if (Opcode == Instruction::ZExt || Opcode == Instruction::SExt) {
Owen Anderson24be4c12009-07-03 00:17:18 +00005082 if (RHS == Context->getConstantExprCast(Opcode,
5083 Context->getConstantIntTrue(),
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005084 Op0C->getDestTy())) {
5085 Instruction *NewCI = InsertNewInstBefore(CmpInst::Create(
Owen Anderson6601fcd2009-07-09 23:48:35 +00005086 *Context,
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005087 CI->getOpcode(), CI->getInversePredicate(),
5088 CI->getOperand(0), CI->getOperand(1)), I);
5089 NewCI->takeName(CI);
5090 return CastInst::Create(Opcode, NewCI, Op0C->getType());
5091 }
5092 }
5093 }
5094 }
5095 }
5096
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005097 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
5098 // ~(c-X) == X-c-1 == X+(-c-1)
5099 if (Op0I->getOpcode() == Instruction::Sub && RHS->isAllOnesValue())
5100 if (Constant *Op0I0C = dyn_cast<Constant>(Op0I->getOperand(0))) {
Owen Anderson24be4c12009-07-03 00:17:18 +00005101 Constant *NegOp0I0C = Context->getConstantExprNeg(Op0I0C);
5102 Constant *ConstantRHS = Context->getConstantExprSub(NegOp0I0C,
5103 Context->getConstantInt(I.getType(), 1));
Gabor Greifa645dd32008-05-16 19:29:10 +00005104 return BinaryOperator::CreateAdd(Op0I->getOperand(1), ConstantRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005105 }
5106
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005107 if (ConstantInt *Op0CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005108 if (Op0I->getOpcode() == Instruction::Add) {
5109 // ~(X-c) --> (-c-1)-X
5110 if (RHS->isAllOnesValue()) {
Owen Anderson24be4c12009-07-03 00:17:18 +00005111 Constant *NegOp0CI = Context->getConstantExprNeg(Op0CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00005112 return BinaryOperator::CreateSub(
Owen Anderson24be4c12009-07-03 00:17:18 +00005113 Context->getConstantExprSub(NegOp0CI,
5114 Context->getConstantInt(I.getType(), 1)),
5115 Op0I->getOperand(0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005116 } else if (RHS->getValue().isSignBit()) {
5117 // (X + C) ^ signbit -> (X + C + signbit)
Owen Anderson24be4c12009-07-03 00:17:18 +00005118 Constant *C =
5119 Context->getConstantInt(RHS->getValue() + Op0CI->getValue());
Gabor Greifa645dd32008-05-16 19:29:10 +00005120 return BinaryOperator::CreateAdd(Op0I->getOperand(0), C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005121
5122 }
5123 } else if (Op0I->getOpcode() == Instruction::Or) {
5124 // (X|C1)^C2 -> X^(C1|C2) iff X&~C1 == 0
5125 if (MaskedValueIsZero(Op0I->getOperand(0), Op0CI->getValue())) {
Owen Anderson24be4c12009-07-03 00:17:18 +00005126 Constant *NewRHS = Context->getConstantExprOr(Op0CI, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005127 // Anything in both C1 and C2 is known to be zero, remove it from
5128 // NewRHS.
Owen Anderson24be4c12009-07-03 00:17:18 +00005129 Constant *CommonBits = Context->getConstantExprAnd(Op0CI, RHS);
5130 NewRHS = Context->getConstantExprAnd(NewRHS,
5131 Context->getConstantExprNot(CommonBits));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005132 AddToWorkList(Op0I);
5133 I.setOperand(0, Op0I->getOperand(0));
5134 I.setOperand(1, NewRHS);
5135 return &I;
5136 }
5137 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00005138 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005139 }
5140
5141 // Try to fold constant and into select arguments.
5142 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
5143 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
5144 return R;
5145 if (isa<PHINode>(Op0))
5146 if (Instruction *NV = FoldOpIntoPhi(I))
5147 return NV;
5148 }
5149
Owen Anderson24be4c12009-07-03 00:17:18 +00005150 if (Value *X = dyn_castNotVal(Op0, Context)) // ~A ^ A == -1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005151 if (X == Op1)
Owen Anderson24be4c12009-07-03 00:17:18 +00005152 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005153
Owen Anderson24be4c12009-07-03 00:17:18 +00005154 if (Value *X = dyn_castNotVal(Op1, Context)) // A ^ ~A == -1
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005155 if (X == Op0)
Owen Anderson24be4c12009-07-03 00:17:18 +00005156 return ReplaceInstUsesWith(I, Context->getAllOnesValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005157
5158
5159 BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1);
5160 if (Op1I) {
5161 Value *A, *B;
Owen Andersona21eb582009-07-10 17:35:01 +00005162 if (match(Op1I, m_Or(m_Value(A), m_Value(B)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005163 if (A == Op0) { // B^(B|A) == (A|B)^B
5164 Op1I->swapOperands();
5165 I.swapOperands();
5166 std::swap(Op0, Op1);
5167 } else if (B == Op0) { // B^(A|B) == (A|B)^B
5168 I.swapOperands(); // Simplified below.
5169 std::swap(Op0, Op1);
5170 }
Owen Andersona21eb582009-07-10 17:35:01 +00005171 } else if (match(Op1I, m_Xor(m_Specific(Op0), m_Value(B)), *Context)) {
Chris Lattner3b874082008-11-16 05:38:51 +00005172 return ReplaceInstUsesWith(I, B); // A^(A^B) == B
Owen Andersona21eb582009-07-10 17:35:01 +00005173 } else if (match(Op1I, m_Xor(m_Value(A), m_Specific(Op0)), *Context)) {
Chris Lattner3b874082008-11-16 05:38:51 +00005174 return ReplaceInstUsesWith(I, A); // A^(B^A) == B
Owen Andersona21eb582009-07-10 17:35:01 +00005175 } else if (match(Op1I, m_And(m_Value(A), m_Value(B)), *Context) &&
5176 Op1I->hasOneUse()){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005177 if (A == Op0) { // A^(A&B) -> A^(B&A)
5178 Op1I->swapOperands();
5179 std::swap(A, B);
5180 }
5181 if (B == Op0) { // A^(B&A) -> (B&A)^A
5182 I.swapOperands(); // Simplified below.
5183 std::swap(Op0, Op1);
5184 }
5185 }
5186 }
5187
5188 BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0);
5189 if (Op0I) {
5190 Value *A, *B;
Owen Andersona21eb582009-07-10 17:35:01 +00005191 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5192 Op0I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005193 if (A == Op1) // (B|A)^B == (A|B)^B
5194 std::swap(A, B);
5195 if (B == Op1) { // (A|B)^B == A & ~B
5196 Instruction *NotB =
Gabor Greifa645dd32008-05-16 19:29:10 +00005197 InsertNewInstBefore(BinaryOperator::CreateNot(Op1, "tmp"), I);
5198 return BinaryOperator::CreateAnd(A, NotB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005199 }
Owen Andersona21eb582009-07-10 17:35:01 +00005200 } else if (match(Op0I, m_Xor(m_Specific(Op1), m_Value(B)), *Context)) {
Chris Lattner3b874082008-11-16 05:38:51 +00005201 return ReplaceInstUsesWith(I, B); // (A^B)^A == B
Owen Andersona21eb582009-07-10 17:35:01 +00005202 } else if (match(Op0I, m_Xor(m_Value(A), m_Specific(Op1)), *Context)) {
Chris Lattner3b874082008-11-16 05:38:51 +00005203 return ReplaceInstUsesWith(I, A); // (B^A)^A == B
Owen Andersona21eb582009-07-10 17:35:01 +00005204 } else if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5205 Op0I->hasOneUse()){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005206 if (A == Op1) // (A&B)^A -> (B&A)^A
5207 std::swap(A, B);
5208 if (B == Op1 && // (B&A)^A == ~B & A
5209 !isa<ConstantInt>(Op1)) { // Canonical form is (B&C)^C
5210 Instruction *N =
Gabor Greifa645dd32008-05-16 19:29:10 +00005211 InsertNewInstBefore(BinaryOperator::CreateNot(A, "tmp"), I);
5212 return BinaryOperator::CreateAnd(N, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005213 }
5214 }
5215 }
5216
5217 // (X >> Z) ^ (Y >> Z) -> (X^Y) >> Z for all shifts.
5218 if (Op0I && Op1I && Op0I->isShift() &&
5219 Op0I->getOpcode() == Op1I->getOpcode() &&
5220 Op0I->getOperand(1) == Op1I->getOperand(1) &&
5221 (Op1I->hasOneUse() || Op1I->hasOneUse())) {
5222 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00005223 InsertNewInstBefore(BinaryOperator::CreateXor(Op0I->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005224 Op1I->getOperand(0),
5225 Op0I->getName()), I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005226 return BinaryOperator::Create(Op1I->getOpcode(), NewOp,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005227 Op1I->getOperand(1));
5228 }
5229
5230 if (Op0I && Op1I) {
5231 Value *A, *B, *C, *D;
5232 // (A & B)^(A | B) -> A ^ B
Owen Andersona21eb582009-07-10 17:35:01 +00005233 if (match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5234 match(Op1I, m_Or(m_Value(C), m_Value(D)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005235 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005236 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005237 }
5238 // (A | B)^(A & B) -> A ^ B
Owen Andersona21eb582009-07-10 17:35:01 +00005239 if (match(Op0I, m_Or(m_Value(A), m_Value(B)), *Context) &&
5240 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005241 if ((A == C && B == D) || (A == D && B == C))
Gabor Greifa645dd32008-05-16 19:29:10 +00005242 return BinaryOperator::CreateXor(A, B);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005243 }
5244
5245 // (A & B)^(C & D)
5246 if ((Op0I->hasOneUse() || Op1I->hasOneUse()) &&
Owen Andersona21eb582009-07-10 17:35:01 +00005247 match(Op0I, m_And(m_Value(A), m_Value(B)), *Context) &&
5248 match(Op1I, m_And(m_Value(C), m_Value(D)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005249 // (X & Y)^(X & Y) -> (Y^Z) & X
5250 Value *X = 0, *Y = 0, *Z = 0;
5251 if (A == C)
5252 X = A, Y = B, Z = D;
5253 else if (A == D)
5254 X = A, Y = B, Z = C;
5255 else if (B == C)
5256 X = B, Y = A, Z = D;
5257 else if (B == D)
5258 X = B, Y = A, Z = C;
5259
5260 if (X) {
5261 Instruction *NewOp =
Gabor Greifa645dd32008-05-16 19:29:10 +00005262 InsertNewInstBefore(BinaryOperator::CreateXor(Y, Z, Op0->getName()), I);
5263 return BinaryOperator::CreateAnd(NewOp, X);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005264 }
5265 }
5266 }
5267
5268 // (icmp1 A, B) ^ (icmp2 A, B) --> (icmp3 A, B)
5269 if (ICmpInst *RHS = dyn_cast<ICmpInst>(I.getOperand(1)))
Owen Anderson24be4c12009-07-03 00:17:18 +00005270 if (Instruction *R = AssociativeOpt(I, FoldICmpLogical(*this, RHS),Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005271 return R;
5272
5273 // fold (xor (cast A), (cast B)) -> (cast (xor A, B))
Chris Lattner91882432007-10-24 05:38:08 +00005274 if (CastInst *Op0C = dyn_cast<CastInst>(Op0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005275 if (CastInst *Op1C = dyn_cast<CastInst>(Op1))
5276 if (Op0C->getOpcode() == Op1C->getOpcode()) { // same cast kind?
5277 const Type *SrcTy = Op0C->getOperand(0)->getType();
5278 if (SrcTy == Op1C->getOperand(0)->getType() && SrcTy->isInteger() &&
5279 // Only do this if the casts both really cause code to be generated.
5280 ValueRequiresCast(Op0C->getOpcode(), Op0C->getOperand(0),
5281 I.getType(), TD) &&
5282 ValueRequiresCast(Op1C->getOpcode(), Op1C->getOperand(0),
5283 I.getType(), TD)) {
Gabor Greifa645dd32008-05-16 19:29:10 +00005284 Instruction *NewOp = BinaryOperator::CreateXor(Op0C->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005285 Op1C->getOperand(0),
5286 I.getName());
5287 InsertNewInstBefore(NewOp, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00005288 return CastInst::Create(Op0C->getOpcode(), NewOp, I.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005289 }
5290 }
Chris Lattner91882432007-10-24 05:38:08 +00005291 }
Nick Lewycky0aa63aa2008-05-31 19:01:33 +00005292
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005293 return Changed ? &I : 0;
5294}
5295
Owen Anderson24be4c12009-07-03 00:17:18 +00005296static ConstantInt *ExtractElement(Constant *V, Constant *Idx,
Owen Anderson5349f052009-07-06 23:00:19 +00005297 LLVMContext *Context) {
Owen Anderson24be4c12009-07-03 00:17:18 +00005298 return cast<ConstantInt>(Context->getConstantExprExtractElement(V, Idx));
Dan Gohman8fd520a2009-06-15 22:12:54 +00005299}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005300
Dan Gohman8fd520a2009-06-15 22:12:54 +00005301static bool HasAddOverflow(ConstantInt *Result,
5302 ConstantInt *In1, ConstantInt *In2,
5303 bool IsSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005304 if (IsSigned)
5305 if (In2->getValue().isNegative())
5306 return Result->getValue().sgt(In1->getValue());
5307 else
5308 return Result->getValue().slt(In1->getValue());
5309 else
5310 return Result->getValue().ult(In1->getValue());
5311}
5312
Dan Gohman8fd520a2009-06-15 22:12:54 +00005313/// AddWithOverflow - Compute Result = In1+In2, returning true if the result
Dan Gohmanb80d5612008-09-10 23:30:57 +00005314/// overflowed for this type.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005315static bool AddWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson5349f052009-07-06 23:00:19 +00005316 Constant *In2, LLVMContext *Context,
Owen Anderson24be4c12009-07-03 00:17:18 +00005317 bool IsSigned = false) {
5318 Result = Context->getConstantExprAdd(In1, In2);
Dan Gohmanb80d5612008-09-10 23:30:57 +00005319
Dan Gohman8fd520a2009-06-15 22:12:54 +00005320 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5321 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson24be4c12009-07-03 00:17:18 +00005322 Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5323 if (HasAddOverflow(ExtractElement(Result, Idx, Context),
5324 ExtractElement(In1, Idx, Context),
5325 ExtractElement(In2, Idx, Context),
Dan Gohman8fd520a2009-06-15 22:12:54 +00005326 IsSigned))
5327 return true;
5328 }
5329 return false;
5330 }
5331
5332 return HasAddOverflow(cast<ConstantInt>(Result),
5333 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5334 IsSigned);
5335}
5336
5337static bool HasSubOverflow(ConstantInt *Result,
5338 ConstantInt *In1, ConstantInt *In2,
5339 bool IsSigned) {
Dan Gohmanb80d5612008-09-10 23:30:57 +00005340 if (IsSigned)
5341 if (In2->getValue().isNegative())
5342 return Result->getValue().slt(In1->getValue());
5343 else
5344 return Result->getValue().sgt(In1->getValue());
5345 else
5346 return Result->getValue().ugt(In1->getValue());
5347}
5348
Dan Gohman8fd520a2009-06-15 22:12:54 +00005349/// SubWithOverflow - Compute Result = In1-In2, returning true if the result
5350/// overflowed for this type.
5351static bool SubWithOverflow(Constant *&Result, Constant *In1,
Owen Anderson5349f052009-07-06 23:00:19 +00005352 Constant *In2, LLVMContext *Context,
Owen Anderson24be4c12009-07-03 00:17:18 +00005353 bool IsSigned = false) {
5354 Result = Context->getConstantExprSub(In1, In2);
Dan Gohman8fd520a2009-06-15 22:12:54 +00005355
5356 if (const VectorType *VTy = dyn_cast<VectorType>(In1->getType())) {
5357 for (unsigned i = 0, e = VTy->getNumElements(); i != e; ++i) {
Owen Anderson24be4c12009-07-03 00:17:18 +00005358 Constant *Idx = Context->getConstantInt(Type::Int32Ty, i);
5359 if (HasSubOverflow(ExtractElement(Result, Idx, Context),
5360 ExtractElement(In1, Idx, Context),
5361 ExtractElement(In2, Idx, Context),
Dan Gohman8fd520a2009-06-15 22:12:54 +00005362 IsSigned))
5363 return true;
5364 }
5365 return false;
5366 }
5367
5368 return HasSubOverflow(cast<ConstantInt>(Result),
5369 cast<ConstantInt>(In1), cast<ConstantInt>(In2),
5370 IsSigned);
5371}
5372
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005373/// EmitGEPOffset - Given a getelementptr instruction/constantexpr, emit the
5374/// code necessary to compute the offset from the base pointer (without adding
5375/// in the base pointer). Return the result as a signed integer of intptr size.
5376static Value *EmitGEPOffset(User *GEP, Instruction &I, InstCombiner &IC) {
5377 TargetData &TD = IC.getTargetData();
5378 gep_type_iterator GTI = gep_type_begin(GEP);
5379 const Type *IntPtrTy = TD.getIntPtrType();
Owen Anderson5349f052009-07-06 23:00:19 +00005380 LLVMContext *Context = IC.getContext();
Owen Anderson24be4c12009-07-03 00:17:18 +00005381 Value *Result = Context->getNullValue(IntPtrTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005382
5383 // Build a mask for high order bits.
Chris Lattnereba75862008-04-22 02:53:33 +00005384 unsigned IntPtrWidth = TD.getPointerSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005385 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5386
Gabor Greif17396002008-06-12 21:37:33 +00005387 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); i != e;
5388 ++i, ++GTI) {
5389 Value *Op = *i;
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005390 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType()) & PtrSizeMask;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005391 if (ConstantInt *OpC = dyn_cast<ConstantInt>(Op)) {
5392 if (OpC->isZero()) continue;
5393
5394 // Handle a struct index, which adds its field offset to the pointer.
5395 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5396 Size = TD.getStructLayout(STy)->getElementOffset(OpC->getZExtValue());
5397
5398 if (ConstantInt *RC = dyn_cast<ConstantInt>(Result))
Owen Anderson24be4c12009-07-03 00:17:18 +00005399 Result =
5400 Context->getConstantInt(RC->getValue() + APInt(IntPtrWidth, Size));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005401 else
5402 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00005403 BinaryOperator::CreateAdd(Result,
Owen Anderson24be4c12009-07-03 00:17:18 +00005404 Context->getConstantInt(IntPtrTy, Size),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005405 GEP->getName()+".offs"), I);
5406 continue;
5407 }
5408
Owen Anderson24be4c12009-07-03 00:17:18 +00005409 Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
5410 Constant *OC =
5411 Context->getConstantExprIntegerCast(OpC, IntPtrTy, true /*SExt*/);
5412 Scale = Context->getConstantExprMul(OC, Scale);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005413 if (Constant *RC = dyn_cast<Constant>(Result))
Owen Anderson24be4c12009-07-03 00:17:18 +00005414 Result = Context->getConstantExprAdd(RC, Scale);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005415 else {
5416 // Emit an add instruction.
5417 Result = IC.InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00005418 BinaryOperator::CreateAdd(Result, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005419 GEP->getName()+".offs"), I);
5420 }
5421 continue;
5422 }
5423 // Convert to correct type.
5424 if (Op->getType() != IntPtrTy) {
5425 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Anderson24be4c12009-07-03 00:17:18 +00005426 Op = Context->getConstantExprIntegerCast(OpC, IntPtrTy, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005427 else
Chris Lattner2941a652009-04-07 05:03:34 +00005428 Op = IC.InsertNewInstBefore(CastInst::CreateIntegerCast(Op, IntPtrTy,
5429 true,
5430 Op->getName()+".c"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005431 }
5432 if (Size != 1) {
Owen Anderson24be4c12009-07-03 00:17:18 +00005433 Constant *Scale = Context->getConstantInt(IntPtrTy, Size);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005434 if (Constant *OpC = dyn_cast<Constant>(Op))
Owen Anderson24be4c12009-07-03 00:17:18 +00005435 Op = Context->getConstantExprMul(OpC, Scale);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005436 else // We'll let instcombine(mul) convert this to a shl if possible.
Gabor Greifa645dd32008-05-16 19:29:10 +00005437 Op = IC.InsertNewInstBefore(BinaryOperator::CreateMul(Op, Scale,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005438 GEP->getName()+".idx"), I);
5439 }
5440
5441 // Emit an add instruction.
5442 if (isa<Constant>(Op) && isa<Constant>(Result))
Owen Anderson24be4c12009-07-03 00:17:18 +00005443 Result = Context->getConstantExprAdd(cast<Constant>(Op),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005444 cast<Constant>(Result));
5445 else
Gabor Greifa645dd32008-05-16 19:29:10 +00005446 Result = IC.InsertNewInstBefore(BinaryOperator::CreateAdd(Op, Result,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005447 GEP->getName()+".offs"), I);
5448 }
5449 return Result;
5450}
5451
Chris Lattnereba75862008-04-22 02:53:33 +00005452
5453/// EvaluateGEPOffsetExpression - Return an value that can be used to compare of
5454/// the *offset* implied by GEP to zero. For example, if we have &A[i], we want
5455/// to return 'i' for "icmp ne i, 0". Note that, in general, indices can be
5456/// complex, and scales are involved. The above expression would also be legal
5457/// to codegen as "icmp ne (i*4), 0" (assuming A is a pointer to i32). This
5458/// later form is less amenable to optimization though, and we are allowed to
5459/// generate the first by knowing that pointer arithmetic doesn't overflow.
5460///
5461/// If we can't emit an optimized form for this expression, this returns null.
5462///
5463static Value *EvaluateGEPOffsetExpression(User *GEP, Instruction &I,
5464 InstCombiner &IC) {
Chris Lattnereba75862008-04-22 02:53:33 +00005465 TargetData &TD = IC.getTargetData();
5466 gep_type_iterator GTI = gep_type_begin(GEP);
5467
5468 // Check to see if this gep only has a single variable index. If so, and if
5469 // any constant indices are a multiple of its scale, then we can compute this
5470 // in terms of the scale of the variable index. For example, if the GEP
5471 // implies an offset of "12 + i*4", then we can codegen this as "3 + i",
5472 // because the expression will cross zero at the same point.
5473 unsigned i, e = GEP->getNumOperands();
5474 int64_t Offset = 0;
5475 for (i = 1; i != e; ++i, ++GTI) {
5476 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
5477 // Compute the aggregate offset of constant indices.
5478 if (CI->isZero()) continue;
5479
5480 // Handle a struct index, which adds its field offset to the pointer.
5481 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5482 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5483 } else {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005484 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005485 Offset += Size*CI->getSExtValue();
5486 }
5487 } else {
5488 // Found our variable index.
5489 break;
5490 }
5491 }
5492
5493 // If there are no variable indices, we must have a constant offset, just
5494 // evaluate it the general way.
5495 if (i == e) return 0;
5496
5497 Value *VariableIdx = GEP->getOperand(i);
5498 // Determine the scale factor of the variable element. For example, this is
5499 // 4 if the variable index is into an array of i32.
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005500 uint64_t VariableScale = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005501
5502 // Verify that there are no other variable indices. If so, emit the hard way.
5503 for (++i, ++GTI; i != e; ++i, ++GTI) {
5504 ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i));
5505 if (!CI) return 0;
5506
5507 // Compute the aggregate offset of constant indices.
5508 if (CI->isZero()) continue;
5509
5510 // Handle a struct index, which adds its field offset to the pointer.
5511 if (const StructType *STy = dyn_cast<StructType>(*GTI)) {
5512 Offset += TD.getStructLayout(STy)->getElementOffset(CI->getZExtValue());
5513 } else {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00005514 uint64_t Size = TD.getTypeAllocSize(GTI.getIndexedType());
Chris Lattnereba75862008-04-22 02:53:33 +00005515 Offset += Size*CI->getSExtValue();
5516 }
5517 }
5518
5519 // Okay, we know we have a single variable index, which must be a
5520 // pointer/array/vector index. If there is no offset, life is simple, return
5521 // the index.
5522 unsigned IntPtrWidth = TD.getPointerSizeInBits();
5523 if (Offset == 0) {
5524 // Cast to intptrty in case a truncation occurs. If an extension is needed,
5525 // we don't need to bother extending: the extension won't affect where the
5526 // computation crosses zero.
5527 if (VariableIdx->getType()->getPrimitiveSizeInBits() > IntPtrWidth)
5528 VariableIdx = new TruncInst(VariableIdx, TD.getIntPtrType(),
5529 VariableIdx->getNameStart(), &I);
5530 return VariableIdx;
5531 }
5532
5533 // Otherwise, there is an index. The computation we will do will be modulo
5534 // the pointer size, so get it.
5535 uint64_t PtrSizeMask = ~0ULL >> (64-IntPtrWidth);
5536
5537 Offset &= PtrSizeMask;
5538 VariableScale &= PtrSizeMask;
5539
5540 // To do this transformation, any constant index must be a multiple of the
5541 // variable scale factor. For example, we can evaluate "12 + 4*i" as "3 + i",
5542 // but we can't evaluate "10 + 3*i" in terms of i. Check that the offset is a
5543 // multiple of the variable scale.
5544 int64_t NewOffs = Offset / (int64_t)VariableScale;
5545 if (Offset != NewOffs*(int64_t)VariableScale)
5546 return 0;
5547
5548 // Okay, we can do this evaluation. Start by converting the index to intptr.
5549 const Type *IntPtrTy = TD.getIntPtrType();
5550 if (VariableIdx->getType() != IntPtrTy)
Gabor Greifa645dd32008-05-16 19:29:10 +00005551 VariableIdx = CastInst::CreateIntegerCast(VariableIdx, IntPtrTy,
Chris Lattnereba75862008-04-22 02:53:33 +00005552 true /*SExt*/,
5553 VariableIdx->getNameStart(), &I);
Owen Anderson24be4c12009-07-03 00:17:18 +00005554 Constant *OffsetVal = IC.getContext()->getConstantInt(IntPtrTy, NewOffs);
Gabor Greifa645dd32008-05-16 19:29:10 +00005555 return BinaryOperator::CreateAdd(VariableIdx, OffsetVal, "offset", &I);
Chris Lattnereba75862008-04-22 02:53:33 +00005556}
5557
5558
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005559/// FoldGEPICmp - Fold comparisons between a GEP instruction and something
5560/// else. At this point we know that the GEP is on the LHS of the comparison.
5561Instruction *InstCombiner::FoldGEPICmp(User *GEPLHS, Value *RHS,
5562 ICmpInst::Predicate Cond,
5563 Instruction &I) {
5564 assert(dyn_castGetElementPtr(GEPLHS) && "LHS is not a getelementptr!");
5565
Chris Lattnereba75862008-04-22 02:53:33 +00005566 // Look through bitcasts.
5567 if (BitCastInst *BCI = dyn_cast<BitCastInst>(RHS))
5568 RHS = BCI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005569
5570 Value *PtrBase = GEPLHS->getOperand(0);
5571 if (PtrBase == RHS) {
Chris Lattneraf97d022008-02-05 04:45:32 +00005572 // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
Chris Lattnereba75862008-04-22 02:53:33 +00005573 // This transformation (ignoring the base and scales) is valid because we
5574 // know pointers can't overflow. See if we can output an optimized form.
5575 Value *Offset = EvaluateGEPOffsetExpression(GEPLHS, I, *this);
5576
5577 // If not, synthesize the offset the hard way.
5578 if (Offset == 0)
5579 Offset = EmitGEPOffset(GEPLHS, I, *this);
Owen Anderson6601fcd2009-07-09 23:48:35 +00005580 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), Offset,
Owen Anderson24be4c12009-07-03 00:17:18 +00005581 Context->getNullValue(Offset->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005582 } else if (User *GEPRHS = dyn_castGetElementPtr(RHS)) {
5583 // If the base pointers are different, but the indices are the same, just
5584 // compare the base pointer.
5585 if (PtrBase != GEPRHS->getOperand(0)) {
5586 bool IndicesTheSame = GEPLHS->getNumOperands()==GEPRHS->getNumOperands();
5587 IndicesTheSame &= GEPLHS->getOperand(0)->getType() ==
5588 GEPRHS->getOperand(0)->getType();
5589 if (IndicesTheSame)
5590 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5591 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5592 IndicesTheSame = false;
5593 break;
5594 }
5595
5596 // If all indices are the same, just compare the base pointers.
5597 if (IndicesTheSame)
Owen Anderson6601fcd2009-07-09 23:48:35 +00005598 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005599 GEPLHS->getOperand(0), GEPRHS->getOperand(0));
5600
5601 // Otherwise, the base pointers are different and the indices are
5602 // different, bail out.
5603 return 0;
5604 }
5605
5606 // If one of the GEPs has all zero indices, recurse.
5607 bool AllZeros = true;
5608 for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
5609 if (!isa<Constant>(GEPLHS->getOperand(i)) ||
5610 !cast<Constant>(GEPLHS->getOperand(i))->isNullValue()) {
5611 AllZeros = false;
5612 break;
5613 }
5614 if (AllZeros)
5615 return FoldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
5616 ICmpInst::getSwappedPredicate(Cond), I);
5617
5618 // If the other GEP has all zero indices, recurse.
5619 AllZeros = true;
5620 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5621 if (!isa<Constant>(GEPRHS->getOperand(i)) ||
5622 !cast<Constant>(GEPRHS->getOperand(i))->isNullValue()) {
5623 AllZeros = false;
5624 break;
5625 }
5626 if (AllZeros)
5627 return FoldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
5628
5629 if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands()) {
5630 // If the GEPs only differ by one index, compare it.
5631 unsigned NumDifferences = 0; // Keep track of # differences.
5632 unsigned DiffOperand = 0; // The operand that differs.
5633 for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
5634 if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
5635 if (GEPLHS->getOperand(i)->getType()->getPrimitiveSizeInBits() !=
5636 GEPRHS->getOperand(i)->getType()->getPrimitiveSizeInBits()) {
5637 // Irreconcilable differences.
5638 NumDifferences = 2;
5639 break;
5640 } else {
5641 if (NumDifferences++) break;
5642 DiffOperand = i;
5643 }
5644 }
5645
5646 if (NumDifferences == 0) // SAME GEP?
5647 return ReplaceInstUsesWith(I, // No comparison is needed here.
Owen Anderson24be4c12009-07-03 00:17:18 +00005648 Context->getConstantInt(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005649 ICmpInst::isTrueWhenEqual(Cond)));
Nick Lewycky2de09a92007-09-06 02:40:25 +00005650
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005651 else if (NumDifferences == 1) {
5652 Value *LHSV = GEPLHS->getOperand(DiffOperand);
5653 Value *RHSV = GEPRHS->getOperand(DiffOperand);
5654 // Make sure we do a signed comparison here.
Owen Anderson6601fcd2009-07-09 23:48:35 +00005655 return new ICmpInst(*Context,
5656 ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005657 }
5658 }
5659
5660 // Only lower this if the icmp is the only user of the GEP or if we expect
5661 // the result to fold to a constant!
5662 if ((isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
5663 (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
5664 // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
5665 Value *L = EmitGEPOffset(GEPLHS, I, *this);
5666 Value *R = EmitGEPOffset(GEPRHS, I, *this);
Owen Anderson6601fcd2009-07-09 23:48:35 +00005667 return new ICmpInst(*Context, ICmpInst::getSignedPredicate(Cond), L, R);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005668 }
5669 }
5670 return 0;
5671}
5672
Chris Lattnere6b62d92008-05-19 20:18:56 +00005673/// FoldFCmp_IntToFP_Cst - Fold fcmp ([us]itofp x, cst) if possible.
5674///
5675Instruction *InstCombiner::FoldFCmp_IntToFP_Cst(FCmpInst &I,
5676 Instruction *LHSI,
5677 Constant *RHSC) {
5678 if (!isa<ConstantFP>(RHSC)) return 0;
5679 const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
5680
5681 // Get the width of the mantissa. We don't want to hack on conversions that
5682 // might lose information from the integer, e.g. "i64 -> float"
Chris Lattner9ce836b2008-05-19 21:17:23 +00005683 int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005684 if (MantissaWidth == -1) return 0; // Unknown.
5685
5686 // Check to see that the input is converted from an integer type that is small
5687 // enough that preserves all bits. TODO: check here for "known" sign bits.
5688 // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005689 unsigned InputSize = LHSI->getOperand(0)->getType()->getScalarSizeInBits();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005690
5691 // If this is a uitofp instruction, we need an extra bit to hold the sign.
Bill Wendling20636df2008-11-09 04:26:50 +00005692 bool LHSUnsigned = isa<UIToFPInst>(LHSI);
5693 if (LHSUnsigned)
Chris Lattnere6b62d92008-05-19 20:18:56 +00005694 ++InputSize;
5695
5696 // If the conversion would lose info, don't hack on this.
5697 if ((int)InputSize > MantissaWidth)
5698 return 0;
5699
5700 // Otherwise, we can potentially simplify the comparison. We know that it
5701 // will always come through as an integer value and we know the constant is
5702 // not a NAN (it would have been previously simplified).
5703 assert(!RHS.isNaN() && "NaN comparison not already folded!");
5704
5705 ICmpInst::Predicate Pred;
5706 switch (I.getPredicate()) {
5707 default: assert(0 && "Unexpected predicate!");
5708 case FCmpInst::FCMP_UEQ:
Bill Wendling20636df2008-11-09 04:26:50 +00005709 case FCmpInst::FCMP_OEQ:
5710 Pred = ICmpInst::ICMP_EQ;
5711 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005712 case FCmpInst::FCMP_UGT:
Bill Wendling20636df2008-11-09 04:26:50 +00005713 case FCmpInst::FCMP_OGT:
5714 Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
5715 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005716 case FCmpInst::FCMP_UGE:
Bill Wendling20636df2008-11-09 04:26:50 +00005717 case FCmpInst::FCMP_OGE:
5718 Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
5719 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005720 case FCmpInst::FCMP_ULT:
Bill Wendling20636df2008-11-09 04:26:50 +00005721 case FCmpInst::FCMP_OLT:
5722 Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
5723 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005724 case FCmpInst::FCMP_ULE:
Bill Wendling20636df2008-11-09 04:26:50 +00005725 case FCmpInst::FCMP_OLE:
5726 Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
5727 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005728 case FCmpInst::FCMP_UNE:
Bill Wendling20636df2008-11-09 04:26:50 +00005729 case FCmpInst::FCMP_ONE:
5730 Pred = ICmpInst::ICMP_NE;
5731 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005732 case FCmpInst::FCMP_ORD:
Owen Anderson24be4c12009-07-03 00:17:18 +00005733 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattnere6b62d92008-05-19 20:18:56 +00005734 case FCmpInst::FCMP_UNO:
Owen Anderson24be4c12009-07-03 00:17:18 +00005735 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattnere6b62d92008-05-19 20:18:56 +00005736 }
5737
5738 const IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
5739
5740 // Now we know that the APFloat is a normal number, zero or inf.
5741
Chris Lattnerf13ff492008-05-20 03:50:52 +00005742 // See if the FP constant is too large for the integer. For example,
Chris Lattnere6b62d92008-05-19 20:18:56 +00005743 // comparing an i8 to 300.0.
Dan Gohman8fd520a2009-06-15 22:12:54 +00005744 unsigned IntWidth = IntTy->getScalarSizeInBits();
Chris Lattnere6b62d92008-05-19 20:18:56 +00005745
Bill Wendling20636df2008-11-09 04:26:50 +00005746 if (!LHSUnsigned) {
5747 // If the RHS value is > SignedMax, fold the comparison. This handles +INF
5748 // and large values.
5749 APFloat SMax(RHS.getSemantics(), APFloat::fcZero, false);
5750 SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
5751 APFloat::rmNearestTiesToEven);
5752 if (SMax.compare(RHS) == APFloat::cmpLessThan) { // smax < 13123.0
5753 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
5754 Pred == ICmpInst::ICMP_SLE)
Owen Anderson24be4c12009-07-03 00:17:18 +00005755 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5756 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Bill Wendling20636df2008-11-09 04:26:50 +00005757 }
5758 } else {
5759 // If the RHS value is > UnsignedMax, fold the comparison. This handles
5760 // +INF and large values.
5761 APFloat UMax(RHS.getSemantics(), APFloat::fcZero, false);
5762 UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
5763 APFloat::rmNearestTiesToEven);
5764 if (UMax.compare(RHS) == APFloat::cmpLessThan) { // umax < 13123.0
5765 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
5766 Pred == ICmpInst::ICMP_ULE)
Owen Anderson24be4c12009-07-03 00:17:18 +00005767 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5768 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Bill Wendling20636df2008-11-09 04:26:50 +00005769 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005770 }
5771
Bill Wendling20636df2008-11-09 04:26:50 +00005772 if (!LHSUnsigned) {
5773 // See if the RHS value is < SignedMin.
5774 APFloat SMin(RHS.getSemantics(), APFloat::fcZero, false);
5775 SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
5776 APFloat::rmNearestTiesToEven);
5777 if (SMin.compare(RHS) == APFloat::cmpGreaterThan) { // smin > 12312.0
5778 if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
5779 Pred == ICmpInst::ICMP_SGE)
Owen Anderson24be4c12009-07-03 00:17:18 +00005780 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
5781 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Bill Wendling20636df2008-11-09 04:26:50 +00005782 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005783 }
5784
Bill Wendling20636df2008-11-09 04:26:50 +00005785 // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
5786 // [0, UMAX], but it may still be fractional. See if it is fractional by
5787 // casting the FP value to the integer value and back, checking for equality.
5788 // Don't do this for zero, because -0.0 is not fractional.
Evan Cheng14118132009-05-22 23:10:53 +00005789 Constant *RHSInt = LHSUnsigned
Owen Anderson24be4c12009-07-03 00:17:18 +00005790 ? Context->getConstantExprFPToUI(RHSC, IntTy)
5791 : Context->getConstantExprFPToSI(RHSC, IntTy);
Evan Cheng14118132009-05-22 23:10:53 +00005792 if (!RHS.isZero()) {
5793 bool Equal = LHSUnsigned
Owen Anderson24be4c12009-07-03 00:17:18 +00005794 ? Context->getConstantExprUIToFP(RHSInt, RHSC->getType()) == RHSC
5795 : Context->getConstantExprSIToFP(RHSInt, RHSC->getType()) == RHSC;
Evan Cheng14118132009-05-22 23:10:53 +00005796 if (!Equal) {
5797 // If we had a comparison against a fractional value, we have to adjust
5798 // the compare predicate and sometimes the value. RHSC is rounded towards
5799 // zero at this point.
5800 switch (Pred) {
5801 default: assert(0 && "Unexpected integer comparison!");
5802 case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
Owen Anderson24be4c12009-07-03 00:17:18 +00005803 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Evan Cheng14118132009-05-22 23:10:53 +00005804 case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
Owen Anderson24be4c12009-07-03 00:17:18 +00005805 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng14118132009-05-22 23:10:53 +00005806 case ICmpInst::ICMP_ULE:
5807 // (float)int <= 4.4 --> int <= 4
5808 // (float)int <= -4.4 --> false
5809 if (RHS.isNegative())
Owen Anderson24be4c12009-07-03 00:17:18 +00005810 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng14118132009-05-22 23:10:53 +00005811 break;
5812 case ICmpInst::ICMP_SLE:
5813 // (float)int <= 4.4 --> int <= 4
5814 // (float)int <= -4.4 --> int < -4
5815 if (RHS.isNegative())
5816 Pred = ICmpInst::ICMP_SLT;
5817 break;
5818 case ICmpInst::ICMP_ULT:
5819 // (float)int < -4.4 --> false
5820 // (float)int < 4.4 --> int <= 4
5821 if (RHS.isNegative())
Owen Anderson24be4c12009-07-03 00:17:18 +00005822 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Evan Cheng14118132009-05-22 23:10:53 +00005823 Pred = ICmpInst::ICMP_ULE;
5824 break;
5825 case ICmpInst::ICMP_SLT:
5826 // (float)int < -4.4 --> int < -4
5827 // (float)int < 4.4 --> int <= 4
5828 if (!RHS.isNegative())
5829 Pred = ICmpInst::ICMP_SLE;
5830 break;
5831 case ICmpInst::ICMP_UGT:
5832 // (float)int > 4.4 --> int > 4
5833 // (float)int > -4.4 --> true
5834 if (RHS.isNegative())
Owen Anderson24be4c12009-07-03 00:17:18 +00005835 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Evan Cheng14118132009-05-22 23:10:53 +00005836 break;
5837 case ICmpInst::ICMP_SGT:
5838 // (float)int > 4.4 --> int > 4
5839 // (float)int > -4.4 --> int >= -4
5840 if (RHS.isNegative())
5841 Pred = ICmpInst::ICMP_SGE;
5842 break;
5843 case ICmpInst::ICMP_UGE:
5844 // (float)int >= -4.4 --> true
5845 // (float)int >= 4.4 --> int > 4
5846 if (!RHS.isNegative())
Owen Anderson24be4c12009-07-03 00:17:18 +00005847 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Evan Cheng14118132009-05-22 23:10:53 +00005848 Pred = ICmpInst::ICMP_UGT;
5849 break;
5850 case ICmpInst::ICMP_SGE:
5851 // (float)int >= -4.4 --> int >= -4
5852 // (float)int >= 4.4 --> int > 4
5853 if (!RHS.isNegative())
5854 Pred = ICmpInst::ICMP_SGT;
5855 break;
5856 }
Chris Lattnere6b62d92008-05-19 20:18:56 +00005857 }
5858 }
5859
5860 // Lower this FP comparison into an appropriate integer version of the
5861 // comparison.
Owen Anderson6601fcd2009-07-09 23:48:35 +00005862 return new ICmpInst(*Context, Pred, LHSI->getOperand(0), RHSInt);
Chris Lattnere6b62d92008-05-19 20:18:56 +00005863}
5864
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005865Instruction *InstCombiner::visitFCmpInst(FCmpInst &I) {
5866 bool Changed = SimplifyCompare(I);
5867 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5868
5869 // Fold trivial predicates.
5870 if (I.getPredicate() == FCmpInst::FCMP_FALSE)
Owen Anderson24be4c12009-07-03 00:17:18 +00005871 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005872 if (I.getPredicate() == FCmpInst::FCMP_TRUE)
Owen Anderson24be4c12009-07-03 00:17:18 +00005873 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005874
5875 // Simplify 'fcmp pred X, X'
5876 if (Op0 == Op1) {
5877 switch (I.getPredicate()) {
5878 default: assert(0 && "Unknown predicate!");
5879 case FCmpInst::FCMP_UEQ: // True if unordered or equal
5880 case FCmpInst::FCMP_UGE: // True if unordered, greater than, or equal
5881 case FCmpInst::FCMP_ULE: // True if unordered, less than, or equal
Owen Anderson24be4c12009-07-03 00:17:18 +00005882 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005883 case FCmpInst::FCMP_OGT: // True if ordered and greater than
5884 case FCmpInst::FCMP_OLT: // True if ordered and less than
5885 case FCmpInst::FCMP_ONE: // True if ordered and operands are unequal
Owen Anderson24be4c12009-07-03 00:17:18 +00005886 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005887
5888 case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
5889 case FCmpInst::FCMP_ULT: // True if unordered or less than
5890 case FCmpInst::FCMP_UGT: // True if unordered or greater than
5891 case FCmpInst::FCMP_UNE: // True if unordered or not equal
5892 // Canonicalize these to be 'fcmp uno %X, 0.0'.
5893 I.setPredicate(FCmpInst::FCMP_UNO);
Owen Anderson24be4c12009-07-03 00:17:18 +00005894 I.setOperand(1, Context->getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005895 return &I;
5896
5897 case FCmpInst::FCMP_ORD: // True if ordered (no nans)
5898 case FCmpInst::FCMP_OEQ: // True if ordered and equal
5899 case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
5900 case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
5901 // Canonicalize these to be 'fcmp ord %X, 0.0'.
5902 I.setPredicate(FCmpInst::FCMP_ORD);
Owen Anderson24be4c12009-07-03 00:17:18 +00005903 I.setOperand(1, Context->getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005904 return &I;
5905 }
5906 }
5907
5908 if (isa<UndefValue>(Op1)) // fcmp pred X, undef -> undef
Owen Anderson24be4c12009-07-03 00:17:18 +00005909 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005910
5911 // Handle fcmp with constant RHS
5912 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
Chris Lattnere6b62d92008-05-19 20:18:56 +00005913 // If the constant is a nan, see if we can fold the comparison based on it.
5914 if (ConstantFP *CFP = dyn_cast<ConstantFP>(RHSC)) {
5915 if (CFP->getValueAPF().isNaN()) {
5916 if (FCmpInst::isOrdered(I.getPredicate())) // True if ordered and...
Owen Anderson24be4c12009-07-03 00:17:18 +00005917 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattnerf13ff492008-05-20 03:50:52 +00005918 assert(FCmpInst::isUnordered(I.getPredicate()) &&
5919 "Comparison must be either ordered or unordered!");
5920 // True if unordered.
Owen Anderson24be4c12009-07-03 00:17:18 +00005921 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattnere6b62d92008-05-19 20:18:56 +00005922 }
5923 }
5924
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005925 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
5926 switch (LHSI->getOpcode()) {
5927 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00005928 // Only fold fcmp into the PHI if the phi and fcmp are in the same
5929 // block. If in the same block, we're encouraging jump threading. If
5930 // not, we are just pessimizing the code by making an i1 phi.
5931 if (LHSI->getParent() == I.getParent())
5932 if (Instruction *NV = FoldOpIntoPhi(I))
5933 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005934 break;
Chris Lattnere6b62d92008-05-19 20:18:56 +00005935 case Instruction::SIToFP:
5936 case Instruction::UIToFP:
5937 if (Instruction *NV = FoldFCmp_IntToFP_Cst(I, LHSI, RHSC))
5938 return NV;
5939 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005940 case Instruction::Select:
5941 // If either operand of the select is a constant, we can fold the
5942 // comparison into the select arms, which will cause one to be
5943 // constant folded and the select turned into a bitwise or.
5944 Value *Op1 = 0, *Op2 = 0;
5945 if (LHSI->hasOneUse()) {
5946 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
5947 // Fold the known value into the constant operand.
Owen Anderson24be4c12009-07-03 00:17:18 +00005948 Op1 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005949 // Insert a new FCmp of the other select operand.
Owen Anderson6601fcd2009-07-09 23:48:35 +00005950 Op2 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005951 LHSI->getOperand(2), RHSC,
5952 I.getName()), I);
5953 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
5954 // Fold the known value into the constant operand.
Owen Anderson24be4c12009-07-03 00:17:18 +00005955 Op2 = Context->getConstantExprCompare(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005956 // Insert a new FCmp of the other select operand.
Owen Anderson6601fcd2009-07-09 23:48:35 +00005957 Op1 = InsertNewInstBefore(new FCmpInst(*Context, I.getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005958 LHSI->getOperand(1), RHSC,
5959 I.getName()), I);
5960 }
5961 }
5962
5963 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00005964 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005965 break;
5966 }
5967 }
5968
5969 return Changed ? &I : 0;
5970}
5971
5972Instruction *InstCombiner::visitICmpInst(ICmpInst &I) {
5973 bool Changed = SimplifyCompare(I);
5974 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
5975 const Type *Ty = Op0->getType();
5976
5977 // icmp X, X
5978 if (Op0 == Op1)
Owen Anderson24be4c12009-07-03 00:17:18 +00005979 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005980 I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005981
5982 if (isa<UndefValue>(Op1)) // X icmp undef -> undef
Owen Anderson24be4c12009-07-03 00:17:18 +00005983 return ReplaceInstUsesWith(I, Context->getUndef(Type::Int1Ty));
Christopher Lambf78cd322007-12-18 21:32:20 +00005984
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005985 // icmp <global/alloca*/null>, <global/alloca*/null> - Global/Stack value
5986 // addresses never equal each other! We already know that Op0 != Op1.
5987 if ((isa<GlobalValue>(Op0) || isa<AllocaInst>(Op0) ||
5988 isa<ConstantPointerNull>(Op0)) &&
5989 (isa<GlobalValue>(Op1) || isa<AllocaInst>(Op1) ||
5990 isa<ConstantPointerNull>(Op1)))
Owen Anderson24be4c12009-07-03 00:17:18 +00005991 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00005992 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00005993
5994 // icmp's with boolean values can always be turned into bitwise operations
5995 if (Ty == Type::Int1Ty) {
5996 switch (I.getPredicate()) {
5997 default: assert(0 && "Invalid icmp instruction!");
Chris Lattnera02893d2008-07-11 04:20:58 +00005998 case ICmpInst::ICMP_EQ: { // icmp eq i1 A, B -> ~(A^B)
Gabor Greifa645dd32008-05-16 19:29:10 +00005999 Instruction *Xor = BinaryOperator::CreateXor(Op0, Op1, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006000 InsertNewInstBefore(Xor, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00006001 return BinaryOperator::CreateNot(Xor);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006002 }
Chris Lattnera02893d2008-07-11 04:20:58 +00006003 case ICmpInst::ICMP_NE: // icmp eq i1 A, B -> A^B
Gabor Greifa645dd32008-05-16 19:29:10 +00006004 return BinaryOperator::CreateXor(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006005
6006 case ICmpInst::ICMP_UGT:
Chris Lattnera02893d2008-07-11 04:20:58 +00006007 std::swap(Op0, Op1); // Change icmp ugt -> icmp ult
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006008 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00006009 case ICmpInst::ICMP_ULT:{ // icmp ult i1 A, B -> ~A & B
Gabor Greifa645dd32008-05-16 19:29:10 +00006010 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006011 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00006012 return BinaryOperator::CreateAnd(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006013 }
Chris Lattnera02893d2008-07-11 04:20:58 +00006014 case ICmpInst::ICMP_SGT:
6015 std::swap(Op0, Op1); // Change icmp sgt -> icmp slt
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006016 // FALL THROUGH
Chris Lattnera02893d2008-07-11 04:20:58 +00006017 case ICmpInst::ICMP_SLT: { // icmp slt i1 A, B -> A & ~B
6018 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
6019 InsertNewInstBefore(Not, I);
6020 return BinaryOperator::CreateAnd(Not, Op0);
6021 }
6022 case ICmpInst::ICMP_UGE:
6023 std::swap(Op0, Op1); // Change icmp uge -> icmp ule
6024 // FALL THROUGH
6025 case ICmpInst::ICMP_ULE: { // icmp ule i1 A, B -> ~A | B
Gabor Greifa645dd32008-05-16 19:29:10 +00006026 Instruction *Not = BinaryOperator::CreateNot(Op0, I.getName()+"tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006027 InsertNewInstBefore(Not, I);
Gabor Greifa645dd32008-05-16 19:29:10 +00006028 return BinaryOperator::CreateOr(Not, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006029 }
Chris Lattnera02893d2008-07-11 04:20:58 +00006030 case ICmpInst::ICMP_SGE:
6031 std::swap(Op0, Op1); // Change icmp sge -> icmp sle
6032 // FALL THROUGH
6033 case ICmpInst::ICMP_SLE: { // icmp sle i1 A, B -> A | ~B
6034 Instruction *Not = BinaryOperator::CreateNot(Op1, I.getName()+"tmp");
6035 InsertNewInstBefore(Not, I);
6036 return BinaryOperator::CreateOr(Not, Op0);
6037 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006038 }
6039 }
6040
Dan Gohman7934d592009-04-25 17:12:48 +00006041 unsigned BitWidth = 0;
6042 if (TD)
Dan Gohman2526aea2009-06-16 19:55:29 +00006043 BitWidth = TD->getTypeSizeInBits(Ty->getScalarType());
6044 else if (Ty->isIntOrIntVector())
6045 BitWidth = Ty->getScalarSizeInBits();
Dan Gohman7934d592009-04-25 17:12:48 +00006046
6047 bool isSignBit = false;
6048
Dan Gohman58c09632008-09-16 18:46:06 +00006049 // See if we are doing a comparison with a constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006050 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Nick Lewycky7c5c2372009-02-27 06:37:39 +00006051 Value *A = 0, *B = 0;
Christopher Lambfa6b3102007-12-20 07:21:11 +00006052
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00006053 // (icmp ne/eq (sub A B) 0) -> (icmp ne/eq A, B)
6054 if (I.isEquality() && CI->isNullValue() &&
Owen Andersona21eb582009-07-10 17:35:01 +00006055 match(Op0, m_Sub(m_Value(A), m_Value(B)), *Context)) {
Chris Lattnerbe6c54a2008-01-05 01:18:20 +00006056 // (icmp cond A B) if cond is equality
Owen Anderson6601fcd2009-07-09 23:48:35 +00006057 return new ICmpInst(*Context, I.getPredicate(), A, B);
Owen Anderson42f61ed2007-12-28 07:42:12 +00006058 }
Christopher Lambfa6b3102007-12-20 07:21:11 +00006059
Dan Gohman58c09632008-09-16 18:46:06 +00006060 // If we have an icmp le or icmp ge instruction, turn it into the
6061 // appropriate icmp lt or icmp gt instruction. This allows us to rely on
6062 // them being folded in the code below.
Chris Lattner62d0f232008-07-11 05:08:55 +00006063 switch (I.getPredicate()) {
6064 default: break;
6065 case ICmpInst::ICMP_ULE:
6066 if (CI->isMaxValue(false)) // A <=u MAX -> TRUE
Owen Anderson24be4c12009-07-03 00:17:18 +00006067 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Owen Anderson6601fcd2009-07-09 23:48:35 +00006068 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, Op0,
6069 AddOne(CI, Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006070 case ICmpInst::ICMP_SLE:
6071 if (CI->isMaxValue(true)) // A <=s MAX -> TRUE
Owen Anderson24be4c12009-07-03 00:17:18 +00006072 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Owen Anderson6601fcd2009-07-09 23:48:35 +00006073 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
6074 AddOne(CI, Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006075 case ICmpInst::ICMP_UGE:
6076 if (CI->isMinValue(false)) // A >=u MIN -> TRUE
Owen Anderson24be4c12009-07-03 00:17:18 +00006077 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Owen Anderson6601fcd2009-07-09 23:48:35 +00006078 return new ICmpInst(*Context, ICmpInst::ICMP_UGT, Op0,
6079 SubOne(CI, Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006080 case ICmpInst::ICMP_SGE:
6081 if (CI->isMinValue(true)) // A >=s MIN -> TRUE
Owen Anderson24be4c12009-07-03 00:17:18 +00006082 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Owen Anderson6601fcd2009-07-09 23:48:35 +00006083 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
6084 SubOne(CI, Context));
Chris Lattner62d0f232008-07-11 05:08:55 +00006085 }
6086
Chris Lattnera1308652008-07-11 05:40:05 +00006087 // If this comparison is a normal comparison, it demands all
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006088 // bits, if it is a sign bit comparison, it only demands the sign bit.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006089 bool UnusedBit;
Dan Gohman7934d592009-04-25 17:12:48 +00006090 isSignBit = isSignBitCheck(I.getPredicate(), CI, UnusedBit);
6091 }
6092
6093 // See if we can fold the comparison based on range information we can get
6094 // by checking whether bits are known to be zero or one in the input.
6095 if (BitWidth != 0) {
6096 APInt Op0KnownZero(BitWidth, 0), Op0KnownOne(BitWidth, 0);
6097 APInt Op1KnownZero(BitWidth, 0), Op1KnownOne(BitWidth, 0);
6098
6099 if (SimplifyDemandedBits(I.getOperandUse(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006100 isSignBit ? APInt::getSignBit(BitWidth)
6101 : APInt::getAllOnesValue(BitWidth),
Dan Gohman7934d592009-04-25 17:12:48 +00006102 Op0KnownZero, Op0KnownOne, 0))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006103 return &I;
Dan Gohman7934d592009-04-25 17:12:48 +00006104 if (SimplifyDemandedBits(I.getOperandUse(1),
6105 APInt::getAllOnesValue(BitWidth),
6106 Op1KnownZero, Op1KnownOne, 0))
6107 return &I;
6108
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006109 // Given the known and unknown bits, compute a range that the LHS could be
Chris Lattner62d0f232008-07-11 05:08:55 +00006110 // in. Compute the Min, Max and RHS values based on the known bits. For the
6111 // EQ and NE we use unsigned values.
Dan Gohman7934d592009-04-25 17:12:48 +00006112 APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
6113 APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
6114 if (ICmpInst::isSignedPredicate(I.getPredicate())) {
6115 ComputeSignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6116 Op0Min, Op0Max);
6117 ComputeSignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6118 Op1Min, Op1Max);
6119 } else {
6120 ComputeUnsignedMinMaxValuesFromKnownBits(Op0KnownZero, Op0KnownOne,
6121 Op0Min, Op0Max);
6122 ComputeUnsignedMinMaxValuesFromKnownBits(Op1KnownZero, Op1KnownOne,
6123 Op1Min, Op1Max);
6124 }
6125
Chris Lattnera1308652008-07-11 05:40:05 +00006126 // If Min and Max are known to be the same, then SimplifyDemandedBits
6127 // figured out that the LHS is a constant. Just constant fold this now so
6128 // that code below can assume that Min != Max.
Dan Gohman7934d592009-04-25 17:12:48 +00006129 if (!isa<Constant>(Op0) && Op0Min == Op0Max)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006130 return new ICmpInst(*Context, I.getPredicate(),
Owen Anderson24be4c12009-07-03 00:17:18 +00006131 Context->getConstantInt(Op0Min), Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006132 if (!isa<Constant>(Op1) && Op1Min == Op1Max)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006133 return new ICmpInst(*Context, I.getPredicate(), Op0,
Owen Anderson24be4c12009-07-03 00:17:18 +00006134 Context->getConstantInt(Op1Min));
Dan Gohman7934d592009-04-25 17:12:48 +00006135
Chris Lattnera1308652008-07-11 05:40:05 +00006136 // Based on the range information we know about the LHS, see if we can
6137 // simplify this comparison. For example, (x&4) < 8 is always true.
Dan Gohman7934d592009-04-25 17:12:48 +00006138 switch (I.getPredicate()) {
Chris Lattner62d0f232008-07-11 05:08:55 +00006139 default: assert(0 && "Unknown icmp opcode!");
6140 case ICmpInst::ICMP_EQ:
Dan Gohman7934d592009-04-25 17:12:48 +00006141 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson24be4c12009-07-03 00:17:18 +00006142 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner62d0f232008-07-11 05:08:55 +00006143 break;
6144 case ICmpInst::ICMP_NE:
Dan Gohman7934d592009-04-25 17:12:48 +00006145 if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
Owen Anderson24be4c12009-07-03 00:17:18 +00006146 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Chris Lattner62d0f232008-07-11 05:08:55 +00006147 break;
6148 case ICmpInst::ICMP_ULT:
Dan Gohman7934d592009-04-25 17:12:48 +00006149 if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
Owen Anderson24be4c12009-07-03 00:17:18 +00006150 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman7934d592009-04-25 17:12:48 +00006151 if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
Owen Anderson24be4c12009-07-03 00:17:18 +00006152 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman7934d592009-04-25 17:12:48 +00006153 if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006154 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006155 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6156 if (Op1Max == Op0Min+1) // A <u C -> A == C-1 if min(A)+1 == C
Owen Anderson6601fcd2009-07-09 23:48:35 +00006157 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6158 SubOne(CI, Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006159
6160 // (x <u 2147483648) -> (x >s -1) -> true if sign bit clear
6161 if (CI->isMinValue(true))
Owen Anderson6601fcd2009-07-09 23:48:35 +00006162 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, Op0,
Owen Anderson24be4c12009-07-03 00:17:18 +00006163 Context->getConstantIntAllOnesValue(Op0->getType()));
Dan Gohman7934d592009-04-25 17:12:48 +00006164 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006165 break;
6166 case ICmpInst::ICMP_UGT:
Dan Gohman7934d592009-04-25 17:12:48 +00006167 if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
Owen Anderson24be4c12009-07-03 00:17:18 +00006168 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman7934d592009-04-25 17:12:48 +00006169 if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
Owen Anderson24be4c12009-07-03 00:17:18 +00006170 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman7934d592009-04-25 17:12:48 +00006171
6172 if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006173 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006174 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6175 if (Op1Min == Op0Max-1) // A >u C -> A == C+1 if max(a)-1 == C
Owen Anderson6601fcd2009-07-09 23:48:35 +00006176 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6177 AddOne(CI, Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006178
6179 // (x >u 2147483647) -> (x <s 0) -> true if sign bit set
6180 if (CI->isMaxValue(true))
Owen Anderson6601fcd2009-07-09 23:48:35 +00006181 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, Op0,
Owen Anderson24be4c12009-07-03 00:17:18 +00006182 Context->getNullValue(Op0->getType()));
Dan Gohman7934d592009-04-25 17:12:48 +00006183 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006184 break;
6185 case ICmpInst::ICMP_SLT:
Dan Gohman7934d592009-04-25 17:12:48 +00006186 if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
Owen Anderson24be4c12009-07-03 00:17:18 +00006187 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman7934d592009-04-25 17:12:48 +00006188 if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
Owen Anderson24be4c12009-07-03 00:17:18 +00006189 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman7934d592009-04-25 17:12:48 +00006190 if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006191 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006192 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6193 if (Op1Max == Op0Min+1) // A <s C -> A == C-1 if min(A)+1 == C
Owen Anderson6601fcd2009-07-09 23:48:35 +00006194 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6195 SubOne(CI, Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006196 }
Chris Lattner62d0f232008-07-11 05:08:55 +00006197 break;
Dan Gohman7934d592009-04-25 17:12:48 +00006198 case ICmpInst::ICMP_SGT:
6199 if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
Owen Anderson24be4c12009-07-03 00:17:18 +00006200 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman7934d592009-04-25 17:12:48 +00006201 if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
Owen Anderson24be4c12009-07-03 00:17:18 +00006202 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman7934d592009-04-25 17:12:48 +00006203
6204 if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006205 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Op0, Op1);
Dan Gohman7934d592009-04-25 17:12:48 +00006206 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
6207 if (Op1Min == Op0Max-1) // A >s C -> A == C+1 if max(A)-1 == C
Owen Anderson6601fcd2009-07-09 23:48:35 +00006208 return new ICmpInst(*Context, ICmpInst::ICMP_EQ, Op0,
6209 AddOne(CI, Context));
Dan Gohman7934d592009-04-25 17:12:48 +00006210 }
6211 break;
6212 case ICmpInst::ICMP_SGE:
6213 assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
6214 if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
Owen Anderson24be4c12009-07-03 00:17:18 +00006215 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman7934d592009-04-25 17:12:48 +00006216 if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
Owen Anderson24be4c12009-07-03 00:17:18 +00006217 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman7934d592009-04-25 17:12:48 +00006218 break;
6219 case ICmpInst::ICMP_SLE:
6220 assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
6221 if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
Owen Anderson24be4c12009-07-03 00:17:18 +00006222 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman7934d592009-04-25 17:12:48 +00006223 if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
Owen Anderson24be4c12009-07-03 00:17:18 +00006224 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman7934d592009-04-25 17:12:48 +00006225 break;
6226 case ICmpInst::ICMP_UGE:
6227 assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
6228 if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
Owen Anderson24be4c12009-07-03 00:17:18 +00006229 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman7934d592009-04-25 17:12:48 +00006230 if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
Owen Anderson24be4c12009-07-03 00:17:18 +00006231 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Dan Gohman7934d592009-04-25 17:12:48 +00006232 break;
6233 case ICmpInst::ICMP_ULE:
6234 assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
6235 if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
Owen Anderson24be4c12009-07-03 00:17:18 +00006236 return ReplaceInstUsesWith(I, Context->getConstantIntTrue());
Dan Gohman7934d592009-04-25 17:12:48 +00006237 if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
Owen Anderson24be4c12009-07-03 00:17:18 +00006238 return ReplaceInstUsesWith(I, Context->getConstantIntFalse());
Chris Lattner62d0f232008-07-11 05:08:55 +00006239 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006240 }
Dan Gohman7934d592009-04-25 17:12:48 +00006241
6242 // Turn a signed comparison into an unsigned one if both operands
6243 // are known to have the same sign.
6244 if (I.isSignedPredicate() &&
6245 ((Op0KnownZero.isNegative() && Op1KnownZero.isNegative()) ||
6246 (Op0KnownOne.isNegative() && Op1KnownOne.isNegative())))
Owen Anderson6601fcd2009-07-09 23:48:35 +00006247 return new ICmpInst(*Context, I.getUnsignedPredicate(), Op0, Op1);
Dan Gohman58c09632008-09-16 18:46:06 +00006248 }
6249
6250 // Test if the ICmpInst instruction is used exclusively by a select as
6251 // part of a minimum or maximum operation. If so, refrain from doing
6252 // any other folding. This helps out other analyses which understand
6253 // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
6254 // and CodeGen. And in this case, at least one of the comparison
6255 // operands has at least one user besides the compare (the select),
6256 // which would often largely negate the benefit of folding anyway.
6257 if (I.hasOneUse())
6258 if (SelectInst *SI = dyn_cast<SelectInst>(*I.use_begin()))
6259 if ((SI->getOperand(1) == Op0 && SI->getOperand(2) == Op1) ||
6260 (SI->getOperand(2) == Op0 && SI->getOperand(1) == Op1))
6261 return 0;
6262
6263 // See if we are doing a comparison between a constant and an instruction that
6264 // can be folded into the comparison.
6265 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op1)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006266 // Since the RHS is a ConstantInt (CI), if the left hand side is an
6267 // instruction, see if that instruction also has constants so that the
6268 // instruction can be folded into the icmp
6269 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6270 if (Instruction *Res = visitICmpInstWithInstAndIntCst(I, LHSI, CI))
6271 return Res;
6272 }
6273
6274 // Handle icmp with constant (but not simple integer constant) RHS
6275 if (Constant *RHSC = dyn_cast<Constant>(Op1)) {
6276 if (Instruction *LHSI = dyn_cast<Instruction>(Op0))
6277 switch (LHSI->getOpcode()) {
6278 case Instruction::GetElementPtr:
6279 if (RHSC->isNullValue()) {
6280 // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
6281 bool isAllZeros = true;
6282 for (unsigned i = 1, e = LHSI->getNumOperands(); i != e; ++i)
6283 if (!isa<Constant>(LHSI->getOperand(i)) ||
6284 !cast<Constant>(LHSI->getOperand(i))->isNullValue()) {
6285 isAllZeros = false;
6286 break;
6287 }
6288 if (isAllZeros)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006289 return new ICmpInst(*Context, I.getPredicate(), LHSI->getOperand(0),
Owen Anderson24be4c12009-07-03 00:17:18 +00006290 Context->getNullValue(LHSI->getOperand(0)->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006291 }
6292 break;
6293
6294 case Instruction::PHI:
Chris Lattnera2417ba2008-06-08 20:52:11 +00006295 // Only fold icmp into the PHI if the phi and fcmp are in the same
6296 // block. If in the same block, we're encouraging jump threading. If
6297 // not, we are just pessimizing the code by making an i1 phi.
6298 if (LHSI->getParent() == I.getParent())
6299 if (Instruction *NV = FoldOpIntoPhi(I))
6300 return NV;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006301 break;
6302 case Instruction::Select: {
6303 // If either operand of the select is a constant, we can fold the
6304 // comparison into the select arms, which will cause one to be
6305 // constant folded and the select turned into a bitwise or.
6306 Value *Op1 = 0, *Op2 = 0;
6307 if (LHSI->hasOneUse()) {
6308 if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(1))) {
6309 // Fold the known value into the constant operand.
Owen Anderson24be4c12009-07-03 00:17:18 +00006310 Op1 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006311 // Insert a new ICmp of the other select operand.
Owen Anderson6601fcd2009-07-09 23:48:35 +00006312 Op2 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006313 LHSI->getOperand(2), RHSC,
6314 I.getName()), I);
6315 } else if (Constant *C = dyn_cast<Constant>(LHSI->getOperand(2))) {
6316 // Fold the known value into the constant operand.
Owen Anderson24be4c12009-07-03 00:17:18 +00006317 Op2 = Context->getConstantExprICmp(I.getPredicate(), C, RHSC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006318 // Insert a new ICmp of the other select operand.
Owen Anderson6601fcd2009-07-09 23:48:35 +00006319 Op1 = InsertNewInstBefore(new ICmpInst(*Context, I.getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006320 LHSI->getOperand(1), RHSC,
6321 I.getName()), I);
6322 }
6323 }
6324
6325 if (Op1)
Gabor Greifd6da1d02008-04-06 20:25:17 +00006326 return SelectInst::Create(LHSI->getOperand(0), Op1, Op2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006327 break;
6328 }
6329 case Instruction::Malloc:
6330 // If we have (malloc != null), and if the malloc has a single use, we
6331 // can assume it is successful and remove the malloc.
6332 if (LHSI->hasOneUse() && isa<ConstantPointerNull>(RHSC)) {
6333 AddToWorkList(LHSI);
Owen Anderson24be4c12009-07-03 00:17:18 +00006334 return ReplaceInstUsesWith(I, Context->getConstantInt(Type::Int1Ty,
Nick Lewycky09284cf2008-05-17 07:33:39 +00006335 !I.isTrueWhenEqual()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006336 }
6337 break;
6338 }
6339 }
6340
6341 // If we can optimize a 'icmp GEP, P' or 'icmp P, GEP', do so now.
6342 if (User *GEP = dyn_castGetElementPtr(Op0))
6343 if (Instruction *NI = FoldGEPICmp(GEP, Op1, I.getPredicate(), I))
6344 return NI;
6345 if (User *GEP = dyn_castGetElementPtr(Op1))
6346 if (Instruction *NI = FoldGEPICmp(GEP, Op0,
6347 ICmpInst::getSwappedPredicate(I.getPredicate()), I))
6348 return NI;
6349
6350 // Test to see if the operands of the icmp are casted versions of other
6351 // values. If the ptr->ptr cast can be stripped off both arguments, we do so
6352 // now.
6353 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op0)) {
6354 if (isa<PointerType>(Op0->getType()) &&
6355 (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
6356 // We keep moving the cast from the left operand over to the right
6357 // operand, where it can often be eliminated completely.
6358 Op0 = CI->getOperand(0);
6359
6360 // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
6361 // so eliminate it as well.
6362 if (BitCastInst *CI2 = dyn_cast<BitCastInst>(Op1))
6363 Op1 = CI2->getOperand(0);
6364
6365 // If Op1 is a constant, we can fold the cast into the constant.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006366 if (Op0->getType() != Op1->getType()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006367 if (Constant *Op1C = dyn_cast<Constant>(Op1)) {
Owen Anderson24be4c12009-07-03 00:17:18 +00006368 Op1 = Context->getConstantExprBitCast(Op1C, Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006369 } else {
6370 // Otherwise, cast the RHS right before the icmp
Chris Lattner13c2d6e2008-01-13 22:23:22 +00006371 Op1 = InsertBitCastBefore(Op1, Op0->getType(), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006372 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006373 }
Owen Anderson6601fcd2009-07-09 23:48:35 +00006374 return new ICmpInst(*Context, I.getPredicate(), Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006375 }
6376 }
6377
6378 if (isa<CastInst>(Op0)) {
6379 // Handle the special case of: icmp (cast bool to X), <cst>
6380 // This comes up when you have code like
6381 // int X = A < B;
6382 // if (X) ...
6383 // For generality, we handle any zero-extension of any operand comparison
6384 // with a constant or another cast from the same type.
6385 if (isa<ConstantInt>(Op1) || isa<CastInst>(Op1))
6386 if (Instruction *R = visitICmpInstWithCastAndCast(I))
6387 return R;
6388 }
6389
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006390 // See if it's the same type of instruction on the left and right.
6391 if (BinaryOperator *Op0I = dyn_cast<BinaryOperator>(Op0)) {
6392 if (BinaryOperator *Op1I = dyn_cast<BinaryOperator>(Op1)) {
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006393 if (Op0I->getOpcode() == Op1I->getOpcode() && Op0I->hasOneUse() &&
Nick Lewyckydac84332009-01-31 21:30:05 +00006394 Op1I->hasOneUse() && Op0I->getOperand(1) == Op1I->getOperand(1)) {
Nick Lewyckycfadfbd2008-09-03 06:24:21 +00006395 switch (Op0I->getOpcode()) {
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006396 default: break;
6397 case Instruction::Add:
6398 case Instruction::Sub:
6399 case Instruction::Xor:
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006400 if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
Owen Anderson6601fcd2009-07-09 23:48:35 +00006401 return new ICmpInst(*Context, I.getPredicate(), Op0I->getOperand(0),
Nick Lewyckydac84332009-01-31 21:30:05 +00006402 Op1I->getOperand(0));
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006403 // icmp u/s (a ^ signbit), (b ^ signbit) --> icmp s/u a, b
6404 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6405 if (CI->getValue().isSignBit()) {
6406 ICmpInst::Predicate Pred = I.isSignedPredicate()
6407 ? I.getUnsignedPredicate()
6408 : I.getSignedPredicate();
Owen Anderson6601fcd2009-07-09 23:48:35 +00006409 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006410 Op1I->getOperand(0));
6411 }
6412
6413 if (CI->getValue().isMaxSignedValue()) {
6414 ICmpInst::Predicate Pred = I.isSignedPredicate()
6415 ? I.getUnsignedPredicate()
6416 : I.getSignedPredicate();
6417 Pred = I.getSwappedPredicate(Pred);
Owen Anderson6601fcd2009-07-09 23:48:35 +00006418 return new ICmpInst(*Context, Pred, Op0I->getOperand(0),
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006419 Op1I->getOperand(0));
Nick Lewyckydac84332009-01-31 21:30:05 +00006420 }
6421 }
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006422 break;
6423 case Instruction::Mul:
Nick Lewyckydac84332009-01-31 21:30:05 +00006424 if (!I.isEquality())
6425 break;
6426
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006427 if (ConstantInt *CI = dyn_cast<ConstantInt>(Op0I->getOperand(1))) {
6428 // a * Cst icmp eq/ne b * Cst --> a & Mask icmp b & Mask
6429 // Mask = -1 >> count-trailing-zeros(Cst).
6430 if (!CI->isZero() && !CI->isOne()) {
6431 const APInt &AP = CI->getValue();
Owen Anderson24be4c12009-07-03 00:17:18 +00006432 ConstantInt *Mask = Context->getConstantInt(
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006433 APInt::getLowBitsSet(AP.getBitWidth(),
6434 AP.getBitWidth() -
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006435 AP.countTrailingZeros()));
Nick Lewycky58ecfb22008-08-21 05:56:10 +00006436 Instruction *And1 = BinaryOperator::CreateAnd(Op0I->getOperand(0),
6437 Mask);
6438 Instruction *And2 = BinaryOperator::CreateAnd(Op1I->getOperand(0),
6439 Mask);
6440 InsertNewInstBefore(And1, I);
6441 InsertNewInstBefore(And2, I);
Owen Anderson6601fcd2009-07-09 23:48:35 +00006442 return new ICmpInst(*Context, I.getPredicate(), And1, And2);
Nick Lewyckyd4c5ea02008-07-11 07:20:53 +00006443 }
6444 }
6445 break;
6446 }
6447 }
6448 }
6449 }
6450
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006451 // ~x < ~y --> y < x
6452 { Value *A, *B;
Owen Andersona21eb582009-07-10 17:35:01 +00006453 if (match(Op0, m_Not(m_Value(A)), *Context) &&
6454 match(Op1, m_Not(m_Value(B)), *Context))
Owen Anderson6601fcd2009-07-09 23:48:35 +00006455 return new ICmpInst(*Context, I.getPredicate(), B, A);
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006456 }
6457
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006458 if (I.isEquality()) {
6459 Value *A, *B, *C, *D;
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006460
6461 // -x == -y --> x == y
Owen Andersona21eb582009-07-10 17:35:01 +00006462 if (match(Op0, m_Neg(m_Value(A)), *Context) &&
6463 match(Op1, m_Neg(m_Value(B)), *Context))
Owen Anderson6601fcd2009-07-09 23:48:35 +00006464 return new ICmpInst(*Context, I.getPredicate(), A, B);
Chris Lattnera4e1eef2008-05-09 05:19:28 +00006465
Owen Andersona21eb582009-07-10 17:35:01 +00006466 if (match(Op0, m_Xor(m_Value(A), m_Value(B)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006467 if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
6468 Value *OtherVal = A == Op1 ? B : A;
Owen Anderson6601fcd2009-07-09 23:48:35 +00006469 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Anderson24be4c12009-07-03 00:17:18 +00006470 Context->getNullValue(A->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006471 }
6472
Owen Andersona21eb582009-07-10 17:35:01 +00006473 if (match(Op1, m_Xor(m_Value(C), m_Value(D)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006474 // A^c1 == C^c2 --> A == C^(c1^c2)
Chris Lattner3b874082008-11-16 05:38:51 +00006475 ConstantInt *C1, *C2;
Owen Andersona21eb582009-07-10 17:35:01 +00006476 if (match(B, m_ConstantInt(C1), *Context) &&
6477 match(D, m_ConstantInt(C2), *Context) && Op1->hasOneUse()) {
Owen Anderson24be4c12009-07-03 00:17:18 +00006478 Constant *NC =
6479 Context->getConstantInt(C1->getValue() ^ C2->getValue());
Chris Lattner3b874082008-11-16 05:38:51 +00006480 Instruction *Xor = BinaryOperator::CreateXor(C, NC, "tmp");
Owen Anderson6601fcd2009-07-09 23:48:35 +00006481 return new ICmpInst(*Context, I.getPredicate(), A,
Chris Lattner3b874082008-11-16 05:38:51 +00006482 InsertNewInstBefore(Xor, I));
6483 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006484
6485 // A^B == A^D -> B == D
Owen Anderson6601fcd2009-07-09 23:48:35 +00006486 if (A == C) return new ICmpInst(*Context, I.getPredicate(), B, D);
6487 if (A == D) return new ICmpInst(*Context, I.getPredicate(), B, C);
6488 if (B == C) return new ICmpInst(*Context, I.getPredicate(), A, D);
6489 if (B == D) return new ICmpInst(*Context, I.getPredicate(), A, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006490 }
6491 }
6492
Owen Andersona21eb582009-07-10 17:35:01 +00006493 if (match(Op1, m_Xor(m_Value(A), m_Value(B)), *Context) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006494 (A == Op0 || B == Op0)) {
6495 // A == (A^B) -> B == 0
6496 Value *OtherVal = A == Op0 ? B : A;
Owen Anderson6601fcd2009-07-09 23:48:35 +00006497 return new ICmpInst(*Context, I.getPredicate(), OtherVal,
Owen Anderson24be4c12009-07-03 00:17:18 +00006498 Context->getNullValue(A->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006499 }
Chris Lattner3b874082008-11-16 05:38:51 +00006500
6501 // (A-B) == A -> B == 0
Owen Andersona21eb582009-07-10 17:35:01 +00006502 if (match(Op0, m_Sub(m_Specific(Op1), m_Value(B)), *Context))
Owen Anderson6601fcd2009-07-09 23:48:35 +00006503 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Anderson24be4c12009-07-03 00:17:18 +00006504 Context->getNullValue(B->getType()));
Chris Lattner3b874082008-11-16 05:38:51 +00006505
6506 // A == (A-B) -> B == 0
Owen Andersona21eb582009-07-10 17:35:01 +00006507 if (match(Op1, m_Sub(m_Specific(Op0), m_Value(B)), *Context))
Owen Anderson6601fcd2009-07-09 23:48:35 +00006508 return new ICmpInst(*Context, I.getPredicate(), B,
Owen Anderson24be4c12009-07-03 00:17:18 +00006509 Context->getNullValue(B->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006510
6511 // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
6512 if (Op0->hasOneUse() && Op1->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00006513 match(Op0, m_And(m_Value(A), m_Value(B)), *Context) &&
6514 match(Op1, m_And(m_Value(C), m_Value(D)), *Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006515 Value *X = 0, *Y = 0, *Z = 0;
6516
6517 if (A == C) {
6518 X = B; Y = D; Z = A;
6519 } else if (A == D) {
6520 X = B; Y = C; Z = A;
6521 } else if (B == C) {
6522 X = A; Y = D; Z = B;
6523 } else if (B == D) {
6524 X = A; Y = C; Z = B;
6525 }
6526
6527 if (X) { // Build (X^Y) & Z
Gabor Greifa645dd32008-05-16 19:29:10 +00006528 Op1 = InsertNewInstBefore(BinaryOperator::CreateXor(X, Y, "tmp"), I);
6529 Op1 = InsertNewInstBefore(BinaryOperator::CreateAnd(Op1, Z, "tmp"), I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006530 I.setOperand(0, Op1);
Owen Anderson24be4c12009-07-03 00:17:18 +00006531 I.setOperand(1, Context->getNullValue(Op1->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006532 return &I;
6533 }
6534 }
6535 }
6536 return Changed ? &I : 0;
6537}
6538
6539
6540/// FoldICmpDivCst - Fold "icmp pred, ([su]div X, DivRHS), CmpRHS" where DivRHS
6541/// and CmpRHS are both known to be integer constants.
6542Instruction *InstCombiner::FoldICmpDivCst(ICmpInst &ICI, BinaryOperator *DivI,
6543 ConstantInt *DivRHS) {
6544 ConstantInt *CmpRHS = cast<ConstantInt>(ICI.getOperand(1));
6545 const APInt &CmpRHSV = CmpRHS->getValue();
6546
6547 // FIXME: If the operand types don't match the type of the divide
6548 // then don't attempt this transform. The code below doesn't have the
6549 // logic to deal with a signed divide and an unsigned compare (and
6550 // vice versa). This is because (x /s C1) <s C2 produces different
6551 // results than (x /s C1) <u C2 or (x /u C1) <s C2 or even
6552 // (x /u C1) <u C2. Simply casting the operands and result won't
6553 // work. :( The if statement below tests that condition and bails
6554 // if it finds it.
6555 bool DivIsSigned = DivI->getOpcode() == Instruction::SDiv;
6556 if (!ICI.isEquality() && DivIsSigned != ICI.isSignedPredicate())
6557 return 0;
6558 if (DivRHS->isZero())
6559 return 0; // The ProdOV computation fails on divide by zero.
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006560 if (DivIsSigned && DivRHS->isAllOnesValue())
6561 return 0; // The overflow computation also screws up here
6562 if (DivRHS->isOne())
6563 return 0; // Not worth bothering, and eliminates some funny cases
6564 // with INT_MIN.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006565
6566 // Compute Prod = CI * DivRHS. We are essentially solving an equation
6567 // of form X/C1=C2. We solve for X by multiplying C1 (DivRHS) and
6568 // C2 (CI). By solving for X we can turn this into a range check
6569 // instead of computing a divide.
Owen Anderson24be4c12009-07-03 00:17:18 +00006570 Constant *Prod = Context->getConstantExprMul(CmpRHS, DivRHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006571
6572 // Determine if the product overflows by seeing if the product is
6573 // not equal to the divide. Make sure we do the same kind of divide
6574 // as in the LHS instruction that we're folding.
Owen Anderson24be4c12009-07-03 00:17:18 +00006575 bool ProdOV = (DivIsSigned ? Context->getConstantExprSDiv(Prod, DivRHS) :
6576 Context->getConstantExprUDiv(Prod, DivRHS)) != CmpRHS;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006577
6578 // Get the ICmp opcode
6579 ICmpInst::Predicate Pred = ICI.getPredicate();
6580
6581 // Figure out the interval that is being checked. For example, a comparison
6582 // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
6583 // Compute this interval based on the constants involved and the signedness of
6584 // the compare/divide. This computes a half-open interval, keeping track of
6585 // whether either value in the interval overflows. After analysis each
6586 // overflow variable is set to 0 if it's corresponding bound variable is valid
6587 // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
6588 int LoOverflow = 0, HiOverflow = 0;
Dan Gohman8fd520a2009-06-15 22:12:54 +00006589 Constant *LoBound = 0, *HiBound = 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006590
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006591 if (!DivIsSigned) { // udiv
6592 // e.g. X/5 op 3 --> [15, 20)
6593 LoBound = Prod;
6594 HiOverflow = LoOverflow = ProdOV;
6595 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006596 HiOverflow = AddWithOverflow(HiBound, LoBound, DivRHS, Context, false);
Dan Gohman5dceed12008-02-13 22:09:18 +00006597 } else if (DivRHS->getValue().isStrictlyPositive()) { // Divisor is > 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006598 if (CmpRHSV == 0) { // (X / pos) op 0
6599 // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
Owen Anderson24be4c12009-07-03 00:17:18 +00006600 LoBound = cast<ConstantInt>(Context->getConstantExprNeg(SubOne(DivRHS,
6601 Context)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006602 HiBound = DivRHS;
Dan Gohman5dceed12008-02-13 22:09:18 +00006603 } else if (CmpRHSV.isStrictlyPositive()) { // (X / pos) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006604 LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
6605 HiOverflow = LoOverflow = ProdOV;
6606 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006607 HiOverflow = AddWithOverflow(HiBound, Prod, DivRHS, Context, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006608 } else { // (X / pos) op neg
6609 // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
Owen Anderson24be4c12009-07-03 00:17:18 +00006610 HiBound = AddOne(Prod, Context);
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006611 LoOverflow = HiOverflow = ProdOV ? -1 : 0;
6612 if (!LoOverflow) {
Owen Anderson24be4c12009-07-03 00:17:18 +00006613 ConstantInt* DivNeg =
6614 cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
6615 LoOverflow = AddWithOverflow(LoBound, HiBound, DivNeg, Context,
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006616 true) ? -1 : 0;
6617 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006618 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006619 } else if (DivRHS->getValue().isNegative()) { // Divisor is < 0.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006620 if (CmpRHSV == 0) { // (X / neg) op 0
6621 // e.g. X/-5 op 0 --> [-4, 5)
Owen Anderson24be4c12009-07-03 00:17:18 +00006622 LoBound = AddOne(DivRHS, Context);
6623 HiBound = cast<ConstantInt>(Context->getConstantExprNeg(DivRHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006624 if (HiBound == DivRHS) { // -INTMIN = INTMIN
6625 HiOverflow = 1; // [INTMIN+1, overflow)
6626 HiBound = 0; // e.g. X/INTMIN = 0 --> X > INTMIN
6627 }
Dan Gohman5dceed12008-02-13 22:09:18 +00006628 } else if (CmpRHSV.isStrictlyPositive()) { // (X / neg) op pos
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006629 // e.g. X/-5 op 3 --> [-19, -14)
Owen Anderson24be4c12009-07-03 00:17:18 +00006630 HiBound = AddOne(Prod, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006631 HiOverflow = LoOverflow = ProdOV ? -1 : 0;
6632 if (!LoOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006633 LoOverflow = AddWithOverflow(LoBound, HiBound,
6634 DivRHS, Context, true) ? -1 : 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006635 } else { // (X / neg) op neg
Chris Lattnerbd85a5f2008-10-11 22:55:00 +00006636 LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
6637 LoOverflow = HiOverflow = ProdOV;
Dan Gohman45408ea2008-09-11 00:25:00 +00006638 if (!HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006639 HiOverflow = SubWithOverflow(HiBound, Prod, DivRHS, Context, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006640 }
6641
6642 // Dividing by a negative swaps the condition. LT <-> GT
6643 Pred = ICmpInst::getSwappedPredicate(Pred);
6644 }
6645
6646 Value *X = DivI->getOperand(0);
6647 switch (Pred) {
6648 default: assert(0 && "Unhandled icmp opcode!");
6649 case ICmpInst::ICMP_EQ:
6650 if (LoOverflow && HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006651 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006652 else if (HiOverflow)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006653 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006654 ICmpInst::ICMP_UGE, X, LoBound);
6655 else if (LoOverflow)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006656 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006657 ICmpInst::ICMP_ULT, X, HiBound);
6658 else
6659 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, true, ICI);
6660 case ICmpInst::ICMP_NE:
6661 if (LoOverflow && HiOverflow)
Owen Anderson24be4c12009-07-03 00:17:18 +00006662 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006663 else if (HiOverflow)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006664 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SLT :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006665 ICmpInst::ICMP_ULT, X, LoBound);
6666 else if (LoOverflow)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006667 return new ICmpInst(*Context, DivIsSigned ? ICmpInst::ICMP_SGE :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006668 ICmpInst::ICMP_UGE, X, HiBound);
6669 else
6670 return InsertRangeTest(X, LoBound, HiBound, DivIsSigned, false, ICI);
6671 case ICmpInst::ICMP_ULT:
6672 case ICmpInst::ICMP_SLT:
6673 if (LoOverflow == +1) // Low bound is greater than input range.
Owen Anderson24be4c12009-07-03 00:17:18 +00006674 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006675 if (LoOverflow == -1) // Low bound is less than input range.
Owen Anderson24be4c12009-07-03 00:17:18 +00006676 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Owen Anderson6601fcd2009-07-09 23:48:35 +00006677 return new ICmpInst(*Context, Pred, X, LoBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006678 case ICmpInst::ICMP_UGT:
6679 case ICmpInst::ICMP_SGT:
6680 if (HiOverflow == +1) // High bound greater than input range.
Owen Anderson24be4c12009-07-03 00:17:18 +00006681 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006682 else if (HiOverflow == -1) // High bound less than input range.
Owen Anderson24be4c12009-07-03 00:17:18 +00006683 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006684 if (Pred == ICmpInst::ICMP_UGT)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006685 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, X, HiBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006686 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00006687 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, X, HiBound);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006688 }
6689}
6690
6691
6692/// visitICmpInstWithInstAndIntCst - Handle "icmp (instr, intcst)".
6693///
6694Instruction *InstCombiner::visitICmpInstWithInstAndIntCst(ICmpInst &ICI,
6695 Instruction *LHSI,
6696 ConstantInt *RHS) {
6697 const APInt &RHSV = RHS->getValue();
6698
6699 switch (LHSI->getOpcode()) {
Chris Lattner56be1232009-01-09 07:47:06 +00006700 case Instruction::Trunc:
6701 if (ICI.isEquality() && LHSI->hasOneUse()) {
6702 // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
6703 // of the high bits truncated out of x are known.
6704 unsigned DstBits = LHSI->getType()->getPrimitiveSizeInBits(),
6705 SrcBits = LHSI->getOperand(0)->getType()->getPrimitiveSizeInBits();
6706 APInt Mask(APInt::getHighBitsSet(SrcBits, SrcBits-DstBits));
6707 APInt KnownZero(SrcBits, 0), KnownOne(SrcBits, 0);
6708 ComputeMaskedBits(LHSI->getOperand(0), Mask, KnownZero, KnownOne);
6709
6710 // If all the high bits are known, we can do this xform.
6711 if ((KnownZero|KnownOne).countLeadingOnes() >= SrcBits-DstBits) {
6712 // Pull in the high bits from known-ones set.
6713 APInt NewRHS(RHS->getValue());
6714 NewRHS.zext(SrcBits);
6715 NewRHS |= KnownOne;
Owen Anderson6601fcd2009-07-09 23:48:35 +00006716 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Anderson24be4c12009-07-03 00:17:18 +00006717 Context->getConstantInt(NewRHS));
Chris Lattner56be1232009-01-09 07:47:06 +00006718 }
6719 }
6720 break;
6721
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006722 case Instruction::Xor: // (icmp pred (xor X, XorCST), CI)
6723 if (ConstantInt *XorCST = dyn_cast<ConstantInt>(LHSI->getOperand(1))) {
6724 // If this is a comparison that tests the signbit (X < 0) or (x > -1),
6725 // fold the xor.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +00006726 if ((ICI.getPredicate() == ICmpInst::ICMP_SLT && RHSV == 0) ||
6727 (ICI.getPredicate() == ICmpInst::ICMP_SGT && RHSV.isAllOnesValue())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006728 Value *CompareVal = LHSI->getOperand(0);
6729
6730 // If the sign bit of the XorCST is not set, there is no change to
6731 // the operation, just stop using the Xor.
6732 if (!XorCST->getValue().isNegative()) {
6733 ICI.setOperand(0, CompareVal);
6734 AddToWorkList(LHSI);
6735 return &ICI;
6736 }
6737
6738 // Was the old condition true if the operand is positive?
6739 bool isTrueIfPositive = ICI.getPredicate() == ICmpInst::ICMP_SGT;
6740
6741 // If so, the new one isn't.
6742 isTrueIfPositive ^= true;
6743
6744 if (isTrueIfPositive)
Owen Anderson6601fcd2009-07-09 23:48:35 +00006745 return new ICmpInst(*Context, ICmpInst::ICMP_SGT, CompareVal,
Owen Anderson24be4c12009-07-03 00:17:18 +00006746 SubOne(RHS, Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006747 else
Owen Anderson6601fcd2009-07-09 23:48:35 +00006748 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, CompareVal,
Owen Anderson24be4c12009-07-03 00:17:18 +00006749 AddOne(RHS, Context));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006750 }
Nick Lewyckydac84332009-01-31 21:30:05 +00006751
6752 if (LHSI->hasOneUse()) {
6753 // (icmp u/s (xor A SignBit), C) -> (icmp s/u A, (xor C SignBit))
6754 if (!ICI.isEquality() && XorCST->getValue().isSignBit()) {
6755 const APInt &SignBit = XorCST->getValue();
6756 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6757 ? ICI.getUnsignedPredicate()
6758 : ICI.getSignedPredicate();
Owen Anderson6601fcd2009-07-09 23:48:35 +00006759 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Anderson24be4c12009-07-03 00:17:18 +00006760 Context->getConstantInt(RHSV ^ SignBit));
Nick Lewyckydac84332009-01-31 21:30:05 +00006761 }
6762
6763 // (icmp u/s (xor A ~SignBit), C) -> (icmp s/u (xor C ~SignBit), A)
Chris Lattnerf3b445e2009-02-02 07:15:30 +00006764 if (!ICI.isEquality() && XorCST->getValue().isMaxSignedValue()) {
Nick Lewyckydac84332009-01-31 21:30:05 +00006765 const APInt &NotSignBit = XorCST->getValue();
6766 ICmpInst::Predicate Pred = ICI.isSignedPredicate()
6767 ? ICI.getUnsignedPredicate()
6768 : ICI.getSignedPredicate();
6769 Pred = ICI.getSwappedPredicate(Pred);
Owen Anderson6601fcd2009-07-09 23:48:35 +00006770 return new ICmpInst(*Context, Pred, LHSI->getOperand(0),
Owen Anderson24be4c12009-07-03 00:17:18 +00006771 Context->getConstantInt(RHSV ^ NotSignBit));
Nick Lewyckydac84332009-01-31 21:30:05 +00006772 }
6773 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006774 }
6775 break;
6776 case Instruction::And: // (icmp pred (and X, AndCST), RHS)
6777 if (LHSI->hasOneUse() && isa<ConstantInt>(LHSI->getOperand(1)) &&
6778 LHSI->getOperand(0)->hasOneUse()) {
6779 ConstantInt *AndCST = cast<ConstantInt>(LHSI->getOperand(1));
6780
6781 // If the LHS is an AND of a truncating cast, we can widen the
6782 // and/compare to be the input width without changing the value
6783 // produced, eliminating a cast.
6784 if (TruncInst *Cast = dyn_cast<TruncInst>(LHSI->getOperand(0))) {
6785 // We can do this transformation if either the AND constant does not
6786 // have its sign bit set or if it is an equality comparison.
6787 // Extending a relational comparison when we're checking the sign
6788 // bit would not work.
6789 if (Cast->hasOneUse() &&
Anton Korobeynikov6a4a9332008-02-20 12:07:57 +00006790 (ICI.isEquality() ||
6791 (AndCST->getValue().isNonNegative() && RHSV.isNonNegative()))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006792 uint32_t BitWidth =
6793 cast<IntegerType>(Cast->getOperand(0)->getType())->getBitWidth();
6794 APInt NewCST = AndCST->getValue();
6795 NewCST.zext(BitWidth);
6796 APInt NewCI = RHSV;
6797 NewCI.zext(BitWidth);
6798 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00006799 BinaryOperator::CreateAnd(Cast->getOperand(0),
Owen Anderson24be4c12009-07-03 00:17:18 +00006800 Context->getConstantInt(NewCST),LHSI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006801 InsertNewInstBefore(NewAnd, ICI);
Owen Anderson6601fcd2009-07-09 23:48:35 +00006802 return new ICmpInst(*Context, ICI.getPredicate(), NewAnd,
Owen Anderson24be4c12009-07-03 00:17:18 +00006803 Context->getConstantInt(NewCI));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006804 }
6805 }
6806
6807 // If this is: (X >> C1) & C2 != C3 (where any shift and any compare
6808 // could exist), turn it into (X & (C2 << C1)) != (C3 << C1). This
6809 // happens a LOT in code produced by the C front-end, for bitfield
6810 // access.
6811 BinaryOperator *Shift = dyn_cast<BinaryOperator>(LHSI->getOperand(0));
6812 if (Shift && !Shift->isShift())
6813 Shift = 0;
6814
6815 ConstantInt *ShAmt;
6816 ShAmt = Shift ? dyn_cast<ConstantInt>(Shift->getOperand(1)) : 0;
6817 const Type *Ty = Shift ? Shift->getType() : 0; // Type of the shift.
6818 const Type *AndTy = AndCST->getType(); // Type of the and.
6819
6820 // We can fold this as long as we can't shift unknown bits
6821 // into the mask. This can only happen with signed shift
6822 // rights, as they sign-extend.
6823 if (ShAmt) {
6824 bool CanFold = Shift->isLogicalShift();
6825 if (!CanFold) {
6826 // To test for the bad case of the signed shr, see if any
6827 // of the bits shifted in could be tested after the mask.
6828 uint32_t TyBits = Ty->getPrimitiveSizeInBits();
6829 int ShAmtVal = TyBits - ShAmt->getLimitedValue(TyBits);
6830
6831 uint32_t BitWidth = AndTy->getPrimitiveSizeInBits();
6832 if ((APInt::getHighBitsSet(BitWidth, BitWidth-ShAmtVal) &
6833 AndCST->getValue()) == 0)
6834 CanFold = true;
6835 }
6836
6837 if (CanFold) {
6838 Constant *NewCst;
6839 if (Shift->getOpcode() == Instruction::Shl)
Owen Anderson24be4c12009-07-03 00:17:18 +00006840 NewCst = Context->getConstantExprLShr(RHS, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006841 else
Owen Anderson24be4c12009-07-03 00:17:18 +00006842 NewCst = Context->getConstantExprShl(RHS, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006843
6844 // Check to see if we are shifting out any of the bits being
6845 // compared.
Owen Anderson24be4c12009-07-03 00:17:18 +00006846 if (Context->getConstantExpr(Shift->getOpcode(),
6847 NewCst, ShAmt) != RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006848 // If we shifted bits out, the fold is not going to work out.
6849 // As a special case, check to see if this means that the
6850 // result is always true or false now.
6851 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson24be4c12009-07-03 00:17:18 +00006852 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006853 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson24be4c12009-07-03 00:17:18 +00006854 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006855 } else {
6856 ICI.setOperand(1, NewCst);
6857 Constant *NewAndCST;
6858 if (Shift->getOpcode() == Instruction::Shl)
Owen Anderson24be4c12009-07-03 00:17:18 +00006859 NewAndCST = Context->getConstantExprLShr(AndCST, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006860 else
Owen Anderson24be4c12009-07-03 00:17:18 +00006861 NewAndCST = Context->getConstantExprShl(AndCST, ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006862 LHSI->setOperand(1, NewAndCST);
6863 LHSI->setOperand(0, Shift->getOperand(0));
6864 AddToWorkList(Shift); // Shift is dead.
6865 AddUsesToWorkList(ICI);
6866 return &ICI;
6867 }
6868 }
6869 }
6870
6871 // Turn ((X >> Y) & C) == 0 into (X & (C << Y)) == 0. The later is
6872 // preferable because it allows the C<<Y expression to be hoisted out
6873 // of a loop if Y is invariant and X is not.
6874 if (Shift && Shift->hasOneUse() && RHSV == 0 &&
Chris Lattnerffd95262009-03-25 00:28:58 +00006875 ICI.isEquality() && !Shift->isArithmeticShift() &&
6876 !isa<Constant>(Shift->getOperand(0))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006877 // Compute C << Y.
6878 Value *NS;
6879 if (Shift->getOpcode() == Instruction::LShr) {
Gabor Greifa645dd32008-05-16 19:29:10 +00006880 NS = BinaryOperator::CreateShl(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006881 Shift->getOperand(1), "tmp");
6882 } else {
6883 // Insert a logical shift.
Gabor Greifa645dd32008-05-16 19:29:10 +00006884 NS = BinaryOperator::CreateLShr(AndCST,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006885 Shift->getOperand(1), "tmp");
6886 }
6887 InsertNewInstBefore(cast<Instruction>(NS), ICI);
6888
6889 // Compute X & (C << Y).
6890 Instruction *NewAnd =
Gabor Greifa645dd32008-05-16 19:29:10 +00006891 BinaryOperator::CreateAnd(Shift->getOperand(0), NS, LHSI->getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006892 InsertNewInstBefore(NewAnd, ICI);
6893
6894 ICI.setOperand(0, NewAnd);
6895 return &ICI;
6896 }
6897 }
6898 break;
6899
6900 case Instruction::Shl: { // (icmp pred (shl X, ShAmt), CI)
6901 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
6902 if (!ShAmt) break;
6903
6904 uint32_t TypeBits = RHSV.getBitWidth();
6905
6906 // Check that the shift amount is in range. If not, don't perform
6907 // undefined shifts. When the shift is visited it will be
6908 // simplified.
6909 if (ShAmt->uge(TypeBits))
6910 break;
6911
6912 if (ICI.isEquality()) {
6913 // If we are comparing against bits always shifted out, the
6914 // comparison cannot succeed.
6915 Constant *Comp =
Owen Anderson24be4c12009-07-03 00:17:18 +00006916 Context->getConstantExprShl(Context->getConstantExprLShr(RHS, ShAmt),
6917 ShAmt);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006918 if (Comp != RHS) {// Comparing against a bit that we know is zero.
6919 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson24be4c12009-07-03 00:17:18 +00006920 Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006921 return ReplaceInstUsesWith(ICI, Cst);
6922 }
6923
6924 if (LHSI->hasOneUse()) {
6925 // Otherwise strength reduce the shift into an and.
6926 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
6927 Constant *Mask =
Owen Anderson24be4c12009-07-03 00:17:18 +00006928 Context->getConstantInt(APInt::getLowBitsSet(TypeBits,
6929 TypeBits-ShAmtVal));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006930
6931 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006932 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006933 Mask, LHSI->getName()+".mask");
6934 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson6601fcd2009-07-09 23:48:35 +00006935 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Anderson24be4c12009-07-03 00:17:18 +00006936 Context->getConstantInt(RHSV.lshr(ShAmtVal)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006937 }
6938 }
6939
6940 // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
6941 bool TrueIfSigned = false;
6942 if (LHSI->hasOneUse() &&
6943 isSignBitCheck(ICI.getPredicate(), RHS, TrueIfSigned)) {
6944 // (X << 31) <s 0 --> (X&1) != 0
Owen Anderson24be4c12009-07-03 00:17:18 +00006945 Constant *Mask = Context->getConstantInt(APInt(TypeBits, 1) <<
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006946 (TypeBits-ShAmt->getZExtValue()-1));
6947 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00006948 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006949 Mask, LHSI->getName()+".mask");
6950 Value *And = InsertNewInstBefore(AndI, ICI);
6951
Owen Anderson6601fcd2009-07-09 23:48:35 +00006952 return new ICmpInst(*Context,
6953 TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
Owen Anderson24be4c12009-07-03 00:17:18 +00006954 And, Context->getNullValue(And->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006955 }
6956 break;
6957 }
6958
6959 case Instruction::LShr: // (icmp pred (shr X, ShAmt), CI)
6960 case Instruction::AShr: {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006961 // Only handle equality comparisons of shift-by-constant.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006962 ConstantInt *ShAmt = dyn_cast<ConstantInt>(LHSI->getOperand(1));
Chris Lattner5ee84f82008-03-21 05:19:58 +00006963 if (!ShAmt || !ICI.isEquality()) break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006964
Chris Lattner5ee84f82008-03-21 05:19:58 +00006965 // Check that the shift amount is in range. If not, don't perform
6966 // undefined shifts. When the shift is visited it will be
6967 // simplified.
6968 uint32_t TypeBits = RHSV.getBitWidth();
6969 if (ShAmt->uge(TypeBits))
6970 break;
6971
6972 uint32_t ShAmtVal = (uint32_t)ShAmt->getLimitedValue(TypeBits);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006973
Chris Lattner5ee84f82008-03-21 05:19:58 +00006974 // If we are comparing against bits always shifted out, the
6975 // comparison cannot succeed.
6976 APInt Comp = RHSV << ShAmtVal;
6977 if (LHSI->getOpcode() == Instruction::LShr)
6978 Comp = Comp.lshr(ShAmtVal);
6979 else
6980 Comp = Comp.ashr(ShAmtVal);
6981
6982 if (Comp != RHSV) { // Comparing against a bit that we know is zero.
6983 bool IsICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
Owen Anderson24be4c12009-07-03 00:17:18 +00006984 Constant *Cst = Context->getConstantInt(Type::Int1Ty, IsICMP_NE);
Chris Lattner5ee84f82008-03-21 05:19:58 +00006985 return ReplaceInstUsesWith(ICI, Cst);
6986 }
6987
6988 // Otherwise, check to see if the bits shifted out are known to be zero.
6989 // If so, we can compare against the unshifted value:
6990 // (X & 4) >> 1 == 2 --> (X & 4) == 4.
Evan Chengfb9292a2008-04-23 00:38:06 +00006991 if (LHSI->hasOneUse() &&
6992 MaskedValueIsZero(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00006993 APInt::getLowBitsSet(Comp.getBitWidth(), ShAmtVal))) {
Owen Anderson6601fcd2009-07-09 23:48:35 +00006994 return new ICmpInst(*Context, ICI.getPredicate(), LHSI->getOperand(0),
Owen Anderson24be4c12009-07-03 00:17:18 +00006995 Context->getConstantExprShl(RHS, ShAmt));
Chris Lattner5ee84f82008-03-21 05:19:58 +00006996 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00006997
Evan Chengfb9292a2008-04-23 00:38:06 +00006998 if (LHSI->hasOneUse()) {
Chris Lattner5ee84f82008-03-21 05:19:58 +00006999 // Otherwise strength reduce the shift into an and.
7000 APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
Owen Anderson24be4c12009-07-03 00:17:18 +00007001 Constant *Mask = Context->getConstantInt(Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007002
Chris Lattner5ee84f82008-03-21 05:19:58 +00007003 Instruction *AndI =
Gabor Greifa645dd32008-05-16 19:29:10 +00007004 BinaryOperator::CreateAnd(LHSI->getOperand(0),
Chris Lattner5ee84f82008-03-21 05:19:58 +00007005 Mask, LHSI->getName()+".mask");
7006 Value *And = InsertNewInstBefore(AndI, ICI);
Owen Anderson6601fcd2009-07-09 23:48:35 +00007007 return new ICmpInst(*Context, ICI.getPredicate(), And,
Owen Anderson24be4c12009-07-03 00:17:18 +00007008 Context->getConstantExprShl(RHS, ShAmt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007009 }
7010 break;
7011 }
7012
7013 case Instruction::SDiv:
7014 case Instruction::UDiv:
7015 // Fold: icmp pred ([us]div X, C1), C2 -> range test
7016 // Fold this div into the comparison, producing a range check.
7017 // Determine, based on the divide type, what the range is being
7018 // checked. If there is an overflow on the low or high side, remember
7019 // it, otherwise compute the range [low, hi) bounding the new value.
7020 // See: InsertRangeTest above for the kinds of replacements possible.
7021 if (ConstantInt *DivRHS = dyn_cast<ConstantInt>(LHSI->getOperand(1)))
7022 if (Instruction *R = FoldICmpDivCst(ICI, cast<BinaryOperator>(LHSI),
7023 DivRHS))
7024 return R;
7025 break;
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007026
7027 case Instruction::Add:
7028 // Fold: icmp pred (add, X, C1), C2
7029
7030 if (!ICI.isEquality()) {
7031 ConstantInt *LHSC = dyn_cast<ConstantInt>(LHSI->getOperand(1));
7032 if (!LHSC) break;
7033 const APInt &LHSV = LHSC->getValue();
7034
7035 ConstantRange CR = ICI.makeConstantRange(ICI.getPredicate(), RHSV)
7036 .subtract(LHSV);
7037
7038 if (ICI.isSignedPredicate()) {
7039 if (CR.getLower().isSignBit()) {
Owen Anderson6601fcd2009-07-09 23:48:35 +00007040 return new ICmpInst(*Context, ICmpInst::ICMP_SLT, LHSI->getOperand(0),
Owen Anderson24be4c12009-07-03 00:17:18 +00007041 Context->getConstantInt(CR.getUpper()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007042 } else if (CR.getUpper().isSignBit()) {
Owen Anderson6601fcd2009-07-09 23:48:35 +00007043 return new ICmpInst(*Context, ICmpInst::ICMP_SGE, LHSI->getOperand(0),
Owen Anderson24be4c12009-07-03 00:17:18 +00007044 Context->getConstantInt(CR.getLower()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007045 }
7046 } else {
7047 if (CR.getLower().isMinValue()) {
Owen Anderson6601fcd2009-07-09 23:48:35 +00007048 return new ICmpInst(*Context, ICmpInst::ICMP_ULT, LHSI->getOperand(0),
Owen Anderson24be4c12009-07-03 00:17:18 +00007049 Context->getConstantInt(CR.getUpper()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007050 } else if (CR.getUpper().isMinValue()) {
Owen Anderson6601fcd2009-07-09 23:48:35 +00007051 return new ICmpInst(*Context, ICmpInst::ICMP_UGE, LHSI->getOperand(0),
Owen Anderson24be4c12009-07-03 00:17:18 +00007052 Context->getConstantInt(CR.getLower()));
Nick Lewycky0185bbf2008-02-03 16:33:09 +00007053 }
7054 }
7055 }
7056 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007057 }
7058
7059 // Simplify icmp_eq and icmp_ne instructions with integer constant RHS.
7060 if (ICI.isEquality()) {
7061 bool isICMP_NE = ICI.getPredicate() == ICmpInst::ICMP_NE;
7062
7063 // If the first operand is (add|sub|and|or|xor|rem) with a constant, and
7064 // the second operand is a constant, simplify a bit.
7065 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(LHSI)) {
7066 switch (BO->getOpcode()) {
7067 case Instruction::SRem:
7068 // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
7069 if (RHSV == 0 && isa<ConstantInt>(BO->getOperand(1)) &&BO->hasOneUse()){
7070 const APInt &V = cast<ConstantInt>(BO->getOperand(1))->getValue();
7071 if (V.sgt(APInt(V.getBitWidth(), 1)) && V.isPowerOf2()) {
7072 Instruction *NewRem =
Gabor Greifa645dd32008-05-16 19:29:10 +00007073 BinaryOperator::CreateURem(BO->getOperand(0), BO->getOperand(1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007074 BO->getName());
7075 InsertNewInstBefore(NewRem, ICI);
Owen Anderson6601fcd2009-07-09 23:48:35 +00007076 return new ICmpInst(*Context, ICI.getPredicate(), NewRem,
Owen Anderson24be4c12009-07-03 00:17:18 +00007077 Context->getNullValue(BO->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007078 }
7079 }
7080 break;
7081 case Instruction::Add:
7082 // Replace ((add A, B) != C) with (A != C-B) if B & C are constants.
7083 if (ConstantInt *BOp1C = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7084 if (BO->hasOneUse())
Owen Anderson6601fcd2009-07-09 23:48:35 +00007085 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Anderson24be4c12009-07-03 00:17:18 +00007086 Context->getConstantExprSub(RHS, BOp1C));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007087 } else if (RHSV == 0) {
7088 // Replace ((add A, B) != 0) with (A != -B) if A or B is
7089 // efficiently invertible, or if the add has just this one use.
7090 Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
7091
Owen Anderson24be4c12009-07-03 00:17:18 +00007092 if (Value *NegVal = dyn_castNegVal(BOp1, Context))
Owen Anderson6601fcd2009-07-09 23:48:35 +00007093 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, NegVal);
Owen Anderson24be4c12009-07-03 00:17:18 +00007094 else if (Value *NegVal = dyn_castNegVal(BOp0, Context))
Owen Anderson6601fcd2009-07-09 23:48:35 +00007095 return new ICmpInst(*Context, ICI.getPredicate(), NegVal, BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007096 else if (BO->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007097 Instruction *Neg = BinaryOperator::CreateNeg(BOp1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007098 InsertNewInstBefore(Neg, ICI);
7099 Neg->takeName(BO);
Owen Anderson6601fcd2009-07-09 23:48:35 +00007100 return new ICmpInst(*Context, ICI.getPredicate(), BOp0, Neg);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007101 }
7102 }
7103 break;
7104 case Instruction::Xor:
7105 // For the xor case, we can xor two constants together, eliminating
7106 // the explicit xor.
7107 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1)))
Owen Anderson6601fcd2009-07-09 23:48:35 +00007108 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Owen Anderson24be4c12009-07-03 00:17:18 +00007109 Context->getConstantExprXor(RHS, BOC));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007110
7111 // FALLTHROUGH
7112 case Instruction::Sub:
7113 // Replace (([sub|xor] A, B) != 0) with (A != B)
7114 if (RHSV == 0)
Owen Anderson6601fcd2009-07-09 23:48:35 +00007115 return new ICmpInst(*Context, ICI.getPredicate(), BO->getOperand(0),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007116 BO->getOperand(1));
7117 break;
7118
7119 case Instruction::Or:
7120 // If bits are being or'd in that are not present in the constant we
7121 // are comparing against, then the comparison could never succeed!
7122 if (Constant *BOC = dyn_cast<Constant>(BO->getOperand(1))) {
Owen Anderson24be4c12009-07-03 00:17:18 +00007123 Constant *NotCI = Context->getConstantExprNot(RHS);
7124 if (!Context->getConstantExprAnd(BOC, NotCI)->isNullValue())
7125 return ReplaceInstUsesWith(ICI,
7126 Context->getConstantInt(Type::Int1Ty,
7127 isICMP_NE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007128 }
7129 break;
7130
7131 case Instruction::And:
7132 if (ConstantInt *BOC = dyn_cast<ConstantInt>(BO->getOperand(1))) {
7133 // If bits are being compared against that are and'd out, then the
7134 // comparison can never succeed!
7135 if ((RHSV & ~BOC->getValue()) != 0)
Owen Anderson24be4c12009-07-03 00:17:18 +00007136 return ReplaceInstUsesWith(ICI,
7137 Context->getConstantInt(Type::Int1Ty,
7138 isICMP_NE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007139
7140 // If we have ((X & C) == C), turn it into ((X & C) != 0).
7141 if (RHS == BOC && RHSV.isPowerOf2())
Owen Anderson6601fcd2009-07-09 23:48:35 +00007142 return new ICmpInst(*Context, isICMP_NE ? ICmpInst::ICMP_EQ :
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007143 ICmpInst::ICMP_NE, LHSI,
Owen Anderson24be4c12009-07-03 00:17:18 +00007144 Context->getNullValue(RHS->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007145
7146 // Replace (and X, (1 << size(X)-1) != 0) with x s< 0
Chris Lattner60813c22008-06-02 01:29:46 +00007147 if (BOC->getValue().isSignBit()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007148 Value *X = BO->getOperand(0);
Owen Anderson24be4c12009-07-03 00:17:18 +00007149 Constant *Zero = Context->getNullValue(X->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007150 ICmpInst::Predicate pred = isICMP_NE ?
7151 ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
Owen Anderson6601fcd2009-07-09 23:48:35 +00007152 return new ICmpInst(*Context, pred, X, Zero);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007153 }
7154
7155 // ((X & ~7) == 0) --> X < 8
7156 if (RHSV == 0 && isHighOnes(BOC)) {
7157 Value *X = BO->getOperand(0);
Owen Anderson24be4c12009-07-03 00:17:18 +00007158 Constant *NegX = Context->getConstantExprNeg(BOC);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007159 ICmpInst::Predicate pred = isICMP_NE ?
7160 ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
Owen Anderson6601fcd2009-07-09 23:48:35 +00007161 return new ICmpInst(*Context, pred, X, NegX);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007162 }
7163 }
7164 default: break;
7165 }
7166 } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(LHSI)) {
7167 // Handle icmp {eq|ne} <intrinsic>, intcst.
7168 if (II->getIntrinsicID() == Intrinsic::bswap) {
7169 AddToWorkList(II);
7170 ICI.setOperand(0, II->getOperand(1));
Owen Anderson24be4c12009-07-03 00:17:18 +00007171 ICI.setOperand(1, Context->getConstantInt(RHSV.byteSwap()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007172 return &ICI;
7173 }
7174 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007175 }
7176 return 0;
7177}
7178
7179/// visitICmpInstWithCastAndCast - Handle icmp (cast x to y), (cast/cst).
7180/// We only handle extending casts so far.
7181///
7182Instruction *InstCombiner::visitICmpInstWithCastAndCast(ICmpInst &ICI) {
7183 const CastInst *LHSCI = cast<CastInst>(ICI.getOperand(0));
7184 Value *LHSCIOp = LHSCI->getOperand(0);
7185 const Type *SrcTy = LHSCIOp->getType();
7186 const Type *DestTy = LHSCI->getType();
7187 Value *RHSCIOp;
7188
7189 // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
7190 // integer type is the same size as the pointer type.
7191 if (LHSCI->getOpcode() == Instruction::PtrToInt &&
7192 getTargetData().getPointerSizeInBits() ==
7193 cast<IntegerType>(DestTy)->getBitWidth()) {
7194 Value *RHSOp = 0;
7195 if (Constant *RHSC = dyn_cast<Constant>(ICI.getOperand(1))) {
Owen Anderson24be4c12009-07-03 00:17:18 +00007196 RHSOp = Context->getConstantExprIntToPtr(RHSC, SrcTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007197 } else if (PtrToIntInst *RHSC = dyn_cast<PtrToIntInst>(ICI.getOperand(1))) {
7198 RHSOp = RHSC->getOperand(0);
7199 // If the pointer types don't match, insert a bitcast.
7200 if (LHSCIOp->getType() != RHSOp->getType())
Chris Lattner13c2d6e2008-01-13 22:23:22 +00007201 RHSOp = InsertBitCastBefore(RHSOp, LHSCIOp->getType(), ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007202 }
7203
7204 if (RHSOp)
Owen Anderson6601fcd2009-07-09 23:48:35 +00007205 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007206 }
7207
7208 // The code below only handles extension cast instructions, so far.
7209 // Enforce this.
7210 if (LHSCI->getOpcode() != Instruction::ZExt &&
7211 LHSCI->getOpcode() != Instruction::SExt)
7212 return 0;
7213
7214 bool isSignedExt = LHSCI->getOpcode() == Instruction::SExt;
7215 bool isSignedCmp = ICI.isSignedPredicate();
7216
7217 if (CastInst *CI = dyn_cast<CastInst>(ICI.getOperand(1))) {
7218 // Not an extension from the same type?
7219 RHSCIOp = CI->getOperand(0);
7220 if (RHSCIOp->getType() != LHSCIOp->getType())
7221 return 0;
7222
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007223 // If the signedness of the two casts doesn't agree (i.e. one is a sext
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007224 // and the other is a zext), then we can't handle this.
7225 if (CI->getOpcode() != LHSCI->getOpcode())
7226 return 0;
7227
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007228 // Deal with equality cases early.
7229 if (ICI.isEquality())
Owen Anderson6601fcd2009-07-09 23:48:35 +00007230 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007231
7232 // A signed comparison of sign extended values simplifies into a
7233 // signed comparison.
7234 if (isSignedCmp && isSignedExt)
Owen Anderson6601fcd2009-07-09 23:48:35 +00007235 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, RHSCIOp);
Nick Lewyckyd4264dc2008-01-28 03:48:02 +00007236
7237 // The other three cases all fold into an unsigned comparison.
Owen Anderson6601fcd2009-07-09 23:48:35 +00007238 return new ICmpInst(*Context, ICI.getUnsignedPredicate(), LHSCIOp, RHSCIOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007239 }
7240
7241 // If we aren't dealing with a constant on the RHS, exit early
7242 ConstantInt *CI = dyn_cast<ConstantInt>(ICI.getOperand(1));
7243 if (!CI)
7244 return 0;
7245
7246 // Compute the constant that would happen if we truncated to SrcTy then
7247 // reextended to DestTy.
Owen Anderson24be4c12009-07-03 00:17:18 +00007248 Constant *Res1 = Context->getConstantExprTrunc(CI, SrcTy);
7249 Constant *Res2 = Context->getConstantExprCast(LHSCI->getOpcode(),
7250 Res1, DestTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007251
7252 // If the re-extended constant didn't change...
7253 if (Res2 == CI) {
7254 // Make sure that sign of the Cmp and the sign of the Cast are the same.
7255 // For example, we might have:
Dan Gohman9e1657f2009-06-14 23:30:43 +00007256 // %A = sext i16 %X to i32
7257 // %B = icmp ugt i32 %A, 1330
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007258 // It is incorrect to transform this into
Dan Gohman9e1657f2009-06-14 23:30:43 +00007259 // %B = icmp ugt i16 %X, 1330
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007260 // because %A may have negative value.
7261 //
Chris Lattner3d816532008-07-11 04:09:09 +00007262 // However, we allow this when the compare is EQ/NE, because they are
7263 // signless.
7264 if (isSignedExt == isSignedCmp || ICI.isEquality())
Owen Anderson6601fcd2009-07-09 23:48:35 +00007265 return new ICmpInst(*Context, ICI.getPredicate(), LHSCIOp, Res1);
Chris Lattner3d816532008-07-11 04:09:09 +00007266 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007267 }
7268
7269 // The re-extended constant changed so the constant cannot be represented
7270 // in the shorter type. Consequently, we cannot emit a simple comparison.
7271
7272 // First, handle some easy cases. We know the result cannot be equal at this
7273 // point so handle the ICI.isEquality() cases
7274 if (ICI.getPredicate() == ICmpInst::ICMP_EQ)
Owen Anderson24be4c12009-07-03 00:17:18 +00007275 return ReplaceInstUsesWith(ICI, Context->getConstantIntFalse());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007276 if (ICI.getPredicate() == ICmpInst::ICMP_NE)
Owen Anderson24be4c12009-07-03 00:17:18 +00007277 return ReplaceInstUsesWith(ICI, Context->getConstantIntTrue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007278
7279 // Evaluate the comparison for LT (we invert for GT below). LE and GE cases
7280 // should have been folded away previously and not enter in here.
7281 Value *Result;
7282 if (isSignedCmp) {
7283 // We're performing a signed comparison.
7284 if (cast<ConstantInt>(CI)->getValue().isNegative())
Owen Anderson24be4c12009-07-03 00:17:18 +00007285 Result = Context->getConstantIntFalse(); // X < (small) --> false
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007286 else
Owen Anderson24be4c12009-07-03 00:17:18 +00007287 Result = Context->getConstantIntTrue(); // X < (large) --> true
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007288 } else {
7289 // We're performing an unsigned comparison.
7290 if (isSignedExt) {
7291 // We're performing an unsigned comp with a sign extended value.
7292 // This is true if the input is >= 0. [aka >s -1]
Owen Anderson24be4c12009-07-03 00:17:18 +00007293 Constant *NegOne = Context->getConstantIntAllOnesValue(SrcTy);
Owen Anderson6601fcd2009-07-09 23:48:35 +00007294 Result = InsertNewInstBefore(new ICmpInst(*Context, ICmpInst::ICMP_SGT,
7295 LHSCIOp, NegOne, ICI.getName()), ICI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007296 } else {
7297 // Unsigned extend & unsigned compare -> always true.
Owen Anderson24be4c12009-07-03 00:17:18 +00007298 Result = Context->getConstantIntTrue();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007299 }
7300 }
7301
7302 // Finally, return the value computed.
7303 if (ICI.getPredicate() == ICmpInst::ICMP_ULT ||
Chris Lattner3d816532008-07-11 04:09:09 +00007304 ICI.getPredicate() == ICmpInst::ICMP_SLT)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007305 return ReplaceInstUsesWith(ICI, Result);
Chris Lattner3d816532008-07-11 04:09:09 +00007306
7307 assert((ICI.getPredicate()==ICmpInst::ICMP_UGT ||
7308 ICI.getPredicate()==ICmpInst::ICMP_SGT) &&
7309 "ICmp should be folded!");
7310 if (Constant *CI = dyn_cast<Constant>(Result))
Owen Anderson24be4c12009-07-03 00:17:18 +00007311 return ReplaceInstUsesWith(ICI, Context->getConstantExprNot(CI));
Chris Lattner3d816532008-07-11 04:09:09 +00007312 return BinaryOperator::CreateNot(Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007313}
7314
7315Instruction *InstCombiner::visitShl(BinaryOperator &I) {
7316 return commonShiftTransforms(I);
7317}
7318
7319Instruction *InstCombiner::visitLShr(BinaryOperator &I) {
7320 return commonShiftTransforms(I);
7321}
7322
7323Instruction *InstCombiner::visitAShr(BinaryOperator &I) {
Chris Lattnere3c504f2007-12-06 01:59:46 +00007324 if (Instruction *R = commonShiftTransforms(I))
7325 return R;
7326
7327 Value *Op0 = I.getOperand(0);
7328
7329 // ashr int -1, X = -1 (for any arithmetic shift rights of ~0)
7330 if (ConstantInt *CSI = dyn_cast<ConstantInt>(Op0))
7331 if (CSI->isAllOnesValue())
7332 return ReplaceInstUsesWith(I, CSI);
Dan Gohman843649e2009-02-24 02:00:40 +00007333
Dan Gohman2526aea2009-06-16 19:55:29 +00007334 // See if we can turn a signed shr into an unsigned shr.
7335 if (MaskedValueIsZero(Op0,
7336 APInt::getSignBit(I.getType()->getScalarSizeInBits())))
7337 return BinaryOperator::CreateLShr(Op0, I.getOperand(1));
7338
7339 // Arithmetic shifting an all-sign-bit value is a no-op.
7340 unsigned NumSignBits = ComputeNumSignBits(Op0);
7341 if (NumSignBits == Op0->getType()->getScalarSizeInBits())
7342 return ReplaceInstUsesWith(I, Op0);
Dan Gohman843649e2009-02-24 02:00:40 +00007343
Chris Lattnere3c504f2007-12-06 01:59:46 +00007344 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007345}
7346
7347Instruction *InstCombiner::commonShiftTransforms(BinaryOperator &I) {
7348 assert(I.getOperand(1)->getType() == I.getOperand(0)->getType());
7349 Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
7350
7351 // shl X, 0 == X and shr X, 0 == X
7352 // shl 0, X == 0 and shr 0, X == 0
Owen Anderson24be4c12009-07-03 00:17:18 +00007353 if (Op1 == Context->getNullValue(Op1->getType()) ||
7354 Op0 == Context->getNullValue(Op0->getType()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007355 return ReplaceInstUsesWith(I, Op0);
7356
7357 if (isa<UndefValue>(Op0)) {
7358 if (I.getOpcode() == Instruction::AShr) // undef >>s X -> undef
7359 return ReplaceInstUsesWith(I, Op0);
7360 else // undef << X -> 0, undef >>u X -> 0
Owen Anderson24be4c12009-07-03 00:17:18 +00007361 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007362 }
7363 if (isa<UndefValue>(Op1)) {
7364 if (I.getOpcode() == Instruction::AShr) // X >>s undef -> X
7365 return ReplaceInstUsesWith(I, Op0);
7366 else // X << undef, X >>u undef -> 0
Owen Anderson24be4c12009-07-03 00:17:18 +00007367 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007368 }
7369
Dan Gohman2bc21562009-05-21 02:28:33 +00007370 // See if we can fold away this shift.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007371 if (SimplifyDemandedInstructionBits(I))
Dan Gohman2bc21562009-05-21 02:28:33 +00007372 return &I;
7373
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007374 // Try to fold constant and into select arguments.
7375 if (isa<Constant>(Op0))
7376 if (SelectInst *SI = dyn_cast<SelectInst>(Op1))
7377 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7378 return R;
7379
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007380 if (ConstantInt *CUI = dyn_cast<ConstantInt>(Op1))
7381 if (Instruction *Res = FoldShiftByConstant(Op0, CUI, I))
7382 return Res;
7383 return 0;
7384}
7385
7386Instruction *InstCombiner::FoldShiftByConstant(Value *Op0, ConstantInt *Op1,
7387 BinaryOperator &I) {
Chris Lattner08817332009-01-31 08:24:16 +00007388 bool isLeftShift = I.getOpcode() == Instruction::Shl;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007389
7390 // See if we can simplify any instructions used by the instruction whose sole
7391 // purpose is to compute bits we don't care about.
Dan Gohman2526aea2009-06-16 19:55:29 +00007392 uint32_t TypeBits = Op0->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007393
Dan Gohman9e1657f2009-06-14 23:30:43 +00007394 // shl i32 X, 32 = 0 and srl i8 Y, 9 = 0, ... just don't eliminate
7395 // a signed shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007396 //
7397 if (Op1->uge(TypeBits)) {
7398 if (I.getOpcode() != Instruction::AShr)
Owen Anderson24be4c12009-07-03 00:17:18 +00007399 return ReplaceInstUsesWith(I, Context->getNullValue(Op0->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007400 else {
Owen Anderson24be4c12009-07-03 00:17:18 +00007401 I.setOperand(1, Context->getConstantInt(I.getType(), TypeBits-1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007402 return &I;
7403 }
7404 }
7405
7406 // ((X*C1) << C2) == (X * (C1 << C2))
7407 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Op0))
7408 if (BO->getOpcode() == Instruction::Mul && isLeftShift)
7409 if (Constant *BOOp = dyn_cast<Constant>(BO->getOperand(1)))
Gabor Greifa645dd32008-05-16 19:29:10 +00007410 return BinaryOperator::CreateMul(BO->getOperand(0),
Owen Anderson24be4c12009-07-03 00:17:18 +00007411 Context->getConstantExprShl(BOOp, Op1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007412
7413 // Try to fold constant and into select arguments.
7414 if (SelectInst *SI = dyn_cast<SelectInst>(Op0))
7415 if (Instruction *R = FoldOpIntoSelect(I, SI, this))
7416 return R;
7417 if (isa<PHINode>(Op0))
7418 if (Instruction *NV = FoldOpIntoPhi(I))
7419 return NV;
7420
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007421 // Fold shift2(trunc(shift1(x,c1)), c2) -> trunc(shift2(shift1(x,c1),c2))
7422 if (TruncInst *TI = dyn_cast<TruncInst>(Op0)) {
7423 Instruction *TrOp = dyn_cast<Instruction>(TI->getOperand(0));
7424 // If 'shift2' is an ashr, we would have to get the sign bit into a funny
7425 // place. Don't try to do this transformation in this case. Also, we
7426 // require that the input operand is a shift-by-constant so that we have
7427 // confidence that the shifts will get folded together. We could do this
7428 // xform in more cases, but it is unlikely to be profitable.
7429 if (TrOp && I.isLogicalShift() && TrOp->isShift() &&
7430 isa<ConstantInt>(TrOp->getOperand(1))) {
7431 // Okay, we'll do this xform. Make the shift of shift.
Owen Anderson24be4c12009-07-03 00:17:18 +00007432 Constant *ShAmt = Context->getConstantExprZExt(Op1, TrOp->getType());
Gabor Greifa645dd32008-05-16 19:29:10 +00007433 Instruction *NSh = BinaryOperator::Create(I.getOpcode(), TrOp, ShAmt,
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007434 I.getName());
7435 InsertNewInstBefore(NSh, I); // (shift2 (shift1 & 0x00FF), c2)
7436
7437 // For logical shifts, the truncation has the effect of making the high
7438 // part of the register be zeros. Emulate this by inserting an AND to
7439 // clear the top bits as needed. This 'and' will usually be zapped by
7440 // other xforms later if dead.
Dan Gohman2526aea2009-06-16 19:55:29 +00007441 unsigned SrcSize = TrOp->getType()->getScalarSizeInBits();
7442 unsigned DstSize = TI->getType()->getScalarSizeInBits();
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007443 APInt MaskV(APInt::getLowBitsSet(SrcSize, DstSize));
7444
7445 // The mask we constructed says what the trunc would do if occurring
7446 // between the shifts. We want to know the effect *after* the second
7447 // shift. We know that it is a logical shift by a constant, so adjust the
7448 // mask as appropriate.
7449 if (I.getOpcode() == Instruction::Shl)
7450 MaskV <<= Op1->getZExtValue();
7451 else {
7452 assert(I.getOpcode() == Instruction::LShr && "Unknown logical shift");
7453 MaskV = MaskV.lshr(Op1->getZExtValue());
7454 }
7455
Owen Anderson24be4c12009-07-03 00:17:18 +00007456 Instruction *And =
7457 BinaryOperator::CreateAnd(NSh, Context->getConstantInt(MaskV),
7458 TI->getName());
Chris Lattnerc6d1f642007-12-22 09:07:47 +00007459 InsertNewInstBefore(And, I); // shift1 & 0x00FF
7460
7461 // Return the value truncated to the interesting size.
7462 return new TruncInst(And, I.getType());
7463 }
7464 }
7465
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007466 if (Op0->hasOneUse()) {
7467 if (BinaryOperator *Op0BO = dyn_cast<BinaryOperator>(Op0)) {
7468 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7469 Value *V1, *V2;
7470 ConstantInt *CC;
7471 switch (Op0BO->getOpcode()) {
7472 default: break;
7473 case Instruction::Add:
7474 case Instruction::And:
7475 case Instruction::Or:
7476 case Instruction::Xor: {
7477 // These operators commute.
7478 // Turn (Y + (X >> C)) << C -> (X + (Y << C)) & (~0 << C)
7479 if (isLeftShift && Op0BO->getOperand(1)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00007480 match(Op0BO->getOperand(1), m_Shr(m_Value(V1),
7481 m_Specific(Op1)), *Context)){
Gabor Greifa645dd32008-05-16 19:29:10 +00007482 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007483 Op0BO->getOperand(0), Op1,
7484 Op0BO->getName());
7485 InsertNewInstBefore(YS, I); // (Y << C)
7486 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00007487 BinaryOperator::Create(Op0BO->getOpcode(), YS, V1,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007488 Op0BO->getOperand(1)->getName());
7489 InsertNewInstBefore(X, I); // (X + (Y << C))
7490 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Anderson24be4c12009-07-03 00:17:18 +00007491 return BinaryOperator::CreateAnd(X, Context->getConstantInt(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007492 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7493 }
7494
7495 // Turn (Y + ((X >> C) & CC)) << C -> ((X & (CC << C)) + (Y << C))
7496 Value *Op0BOOp1 = Op0BO->getOperand(1);
7497 if (isLeftShift && Op0BOOp1->hasOneUse() &&
7498 match(Op0BOOp1,
Chris Lattner3b874082008-11-16 05:38:51 +00007499 m_And(m_Shr(m_Value(V1), m_Specific(Op1)),
Owen Andersona21eb582009-07-10 17:35:01 +00007500 m_ConstantInt(CC)), *Context) &&
Chris Lattner3b874082008-11-16 05:38:51 +00007501 cast<BinaryOperator>(Op0BOOp1)->getOperand(0)->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007502 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007503 Op0BO->getOperand(0), Op1,
7504 Op0BO->getName());
7505 InsertNewInstBefore(YS, I); // (Y << C)
7506 Instruction *XM =
Owen Anderson24be4c12009-07-03 00:17:18 +00007507 BinaryOperator::CreateAnd(V1,
7508 Context->getConstantExprShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007509 V1->getName()+".mask");
7510 InsertNewInstBefore(XM, I); // X & (CC << C)
7511
Gabor Greifa645dd32008-05-16 19:29:10 +00007512 return BinaryOperator::Create(Op0BO->getOpcode(), YS, XM);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007513 }
7514 }
7515
7516 // FALL THROUGH.
7517 case Instruction::Sub: {
7518 // Turn ((X >> C) + Y) << C -> (X + (Y << C)) & (~0 << C)
7519 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00007520 match(Op0BO->getOperand(0), m_Shr(m_Value(V1),
7521 m_Specific(Op1)), *Context)){
Gabor Greifa645dd32008-05-16 19:29:10 +00007522 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007523 Op0BO->getOperand(1), Op1,
7524 Op0BO->getName());
7525 InsertNewInstBefore(YS, I); // (Y << C)
7526 Instruction *X =
Gabor Greifa645dd32008-05-16 19:29:10 +00007527 BinaryOperator::Create(Op0BO->getOpcode(), V1, YS,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007528 Op0BO->getOperand(0)->getName());
7529 InsertNewInstBefore(X, I); // (X + (Y << C))
7530 uint32_t Op1Val = Op1->getLimitedValue(TypeBits);
Owen Anderson24be4c12009-07-03 00:17:18 +00007531 return BinaryOperator::CreateAnd(X, Context->getConstantInt(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007532 APInt::getHighBitsSet(TypeBits, TypeBits-Op1Val)));
7533 }
7534
7535 // Turn (((X >> C)&CC) + Y) << C -> (X + (Y << C)) & (CC << C)
7536 if (isLeftShift && Op0BO->getOperand(0)->hasOneUse() &&
7537 match(Op0BO->getOperand(0),
7538 m_And(m_Shr(m_Value(V1), m_Value(V2)),
Owen Andersona21eb582009-07-10 17:35:01 +00007539 m_ConstantInt(CC)), *Context) && V2 == Op1 &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007540 cast<BinaryOperator>(Op0BO->getOperand(0))
7541 ->getOperand(0)->hasOneUse()) {
Gabor Greifa645dd32008-05-16 19:29:10 +00007542 Instruction *YS = BinaryOperator::CreateShl(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007543 Op0BO->getOperand(1), Op1,
7544 Op0BO->getName());
7545 InsertNewInstBefore(YS, I); // (Y << C)
7546 Instruction *XM =
Owen Anderson24be4c12009-07-03 00:17:18 +00007547 BinaryOperator::CreateAnd(V1,
7548 Context->getConstantExprShl(CC, Op1),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007549 V1->getName()+".mask");
7550 InsertNewInstBefore(XM, I); // X & (CC << C)
7551
Gabor Greifa645dd32008-05-16 19:29:10 +00007552 return BinaryOperator::Create(Op0BO->getOpcode(), XM, YS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007553 }
7554
7555 break;
7556 }
7557 }
7558
7559
7560 // If the operand is an bitwise operator with a constant RHS, and the
7561 // shift is the only use, we can pull it out of the shift.
7562 if (ConstantInt *Op0C = dyn_cast<ConstantInt>(Op0BO->getOperand(1))) {
7563 bool isValid = true; // Valid only for And, Or, Xor
7564 bool highBitSet = false; // Transform if high bit of constant set?
7565
7566 switch (Op0BO->getOpcode()) {
7567 default: isValid = false; break; // Do not perform transform!
7568 case Instruction::Add:
7569 isValid = isLeftShift;
7570 break;
7571 case Instruction::Or:
7572 case Instruction::Xor:
7573 highBitSet = false;
7574 break;
7575 case Instruction::And:
7576 highBitSet = true;
7577 break;
7578 }
7579
7580 // If this is a signed shift right, and the high bit is modified
7581 // by the logical operation, do not perform the transformation.
7582 // The highBitSet boolean indicates the value of the high bit of
7583 // the constant which would cause it to be modified for this
7584 // operation.
7585 //
Chris Lattner15b76e32007-12-06 06:25:04 +00007586 if (isValid && I.getOpcode() == Instruction::AShr)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007587 isValid = Op0C->getValue()[TypeBits-1] == highBitSet;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007588
7589 if (isValid) {
Owen Anderson24be4c12009-07-03 00:17:18 +00007590 Constant *NewRHS = Context->getConstantExpr(I.getOpcode(), Op0C, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007591
7592 Instruction *NewShift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007593 BinaryOperator::Create(I.getOpcode(), Op0BO->getOperand(0), Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007594 InsertNewInstBefore(NewShift, I);
7595 NewShift->takeName(Op0BO);
7596
Gabor Greifa645dd32008-05-16 19:29:10 +00007597 return BinaryOperator::Create(Op0BO->getOpcode(), NewShift,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007598 NewRHS);
7599 }
7600 }
7601 }
7602 }
7603
7604 // Find out if this is a shift of a shift by a constant.
7605 BinaryOperator *ShiftOp = dyn_cast<BinaryOperator>(Op0);
7606 if (ShiftOp && !ShiftOp->isShift())
7607 ShiftOp = 0;
7608
7609 if (ShiftOp && isa<ConstantInt>(ShiftOp->getOperand(1))) {
7610 ConstantInt *ShiftAmt1C = cast<ConstantInt>(ShiftOp->getOperand(1));
7611 uint32_t ShiftAmt1 = ShiftAmt1C->getLimitedValue(TypeBits);
7612 uint32_t ShiftAmt2 = Op1->getLimitedValue(TypeBits);
7613 assert(ShiftAmt2 != 0 && "Should have been simplified earlier");
7614 if (ShiftAmt1 == 0) return 0; // Will be simplified in the future.
7615 Value *X = ShiftOp->getOperand(0);
7616
7617 uint32_t AmtSum = ShiftAmt1+ShiftAmt2; // Fold into one big shift.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007618
7619 const IntegerType *Ty = cast<IntegerType>(I.getType());
7620
7621 // Check for (X << c1) << c2 and (X >> c1) >> c2
7622 if (I.getOpcode() == ShiftOp->getOpcode()) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00007623 // If this is oversized composite shift, then unsigned shifts get 0, ashr
7624 // saturates.
7625 if (AmtSum >= TypeBits) {
7626 if (I.getOpcode() != Instruction::AShr)
Owen Anderson24be4c12009-07-03 00:17:18 +00007627 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00007628 AmtSum = TypeBits-1; // Saturate to 31 for i32 ashr.
7629 }
7630
Gabor Greifa645dd32008-05-16 19:29:10 +00007631 return BinaryOperator::Create(I.getOpcode(), X,
Owen Anderson24be4c12009-07-03 00:17:18 +00007632 Context->getConstantInt(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007633 } else if (ShiftOp->getOpcode() == Instruction::LShr &&
7634 I.getOpcode() == Instruction::AShr) {
Chris Lattnerb36c7012009-03-20 22:41:15 +00007635 if (AmtSum >= TypeBits)
Owen Anderson24be4c12009-07-03 00:17:18 +00007636 return ReplaceInstUsesWith(I, Context->getNullValue(I.getType()));
Chris Lattnerb36c7012009-03-20 22:41:15 +00007637
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007638 // ((X >>u C1) >>s C2) -> (X >>u (C1+C2)) since C1 != 0.
Owen Anderson24be4c12009-07-03 00:17:18 +00007639 return BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007640 } else if (ShiftOp->getOpcode() == Instruction::AShr &&
7641 I.getOpcode() == Instruction::LShr) {
7642 // ((X >>s C1) >>u C2) -> ((X >>s (C1+C2)) & mask) since C1 != 0.
Chris Lattnerb36c7012009-03-20 22:41:15 +00007643 if (AmtSum >= TypeBits)
7644 AmtSum = TypeBits-1;
7645
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007646 Instruction *Shift =
Owen Anderson24be4c12009-07-03 00:17:18 +00007647 BinaryOperator::CreateAShr(X, Context->getConstantInt(Ty, AmtSum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007648 InsertNewInstBefore(Shift, I);
7649
7650 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Anderson24be4c12009-07-03 00:17:18 +00007651 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007652 }
7653
7654 // Okay, if we get here, one shift must be left, and the other shift must be
7655 // right. See if the amounts are equal.
7656 if (ShiftAmt1 == ShiftAmt2) {
7657 // If we have ((X >>? C) << C), turn this into X & (-1 << C).
7658 if (I.getOpcode() == Instruction::Shl) {
7659 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Anderson24be4c12009-07-03 00:17:18 +00007660 return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007661 }
7662 // If we have ((X << C) >>u C), turn this into X & (-1 >>u C).
7663 if (I.getOpcode() == Instruction::LShr) {
7664 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt1));
Owen Anderson24be4c12009-07-03 00:17:18 +00007665 return BinaryOperator::CreateAnd(X, Context->getConstantInt(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007666 }
7667 // We can simplify ((X << C) >>s C) into a trunc + sext.
7668 // NOTE: we could do this for any C, but that would make 'unusual' integer
7669 // types. For now, just stick to ones well-supported by the code
7670 // generators.
7671 const Type *SExtType = 0;
7672 switch (Ty->getBitWidth() - ShiftAmt1) {
7673 case 1 :
7674 case 8 :
7675 case 16 :
7676 case 32 :
7677 case 64 :
7678 case 128:
Owen Anderson24be4c12009-07-03 00:17:18 +00007679 SExtType = Context->getIntegerType(Ty->getBitWidth() - ShiftAmt1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007680 break;
7681 default: break;
7682 }
7683 if (SExtType) {
7684 Instruction *NewTrunc = new TruncInst(X, SExtType, "sext");
7685 InsertNewInstBefore(NewTrunc, I);
7686 return new SExtInst(NewTrunc, Ty);
7687 }
7688 // Otherwise, we can't handle it yet.
7689 } else if (ShiftAmt1 < ShiftAmt2) {
7690 uint32_t ShiftDiff = ShiftAmt2-ShiftAmt1;
7691
7692 // (X >>? C1) << C2 --> X << (C2-C1) & (-1 << C2)
7693 if (I.getOpcode() == Instruction::Shl) {
7694 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7695 ShiftOp->getOpcode() == Instruction::AShr);
7696 Instruction *Shift =
Owen Anderson24be4c12009-07-03 00:17:18 +00007697 BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007698 InsertNewInstBefore(Shift, I);
7699
7700 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Anderson24be4c12009-07-03 00:17:18 +00007701 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007702 }
7703
7704 // (X << C1) >>u C2 --> X >>u (C2-C1) & (-1 >> C2)
7705 if (I.getOpcode() == Instruction::LShr) {
7706 assert(ShiftOp->getOpcode() == Instruction::Shl);
7707 Instruction *Shift =
Owen Anderson24be4c12009-07-03 00:17:18 +00007708 BinaryOperator::CreateLShr(X, Context->getConstantInt(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007709 InsertNewInstBefore(Shift, I);
7710
7711 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Anderson24be4c12009-07-03 00:17:18 +00007712 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007713 }
7714
7715 // We can't handle (X << C1) >>s C2, it shifts arbitrary bits in.
7716 } else {
7717 assert(ShiftAmt2 < ShiftAmt1);
7718 uint32_t ShiftDiff = ShiftAmt1-ShiftAmt2;
7719
7720 // (X >>? C1) << C2 --> X >>? (C1-C2) & (-1 << C2)
7721 if (I.getOpcode() == Instruction::Shl) {
7722 assert(ShiftOp->getOpcode() == Instruction::LShr ||
7723 ShiftOp->getOpcode() == Instruction::AShr);
7724 Instruction *Shift =
Gabor Greifa645dd32008-05-16 19:29:10 +00007725 BinaryOperator::Create(ShiftOp->getOpcode(), X,
Owen Anderson24be4c12009-07-03 00:17:18 +00007726 Context->getConstantInt(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007727 InsertNewInstBefore(Shift, I);
7728
7729 APInt Mask(APInt::getHighBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Anderson24be4c12009-07-03 00:17:18 +00007730 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007731 }
7732
7733 // (X << C1) >>u C2 --> X << (C1-C2) & (-1 >> C2)
7734 if (I.getOpcode() == Instruction::LShr) {
7735 assert(ShiftOp->getOpcode() == Instruction::Shl);
7736 Instruction *Shift =
Owen Anderson24be4c12009-07-03 00:17:18 +00007737 BinaryOperator::CreateShl(X, Context->getConstantInt(Ty, ShiftDiff));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007738 InsertNewInstBefore(Shift, I);
7739
7740 APInt Mask(APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt2));
Owen Anderson24be4c12009-07-03 00:17:18 +00007741 return BinaryOperator::CreateAnd(Shift, Context->getConstantInt(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007742 }
7743
7744 // We can't handle (X << C1) >>a C2, it shifts arbitrary bits in.
7745 }
7746 }
7747 return 0;
7748}
7749
7750
7751/// DecomposeSimpleLinearExpr - Analyze 'Val', seeing if it is a simple linear
7752/// expression. If so, decompose it, returning some value X, such that Val is
7753/// X*Scale+Offset.
7754///
7755static Value *DecomposeSimpleLinearExpr(Value *Val, unsigned &Scale,
Owen Anderson5349f052009-07-06 23:00:19 +00007756 int &Offset, LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007757 assert(Val->getType() == Type::Int32Ty && "Unexpected allocation size type!");
7758 if (ConstantInt *CI = dyn_cast<ConstantInt>(Val)) {
7759 Offset = CI->getZExtValue();
Chris Lattnerc59171a2007-10-12 05:30:59 +00007760 Scale = 0;
Owen Anderson24be4c12009-07-03 00:17:18 +00007761 return Context->getConstantInt(Type::Int32Ty, 0);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007762 } else if (BinaryOperator *I = dyn_cast<BinaryOperator>(Val)) {
7763 if (ConstantInt *RHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
7764 if (I->getOpcode() == Instruction::Shl) {
7765 // This is a value scaled by '1 << the shift amt'.
7766 Scale = 1U << RHS->getZExtValue();
7767 Offset = 0;
7768 return I->getOperand(0);
7769 } else if (I->getOpcode() == Instruction::Mul) {
7770 // This value is scaled by 'RHS'.
7771 Scale = RHS->getZExtValue();
7772 Offset = 0;
7773 return I->getOperand(0);
7774 } else if (I->getOpcode() == Instruction::Add) {
7775 // We have X+C. Check to see if we really have (X*C2)+C1,
7776 // where C1 is divisible by C2.
7777 unsigned SubScale;
7778 Value *SubVal =
Owen Anderson24be4c12009-07-03 00:17:18 +00007779 DecomposeSimpleLinearExpr(I->getOperand(0), SubScale,
7780 Offset, Context);
Chris Lattnerc59171a2007-10-12 05:30:59 +00007781 Offset += RHS->getZExtValue();
7782 Scale = SubScale;
7783 return SubVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007784 }
7785 }
7786 }
7787
7788 // Otherwise, we can't look past this.
7789 Scale = 1;
7790 Offset = 0;
7791 return Val;
7792}
7793
7794
7795/// PromoteCastOfAllocation - If we find a cast of an allocation instruction,
7796/// try to eliminate the cast by moving the type information into the alloc.
7797Instruction *InstCombiner::PromoteCastOfAllocation(BitCastInst &CI,
7798 AllocationInst &AI) {
7799 const PointerType *PTy = cast<PointerType>(CI.getType());
7800
7801 // Remove any uses of AI that are dead.
7802 assert(!CI.use_empty() && "Dead instructions should be removed earlier!");
7803
7804 for (Value::use_iterator UI = AI.use_begin(), E = AI.use_end(); UI != E; ) {
7805 Instruction *User = cast<Instruction>(*UI++);
7806 if (isInstructionTriviallyDead(User)) {
7807 while (UI != E && *UI == User)
7808 ++UI; // If this instruction uses AI more than once, don't break UI.
7809
7810 ++NumDeadInst;
7811 DOUT << "IC: DCE: " << *User;
7812 EraseInstFromFunction(*User);
7813 }
7814 }
7815
7816 // Get the type really allocated and the type casted to.
7817 const Type *AllocElTy = AI.getAllocatedType();
7818 const Type *CastElTy = PTy->getElementType();
7819 if (!AllocElTy->isSized() || !CastElTy->isSized()) return 0;
7820
7821 unsigned AllocElTyAlign = TD->getABITypeAlignment(AllocElTy);
7822 unsigned CastElTyAlign = TD->getABITypeAlignment(CastElTy);
7823 if (CastElTyAlign < AllocElTyAlign) return 0;
7824
7825 // If the allocation has multiple uses, only promote it if we are strictly
7826 // increasing the alignment of the resultant allocation. If we keep it the
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00007827 // same, we open the door to infinite loops of various kinds. (A reference
7828 // from a dbg.declare doesn't count as a use for this purpose.)
7829 if (!AI.hasOneUse() && !hasOneUsePlusDeclare(&AI) &&
7830 CastElTyAlign == AllocElTyAlign) return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007831
Duncan Sandsec4f97d2009-05-09 07:06:46 +00007832 uint64_t AllocElTySize = TD->getTypeAllocSize(AllocElTy);
7833 uint64_t CastElTySize = TD->getTypeAllocSize(CastElTy);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007834 if (CastElTySize == 0 || AllocElTySize == 0) return 0;
7835
7836 // See if we can satisfy the modulus by pulling a scale out of the array
7837 // size argument.
7838 unsigned ArraySizeScale;
7839 int ArrayOffset;
7840 Value *NumElements = // See if the array size is a decomposable linear expr.
Owen Anderson24be4c12009-07-03 00:17:18 +00007841 DecomposeSimpleLinearExpr(AI.getOperand(0), ArraySizeScale,
7842 ArrayOffset, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007843
7844 // If we can now satisfy the modulus, by using a non-1 scale, we really can
7845 // do the xform.
7846 if ((AllocElTySize*ArraySizeScale) % CastElTySize != 0 ||
7847 (AllocElTySize*ArrayOffset ) % CastElTySize != 0) return 0;
7848
7849 unsigned Scale = (AllocElTySize*ArraySizeScale)/CastElTySize;
7850 Value *Amt = 0;
7851 if (Scale == 1) {
7852 Amt = NumElements;
7853 } else {
7854 // If the allocation size is constant, form a constant mul expression
Owen Anderson24be4c12009-07-03 00:17:18 +00007855 Amt = Context->getConstantInt(Type::Int32Ty, Scale);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007856 if (isa<ConstantInt>(NumElements))
Owen Anderson24be4c12009-07-03 00:17:18 +00007857 Amt = Context->getConstantExprMul(cast<ConstantInt>(NumElements),
Dan Gohman8fd520a2009-06-15 22:12:54 +00007858 cast<ConstantInt>(Amt));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007859 // otherwise multiply the amount and the number of elements
Chris Lattner27cc5472009-03-17 17:55:15 +00007860 else {
Gabor Greifa645dd32008-05-16 19:29:10 +00007861 Instruction *Tmp = BinaryOperator::CreateMul(Amt, NumElements, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007862 Amt = InsertNewInstBefore(Tmp, AI);
7863 }
7864 }
7865
7866 if (int Offset = (AllocElTySize*ArrayOffset)/CastElTySize) {
Owen Anderson24be4c12009-07-03 00:17:18 +00007867 Value *Off = Context->getConstantInt(Type::Int32Ty, Offset, true);
Gabor Greifa645dd32008-05-16 19:29:10 +00007868 Instruction *Tmp = BinaryOperator::CreateAdd(Amt, Off, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007869 Amt = InsertNewInstBefore(Tmp, AI);
7870 }
7871
7872 AllocationInst *New;
7873 if (isa<MallocInst>(AI))
7874 New = new MallocInst(CastElTy, Amt, AI.getAlignment());
7875 else
7876 New = new AllocaInst(CastElTy, Amt, AI.getAlignment());
7877 InsertNewInstBefore(New, AI);
7878 New->takeName(&AI);
7879
Dale Johannesen1ef9dc12009-03-05 00:39:02 +00007880 // If the allocation has one real use plus a dbg.declare, just remove the
7881 // declare.
7882 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(&AI)) {
7883 EraseInstFromFunction(*DI);
7884 }
7885 // If the allocation has multiple real uses, insert a cast and change all
7886 // things that used it to use the new cast. This will also hack on CI, but it
7887 // will die soon.
7888 else if (!AI.hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007889 AddUsesToWorkList(AI);
7890 // New is the allocation instruction, pointer typed. AI is the original
7891 // allocation instruction, also pointer typed. Thus, cast to use is BitCast.
7892 CastInst *NewCast = new BitCastInst(New, AI.getType(), "tmpcast");
7893 InsertNewInstBefore(NewCast, AI);
7894 AI.replaceAllUsesWith(NewCast);
7895 }
7896 return ReplaceInstUsesWith(CI, New);
7897}
7898
7899/// CanEvaluateInDifferentType - Return true if we can take the specified value
7900/// and return it as type Ty without inserting any new casts and without
7901/// changing the computed value. This is used by code that tries to decide
7902/// whether promoting or shrinking integer operations to wider or smaller types
7903/// will allow us to eliminate a truncate or extend.
7904///
7905/// This is a truncation operation if Ty is smaller than V->getType(), or an
7906/// extension operation if Ty is larger.
Chris Lattner4200c2062008-06-18 04:00:49 +00007907///
7908/// If CastOpc is a truncation, then Ty will be a type smaller than V. We
7909/// should return true if trunc(V) can be computed by computing V in the smaller
7910/// type. If V is an instruction, then trunc(inst(x,y)) can be computed as
7911/// inst(trunc(x),trunc(y)), which only makes sense if x and y can be
7912/// efficiently truncated.
7913///
7914/// If CastOpc is a sext or zext, we are asking if the low bits of the value can
7915/// bit computed in a larger type, which is then and'd or sext_in_reg'd to get
7916/// the final result.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007917bool InstCombiner::CanEvaluateInDifferentType(Value *V, const Type *Ty,
Evan Cheng814a00c2009-01-16 02:11:43 +00007918 unsigned CastOpc,
7919 int &NumCastsRemoved){
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007920 // We can always evaluate constants in another type.
Dan Gohman8fd520a2009-06-15 22:12:54 +00007921 if (isa<Constant>(V))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007922 return true;
7923
7924 Instruction *I = dyn_cast<Instruction>(V);
7925 if (!I) return false;
7926
Dan Gohman8fd520a2009-06-15 22:12:54 +00007927 const Type *OrigTy = V->getType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007928
Chris Lattneref70bb82007-08-02 06:11:14 +00007929 // If this is an extension or truncate, we can often eliminate it.
7930 if (isa<TruncInst>(I) || isa<ZExtInst>(I) || isa<SExtInst>(I)) {
7931 // If this is a cast from the destination type, we can trivially eliminate
7932 // it, and this will remove a cast overall.
7933 if (I->getOperand(0)->getType() == Ty) {
7934 // If the first operand is itself a cast, and is eliminable, do not count
7935 // this as an eliminable cast. We would prefer to eliminate those two
7936 // casts first.
Chris Lattner4200c2062008-06-18 04:00:49 +00007937 if (!isa<CastInst>(I->getOperand(0)) && I->hasOneUse())
Chris Lattneref70bb82007-08-02 06:11:14 +00007938 ++NumCastsRemoved;
7939 return true;
7940 }
7941 }
7942
7943 // We can't extend or shrink something that has multiple uses: doing so would
7944 // require duplicating the instruction in general, which isn't profitable.
7945 if (!I->hasOneUse()) return false;
7946
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007947 unsigned Opc = I->getOpcode();
7948 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007949 case Instruction::Add:
7950 case Instruction::Sub:
Nick Lewycky1265a7d2008-07-05 21:19:34 +00007951 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007952 case Instruction::And:
7953 case Instruction::Or:
7954 case Instruction::Xor:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007955 // These operators can all arbitrarily be extended or truncated.
Chris Lattneref70bb82007-08-02 06:11:14 +00007956 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007957 NumCastsRemoved) &&
Chris Lattneref70bb82007-08-02 06:11:14 +00007958 CanEvaluateInDifferentType(I->getOperand(1), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007959 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007960
7961 case Instruction::Shl:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007962 // If we are truncating the result of this SHL, and if it's a shift of a
7963 // constant amount, we can always perform a SHL in a smaller type.
7964 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00007965 uint32_t BitWidth = Ty->getScalarSizeInBits();
7966 if (BitWidth < OrigTy->getScalarSizeInBits() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007967 CI->getLimitedValue(BitWidth) < BitWidth)
Chris Lattneref70bb82007-08-02 06:11:14 +00007968 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007969 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007970 }
7971 break;
7972 case Instruction::LShr:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007973 // If this is a truncate of a logical shr, we can truncate it to a smaller
7974 // lshr iff we know that the bits we would otherwise be shifting in are
7975 // already zeros.
7976 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00007977 uint32_t OrigBitWidth = OrigTy->getScalarSizeInBits();
7978 uint32_t BitWidth = Ty->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007979 if (BitWidth < OrigBitWidth &&
7980 MaskedValueIsZero(I->getOperand(0),
7981 APInt::getHighBitsSet(OrigBitWidth, OrigBitWidth-BitWidth)) &&
7982 CI->getLimitedValue(BitWidth) < BitWidth) {
Chris Lattneref70bb82007-08-02 06:11:14 +00007983 return CanEvaluateInDifferentType(I->getOperand(0), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00007984 NumCastsRemoved);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007985 }
7986 }
7987 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007988 case Instruction::ZExt:
7989 case Instruction::SExt:
Chris Lattneref70bb82007-08-02 06:11:14 +00007990 case Instruction::Trunc:
7991 // If this is the same kind of case as our original (e.g. zext+zext), we
Chris Lattner9c909d22007-08-02 17:23:38 +00007992 // can safely replace it. Note that replacing it does not reduce the number
7993 // of casts in the input.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00007994 if (Opc == CastOpc)
7995 return true;
7996
7997 // sext (zext ty1), ty2 -> zext ty2
Evan Cheng7bb0d952009-01-15 17:09:07 +00007998 if (CastOpc == Instruction::SExt && Opc == Instruction::ZExt)
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007999 return true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008000 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008001 case Instruction::Select: {
8002 SelectInst *SI = cast<SelectInst>(I);
8003 return CanEvaluateInDifferentType(SI->getTrueValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008004 NumCastsRemoved) &&
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008005 CanEvaluateInDifferentType(SI->getFalseValue(), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008006 NumCastsRemoved);
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008007 }
Chris Lattner4200c2062008-06-18 04:00:49 +00008008 case Instruction::PHI: {
8009 // We can change a phi if we can change all operands.
8010 PHINode *PN = cast<PHINode>(I);
8011 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
8012 if (!CanEvaluateInDifferentType(PN->getIncomingValue(i), Ty, CastOpc,
Evan Cheng814a00c2009-01-16 02:11:43 +00008013 NumCastsRemoved))
Chris Lattner4200c2062008-06-18 04:00:49 +00008014 return false;
8015 return true;
8016 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008017 default:
8018 // TODO: Can handle more cases here.
8019 break;
8020 }
8021
8022 return false;
8023}
8024
8025/// EvaluateInDifferentType - Given an expression that
8026/// CanEvaluateInDifferentType returns true for, actually insert the code to
8027/// evaluate the expression.
8028Value *InstCombiner::EvaluateInDifferentType(Value *V, const Type *Ty,
8029 bool isSigned) {
8030 if (Constant *C = dyn_cast<Constant>(V))
Owen Anderson24be4c12009-07-03 00:17:18 +00008031 return Context->getConstantExprIntegerCast(C, Ty,
8032 isSigned /*Sext or ZExt*/);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008033
8034 // Otherwise, it must be an instruction.
8035 Instruction *I = cast<Instruction>(V);
8036 Instruction *Res = 0;
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008037 unsigned Opc = I->getOpcode();
8038 switch (Opc) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008039 case Instruction::Add:
8040 case Instruction::Sub:
Nick Lewyckyc52646a2008-01-22 05:08:48 +00008041 case Instruction::Mul:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008042 case Instruction::And:
8043 case Instruction::Or:
8044 case Instruction::Xor:
8045 case Instruction::AShr:
8046 case Instruction::LShr:
8047 case Instruction::Shl: {
8048 Value *LHS = EvaluateInDifferentType(I->getOperand(0), Ty, isSigned);
8049 Value *RHS = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008050 Res = BinaryOperator::Create((Instruction::BinaryOps)Opc, LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008051 break;
8052 }
8053 case Instruction::Trunc:
8054 case Instruction::ZExt:
8055 case Instruction::SExt:
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008056 // If the source type of the cast is the type we're trying for then we can
Chris Lattneref70bb82007-08-02 06:11:14 +00008057 // just return the source. There's no need to insert it because it is not
8058 // new.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008059 if (I->getOperand(0)->getType() == Ty)
8060 return I->getOperand(0);
8061
Chris Lattner4200c2062008-06-18 04:00:49 +00008062 // Otherwise, must be the same type of cast, so just reinsert a new one.
Gabor Greifa645dd32008-05-16 19:29:10 +00008063 Res = CastInst::Create(cast<CastInst>(I)->getOpcode(), I->getOperand(0),
Chris Lattner4200c2062008-06-18 04:00:49 +00008064 Ty);
Chris Lattneref70bb82007-08-02 06:11:14 +00008065 break;
Nick Lewycky1265a7d2008-07-05 21:19:34 +00008066 case Instruction::Select: {
8067 Value *True = EvaluateInDifferentType(I->getOperand(1), Ty, isSigned);
8068 Value *False = EvaluateInDifferentType(I->getOperand(2), Ty, isSigned);
8069 Res = SelectInst::Create(I->getOperand(0), True, False);
8070 break;
8071 }
Chris Lattner4200c2062008-06-18 04:00:49 +00008072 case Instruction::PHI: {
8073 PHINode *OPN = cast<PHINode>(I);
8074 PHINode *NPN = PHINode::Create(Ty);
8075 for (unsigned i = 0, e = OPN->getNumIncomingValues(); i != e; ++i) {
8076 Value *V =EvaluateInDifferentType(OPN->getIncomingValue(i), Ty, isSigned);
8077 NPN->addIncoming(V, OPN->getIncomingBlock(i));
8078 }
8079 Res = NPN;
8080 break;
8081 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008082 default:
8083 // TODO: Can handle more cases here.
8084 assert(0 && "Unreachable!");
8085 break;
8086 }
8087
Chris Lattner4200c2062008-06-18 04:00:49 +00008088 Res->takeName(I);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008089 return InsertNewInstBefore(Res, *I);
8090}
8091
8092/// @brief Implement the transforms common to all CastInst visitors.
8093Instruction *InstCombiner::commonCastTransforms(CastInst &CI) {
8094 Value *Src = CI.getOperand(0);
8095
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008096 // Many cases of "cast of a cast" are eliminable. If it's eliminable we just
8097 // eliminate it now.
8098 if (CastInst *CSrc = dyn_cast<CastInst>(Src)) { // A->B->C cast
8099 if (Instruction::CastOps opc =
8100 isEliminableCastPair(CSrc, CI.getOpcode(), CI.getType(), TD)) {
8101 // The first cast (CSrc) is eliminable so we need to fix up or replace
8102 // the second cast (CI). CSrc will then have a good chance of being dead.
Gabor Greifa645dd32008-05-16 19:29:10 +00008103 return CastInst::Create(opc, CSrc->getOperand(0), CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008104 }
8105 }
8106
8107 // If we are casting a select then fold the cast into the select
8108 if (SelectInst *SI = dyn_cast<SelectInst>(Src))
8109 if (Instruction *NV = FoldOpIntoSelect(CI, SI, this))
8110 return NV;
8111
8112 // If we are casting a PHI then fold the cast into the PHI
8113 if (isa<PHINode>(Src))
8114 if (Instruction *NV = FoldOpIntoPhi(CI))
8115 return NV;
8116
8117 return 0;
8118}
8119
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008120/// FindElementAtOffset - Given a type and a constant offset, determine whether
8121/// or not there is a sequence of GEP indices into the type that will land us at
Chris Lattner54dddc72009-01-24 01:00:13 +00008122/// the specified offset. If so, fill them into NewIndices and return the
8123/// resultant element type, otherwise return null.
8124static const Type *FindElementAtOffset(const Type *Ty, int64_t Offset,
8125 SmallVectorImpl<Value*> &NewIndices,
Owen Anderson24be4c12009-07-03 00:17:18 +00008126 const TargetData *TD,
Owen Anderson5349f052009-07-06 23:00:19 +00008127 LLVMContext *Context) {
Chris Lattner54dddc72009-01-24 01:00:13 +00008128 if (!Ty->isSized()) return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008129
8130 // Start with the index over the outer type. Note that the type size
8131 // might be zero (even if the offset isn't zero) if the indexed type
8132 // is something like [0 x {int, int}]
8133 const Type *IntPtrTy = TD->getIntPtrType();
8134 int64_t FirstIdx = 0;
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008135 if (int64_t TySize = TD->getTypeAllocSize(Ty)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008136 FirstIdx = Offset/TySize;
Chris Lattner0bd6f2b2009-01-11 20:41:36 +00008137 Offset -= FirstIdx*TySize;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008138
Chris Lattnerce48c462009-01-11 20:15:20 +00008139 // Handle hosts where % returns negative instead of values [0..TySize).
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008140 if (Offset < 0) {
8141 --FirstIdx;
8142 Offset += TySize;
8143 assert(Offset >= 0);
8144 }
8145 assert((uint64_t)Offset < (uint64_t)TySize && "Out of range offset");
8146 }
8147
Owen Anderson24be4c12009-07-03 00:17:18 +00008148 NewIndices.push_back(Context->getConstantInt(IntPtrTy, FirstIdx));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008149
8150 // Index into the types. If we fail, set OrigBase to null.
8151 while (Offset) {
Chris Lattnerce48c462009-01-11 20:15:20 +00008152 // Indexing into tail padding between struct/array elements.
8153 if (uint64_t(Offset*8) >= TD->getTypeSizeInBits(Ty))
Chris Lattner54dddc72009-01-24 01:00:13 +00008154 return 0;
Chris Lattnerce48c462009-01-11 20:15:20 +00008155
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008156 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
8157 const StructLayout *SL = TD->getStructLayout(STy);
Chris Lattnerce48c462009-01-11 20:15:20 +00008158 assert(Offset < (int64_t)SL->getSizeInBytes() &&
8159 "Offset must stay within the indexed type");
8160
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008161 unsigned Elt = SL->getElementContainingOffset(Offset);
Owen Anderson24be4c12009-07-03 00:17:18 +00008162 NewIndices.push_back(Context->getConstantInt(Type::Int32Ty, Elt));
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008163
8164 Offset -= SL->getElementOffset(Elt);
8165 Ty = STy->getElementType(Elt);
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00008166 } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008167 uint64_t EltSize = TD->getTypeAllocSize(AT->getElementType());
Chris Lattnerce48c462009-01-11 20:15:20 +00008168 assert(EltSize && "Cannot index into a zero-sized array");
Owen Anderson24be4c12009-07-03 00:17:18 +00008169 NewIndices.push_back(Context->getConstantInt(IntPtrTy,Offset/EltSize));
Chris Lattnerce48c462009-01-11 20:15:20 +00008170 Offset %= EltSize;
Chris Lattnerd35ce6a2009-01-11 20:23:52 +00008171 Ty = AT->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008172 } else {
Chris Lattnerce48c462009-01-11 20:15:20 +00008173 // Otherwise, we can't index into the middle of this atomic type, bail.
Chris Lattner54dddc72009-01-24 01:00:13 +00008174 return 0;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008175 }
8176 }
8177
Chris Lattner54dddc72009-01-24 01:00:13 +00008178 return Ty;
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008179}
8180
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008181/// @brief Implement the transforms for cast of pointer (bitcast/ptrtoint)
8182Instruction *InstCombiner::commonPointerCastTransforms(CastInst &CI) {
8183 Value *Src = CI.getOperand(0);
8184
8185 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Src)) {
8186 // If casting the result of a getelementptr instruction with no offset, turn
8187 // this into a cast of the original pointer!
8188 if (GEP->hasAllZeroIndices()) {
8189 // Changing the cast operand is usually not a good idea but it is safe
8190 // here because the pointer operand is being replaced with another
8191 // pointer operand so the opcode doesn't need to change.
8192 AddToWorkList(GEP);
8193 CI.setOperand(0, GEP->getOperand(0));
8194 return &CI;
8195 }
8196
8197 // If the GEP has a single use, and the base pointer is a bitcast, and the
8198 // GEP computes a constant offset, see if we can convert these three
8199 // instructions into fewer. This typically happens with unions and other
8200 // non-type-safe code.
8201 if (GEP->hasOneUse() && isa<BitCastInst>(GEP->getOperand(0))) {
8202 if (GEP->hasAllConstantIndices()) {
8203 // We are guaranteed to get a constant from EmitGEPOffset.
Owen Anderson24be4c12009-07-03 00:17:18 +00008204 ConstantInt *OffsetV =
8205 cast<ConstantInt>(EmitGEPOffset(GEP, CI, *this));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008206 int64_t Offset = OffsetV->getSExtValue();
8207
8208 // Get the base pointer input of the bitcast, and the type it points to.
8209 Value *OrigBase = cast<BitCastInst>(GEP->getOperand(0))->getOperand(0);
8210 const Type *GEPIdxTy =
8211 cast<PointerType>(OrigBase->getType())->getElementType();
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008212 SmallVector<Value*, 8> NewIndices;
Owen Anderson24be4c12009-07-03 00:17:18 +00008213 if (FindElementAtOffset(GEPIdxTy, Offset, NewIndices, TD, Context)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008214 // If we were able to index down into an element, create the GEP
8215 // and bitcast the result. This eliminates one bitcast, potentially
8216 // two.
8217 Instruction *NGEP = GetElementPtrInst::Create(OrigBase,
8218 NewIndices.begin(),
8219 NewIndices.end(), "");
8220 InsertNewInstBefore(NGEP, CI);
8221 NGEP->takeName(GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008222
Chris Lattner94ccd5f2009-01-09 05:44:56 +00008223 if (isa<BitCastInst>(CI))
8224 return new BitCastInst(NGEP, CI.getType());
8225 assert(isa<PtrToIntInst>(CI));
8226 return new PtrToIntInst(NGEP, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008227 }
8228 }
8229 }
8230 }
8231
8232 return commonCastTransforms(CI);
8233}
8234
Chris Lattner8d8ce9b2009-04-08 05:41:03 +00008235/// isSafeIntegerType - Return true if this is a basic integer type, not a crazy
8236/// type like i42. We don't want to introduce operations on random non-legal
8237/// integer types where they don't already exist in the code. In the future,
8238/// we should consider making this based off target-data, so that 32-bit targets
8239/// won't get i64 operations etc.
8240static bool isSafeIntegerType(const Type *Ty) {
8241 switch (Ty->getPrimitiveSizeInBits()) {
8242 case 8:
8243 case 16:
8244 case 32:
8245 case 64:
8246 return true;
8247 default:
8248 return false;
8249 }
8250}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008251
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008252/// Only the TRUNC, ZEXT, SEXT, and BITCAST can both operand and result as
8253/// integer types. This function implements the common transforms for all those
8254/// cases.
8255/// @brief Implement the transforms common to CastInst with integer operands
8256Instruction *InstCombiner::commonIntCastTransforms(CastInst &CI) {
8257 if (Instruction *Result = commonCastTransforms(CI))
8258 return Result;
8259
8260 Value *Src = CI.getOperand(0);
8261 const Type *SrcTy = Src->getType();
8262 const Type *DestTy = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00008263 uint32_t SrcBitSize = SrcTy->getScalarSizeInBits();
8264 uint32_t DestBitSize = DestTy->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008265
8266 // See if we can simplify any instructions used by the LHS whose sole
8267 // purpose is to compute bits we don't care about.
Chris Lattner676c78e2009-01-31 08:15:18 +00008268 if (SimplifyDemandedInstructionBits(CI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008269 return &CI;
8270
8271 // If the source isn't an instruction or has more than one use then we
8272 // can't do anything more.
8273 Instruction *SrcI = dyn_cast<Instruction>(Src);
8274 if (!SrcI || !Src->hasOneUse())
8275 return 0;
8276
8277 // Attempt to propagate the cast into the instruction for int->int casts.
8278 int NumCastsRemoved = 0;
8279 if (!isa<BitCastInst>(CI) &&
Chris Lattner8d8ce9b2009-04-08 05:41:03 +00008280 // Only do this if the dest type is a simple type, don't convert the
8281 // expression tree to something weird like i93 unless the source is also
8282 // strange.
Dan Gohman8fd520a2009-06-15 22:12:54 +00008283 (isSafeIntegerType(DestTy->getScalarType()) ||
8284 !isSafeIntegerType(SrcI->getType()->getScalarType())) &&
8285 CanEvaluateInDifferentType(SrcI, DestTy,
Evan Cheng814a00c2009-01-16 02:11:43 +00008286 CI.getOpcode(), NumCastsRemoved)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008287 // If this cast is a truncate, evaluting in a different type always
Chris Lattneref70bb82007-08-02 06:11:14 +00008288 // eliminates the cast, so it is always a win. If this is a zero-extension,
8289 // we need to do an AND to maintain the clear top-part of the computation,
8290 // so we require that the input have eliminated at least one cast. If this
8291 // is a sign extension, we insert two new casts (to do the extension) so we
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008292 // require that two casts have been eliminated.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008293 bool DoXForm = false;
8294 bool JustReplace = false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008295 switch (CI.getOpcode()) {
8296 default:
8297 // All the others use floating point so we shouldn't actually
8298 // get here because of the check above.
8299 assert(0 && "Unknown cast type");
8300 case Instruction::Trunc:
8301 DoXForm = true;
8302 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00008303 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008304 DoXForm = NumCastsRemoved >= 1;
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008305 if (!DoXForm && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00008306 // If it's unnecessary to issue an AND to clear the high bits, it's
8307 // always profitable to do this xform.
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008308 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, false);
Evan Cheng814a00c2009-01-16 02:11:43 +00008309 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8310 if (MaskedValueIsZero(TryRes, Mask))
8311 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008312
8313 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00008314 if (TryI->use_empty())
8315 EraseInstFromFunction(*TryI);
8316 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008317 break;
Evan Cheng814a00c2009-01-16 02:11:43 +00008318 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008319 case Instruction::SExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008320 DoXForm = NumCastsRemoved >= 2;
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008321 if (!DoXForm && !isa<TruncInst>(SrcI) && 0) {
Evan Cheng814a00c2009-01-16 02:11:43 +00008322 // If we do not have to emit the truncate + sext pair, then it's always
8323 // profitable to do this xform.
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008324 //
8325 // It's not safe to eliminate the trunc + sext pair if one of the
8326 // eliminated cast is a truncate. e.g.
8327 // t2 = trunc i32 t1 to i16
8328 // t3 = sext i16 t2 to i32
8329 // !=
8330 // i32 t1
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008331 Value *TryRes = EvaluateInDifferentType(SrcI, DestTy, true);
Evan Cheng814a00c2009-01-16 02:11:43 +00008332 unsigned NumSignBits = ComputeNumSignBits(TryRes);
8333 if (NumSignBits > (DestBitSize - SrcBitSize))
8334 return ReplaceInstUsesWith(CI, TryRes);
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008335
8336 if (Instruction *TryI = dyn_cast<Instruction>(TryRes))
Evan Cheng814a00c2009-01-16 02:11:43 +00008337 if (TryI->use_empty())
8338 EraseInstFromFunction(*TryI);
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008339 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008340 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008341 }
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008342 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008343
8344 if (DoXForm) {
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008345 DOUT << "ICE: EvaluateInDifferentType converting expression type to avoid"
8346 << " cast: " << CI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008347 Value *Res = EvaluateInDifferentType(SrcI, DestTy,
8348 CI.getOpcode() == Instruction::SExt);
Evan Cheng814a00c2009-01-16 02:11:43 +00008349 if (JustReplace)
Chris Lattner3c0e6f42009-01-31 19:05:27 +00008350 // Just replace this cast with the result.
8351 return ReplaceInstUsesWith(CI, Res);
Evan Cheng814a00c2009-01-16 02:11:43 +00008352
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008353 assert(Res->getType() == DestTy);
8354 switch (CI.getOpcode()) {
8355 default: assert(0 && "Unknown cast type!");
8356 case Instruction::Trunc:
8357 case Instruction::BitCast:
8358 // Just replace this cast with the result.
8359 return ReplaceInstUsesWith(CI, Res);
8360 case Instruction::ZExt: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008361 assert(SrcBitSize < DestBitSize && "Not a zext?");
Evan Cheng814a00c2009-01-16 02:11:43 +00008362
8363 // If the high bits are already zero, just replace this cast with the
8364 // result.
8365 APInt Mask(APInt::getBitsSet(DestBitSize, SrcBitSize, DestBitSize));
8366 if (MaskedValueIsZero(Res, Mask))
8367 return ReplaceInstUsesWith(CI, Res);
8368
8369 // We need to emit an AND to clear the high bits.
Owen Anderson24be4c12009-07-03 00:17:18 +00008370 Constant *C = Context->getConstantInt(APInt::getLowBitsSet(DestBitSize,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008371 SrcBitSize));
Gabor Greifa645dd32008-05-16 19:29:10 +00008372 return BinaryOperator::CreateAnd(Res, C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008373 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008374 case Instruction::SExt: {
8375 // If the high bits are already filled with sign bit, just replace this
8376 // cast with the result.
8377 unsigned NumSignBits = ComputeNumSignBits(Res);
8378 if (NumSignBits > (DestBitSize - SrcBitSize))
Evan Cheng9ca34ab2009-01-15 17:01:23 +00008379 return ReplaceInstUsesWith(CI, Res);
8380
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008381 // We need to emit a cast to truncate, then a cast to sext.
Gabor Greifa645dd32008-05-16 19:29:10 +00008382 return CastInst::Create(Instruction::SExt,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008383 InsertCastBefore(Instruction::Trunc, Res, Src->getType(),
8384 CI), DestTy);
8385 }
Evan Cheng814a00c2009-01-16 02:11:43 +00008386 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008387 }
8388 }
8389
8390 Value *Op0 = SrcI->getNumOperands() > 0 ? SrcI->getOperand(0) : 0;
8391 Value *Op1 = SrcI->getNumOperands() > 1 ? SrcI->getOperand(1) : 0;
8392
8393 switch (SrcI->getOpcode()) {
8394 case Instruction::Add:
8395 case Instruction::Mul:
8396 case Instruction::And:
8397 case Instruction::Or:
8398 case Instruction::Xor:
8399 // If we are discarding information, rewrite.
8400 if (DestBitSize <= SrcBitSize && DestBitSize != 1) {
8401 // Don't insert two casts if they cannot be eliminated. We allow
8402 // two casts to be inserted if the sizes are the same. This could
8403 // only be converting signedness, which is a noop.
8404 if (DestBitSize == SrcBitSize ||
8405 !ValueRequiresCast(CI.getOpcode(), Op1, DestTy,TD) ||
8406 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
8407 Instruction::CastOps opcode = CI.getOpcode();
Eli Friedman722b4792008-11-30 21:09:11 +00008408 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8409 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008410 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008411 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8412 }
8413 }
8414
8415 // cast (xor bool X, true) to int --> xor (cast bool X to int), 1
8416 if (isa<ZExtInst>(CI) && SrcBitSize == 1 &&
8417 SrcI->getOpcode() == Instruction::Xor &&
Owen Anderson24be4c12009-07-03 00:17:18 +00008418 Op1 == Context->getConstantIntTrue() &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008419 (!Op0->hasOneUse() || !isa<CmpInst>(Op0))) {
Eli Friedman722b4792008-11-30 21:09:11 +00008420 Value *New = InsertCastBefore(Instruction::ZExt, Op0, DestTy, CI);
Owen Anderson24be4c12009-07-03 00:17:18 +00008421 return BinaryOperator::CreateXor(New,
8422 Context->getConstantInt(CI.getType(), 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008423 }
8424 break;
8425 case Instruction::SDiv:
8426 case Instruction::UDiv:
8427 case Instruction::SRem:
8428 case Instruction::URem:
8429 // If we are just changing the sign, rewrite.
8430 if (DestBitSize == SrcBitSize) {
8431 // Don't insert two casts if they cannot be eliminated. We allow
8432 // two casts to be inserted if the sizes are the same. This could
8433 // only be converting signedness, which is a noop.
8434 if (!ValueRequiresCast(CI.getOpcode(), Op1, DestTy, TD) ||
8435 !ValueRequiresCast(CI.getOpcode(), Op0, DestTy, TD)) {
Eli Friedman722b4792008-11-30 21:09:11 +00008436 Value *Op0c = InsertCastBefore(Instruction::BitCast,
8437 Op0, DestTy, *SrcI);
8438 Value *Op1c = InsertCastBefore(Instruction::BitCast,
8439 Op1, DestTy, *SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008440 return BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008441 cast<BinaryOperator>(SrcI)->getOpcode(), Op0c, Op1c);
8442 }
8443 }
8444 break;
8445
8446 case Instruction::Shl:
8447 // Allow changing the sign of the source operand. Do not allow
8448 // changing the size of the shift, UNLESS the shift amount is a
8449 // constant. We must not change variable sized shifts to a smaller
8450 // size, because it is undefined to shift more bits out than exist
8451 // in the value.
8452 if (DestBitSize == SrcBitSize ||
8453 (DestBitSize < SrcBitSize && isa<Constant>(Op1))) {
8454 Instruction::CastOps opcode = (DestBitSize == SrcBitSize ?
8455 Instruction::BitCast : Instruction::Trunc);
Eli Friedman722b4792008-11-30 21:09:11 +00008456 Value *Op0c = InsertCastBefore(opcode, Op0, DestTy, *SrcI);
8457 Value *Op1c = InsertCastBefore(opcode, Op1, DestTy, *SrcI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008458 return BinaryOperator::CreateShl(Op0c, Op1c);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008459 }
8460 break;
8461 case Instruction::AShr:
8462 // If this is a signed shr, and if all bits shifted in are about to be
8463 // truncated off, turn it into an unsigned shr to allow greater
8464 // simplifications.
8465 if (DestBitSize < SrcBitSize &&
8466 isa<ConstantInt>(Op1)) {
8467 uint32_t ShiftAmt = cast<ConstantInt>(Op1)->getLimitedValue(SrcBitSize);
8468 if (SrcBitSize > ShiftAmt && SrcBitSize-ShiftAmt >= DestBitSize) {
8469 // Insert the new logical shift right.
Gabor Greifa645dd32008-05-16 19:29:10 +00008470 return BinaryOperator::CreateLShr(Op0, Op1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008471 }
8472 }
8473 break;
8474 }
8475 return 0;
8476}
8477
8478Instruction *InstCombiner::visitTrunc(TruncInst &CI) {
8479 if (Instruction *Result = commonIntCastTransforms(CI))
8480 return Result;
8481
8482 Value *Src = CI.getOperand(0);
8483 const Type *Ty = CI.getType();
Dan Gohman8fd520a2009-06-15 22:12:54 +00008484 uint32_t DestBitWidth = Ty->getScalarSizeInBits();
8485 uint32_t SrcBitWidth = Src->getType()->getScalarSizeInBits();
Chris Lattner32177f82009-03-24 18:15:30 +00008486
8487 // Canonicalize trunc x to i1 -> (icmp ne (and x, 1), 0)
Dan Gohman2526aea2009-06-16 19:55:29 +00008488 if (DestBitWidth == 1 &&
8489 isa<VectorType>(Ty) == isa<VectorType>(Src->getType())) {
Owen Anderson24be4c12009-07-03 00:17:18 +00008490 Constant *One = Context->getConstantInt(Src->getType(), 1);
Chris Lattner32177f82009-03-24 18:15:30 +00008491 Src = InsertNewInstBefore(BinaryOperator::CreateAnd(Src, One, "tmp"), CI);
Owen Anderson24be4c12009-07-03 00:17:18 +00008492 Value *Zero = Context->getNullValue(Src->getType());
Owen Anderson6601fcd2009-07-09 23:48:35 +00008493 return new ICmpInst(*Context, ICmpInst::ICMP_NE, Src, Zero);
Chris Lattner32177f82009-03-24 18:15:30 +00008494 }
Dan Gohman8fd520a2009-06-15 22:12:54 +00008495
Chris Lattner32177f82009-03-24 18:15:30 +00008496 // Optimize trunc(lshr(), c) to pull the shift through the truncate.
8497 ConstantInt *ShAmtV = 0;
8498 Value *ShiftOp = 0;
8499 if (Src->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00008500 match(Src, m_LShr(m_Value(ShiftOp), m_ConstantInt(ShAmtV)), *Context)) {
Chris Lattner32177f82009-03-24 18:15:30 +00008501 uint32_t ShAmt = ShAmtV->getLimitedValue(SrcBitWidth);
8502
8503 // Get a mask for the bits shifting in.
8504 APInt Mask(APInt::getLowBitsSet(SrcBitWidth, ShAmt).shl(DestBitWidth));
8505 if (MaskedValueIsZero(ShiftOp, Mask)) {
8506 if (ShAmt >= DestBitWidth) // All zeros.
Owen Anderson24be4c12009-07-03 00:17:18 +00008507 return ReplaceInstUsesWith(CI, Context->getNullValue(Ty));
Chris Lattner32177f82009-03-24 18:15:30 +00008508
8509 // Okay, we can shrink this. Truncate the input, then return a new
8510 // shift.
8511 Value *V1 = InsertCastBefore(Instruction::Trunc, ShiftOp, Ty, CI);
Owen Anderson24be4c12009-07-03 00:17:18 +00008512 Value *V2 = Context->getConstantExprTrunc(ShAmtV, Ty);
Chris Lattner32177f82009-03-24 18:15:30 +00008513 return BinaryOperator::CreateLShr(V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008514 }
8515 }
8516
8517 return 0;
8518}
8519
Evan Chenge3779cf2008-03-24 00:21:34 +00008520/// transformZExtICmp - Transform (zext icmp) to bitwise / integer operations
8521/// in order to eliminate the icmp.
8522Instruction *InstCombiner::transformZExtICmp(ICmpInst *ICI, Instruction &CI,
8523 bool DoXform) {
8524 // If we are just checking for a icmp eq of a single bit and zext'ing it
8525 // to an integer, then shift the bit to the appropriate place and then
8526 // cast to integer to avoid the comparison.
8527 if (ConstantInt *Op1C = dyn_cast<ConstantInt>(ICI->getOperand(1))) {
8528 const APInt &Op1CV = Op1C->getValue();
8529
8530 // zext (x <s 0) to i32 --> x>>u31 true if signbit set.
8531 // zext (x >s -1) to i32 --> (x>>u31)^1 true if signbit clear.
8532 if ((ICI->getPredicate() == ICmpInst::ICMP_SLT && Op1CV == 0) ||
8533 (ICI->getPredicate() == ICmpInst::ICMP_SGT &&Op1CV.isAllOnesValue())) {
8534 if (!DoXform) return ICI;
8535
8536 Value *In = ICI->getOperand(0);
Owen Anderson24be4c12009-07-03 00:17:18 +00008537 Value *Sh = Context->getConstantInt(In->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008538 In->getType()->getScalarSizeInBits()-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008539 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In, Sh,
Evan Chenge3779cf2008-03-24 00:21:34 +00008540 In->getName()+".lobit"),
8541 CI);
8542 if (In->getType() != CI.getType())
Gabor Greifa645dd32008-05-16 19:29:10 +00008543 In = CastInst::CreateIntegerCast(In, CI.getType(),
Evan Chenge3779cf2008-03-24 00:21:34 +00008544 false/*ZExt*/, "tmp", &CI);
8545
8546 if (ICI->getPredicate() == ICmpInst::ICMP_SGT) {
Owen Anderson24be4c12009-07-03 00:17:18 +00008547 Constant *One = Context->getConstantInt(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008548 In = InsertNewInstBefore(BinaryOperator::CreateXor(In, One,
Evan Chenge3779cf2008-03-24 00:21:34 +00008549 In->getName()+".not"),
8550 CI);
8551 }
8552
8553 return ReplaceInstUsesWith(CI, In);
8554 }
8555
8556
8557
8558 // zext (X == 0) to i32 --> X^1 iff X has only the low bit set.
8559 // zext (X == 0) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8560 // zext (X == 1) to i32 --> X iff X has only the low bit set.
8561 // zext (X == 2) to i32 --> X>>1 iff X has only the 2nd bit set.
8562 // zext (X != 0) to i32 --> X iff X has only the low bit set.
8563 // zext (X != 0) to i32 --> X>>1 iff X has only the 2nd bit set.
8564 // zext (X != 1) to i32 --> X^1 iff X has only the low bit set.
8565 // zext (X != 2) to i32 --> (X>>1)^1 iff X has only the 2nd bit set.
8566 if ((Op1CV == 0 || Op1CV.isPowerOf2()) &&
8567 // This only works for EQ and NE
8568 ICI->isEquality()) {
8569 // If Op1C some other power of two, convert:
8570 uint32_t BitWidth = Op1C->getType()->getBitWidth();
8571 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
8572 APInt TypeMask(APInt::getAllOnesValue(BitWidth));
8573 ComputeMaskedBits(ICI->getOperand(0), TypeMask, KnownZero, KnownOne);
8574
8575 APInt KnownZeroMask(~KnownZero);
8576 if (KnownZeroMask.isPowerOf2()) { // Exactly 1 possible 1?
8577 if (!DoXform) return ICI;
8578
8579 bool isNE = ICI->getPredicate() == ICmpInst::ICMP_NE;
8580 if (Op1CV != 0 && (Op1CV != KnownZeroMask)) {
8581 // (X&4) == 2 --> false
8582 // (X&4) != 2 --> true
Owen Anderson24be4c12009-07-03 00:17:18 +00008583 Constant *Res = Context->getConstantInt(Type::Int1Ty, isNE);
8584 Res = Context->getConstantExprZExt(Res, CI.getType());
Evan Chenge3779cf2008-03-24 00:21:34 +00008585 return ReplaceInstUsesWith(CI, Res);
8586 }
8587
8588 uint32_t ShiftAmt = KnownZeroMask.logBase2();
8589 Value *In = ICI->getOperand(0);
8590 if (ShiftAmt) {
8591 // Perform a logical shr by shiftamt.
8592 // Insert the shift to put the result in the low bit.
Gabor Greifa645dd32008-05-16 19:29:10 +00008593 In = InsertNewInstBefore(BinaryOperator::CreateLShr(In,
Owen Anderson24be4c12009-07-03 00:17:18 +00008594 Context->getConstantInt(In->getType(), ShiftAmt),
Evan Chenge3779cf2008-03-24 00:21:34 +00008595 In->getName()+".lobit"), CI);
8596 }
8597
8598 if ((Op1CV != 0) == isNE) { // Toggle the low bit.
Owen Anderson24be4c12009-07-03 00:17:18 +00008599 Constant *One = Context->getConstantInt(In->getType(), 1);
Gabor Greifa645dd32008-05-16 19:29:10 +00008600 In = BinaryOperator::CreateXor(In, One, "tmp");
Evan Chenge3779cf2008-03-24 00:21:34 +00008601 InsertNewInstBefore(cast<Instruction>(In), CI);
8602 }
8603
8604 if (CI.getType() == In->getType())
8605 return ReplaceInstUsesWith(CI, In);
8606 else
Gabor Greifa645dd32008-05-16 19:29:10 +00008607 return CastInst::CreateIntegerCast(In, CI.getType(), false/*ZExt*/);
Evan Chenge3779cf2008-03-24 00:21:34 +00008608 }
8609 }
8610 }
8611
8612 return 0;
8613}
8614
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008615Instruction *InstCombiner::visitZExt(ZExtInst &CI) {
8616 // If one of the common conversion will work ..
8617 if (Instruction *Result = commonIntCastTransforms(CI))
8618 return Result;
8619
8620 Value *Src = CI.getOperand(0);
8621
Chris Lattner215d56e2009-02-17 20:47:23 +00008622 // If this is a TRUNC followed by a ZEXT then we are dealing with integral
8623 // types and if the sizes are just right we can convert this into a logical
8624 // 'and' which will be much cheaper than the pair of casts.
8625 if (TruncInst *CSrc = dyn_cast<TruncInst>(Src)) { // A->B->C cast
8626 // Get the sizes of the types involved. We know that the intermediate type
8627 // will be smaller than A or C, but don't know the relation between A and C.
8628 Value *A = CSrc->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00008629 unsigned SrcSize = A->getType()->getScalarSizeInBits();
8630 unsigned MidSize = CSrc->getType()->getScalarSizeInBits();
8631 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner215d56e2009-02-17 20:47:23 +00008632 // If we're actually extending zero bits, then if
8633 // SrcSize < DstSize: zext(a & mask)
8634 // SrcSize == DstSize: a & mask
8635 // SrcSize > DstSize: trunc(a) & mask
8636 if (SrcSize < DstSize) {
8637 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Anderson24be4c12009-07-03 00:17:18 +00008638 Constant *AndConst = Context->getConstantInt(A->getType(), AndValue);
Chris Lattner215d56e2009-02-17 20:47:23 +00008639 Instruction *And =
8640 BinaryOperator::CreateAnd(A, AndConst, CSrc->getName()+".mask");
8641 InsertNewInstBefore(And, CI);
8642 return new ZExtInst(And, CI.getType());
8643 } else if (SrcSize == DstSize) {
8644 APInt AndValue(APInt::getLowBitsSet(SrcSize, MidSize));
Owen Anderson24be4c12009-07-03 00:17:18 +00008645 return BinaryOperator::CreateAnd(A, Context->getConstantInt(A->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008646 AndValue));
Chris Lattner215d56e2009-02-17 20:47:23 +00008647 } else if (SrcSize > DstSize) {
8648 Instruction *Trunc = new TruncInst(A, CI.getType(), "tmp");
8649 InsertNewInstBefore(Trunc, CI);
8650 APInt AndValue(APInt::getLowBitsSet(DstSize, MidSize));
Owen Anderson24be4c12009-07-03 00:17:18 +00008651 return BinaryOperator::CreateAnd(Trunc,
8652 Context->getConstantInt(Trunc->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00008653 AndValue));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008654 }
8655 }
8656
Evan Chenge3779cf2008-03-24 00:21:34 +00008657 if (ICmpInst *ICI = dyn_cast<ICmpInst>(Src))
8658 return transformZExtICmp(ICI, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008659
Evan Chenge3779cf2008-03-24 00:21:34 +00008660 BinaryOperator *SrcI = dyn_cast<BinaryOperator>(Src);
8661 if (SrcI && SrcI->getOpcode() == Instruction::Or) {
8662 // zext (or icmp, icmp) --> or (zext icmp), (zext icmp) if at least one
8663 // of the (zext icmp) will be transformed.
8664 ICmpInst *LHS = dyn_cast<ICmpInst>(SrcI->getOperand(0));
8665 ICmpInst *RHS = dyn_cast<ICmpInst>(SrcI->getOperand(1));
8666 if (LHS && RHS && LHS->hasOneUse() && RHS->hasOneUse() &&
8667 (transformZExtICmp(LHS, CI, false) ||
8668 transformZExtICmp(RHS, CI, false))) {
8669 Value *LCast = InsertCastBefore(Instruction::ZExt, LHS, CI.getType(), CI);
8670 Value *RCast = InsertCastBefore(Instruction::ZExt, RHS, CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008671 return BinaryOperator::Create(Instruction::Or, LCast, RCast);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008672 }
Evan Chenge3779cf2008-03-24 00:21:34 +00008673 }
8674
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008675 // zext(trunc(t) & C) -> (t & zext(C)).
Dan Gohmanead83a52009-06-17 23:17:05 +00008676 if (SrcI && SrcI->getOpcode() == Instruction::And && SrcI->hasOneUse())
8677 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8678 if (TruncInst *TI = dyn_cast<TruncInst>(SrcI->getOperand(0))) {
8679 Value *TI0 = TI->getOperand(0);
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008680 if (TI0->getType() == CI.getType())
8681 return
8682 BinaryOperator::CreateAnd(TI0,
Owen Anderson24be4c12009-07-03 00:17:18 +00008683 Context->getConstantExprZExt(C, CI.getType()));
Dan Gohmanead83a52009-06-17 23:17:05 +00008684 }
8685
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008686 // zext((trunc(t) & C) ^ C) -> ((t & zext(C)) ^ zext(C)).
8687 if (SrcI && SrcI->getOpcode() == Instruction::Xor && SrcI->hasOneUse())
8688 if (ConstantInt *C = dyn_cast<ConstantInt>(SrcI->getOperand(1)))
8689 if (BinaryOperator *And = dyn_cast<BinaryOperator>(SrcI->getOperand(0)))
8690 if (And->getOpcode() == Instruction::And && And->hasOneUse() &&
8691 And->getOperand(1) == C)
8692 if (TruncInst *TI = dyn_cast<TruncInst>(And->getOperand(0))) {
8693 Value *TI0 = TI->getOperand(0);
8694 if (TI0->getType() == CI.getType()) {
Owen Anderson24be4c12009-07-03 00:17:18 +00008695 Constant *ZC = Context->getConstantExprZExt(C, CI.getType());
Dan Gohman7ac1e4a2009-06-18 16:30:21 +00008696 Instruction *NewAnd = BinaryOperator::CreateAnd(TI0, ZC, "tmp");
8697 InsertNewInstBefore(NewAnd, *And);
8698 return BinaryOperator::CreateXor(NewAnd, ZC);
8699 }
8700 }
8701
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008702 return 0;
8703}
8704
8705Instruction *InstCombiner::visitSExt(SExtInst &CI) {
8706 if (Instruction *I = commonIntCastTransforms(CI))
8707 return I;
8708
8709 Value *Src = CI.getOperand(0);
8710
Dan Gohman35b76162008-10-30 20:40:10 +00008711 // Canonicalize sign-extend from i1 to a select.
8712 if (Src->getType() == Type::Int1Ty)
8713 return SelectInst::Create(Src,
Owen Anderson24be4c12009-07-03 00:17:18 +00008714 Context->getConstantIntAllOnesValue(CI.getType()),
8715 Context->getNullValue(CI.getType()));
Dan Gohmanf0f12022008-05-20 21:01:12 +00008716
8717 // See if the value being truncated is already sign extended. If so, just
8718 // eliminate the trunc/sext pair.
8719 if (getOpcode(Src) == Instruction::Trunc) {
8720 Value *Op = cast<User>(Src)->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00008721 unsigned OpBits = Op->getType()->getScalarSizeInBits();
8722 unsigned MidBits = Src->getType()->getScalarSizeInBits();
8723 unsigned DestBits = CI.getType()->getScalarSizeInBits();
Dan Gohmanf0f12022008-05-20 21:01:12 +00008724 unsigned NumSignBits = ComputeNumSignBits(Op);
8725
8726 if (OpBits == DestBits) {
8727 // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
8728 // bits, it is already ready.
8729 if (NumSignBits > DestBits-MidBits)
8730 return ReplaceInstUsesWith(CI, Op);
8731 } else if (OpBits < DestBits) {
8732 // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
8733 // bits, just sext from i32.
8734 if (NumSignBits > OpBits-MidBits)
8735 return new SExtInst(Op, CI.getType(), "tmp");
8736 } else {
8737 // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
8738 // bits, just truncate to i32.
8739 if (NumSignBits > OpBits-MidBits)
8740 return new TruncInst(Op, CI.getType(), "tmp");
8741 }
8742 }
Chris Lattner8a2d0592008-08-06 07:35:52 +00008743
8744 // If the input is a shl/ashr pair of a same constant, then this is a sign
8745 // extension from a smaller value. If we could trust arbitrary bitwidth
8746 // integers, we could turn this into a truncate to the smaller bit and then
8747 // use a sext for the whole extension. Since we don't, look deeper and check
8748 // for a truncate. If the source and dest are the same type, eliminate the
8749 // trunc and extend and just do shifts. For example, turn:
8750 // %a = trunc i32 %i to i8
8751 // %b = shl i8 %a, 6
8752 // %c = ashr i8 %b, 6
8753 // %d = sext i8 %c to i32
8754 // into:
8755 // %a = shl i32 %i, 30
8756 // %d = ashr i32 %a, 30
8757 Value *A = 0;
8758 ConstantInt *BA = 0, *CA = 0;
8759 if (match(Src, m_AShr(m_Shl(m_Value(A), m_ConstantInt(BA)),
Owen Andersona21eb582009-07-10 17:35:01 +00008760 m_ConstantInt(CA)), *Context) &&
Chris Lattner8a2d0592008-08-06 07:35:52 +00008761 BA == CA && isa<TruncInst>(A)) {
8762 Value *I = cast<TruncInst>(A)->getOperand(0);
8763 if (I->getType() == CI.getType()) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008764 unsigned MidSize = Src->getType()->getScalarSizeInBits();
8765 unsigned SrcDstSize = CI.getType()->getScalarSizeInBits();
Chris Lattner8a2d0592008-08-06 07:35:52 +00008766 unsigned ShAmt = CA->getZExtValue()+SrcDstSize-MidSize;
Owen Anderson24be4c12009-07-03 00:17:18 +00008767 Constant *ShAmtV = Context->getConstantInt(CI.getType(), ShAmt);
Chris Lattner8a2d0592008-08-06 07:35:52 +00008768 I = InsertNewInstBefore(BinaryOperator::CreateShl(I, ShAmtV,
8769 CI.getName()), CI);
8770 return BinaryOperator::CreateAShr(I, ShAmtV);
8771 }
8772 }
8773
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008774 return 0;
8775}
8776
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008777/// FitsInFPType - Return a Constant* for the specified FP constant if it fits
8778/// in the specified FP type without changing its value.
Owen Anderson24be4c12009-07-03 00:17:18 +00008779static Constant *FitsInFPType(ConstantFP *CFP, const fltSemantics &Sem,
Owen Anderson5349f052009-07-06 23:00:19 +00008780 LLVMContext *Context) {
Dale Johannesen6e547b42008-10-09 23:00:39 +00008781 bool losesInfo;
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008782 APFloat F = CFP->getValueAPF();
Dale Johannesen6e547b42008-10-09 23:00:39 +00008783 (void)F.convert(Sem, APFloat::rmNearestTiesToEven, &losesInfo);
8784 if (!losesInfo)
Owen Anderson24be4c12009-07-03 00:17:18 +00008785 return Context->getConstantFP(F);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008786 return 0;
8787}
8788
8789/// LookThroughFPExtensions - If this is an fp extension instruction, look
8790/// through it until we get the source value.
Owen Anderson5349f052009-07-06 23:00:19 +00008791static Value *LookThroughFPExtensions(Value *V, LLVMContext *Context) {
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008792 if (Instruction *I = dyn_cast<Instruction>(V))
8793 if (I->getOpcode() == Instruction::FPExt)
Owen Anderson24be4c12009-07-03 00:17:18 +00008794 return LookThroughFPExtensions(I->getOperand(0), Context);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008795
8796 // If this value is a constant, return the constant in the smallest FP type
8797 // that can accurately represent it. This allows us to turn
8798 // (float)((double)X+2.0) into x+2.0f.
8799 if (ConstantFP *CFP = dyn_cast<ConstantFP>(V)) {
8800 if (CFP->getType() == Type::PPC_FP128Ty)
8801 return V; // No constant folding of this.
8802 // See if the value can be truncated to float and then reextended.
Owen Anderson24be4c12009-07-03 00:17:18 +00008803 if (Value *V = FitsInFPType(CFP, APFloat::IEEEsingle, Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008804 return V;
8805 if (CFP->getType() == Type::DoubleTy)
8806 return V; // Won't shrink.
Owen Anderson24be4c12009-07-03 00:17:18 +00008807 if (Value *V = FitsInFPType(CFP, APFloat::IEEEdouble, Context))
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008808 return V;
8809 // Don't try to shrink to various long double types.
8810 }
8811
8812 return V;
8813}
8814
8815Instruction *InstCombiner::visitFPTrunc(FPTruncInst &CI) {
8816 if (Instruction *I = commonCastTransforms(CI))
8817 return I;
8818
Dan Gohman7ce405e2009-06-04 22:49:04 +00008819 // If we have fptrunc(fadd (fpextend x), (fpextend y)), where x and y are
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008820 // smaller than the destination type, we can eliminate the truncate by doing
Dan Gohman7ce405e2009-06-04 22:49:04 +00008821 // the add as the smaller type. This applies to fadd/fsub/fmul/fdiv as well as
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008822 // many builtins (sqrt, etc).
8823 BinaryOperator *OpI = dyn_cast<BinaryOperator>(CI.getOperand(0));
8824 if (OpI && OpI->hasOneUse()) {
8825 switch (OpI->getOpcode()) {
8826 default: break;
Dan Gohman7ce405e2009-06-04 22:49:04 +00008827 case Instruction::FAdd:
8828 case Instruction::FSub:
8829 case Instruction::FMul:
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008830 case Instruction::FDiv:
8831 case Instruction::FRem:
8832 const Type *SrcTy = OpI->getType();
Owen Anderson24be4c12009-07-03 00:17:18 +00008833 Value *LHSTrunc = LookThroughFPExtensions(OpI->getOperand(0), Context);
8834 Value *RHSTrunc = LookThroughFPExtensions(OpI->getOperand(1), Context);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008835 if (LHSTrunc->getType() != SrcTy &&
8836 RHSTrunc->getType() != SrcTy) {
Dan Gohman8fd520a2009-06-15 22:12:54 +00008837 unsigned DstSize = CI.getType()->getScalarSizeInBits();
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008838 // If the source types were both smaller than the destination type of
8839 // the cast, do this xform.
Dan Gohman8fd520a2009-06-15 22:12:54 +00008840 if (LHSTrunc->getType()->getScalarSizeInBits() <= DstSize &&
8841 RHSTrunc->getType()->getScalarSizeInBits() <= DstSize) {
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008842 LHSTrunc = InsertCastBefore(Instruction::FPExt, LHSTrunc,
8843 CI.getType(), CI);
8844 RHSTrunc = InsertCastBefore(Instruction::FPExt, RHSTrunc,
8845 CI.getType(), CI);
Gabor Greifa645dd32008-05-16 19:29:10 +00008846 return BinaryOperator::Create(OpI->getOpcode(), LHSTrunc, RHSTrunc);
Chris Lattnerdf7e8402008-01-27 05:29:54 +00008847 }
8848 }
8849 break;
8850 }
8851 }
8852 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008853}
8854
8855Instruction *InstCombiner::visitFPExt(CastInst &CI) {
8856 return commonCastTransforms(CI);
8857}
8858
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008859Instruction *InstCombiner::visitFPToUI(FPToUIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00008860 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8861 if (OpI == 0)
8862 return commonCastTransforms(FI);
8863
8864 // fptoui(uitofp(X)) --> X
8865 // fptoui(sitofp(X)) --> X
8866 // This is safe if the intermediate type has enough bits in its mantissa to
8867 // accurately represent all values of X. For example, do not do this with
8868 // i64->float->i64. This is also safe for sitofp case, because any negative
8869 // 'X' value would cause an undefined result for the fptoui.
8870 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8871 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00008872 (int)FI.getType()->getScalarSizeInBits() < /*extra bit for sign */
Chris Lattner5f4d6912008-08-06 05:13:06 +00008873 OpI->getType()->getFPMantissaWidth())
8874 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008875
8876 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008877}
8878
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008879Instruction *InstCombiner::visitFPToSI(FPToSIInst &FI) {
Chris Lattner5f4d6912008-08-06 05:13:06 +00008880 Instruction *OpI = dyn_cast<Instruction>(FI.getOperand(0));
8881 if (OpI == 0)
8882 return commonCastTransforms(FI);
8883
8884 // fptosi(sitofp(X)) --> X
8885 // fptosi(uitofp(X)) --> X
8886 // This is safe if the intermediate type has enough bits in its mantissa to
8887 // accurately represent all values of X. For example, do not do this with
8888 // i64->float->i64. This is also safe for sitofp case, because any negative
8889 // 'X' value would cause an undefined result for the fptoui.
8890 if ((isa<UIToFPInst>(OpI) || isa<SIToFPInst>(OpI)) &&
8891 OpI->getOperand(0)->getType() == FI.getType() &&
Dan Gohman8fd520a2009-06-15 22:12:54 +00008892 (int)FI.getType()->getScalarSizeInBits() <=
Chris Lattner5f4d6912008-08-06 05:13:06 +00008893 OpI->getType()->getFPMantissaWidth())
8894 return ReplaceInstUsesWith(FI, OpI->getOperand(0));
Chris Lattnerdeef1a72008-05-19 20:25:04 +00008895
8896 return commonCastTransforms(FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008897}
8898
8899Instruction *InstCombiner::visitUIToFP(CastInst &CI) {
8900 return commonCastTransforms(CI);
8901}
8902
8903Instruction *InstCombiner::visitSIToFP(CastInst &CI) {
8904 return commonCastTransforms(CI);
8905}
8906
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008907Instruction *InstCombiner::visitPtrToInt(PtrToIntInst &CI) {
8908 // If the destination integer type is smaller than the intptr_t type for
8909 // this target, do a ptrtoint to intptr_t then do a trunc. This allows the
8910 // trunc to be exposed to other transforms. Don't do this for extending
8911 // ptrtoint's, because we don't know if the target sign or zero extends its
8912 // pointers.
Dan Gohman8fd520a2009-06-15 22:12:54 +00008913 if (CI.getType()->getScalarSizeInBits() < TD->getPointerSizeInBits()) {
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008914 Value *P = InsertNewInstBefore(new PtrToIntInst(CI.getOperand(0),
8915 TD->getIntPtrType(),
8916 "tmp"), CI);
8917 return new TruncInst(P, CI.getType());
8918 }
8919
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008920 return commonPointerCastTransforms(CI);
8921}
8922
Chris Lattner7c1626482008-01-08 07:23:51 +00008923Instruction *InstCombiner::visitIntToPtr(IntToPtrInst &CI) {
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008924 // If the source integer type is larger than the intptr_t type for
8925 // this target, do a trunc to the intptr_t type, then inttoptr of it. This
8926 // allows the trunc to be exposed to other transforms. Don't do this for
8927 // extending inttoptr's, because we don't know if the target sign or zero
8928 // extends to pointers.
Dan Gohman8fd520a2009-06-15 22:12:54 +00008929 if (CI.getOperand(0)->getType()->getScalarSizeInBits() >
Chris Lattner3e10f8d2009-03-24 18:35:40 +00008930 TD->getPointerSizeInBits()) {
8931 Value *P = InsertNewInstBefore(new TruncInst(CI.getOperand(0),
8932 TD->getIntPtrType(),
8933 "tmp"), CI);
8934 return new IntToPtrInst(P, CI.getType());
8935 }
8936
Chris Lattner7c1626482008-01-08 07:23:51 +00008937 if (Instruction *I = commonCastTransforms(CI))
8938 return I;
8939
8940 const Type *DestPointee = cast<PointerType>(CI.getType())->getElementType();
8941 if (!DestPointee->isSized()) return 0;
8942
8943 // If this is inttoptr(add (ptrtoint x), cst), try to turn this into a GEP.
8944 ConstantInt *Cst;
8945 Value *X;
8946 if (match(CI.getOperand(0), m_Add(m_Cast<PtrToIntInst>(m_Value(X)),
Owen Andersona21eb582009-07-10 17:35:01 +00008947 m_ConstantInt(Cst)), *Context)) {
Chris Lattner7c1626482008-01-08 07:23:51 +00008948 // If the source and destination operands have the same type, see if this
8949 // is a single-index GEP.
8950 if (X->getType() == CI.getType()) {
8951 // Get the size of the pointee type.
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008952 uint64_t Size = TD->getTypeAllocSize(DestPointee);
Chris Lattner7c1626482008-01-08 07:23:51 +00008953
8954 // Convert the constant to intptr type.
8955 APInt Offset = Cst->getValue();
8956 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8957
8958 // If Offset is evenly divisible by Size, we can do this xform.
8959 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8960 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
Owen Anderson24be4c12009-07-03 00:17:18 +00008961 return GetElementPtrInst::Create(X, Context->getConstantInt(Offset));
Chris Lattner7c1626482008-01-08 07:23:51 +00008962 }
8963 }
8964 // TODO: Could handle other cases, e.g. where add is indexing into field of
8965 // struct etc.
8966 } else if (CI.getOperand(0)->hasOneUse() &&
Owen Andersona21eb582009-07-10 17:35:01 +00008967 match(CI.getOperand(0), m_Add(m_Value(X),
8968 m_ConstantInt(Cst)), *Context)) {
Chris Lattner7c1626482008-01-08 07:23:51 +00008969 // Otherwise, if this is inttoptr(add x, cst), try to turn this into an
8970 // "inttoptr+GEP" instead of "add+intptr".
8971
8972 // Get the size of the pointee type.
Duncan Sandsec4f97d2009-05-09 07:06:46 +00008973 uint64_t Size = TD->getTypeAllocSize(DestPointee);
Chris Lattner7c1626482008-01-08 07:23:51 +00008974
8975 // Convert the constant to intptr type.
8976 APInt Offset = Cst->getValue();
8977 Offset.sextOrTrunc(TD->getPointerSizeInBits());
8978
8979 // If Offset is evenly divisible by Size, we can do this xform.
8980 if (Size && !APIntOps::srem(Offset, APInt(Offset.getBitWidth(), Size))){
8981 Offset = APIntOps::sdiv(Offset, APInt(Offset.getBitWidth(), Size));
8982
8983 Instruction *P = InsertNewInstBefore(new IntToPtrInst(X, CI.getType(),
8984 "tmp"), CI);
Owen Anderson24be4c12009-07-03 00:17:18 +00008985 return GetElementPtrInst::Create(P,
8986 Context->getConstantInt(Offset), "tmp");
Chris Lattner7c1626482008-01-08 07:23:51 +00008987 }
8988 }
8989 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00008990}
8991
8992Instruction *InstCombiner::visitBitCast(BitCastInst &CI) {
8993 // If the operands are integer typed then apply the integer transforms,
8994 // otherwise just apply the common ones.
8995 Value *Src = CI.getOperand(0);
8996 const Type *SrcTy = Src->getType();
8997 const Type *DestTy = CI.getType();
8998
8999 if (SrcTy->isInteger() && DestTy->isInteger()) {
9000 if (Instruction *Result = commonIntCastTransforms(CI))
9001 return Result;
9002 } else if (isa<PointerType>(SrcTy)) {
9003 if (Instruction *I = commonPointerCastTransforms(CI))
9004 return I;
9005 } else {
9006 if (Instruction *Result = commonCastTransforms(CI))
9007 return Result;
9008 }
9009
9010
9011 // Get rid of casts from one type to the same type. These are useless and can
9012 // be replaced by the operand.
9013 if (DestTy == Src->getType())
9014 return ReplaceInstUsesWith(CI, Src);
9015
9016 if (const PointerType *DstPTy = dyn_cast<PointerType>(DestTy)) {
9017 const PointerType *SrcPTy = cast<PointerType>(SrcTy);
9018 const Type *DstElTy = DstPTy->getElementType();
9019 const Type *SrcElTy = SrcPTy->getElementType();
9020
Nate Begemandf5b3612008-03-31 00:22:16 +00009021 // If the address spaces don't match, don't eliminate the bitcast, which is
9022 // required for changing types.
9023 if (SrcPTy->getAddressSpace() != DstPTy->getAddressSpace())
9024 return 0;
9025
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009026 // If we are casting a malloc or alloca to a pointer to a type of the same
9027 // size, rewrite the allocation instruction to allocate the "right" type.
9028 if (AllocationInst *AI = dyn_cast<AllocationInst>(Src))
9029 if (Instruction *V = PromoteCastOfAllocation(CI, *AI))
9030 return V;
9031
9032 // If the source and destination are pointers, and this cast is equivalent
9033 // to a getelementptr X, 0, 0, 0... turn it into the appropriate gep.
9034 // This can enhance SROA and other transforms that want type-safe pointers.
Owen Anderson24be4c12009-07-03 00:17:18 +00009035 Constant *ZeroUInt = Context->getNullValue(Type::Int32Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009036 unsigned NumZeros = 0;
9037 while (SrcElTy != DstElTy &&
9038 isa<CompositeType>(SrcElTy) && !isa<PointerType>(SrcElTy) &&
9039 SrcElTy->getNumContainedTypes() /* not "{}" */) {
9040 SrcElTy = cast<CompositeType>(SrcElTy)->getTypeAtIndex(ZeroUInt);
9041 ++NumZeros;
9042 }
9043
9044 // If we found a path from the src to dest, create the getelementptr now.
9045 if (SrcElTy == DstElTy) {
9046 SmallVector<Value*, 8> Idxs(NumZeros+1, ZeroUInt);
Gabor Greifd6da1d02008-04-06 20:25:17 +00009047 return GetElementPtrInst::Create(Src, Idxs.begin(), Idxs.end(), "",
9048 ((Instruction*) NULL));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009049 }
9050 }
9051
9052 if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(Src)) {
9053 if (SVI->hasOneUse()) {
9054 // Okay, we have (bitconvert (shuffle ..)). Check to see if this is
9055 // a bitconvert to a vector with the same # elts.
9056 if (isa<VectorType>(DestTy) &&
Mon P Wangbff5d9c2008-11-10 04:46:22 +00009057 cast<VectorType>(DestTy)->getNumElements() ==
9058 SVI->getType()->getNumElements() &&
9059 SVI->getType()->getNumElements() ==
9060 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009061 CastInst *Tmp;
9062 // If either of the operands is a cast from CI.getType(), then
9063 // evaluating the shuffle in the casted destination's type will allow
9064 // us to eliminate at least one cast.
9065 if (((Tmp = dyn_cast<CastInst>(SVI->getOperand(0))) &&
9066 Tmp->getOperand(0)->getType() == DestTy) ||
9067 ((Tmp = dyn_cast<CastInst>(SVI->getOperand(1))) &&
9068 Tmp->getOperand(0)->getType() == DestTy)) {
Eli Friedman722b4792008-11-30 21:09:11 +00009069 Value *LHS = InsertCastBefore(Instruction::BitCast,
9070 SVI->getOperand(0), DestTy, CI);
9071 Value *RHS = InsertCastBefore(Instruction::BitCast,
9072 SVI->getOperand(1), DestTy, CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009073 // Return a new shuffle vector. Use the same element ID's, as we
9074 // know the vector types match #elts.
9075 return new ShuffleVectorInst(LHS, RHS, SVI->getOperand(2));
9076 }
9077 }
9078 }
9079 }
9080 return 0;
9081}
9082
9083/// GetSelectFoldableOperands - We want to turn code that looks like this:
9084/// %C = or %A, %B
9085/// %D = select %cond, %C, %A
9086/// into:
9087/// %C = select %cond, %B, 0
9088/// %D = or %A, %C
9089///
9090/// Assuming that the specified instruction is an operand to the select, return
9091/// a bitmask indicating which operands of this instruction are foldable if they
9092/// equal the other incoming value of the select.
9093///
9094static unsigned GetSelectFoldableOperands(Instruction *I) {
9095 switch (I->getOpcode()) {
9096 case Instruction::Add:
9097 case Instruction::Mul:
9098 case Instruction::And:
9099 case Instruction::Or:
9100 case Instruction::Xor:
9101 return 3; // Can fold through either operand.
9102 case Instruction::Sub: // Can only fold on the amount subtracted.
9103 case Instruction::Shl: // Can only fold on the shift amount.
9104 case Instruction::LShr:
9105 case Instruction::AShr:
9106 return 1;
9107 default:
9108 return 0; // Cannot fold
9109 }
9110}
9111
9112/// GetSelectFoldableConstant - For the same transformation as the previous
9113/// function, return the identity constant that goes into the select.
Owen Anderson24be4c12009-07-03 00:17:18 +00009114static Constant *GetSelectFoldableConstant(Instruction *I,
Owen Anderson5349f052009-07-06 23:00:19 +00009115 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009116 switch (I->getOpcode()) {
Edwin Törökced9ff82009-07-11 13:10:19 +00009117 default: LLVM_UNREACHABLE("This cannot happen!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009118 case Instruction::Add:
9119 case Instruction::Sub:
9120 case Instruction::Or:
9121 case Instruction::Xor:
9122 case Instruction::Shl:
9123 case Instruction::LShr:
9124 case Instruction::AShr:
Owen Anderson24be4c12009-07-03 00:17:18 +00009125 return Context->getNullValue(I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009126 case Instruction::And:
Owen Anderson24be4c12009-07-03 00:17:18 +00009127 return Context->getAllOnesValue(I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009128 case Instruction::Mul:
Owen Anderson24be4c12009-07-03 00:17:18 +00009129 return Context->getConstantInt(I->getType(), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009130 }
9131}
9132
9133/// FoldSelectOpOp - Here we have (select c, TI, FI), and we know that TI and FI
9134/// have the same opcode and only one use each. Try to simplify this.
9135Instruction *InstCombiner::FoldSelectOpOp(SelectInst &SI, Instruction *TI,
9136 Instruction *FI) {
9137 if (TI->getNumOperands() == 1) {
9138 // If this is a non-volatile load or a cast from the same type,
9139 // merge.
9140 if (TI->isCast()) {
9141 if (TI->getOperand(0)->getType() != FI->getOperand(0)->getType())
9142 return 0;
9143 } else {
9144 return 0; // unknown unary op.
9145 }
9146
9147 // Fold this by inserting a select from the input values.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009148 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), TI->getOperand(0),
9149 FI->getOperand(0), SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009150 InsertNewInstBefore(NewSI, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009151 return CastInst::Create(Instruction::CastOps(TI->getOpcode()), NewSI,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009152 TI->getType());
9153 }
9154
9155 // Only handle binary operators here.
9156 if (!isa<BinaryOperator>(TI))
9157 return 0;
9158
9159 // Figure out if the operations have any operands in common.
9160 Value *MatchOp, *OtherOpT, *OtherOpF;
9161 bool MatchIsOpZero;
9162 if (TI->getOperand(0) == FI->getOperand(0)) {
9163 MatchOp = TI->getOperand(0);
9164 OtherOpT = TI->getOperand(1);
9165 OtherOpF = FI->getOperand(1);
9166 MatchIsOpZero = true;
9167 } else if (TI->getOperand(1) == FI->getOperand(1)) {
9168 MatchOp = TI->getOperand(1);
9169 OtherOpT = TI->getOperand(0);
9170 OtherOpF = FI->getOperand(0);
9171 MatchIsOpZero = false;
9172 } else if (!TI->isCommutative()) {
9173 return 0;
9174 } else if (TI->getOperand(0) == FI->getOperand(1)) {
9175 MatchOp = TI->getOperand(0);
9176 OtherOpT = TI->getOperand(1);
9177 OtherOpF = FI->getOperand(0);
9178 MatchIsOpZero = true;
9179 } else if (TI->getOperand(1) == FI->getOperand(0)) {
9180 MatchOp = TI->getOperand(1);
9181 OtherOpT = TI->getOperand(0);
9182 OtherOpF = FI->getOperand(1);
9183 MatchIsOpZero = true;
9184 } else {
9185 return 0;
9186 }
9187
9188 // If we reach here, they do have operations in common.
Gabor Greifd6da1d02008-04-06 20:25:17 +00009189 SelectInst *NewSI = SelectInst::Create(SI.getCondition(), OtherOpT,
9190 OtherOpF, SI.getName()+".v");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009191 InsertNewInstBefore(NewSI, SI);
9192
9193 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TI)) {
9194 if (MatchIsOpZero)
Gabor Greifa645dd32008-05-16 19:29:10 +00009195 return BinaryOperator::Create(BO->getOpcode(), MatchOp, NewSI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009196 else
Gabor Greifa645dd32008-05-16 19:29:10 +00009197 return BinaryOperator::Create(BO->getOpcode(), NewSI, MatchOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009198 }
9199 assert(0 && "Shouldn't get here");
9200 return 0;
9201}
9202
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009203static bool isSelect01(Constant *C1, Constant *C2) {
9204 ConstantInt *C1I = dyn_cast<ConstantInt>(C1);
9205 if (!C1I)
9206 return false;
9207 ConstantInt *C2I = dyn_cast<ConstantInt>(C2);
9208 if (!C2I)
9209 return false;
9210 return (C1I->isZero() || C1I->isOne()) && (C2I->isZero() || C2I->isOne());
9211}
9212
9213/// FoldSelectIntoOp - Try fold the select into one of the operands to
9214/// facilitate further optimization.
9215Instruction *InstCombiner::FoldSelectIntoOp(SelectInst &SI, Value *TrueVal,
9216 Value *FalseVal) {
9217 // See the comment above GetSelectFoldableOperands for a description of the
9218 // transformation we are doing here.
9219 if (Instruction *TVI = dyn_cast<Instruction>(TrueVal)) {
9220 if (TVI->hasOneUse() && TVI->getNumOperands() == 2 &&
9221 !isa<Constant>(FalseVal)) {
9222 if (unsigned SFO = GetSelectFoldableOperands(TVI)) {
9223 unsigned OpToFold = 0;
9224 if ((SFO & 1) && FalseVal == TVI->getOperand(0)) {
9225 OpToFold = 1;
9226 } else if ((SFO & 2) && FalseVal == TVI->getOperand(1)) {
9227 OpToFold = 2;
9228 }
9229
9230 if (OpToFold) {
Owen Anderson24be4c12009-07-03 00:17:18 +00009231 Constant *C = GetSelectFoldableConstant(TVI, Context);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009232 Value *OOp = TVI->getOperand(2-OpToFold);
9233 // Avoid creating select between 2 constants unless it's selecting
9234 // between 0 and 1.
9235 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9236 Instruction *NewSel = SelectInst::Create(SI.getCondition(), OOp, C);
9237 InsertNewInstBefore(NewSel, SI);
9238 NewSel->takeName(TVI);
9239 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(TVI))
9240 return BinaryOperator::Create(BO->getOpcode(), FalseVal, NewSel);
9241 assert(0 && "Unknown instruction!!");
9242 }
9243 }
9244 }
9245 }
9246 }
9247
9248 if (Instruction *FVI = dyn_cast<Instruction>(FalseVal)) {
9249 if (FVI->hasOneUse() && FVI->getNumOperands() == 2 &&
9250 !isa<Constant>(TrueVal)) {
9251 if (unsigned SFO = GetSelectFoldableOperands(FVI)) {
9252 unsigned OpToFold = 0;
9253 if ((SFO & 1) && TrueVal == FVI->getOperand(0)) {
9254 OpToFold = 1;
9255 } else if ((SFO & 2) && TrueVal == FVI->getOperand(1)) {
9256 OpToFold = 2;
9257 }
9258
9259 if (OpToFold) {
Owen Anderson24be4c12009-07-03 00:17:18 +00009260 Constant *C = GetSelectFoldableConstant(FVI, Context);
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009261 Value *OOp = FVI->getOperand(2-OpToFold);
9262 // Avoid creating select between 2 constants unless it's selecting
9263 // between 0 and 1.
9264 if (!isa<Constant>(OOp) || isSelect01(C, cast<Constant>(OOp))) {
9265 Instruction *NewSel = SelectInst::Create(SI.getCondition(), C, OOp);
9266 InsertNewInstBefore(NewSel, SI);
9267 NewSel->takeName(FVI);
9268 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(FVI))
9269 return BinaryOperator::Create(BO->getOpcode(), TrueVal, NewSel);
9270 assert(0 && "Unknown instruction!!");
9271 }
9272 }
9273 }
9274 }
9275 }
9276
9277 return 0;
9278}
9279
Dan Gohman58c09632008-09-16 18:46:06 +00009280/// visitSelectInstWithICmp - Visit a SelectInst that has an
9281/// ICmpInst as its first operand.
9282///
9283Instruction *InstCombiner::visitSelectInstWithICmp(SelectInst &SI,
9284 ICmpInst *ICI) {
9285 bool Changed = false;
9286 ICmpInst::Predicate Pred = ICI->getPredicate();
9287 Value *CmpLHS = ICI->getOperand(0);
9288 Value *CmpRHS = ICI->getOperand(1);
9289 Value *TrueVal = SI.getTrueValue();
9290 Value *FalseVal = SI.getFalseValue();
9291
9292 // Check cases where the comparison is with a constant that
9293 // can be adjusted to fit the min/max idiom. We may edit ICI in
9294 // place here, so make sure the select is the only user.
9295 if (ICI->hasOneUse())
Dan Gohman35b76162008-10-30 20:40:10 +00009296 if (ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS)) {
Dan Gohman58c09632008-09-16 18:46:06 +00009297 switch (Pred) {
9298 default: break;
9299 case ICmpInst::ICMP_ULT:
9300 case ICmpInst::ICMP_SLT: {
9301 // X < MIN ? T : F --> F
9302 if (CI->isMinValue(Pred == ICmpInst::ICMP_SLT))
9303 return ReplaceInstUsesWith(SI, FalseVal);
9304 // X < C ? X : C-1 --> X > C-1 ? C-1 : X
Owen Anderson24be4c12009-07-03 00:17:18 +00009305 Constant *AdjustedRHS = SubOne(CI, Context);
Dan Gohman58c09632008-09-16 18:46:06 +00009306 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9307 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9308 Pred = ICmpInst::getSwappedPredicate(Pred);
9309 CmpRHS = AdjustedRHS;
9310 std::swap(FalseVal, TrueVal);
9311 ICI->setPredicate(Pred);
9312 ICI->setOperand(1, CmpRHS);
9313 SI.setOperand(1, TrueVal);
9314 SI.setOperand(2, FalseVal);
9315 Changed = true;
9316 }
9317 break;
9318 }
9319 case ICmpInst::ICMP_UGT:
9320 case ICmpInst::ICMP_SGT: {
9321 // X > MAX ? T : F --> F
9322 if (CI->isMaxValue(Pred == ICmpInst::ICMP_SGT))
9323 return ReplaceInstUsesWith(SI, FalseVal);
9324 // X > C ? X : C+1 --> X < C+1 ? C+1 : X
Owen Anderson24be4c12009-07-03 00:17:18 +00009325 Constant *AdjustedRHS = AddOne(CI, Context);
Dan Gohman58c09632008-09-16 18:46:06 +00009326 if ((CmpLHS == TrueVal && AdjustedRHS == FalseVal) ||
9327 (CmpLHS == FalseVal && AdjustedRHS == TrueVal)) {
9328 Pred = ICmpInst::getSwappedPredicate(Pred);
9329 CmpRHS = AdjustedRHS;
9330 std::swap(FalseVal, TrueVal);
9331 ICI->setPredicate(Pred);
9332 ICI->setOperand(1, CmpRHS);
9333 SI.setOperand(1, TrueVal);
9334 SI.setOperand(2, FalseVal);
9335 Changed = true;
9336 }
9337 break;
9338 }
9339 }
9340
Dan Gohman35b76162008-10-30 20:40:10 +00009341 // (x <s 0) ? -1 : 0 -> ashr x, 31 -> all ones if signed
9342 // (x >s -1) ? -1 : 0 -> ashr x, 31 -> all ones if not signed
Chris Lattner3b874082008-11-16 05:38:51 +00009343 CmpInst::Predicate Pred = CmpInst::BAD_ICMP_PREDICATE;
Owen Andersona21eb582009-07-10 17:35:01 +00009344 if (match(TrueVal, m_ConstantInt<-1>(), *Context) &&
9345 match(FalseVal, m_ConstantInt<0>(), *Context))
Chris Lattner3b874082008-11-16 05:38:51 +00009346 Pred = ICI->getPredicate();
Owen Andersona21eb582009-07-10 17:35:01 +00009347 else if (match(TrueVal, m_ConstantInt<0>(), *Context) &&
9348 match(FalseVal, m_ConstantInt<-1>(), *Context))
Chris Lattner3b874082008-11-16 05:38:51 +00009349 Pred = CmpInst::getInversePredicate(ICI->getPredicate());
9350
Dan Gohman35b76162008-10-30 20:40:10 +00009351 if (Pred != CmpInst::BAD_ICMP_PREDICATE) {
9352 // If we are just checking for a icmp eq of a single bit and zext'ing it
9353 // to an integer, then shift the bit to the appropriate place and then
9354 // cast to integer to avoid the comparison.
9355 const APInt &Op1CV = CI->getValue();
9356
9357 // sext (x <s 0) to i32 --> x>>s31 true if signbit set.
9358 // sext (x >s -1) to i32 --> (x>>s31)^-1 true if signbit clear.
9359 if ((Pred == ICmpInst::ICMP_SLT && Op1CV == 0) ||
Chris Lattner3b874082008-11-16 05:38:51 +00009360 (Pred == ICmpInst::ICMP_SGT && Op1CV.isAllOnesValue())) {
Dan Gohman35b76162008-10-30 20:40:10 +00009361 Value *In = ICI->getOperand(0);
Owen Anderson24be4c12009-07-03 00:17:18 +00009362 Value *Sh = Context->getConstantInt(In->getType(),
Dan Gohman8fd520a2009-06-15 22:12:54 +00009363 In->getType()->getScalarSizeInBits()-1);
Dan Gohman35b76162008-10-30 20:40:10 +00009364 In = InsertNewInstBefore(BinaryOperator::CreateAShr(In, Sh,
9365 In->getName()+".lobit"),
9366 *ICI);
Dan Gohman47a60772008-11-02 00:17:33 +00009367 if (In->getType() != SI.getType())
9368 In = CastInst::CreateIntegerCast(In, SI.getType(),
Dan Gohman35b76162008-10-30 20:40:10 +00009369 true/*SExt*/, "tmp", ICI);
9370
9371 if (Pred == ICmpInst::ICMP_SGT)
9372 In = InsertNewInstBefore(BinaryOperator::CreateNot(In,
9373 In->getName()+".not"), *ICI);
9374
9375 return ReplaceInstUsesWith(SI, In);
9376 }
9377 }
9378 }
9379
Dan Gohman58c09632008-09-16 18:46:06 +00009380 if (CmpLHS == TrueVal && CmpRHS == FalseVal) {
9381 // Transform (X == Y) ? X : Y -> Y
9382 if (Pred == ICmpInst::ICMP_EQ)
9383 return ReplaceInstUsesWith(SI, FalseVal);
9384 // Transform (X != Y) ? X : Y -> X
9385 if (Pred == ICmpInst::ICMP_NE)
9386 return ReplaceInstUsesWith(SI, TrueVal);
9387 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9388
9389 } else if (CmpLHS == FalseVal && CmpRHS == TrueVal) {
9390 // Transform (X == Y) ? Y : X -> X
9391 if (Pred == ICmpInst::ICMP_EQ)
9392 return ReplaceInstUsesWith(SI, FalseVal);
9393 // Transform (X != Y) ? Y : X -> Y
9394 if (Pred == ICmpInst::ICMP_NE)
9395 return ReplaceInstUsesWith(SI, TrueVal);
9396 /// NOTE: if we wanted to, this is where to detect integer MIN/MAX
9397 }
9398
9399 /// NOTE: if we wanted to, this is where to detect integer ABS
9400
9401 return Changed ? &SI : 0;
9402}
9403
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009404Instruction *InstCombiner::visitSelectInst(SelectInst &SI) {
9405 Value *CondVal = SI.getCondition();
9406 Value *TrueVal = SI.getTrueValue();
9407 Value *FalseVal = SI.getFalseValue();
9408
9409 // select true, X, Y -> X
9410 // select false, X, Y -> Y
9411 if (ConstantInt *C = dyn_cast<ConstantInt>(CondVal))
9412 return ReplaceInstUsesWith(SI, C->getZExtValue() ? TrueVal : FalseVal);
9413
9414 // select C, X, X -> X
9415 if (TrueVal == FalseVal)
9416 return ReplaceInstUsesWith(SI, TrueVal);
9417
9418 if (isa<UndefValue>(TrueVal)) // select C, undef, X -> X
9419 return ReplaceInstUsesWith(SI, FalseVal);
9420 if (isa<UndefValue>(FalseVal)) // select C, X, undef -> X
9421 return ReplaceInstUsesWith(SI, TrueVal);
9422 if (isa<UndefValue>(CondVal)) { // select undef, X, Y -> X or Y
9423 if (isa<Constant>(TrueVal))
9424 return ReplaceInstUsesWith(SI, TrueVal);
9425 else
9426 return ReplaceInstUsesWith(SI, FalseVal);
9427 }
9428
9429 if (SI.getType() == Type::Int1Ty) {
9430 if (ConstantInt *C = dyn_cast<ConstantInt>(TrueVal)) {
9431 if (C->getZExtValue()) {
9432 // Change: A = select B, true, C --> A = or B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00009433 return BinaryOperator::CreateOr(CondVal, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009434 } else {
9435 // Change: A = select B, false, C --> A = and !B, C
9436 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00009437 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009438 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009439 return BinaryOperator::CreateAnd(NotCond, FalseVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009440 }
9441 } else if (ConstantInt *C = dyn_cast<ConstantInt>(FalseVal)) {
9442 if (C->getZExtValue() == false) {
9443 // Change: A = select B, C, false --> A = and B, C
Gabor Greifa645dd32008-05-16 19:29:10 +00009444 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009445 } else {
9446 // Change: A = select B, C, true --> A = or !B, C
9447 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00009448 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009449 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009450 return BinaryOperator::CreateOr(NotCond, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009451 }
9452 }
Chris Lattner53f85a72007-11-25 21:27:53 +00009453
9454 // select a, b, a -> a&b
9455 // select a, a, b -> a|b
9456 if (CondVal == TrueVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009457 return BinaryOperator::CreateOr(CondVal, FalseVal);
Chris Lattner53f85a72007-11-25 21:27:53 +00009458 else if (CondVal == FalseVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009459 return BinaryOperator::CreateAnd(CondVal, TrueVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009460 }
9461
9462 // Selecting between two integer constants?
9463 if (ConstantInt *TrueValC = dyn_cast<ConstantInt>(TrueVal))
9464 if (ConstantInt *FalseValC = dyn_cast<ConstantInt>(FalseVal)) {
9465 // select C, 1, 0 -> zext C to int
9466 if (FalseValC->isZero() && TrueValC->getValue() == 1) {
Gabor Greifa645dd32008-05-16 19:29:10 +00009467 return CastInst::Create(Instruction::ZExt, CondVal, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009468 } else if (TrueValC->isZero() && FalseValC->getValue() == 1) {
9469 // select C, 0, 1 -> zext !C to int
9470 Value *NotCond =
Gabor Greifa645dd32008-05-16 19:29:10 +00009471 InsertNewInstBefore(BinaryOperator::CreateNot(CondVal,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009472 "not."+CondVal->getName()), SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009473 return CastInst::Create(Instruction::ZExt, NotCond, SI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009474 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009475
9476 if (ICmpInst *IC = dyn_cast<ICmpInst>(SI.getCondition())) {
9477
9478 // (x <s 0) ? -1 : 0 -> ashr x, 31
9479 if (TrueValC->isAllOnesValue() && FalseValC->isZero())
9480 if (ConstantInt *CmpCst = dyn_cast<ConstantInt>(IC->getOperand(1))) {
9481 if (IC->getPredicate() == ICmpInst::ICMP_SLT && CmpCst->isZero()) {
9482 // The comparison constant and the result are not neccessarily the
9483 // same width. Make an all-ones value by inserting a AShr.
9484 Value *X = IC->getOperand(0);
Dan Gohman8fd520a2009-06-15 22:12:54 +00009485 uint32_t Bits = X->getType()->getScalarSizeInBits();
Owen Anderson24be4c12009-07-03 00:17:18 +00009486 Constant *ShAmt = Context->getConstantInt(X->getType(), Bits-1);
Gabor Greifa645dd32008-05-16 19:29:10 +00009487 Instruction *SRA = BinaryOperator::Create(Instruction::AShr, X,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009488 ShAmt, "ones");
9489 InsertNewInstBefore(SRA, SI);
Eli Friedman722b4792008-11-30 21:09:11 +00009490
9491 // Then cast to the appropriate width.
9492 return CastInst::CreateIntegerCast(SRA, SI.getType(), true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009493 }
9494 }
9495
9496
9497 // If one of the constants is zero (we know they can't both be) and we
9498 // have an icmp instruction with zero, and we have an 'and' with the
9499 // non-constant value, eliminate this whole mess. This corresponds to
9500 // cases like this: ((X & 27) ? 27 : 0)
9501 if (TrueValC->isZero() || FalseValC->isZero())
9502 if (IC->isEquality() && isa<ConstantInt>(IC->getOperand(1)) &&
9503 cast<Constant>(IC->getOperand(1))->isNullValue())
9504 if (Instruction *ICA = dyn_cast<Instruction>(IC->getOperand(0)))
9505 if (ICA->getOpcode() == Instruction::And &&
9506 isa<ConstantInt>(ICA->getOperand(1)) &&
9507 (ICA->getOperand(1) == TrueValC ||
9508 ICA->getOperand(1) == FalseValC) &&
9509 isOneBitSet(cast<ConstantInt>(ICA->getOperand(1)))) {
9510 // Okay, now we know that everything is set up, we just don't
9511 // know whether we have a icmp_ne or icmp_eq and whether the
9512 // true or false val is the zero.
9513 bool ShouldNotVal = !TrueValC->isZero();
9514 ShouldNotVal ^= IC->getPredicate() == ICmpInst::ICMP_NE;
9515 Value *V = ICA;
9516 if (ShouldNotVal)
Gabor Greifa645dd32008-05-16 19:29:10 +00009517 V = InsertNewInstBefore(BinaryOperator::Create(
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009518 Instruction::Xor, V, ICA->getOperand(1)), SI);
9519 return ReplaceInstUsesWith(SI, V);
9520 }
9521 }
9522 }
9523
9524 // See if we are selecting two values based on a comparison of the two values.
9525 if (FCmpInst *FCI = dyn_cast<FCmpInst>(CondVal)) {
9526 if (FCI->getOperand(0) == TrueVal && FCI->getOperand(1) == FalseVal) {
9527 // Transform (X == Y) ? X : Y -> Y
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009528 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9529 // This is not safe in general for floating point:
9530 // consider X== -0, Y== +0.
9531 // It becomes safe if either operand is a nonzero constant.
9532 ConstantFP *CFPt, *CFPf;
9533 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9534 !CFPt->getValueAPF().isZero()) ||
9535 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9536 !CFPf->getValueAPF().isZero()))
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009537 return ReplaceInstUsesWith(SI, FalseVal);
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009538 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009539 // Transform (X != Y) ? X : Y -> X
9540 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9541 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00009542 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009543
9544 } else if (FCI->getOperand(0) == FalseVal && FCI->getOperand(1) == TrueVal){
9545 // Transform (X == Y) ? Y : X -> X
Dale Johannesen2e1b7692007-10-03 17:45:27 +00009546 if (FCI->getPredicate() == FCmpInst::FCMP_OEQ) {
9547 // This is not safe in general for floating point:
9548 // consider X== -0, Y== +0.
9549 // It becomes safe if either operand is a nonzero constant.
9550 ConstantFP *CFPt, *CFPf;
9551 if (((CFPt = dyn_cast<ConstantFP>(TrueVal)) &&
9552 !CFPt->getValueAPF().isZero()) ||
9553 ((CFPf = dyn_cast<ConstantFP>(FalseVal)) &&
9554 !CFPf->getValueAPF().isZero()))
9555 return ReplaceInstUsesWith(SI, FalseVal);
9556 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009557 // Transform (X != Y) ? Y : X -> Y
9558 if (FCI->getPredicate() == FCmpInst::FCMP_ONE)
9559 return ReplaceInstUsesWith(SI, TrueVal);
Dan Gohman58c09632008-09-16 18:46:06 +00009560 // NOTE: if we wanted to, this is where to detect MIN/MAX
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009561 }
Dan Gohman58c09632008-09-16 18:46:06 +00009562 // NOTE: if we wanted to, this is where to detect ABS
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009563 }
9564
9565 // See if we are selecting two values based on a comparison of the two values.
Dan Gohman58c09632008-09-16 18:46:06 +00009566 if (ICmpInst *ICI = dyn_cast<ICmpInst>(CondVal))
9567 if (Instruction *Result = visitSelectInstWithICmp(SI, ICI))
9568 return Result;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009569
9570 if (Instruction *TI = dyn_cast<Instruction>(TrueVal))
9571 if (Instruction *FI = dyn_cast<Instruction>(FalseVal))
9572 if (TI->hasOneUse() && FI->hasOneUse()) {
9573 Instruction *AddOp = 0, *SubOp = 0;
9574
9575 // Turn (select C, (op X, Y), (op X, Z)) -> (op X, (select C, Y, Z))
9576 if (TI->getOpcode() == FI->getOpcode())
9577 if (Instruction *IV = FoldSelectOpOp(SI, TI, FI))
9578 return IV;
9579
9580 // Turn select C, (X+Y), (X-Y) --> (X+(select C, Y, (-Y))). This is
9581 // even legal for FP.
Dan Gohman7ce405e2009-06-04 22:49:04 +00009582 if ((TI->getOpcode() == Instruction::Sub &&
9583 FI->getOpcode() == Instruction::Add) ||
9584 (TI->getOpcode() == Instruction::FSub &&
9585 FI->getOpcode() == Instruction::FAdd)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009586 AddOp = FI; SubOp = TI;
Dan Gohman7ce405e2009-06-04 22:49:04 +00009587 } else if ((FI->getOpcode() == Instruction::Sub &&
9588 TI->getOpcode() == Instruction::Add) ||
9589 (FI->getOpcode() == Instruction::FSub &&
9590 TI->getOpcode() == Instruction::FAdd)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009591 AddOp = TI; SubOp = FI;
9592 }
9593
9594 if (AddOp) {
9595 Value *OtherAddOp = 0;
9596 if (SubOp->getOperand(0) == AddOp->getOperand(0)) {
9597 OtherAddOp = AddOp->getOperand(1);
9598 } else if (SubOp->getOperand(0) == AddOp->getOperand(1)) {
9599 OtherAddOp = AddOp->getOperand(0);
9600 }
9601
9602 if (OtherAddOp) {
9603 // So at this point we know we have (Y -> OtherAddOp):
9604 // select C, (add X, Y), (sub X, Z)
9605 Value *NegVal; // Compute -Z
9606 if (Constant *C = dyn_cast<Constant>(SubOp->getOperand(1))) {
Owen Anderson24be4c12009-07-03 00:17:18 +00009607 NegVal = Context->getConstantExprNeg(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009608 } else {
9609 NegVal = InsertNewInstBefore(
Gabor Greifa645dd32008-05-16 19:29:10 +00009610 BinaryOperator::CreateNeg(SubOp->getOperand(1), "tmp"), SI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009611 }
9612
9613 Value *NewTrueOp = OtherAddOp;
9614 Value *NewFalseOp = NegVal;
9615 if (AddOp != TI)
9616 std::swap(NewTrueOp, NewFalseOp);
9617 Instruction *NewSel =
Gabor Greifb91ea9d2008-05-15 10:04:30 +00009618 SelectInst::Create(CondVal, NewTrueOp,
9619 NewFalseOp, SI.getName() + ".p");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009620
9621 NewSel = InsertNewInstBefore(NewSel, SI);
Gabor Greifa645dd32008-05-16 19:29:10 +00009622 return BinaryOperator::CreateAdd(SubOp->getOperand(0), NewSel);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009623 }
9624 }
9625 }
9626
9627 // See if we can fold the select into one of our operands.
9628 if (SI.getType()->isInteger()) {
Evan Cheng9f8ee8f2009-03-31 20:42:45 +00009629 Instruction *FoldI = FoldSelectIntoOp(SI, TrueVal, FalseVal);
9630 if (FoldI)
9631 return FoldI;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009632 }
9633
9634 if (BinaryOperator::isNot(CondVal)) {
9635 SI.setOperand(0, BinaryOperator::getNotArgument(CondVal));
9636 SI.setOperand(1, FalseVal);
9637 SI.setOperand(2, TrueVal);
9638 return &SI;
9639 }
9640
9641 return 0;
9642}
9643
Dan Gohman2d648bb2008-04-10 18:43:06 +00009644/// EnforceKnownAlignment - If the specified pointer points to an object that
9645/// we control, modify the object's alignment to PrefAlign. This isn't
9646/// often possible though. If alignment is important, a more reliable approach
9647/// is to simply align all global variables and allocation instructions to
9648/// their preferred alignment from the beginning.
9649///
9650static unsigned EnforceKnownAlignment(Value *V,
9651 unsigned Align, unsigned PrefAlign) {
Chris Lattner47cf3452007-08-09 19:05:49 +00009652
Dan Gohman2d648bb2008-04-10 18:43:06 +00009653 User *U = dyn_cast<User>(V);
9654 if (!U) return Align;
9655
9656 switch (getOpcode(U)) {
9657 default: break;
9658 case Instruction::BitCast:
9659 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
9660 case Instruction::GetElementPtr: {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009661 // If all indexes are zero, it is just the alignment of the base pointer.
9662 bool AllZeroOperands = true;
Gabor Greife92fbe22008-06-12 21:51:29 +00009663 for (User::op_iterator i = U->op_begin() + 1, e = U->op_end(); i != e; ++i)
Gabor Greif17396002008-06-12 21:37:33 +00009664 if (!isa<Constant>(*i) ||
9665 !cast<Constant>(*i)->isNullValue()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009666 AllZeroOperands = false;
9667 break;
9668 }
Chris Lattner47cf3452007-08-09 19:05:49 +00009669
9670 if (AllZeroOperands) {
9671 // Treat this like a bitcast.
Dan Gohman2d648bb2008-04-10 18:43:06 +00009672 return EnforceKnownAlignment(U->getOperand(0), Align, PrefAlign);
Chris Lattner47cf3452007-08-09 19:05:49 +00009673 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009674 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009675 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009676 }
9677
9678 if (GlobalValue *GV = dyn_cast<GlobalValue>(V)) {
9679 // If there is a large requested alignment and we can, bump up the alignment
9680 // of the global.
9681 if (!GV->isDeclaration()) {
Dan Gohmanf6fe71e2009-02-16 23:02:21 +00009682 if (GV->getAlignment() >= PrefAlign)
9683 Align = GV->getAlignment();
9684 else {
9685 GV->setAlignment(PrefAlign);
9686 Align = PrefAlign;
9687 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009688 }
9689 } else if (AllocationInst *AI = dyn_cast<AllocationInst>(V)) {
9690 // If there is a requested alignment and if this is an alloca, round up. We
9691 // don't do this for malloc, because some systems can't respect the request.
9692 if (isa<AllocaInst>(AI)) {
Dan Gohmanf6fe71e2009-02-16 23:02:21 +00009693 if (AI->getAlignment() >= PrefAlign)
9694 Align = AI->getAlignment();
9695 else {
9696 AI->setAlignment(PrefAlign);
9697 Align = PrefAlign;
9698 }
Dan Gohman2d648bb2008-04-10 18:43:06 +00009699 }
9700 }
9701
9702 return Align;
9703}
9704
9705/// GetOrEnforceKnownAlignment - If the specified pointer has an alignment that
9706/// we can determine, return it, otherwise return 0. If PrefAlign is specified,
9707/// and it is more than the alignment of the ultimate object, see if we can
9708/// increase the alignment of the ultimate object, making this check succeed.
9709unsigned InstCombiner::GetOrEnforceKnownAlignment(Value *V,
9710 unsigned PrefAlign) {
9711 unsigned BitWidth = TD ? TD->getTypeSizeInBits(V->getType()) :
9712 sizeof(PrefAlign) * CHAR_BIT;
9713 APInt Mask = APInt::getAllOnesValue(BitWidth);
9714 APInt KnownZero(BitWidth, 0), KnownOne(BitWidth, 0);
9715 ComputeMaskedBits(V, Mask, KnownZero, KnownOne);
9716 unsigned TrailZ = KnownZero.countTrailingOnes();
9717 unsigned Align = 1u << std::min(BitWidth - 1, TrailZ);
9718
9719 if (PrefAlign > Align)
9720 Align = EnforceKnownAlignment(V, Align, PrefAlign);
9721
9722 // We don't need to make any adjustment.
9723 return Align;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009724}
9725
Chris Lattner00ae5132008-01-13 23:50:23 +00009726Instruction *InstCombiner::SimplifyMemTransfer(MemIntrinsic *MI) {
Dan Gohman2d648bb2008-04-10 18:43:06 +00009727 unsigned DstAlign = GetOrEnforceKnownAlignment(MI->getOperand(1));
Dan Gohmaneb254912009-02-22 18:06:32 +00009728 unsigned SrcAlign = GetOrEnforceKnownAlignment(MI->getOperand(2));
Chris Lattner00ae5132008-01-13 23:50:23 +00009729 unsigned MinAlign = std::min(DstAlign, SrcAlign);
Chris Lattner3947da72009-03-08 03:59:00 +00009730 unsigned CopyAlign = MI->getAlignment();
Chris Lattner00ae5132008-01-13 23:50:23 +00009731
9732 if (CopyAlign < MinAlign) {
Owen Andersonf9f99362009-07-09 18:36:20 +00009733 MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9734 MinAlign, false));
Chris Lattner00ae5132008-01-13 23:50:23 +00009735 return MI;
9736 }
9737
9738 // If MemCpyInst length is 1/2/4/8 bytes then replace memcpy with
9739 // load/store.
9740 ConstantInt *MemOpLength = dyn_cast<ConstantInt>(MI->getOperand(3));
9741 if (MemOpLength == 0) return 0;
9742
Chris Lattnerc669fb62008-01-14 00:28:35 +00009743 // Source and destination pointer types are always "i8*" for intrinsic. See
9744 // if the size is something we can handle with a single primitive load/store.
9745 // A single load+store correctly handles overlapping memory in the memmove
9746 // case.
Chris Lattner00ae5132008-01-13 23:50:23 +00009747 unsigned Size = MemOpLength->getZExtValue();
Chris Lattner5af8a912008-04-30 06:39:11 +00009748 if (Size == 0) return MI; // Delete this mem transfer.
9749
9750 if (Size > 8 || (Size&(Size-1)))
Chris Lattnerc669fb62008-01-14 00:28:35 +00009751 return 0; // If not 1/2/4/8 bytes, exit.
Chris Lattner00ae5132008-01-13 23:50:23 +00009752
Chris Lattnerc669fb62008-01-14 00:28:35 +00009753 // Use an integer load+store unless we can find something better.
Owen Anderson24be4c12009-07-03 00:17:18 +00009754 Type *NewPtrTy =
9755 Context->getPointerTypeUnqual(Context->getIntegerType(Size<<3));
Chris Lattnerc669fb62008-01-14 00:28:35 +00009756
9757 // Memcpy forces the use of i8* for the source and destination. That means
9758 // that if you're using memcpy to move one double around, you'll get a cast
9759 // from double* to i8*. We'd much rather use a double load+store rather than
9760 // an i64 load+store, here because this improves the odds that the source or
9761 // dest address will be promotable. See if we can find a better type than the
9762 // integer datatype.
9763 if (Value *Op = getBitCastOperand(MI->getOperand(1))) {
9764 const Type *SrcETy = cast<PointerType>(Op->getType())->getElementType();
9765 if (SrcETy->isSized() && TD->getTypeStoreSize(SrcETy) == Size) {
9766 // The SrcETy might be something like {{{double}}} or [1 x double]. Rip
9767 // down through these levels if so.
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009768 while (!SrcETy->isSingleValueType()) {
Chris Lattnerc669fb62008-01-14 00:28:35 +00009769 if (const StructType *STy = dyn_cast<StructType>(SrcETy)) {
9770 if (STy->getNumElements() == 1)
9771 SrcETy = STy->getElementType(0);
9772 else
9773 break;
9774 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcETy)) {
9775 if (ATy->getNumElements() == 1)
9776 SrcETy = ATy->getElementType();
9777 else
9778 break;
9779 } else
9780 break;
9781 }
9782
Dan Gohmanb8e94f62008-05-23 01:52:21 +00009783 if (SrcETy->isSingleValueType())
Owen Anderson24be4c12009-07-03 00:17:18 +00009784 NewPtrTy = Context->getPointerTypeUnqual(SrcETy);
Chris Lattnerc669fb62008-01-14 00:28:35 +00009785 }
9786 }
9787
9788
Chris Lattner00ae5132008-01-13 23:50:23 +00009789 // If the memcpy/memmove provides better alignment info than we can
9790 // infer, use it.
9791 SrcAlign = std::max(SrcAlign, CopyAlign);
9792 DstAlign = std::max(DstAlign, CopyAlign);
9793
9794 Value *Src = InsertBitCastBefore(MI->getOperand(2), NewPtrTy, *MI);
9795 Value *Dest = InsertBitCastBefore(MI->getOperand(1), NewPtrTy, *MI);
Chris Lattnerc669fb62008-01-14 00:28:35 +00009796 Instruction *L = new LoadInst(Src, "tmp", false, SrcAlign);
9797 InsertNewInstBefore(L, *MI);
9798 InsertNewInstBefore(new StoreInst(L, Dest, false, DstAlign), *MI);
9799
9800 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Anderson24be4c12009-07-03 00:17:18 +00009801 MI->setOperand(3, Context->getNullValue(MemOpLength->getType()));
Chris Lattnerc669fb62008-01-14 00:28:35 +00009802 return MI;
Chris Lattner00ae5132008-01-13 23:50:23 +00009803}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009804
Chris Lattner5af8a912008-04-30 06:39:11 +00009805Instruction *InstCombiner::SimplifyMemSet(MemSetInst *MI) {
9806 unsigned Alignment = GetOrEnforceKnownAlignment(MI->getDest());
Chris Lattner3947da72009-03-08 03:59:00 +00009807 if (MI->getAlignment() < Alignment) {
Owen Andersonf9f99362009-07-09 18:36:20 +00009808 MI->setAlignment(Context->getConstantInt(MI->getAlignmentType(),
9809 Alignment, false));
Chris Lattner5af8a912008-04-30 06:39:11 +00009810 return MI;
9811 }
9812
9813 // Extract the length and alignment and fill if they are constant.
9814 ConstantInt *LenC = dyn_cast<ConstantInt>(MI->getLength());
9815 ConstantInt *FillC = dyn_cast<ConstantInt>(MI->getValue());
9816 if (!LenC || !FillC || FillC->getType() != Type::Int8Ty)
9817 return 0;
9818 uint64_t Len = LenC->getZExtValue();
Chris Lattner3947da72009-03-08 03:59:00 +00009819 Alignment = MI->getAlignment();
Chris Lattner5af8a912008-04-30 06:39:11 +00009820
9821 // If the length is zero, this is a no-op
9822 if (Len == 0) return MI; // memset(d,c,0,a) -> noop
9823
9824 // memset(s,c,n) -> store s, c (for n=1,2,4,8)
9825 if (Len <= 8 && isPowerOf2_32((uint32_t)Len)) {
Owen Anderson24be4c12009-07-03 00:17:18 +00009826 const Type *ITy = Context->getIntegerType(Len*8); // n=1 -> i8.
Chris Lattner5af8a912008-04-30 06:39:11 +00009827
9828 Value *Dest = MI->getDest();
Owen Anderson24be4c12009-07-03 00:17:18 +00009829 Dest = InsertBitCastBefore(Dest, Context->getPointerTypeUnqual(ITy), *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +00009830
9831 // Alignment 0 is identity for alignment 1 for memset, but not store.
9832 if (Alignment == 0) Alignment = 1;
9833
9834 // Extract the fill value and store.
9835 uint64_t Fill = FillC->getZExtValue()*0x0101010101010101ULL;
Owen Anderson24be4c12009-07-03 00:17:18 +00009836 InsertNewInstBefore(new StoreInst(Context->getConstantInt(ITy, Fill),
9837 Dest, false, Alignment), *MI);
Chris Lattner5af8a912008-04-30 06:39:11 +00009838
9839 // Set the size of the copy to 0, it will be deleted on the next iteration.
Owen Anderson24be4c12009-07-03 00:17:18 +00009840 MI->setLength(Context->getNullValue(LenC->getType()));
Chris Lattner5af8a912008-04-30 06:39:11 +00009841 return MI;
9842 }
9843
9844 return 0;
9845}
9846
9847
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009848/// visitCallInst - CallInst simplification. This mostly only handles folding
9849/// of intrinsic instructions. For normal calls, it allows visitCallSite to do
9850/// the heavy lifting.
9851///
9852Instruction *InstCombiner::visitCallInst(CallInst &CI) {
Chris Lattneraa295aa2009-05-13 17:39:14 +00009853 // If the caller function is nounwind, mark the call as nounwind, even if the
9854 // callee isn't.
9855 if (CI.getParent()->getParent()->doesNotThrow() &&
9856 !CI.doesNotThrow()) {
9857 CI.setDoesNotThrow();
9858 return &CI;
9859 }
9860
9861
9862
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009863 IntrinsicInst *II = dyn_cast<IntrinsicInst>(&CI);
9864 if (!II) return visitCallSite(&CI);
9865
9866 // Intrinsics cannot occur in an invoke, so handle them here instead of in
9867 // visitCallSite.
9868 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(II)) {
9869 bool Changed = false;
9870
9871 // memmove/cpy/set of zero bytes is a noop.
9872 if (Constant *NumBytes = dyn_cast<Constant>(MI->getLength())) {
9873 if (NumBytes->isNullValue()) return EraseInstFromFunction(CI);
9874
9875 if (ConstantInt *CI = dyn_cast<ConstantInt>(NumBytes))
9876 if (CI->getZExtValue() == 1) {
9877 // Replace the instruction with just byte operations. We would
9878 // transform other cases to loads/stores, but we don't know if
9879 // alignment is sufficient.
9880 }
9881 }
9882
9883 // If we have a memmove and the source operation is a constant global,
9884 // then the source and dest pointers can't alias, so we can change this
9885 // into a call to memcpy.
Chris Lattner00ae5132008-01-13 23:50:23 +00009886 if (MemMoveInst *MMI = dyn_cast<MemMoveInst>(MI)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009887 if (GlobalVariable *GVSrc = dyn_cast<GlobalVariable>(MMI->getSource()))
9888 if (GVSrc->isConstant()) {
9889 Module *M = CI.getParent()->getParent()->getParent();
Chris Lattner82c2e432008-11-21 16:42:48 +00009890 Intrinsic::ID MemCpyID = Intrinsic::memcpy;
9891 const Type *Tys[1];
9892 Tys[0] = CI.getOperand(3)->getType();
9893 CI.setOperand(0,
9894 Intrinsic::getDeclaration(M, MemCpyID, Tys, 1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009895 Changed = true;
9896 }
Chris Lattner59b27d92008-05-28 05:30:41 +00009897
9898 // memmove(x,x,size) -> noop.
9899 if (MMI->getSource() == MMI->getDest())
9900 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009901 }
9902
9903 // If we can determine a pointer alignment that is bigger than currently
9904 // set, update the alignment.
Chris Lattnera86628a2009-03-08 03:37:16 +00009905 if (isa<MemTransferInst>(MI)) {
Chris Lattner00ae5132008-01-13 23:50:23 +00009906 if (Instruction *I = SimplifyMemTransfer(MI))
9907 return I;
Chris Lattner5af8a912008-04-30 06:39:11 +00009908 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(MI)) {
9909 if (Instruction *I = SimplifyMemSet(MSI))
9910 return I;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009911 }
9912
9913 if (Changed) return II;
Chris Lattner989ba312008-06-18 04:33:20 +00009914 }
9915
9916 switch (II->getIntrinsicID()) {
9917 default: break;
9918 case Intrinsic::bswap:
9919 // bswap(bswap(x)) -> x
9920 if (IntrinsicInst *Operand = dyn_cast<IntrinsicInst>(II->getOperand(1)))
9921 if (Operand->getIntrinsicID() == Intrinsic::bswap)
9922 return ReplaceInstUsesWith(CI, Operand->getOperand(1));
9923 break;
9924 case Intrinsic::ppc_altivec_lvx:
9925 case Intrinsic::ppc_altivec_lvxl:
9926 case Intrinsic::x86_sse_loadu_ps:
9927 case Intrinsic::x86_sse2_loadu_pd:
9928 case Intrinsic::x86_sse2_loadu_dq:
9929 // Turn PPC lvx -> load if the pointer is known aligned.
9930 // Turn X86 loadups -> load if the pointer is known aligned.
9931 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9932 Value *Ptr = InsertBitCastBefore(II->getOperand(1),
Owen Anderson24be4c12009-07-03 00:17:18 +00009933 Context->getPointerTypeUnqual(II->getType()),
Chris Lattner989ba312008-06-18 04:33:20 +00009934 CI);
9935 return new LoadInst(Ptr);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009936 }
Chris Lattner989ba312008-06-18 04:33:20 +00009937 break;
9938 case Intrinsic::ppc_altivec_stvx:
9939 case Intrinsic::ppc_altivec_stvxl:
9940 // Turn stvx -> store if the pointer is known aligned.
9941 if (GetOrEnforceKnownAlignment(II->getOperand(2), 16) >= 16) {
9942 const Type *OpPtrTy =
Owen Anderson24be4c12009-07-03 00:17:18 +00009943 Context->getPointerTypeUnqual(II->getOperand(1)->getType());
Chris Lattner989ba312008-06-18 04:33:20 +00009944 Value *Ptr = InsertBitCastBefore(II->getOperand(2), OpPtrTy, CI);
9945 return new StoreInst(II->getOperand(1), Ptr);
9946 }
9947 break;
9948 case Intrinsic::x86_sse_storeu_ps:
9949 case Intrinsic::x86_sse2_storeu_pd:
9950 case Intrinsic::x86_sse2_storeu_dq:
Chris Lattner989ba312008-06-18 04:33:20 +00009951 // Turn X86 storeu -> store if the pointer is known aligned.
9952 if (GetOrEnforceKnownAlignment(II->getOperand(1), 16) >= 16) {
9953 const Type *OpPtrTy =
Owen Anderson24be4c12009-07-03 00:17:18 +00009954 Context->getPointerTypeUnqual(II->getOperand(2)->getType());
Chris Lattner989ba312008-06-18 04:33:20 +00009955 Value *Ptr = InsertBitCastBefore(II->getOperand(1), OpPtrTy, CI);
9956 return new StoreInst(II->getOperand(2), Ptr);
9957 }
9958 break;
9959
9960 case Intrinsic::x86_sse_cvttss2si: {
9961 // These intrinsics only demands the 0th element of its input vector. If
9962 // we can simplify the input based on that, do so now.
Evan Cheng63295ab2009-02-03 10:05:09 +00009963 unsigned VWidth =
9964 cast<VectorType>(II->getOperand(1)->getType())->getNumElements();
9965 APInt DemandedElts(VWidth, 1);
9966 APInt UndefElts(VWidth, 0);
9967 if (Value *V = SimplifyDemandedVectorElts(II->getOperand(1), DemandedElts,
Chris Lattner989ba312008-06-18 04:33:20 +00009968 UndefElts)) {
9969 II->setOperand(1, V);
9970 return II;
9971 }
9972 break;
9973 }
9974
9975 case Intrinsic::ppc_altivec_vperm:
9976 // Turn vperm(V1,V2,mask) -> shuffle(V1,V2,mask) if mask is a constant.
9977 if (ConstantVector *Mask = dyn_cast<ConstantVector>(II->getOperand(3))) {
9978 assert(Mask->getNumOperands() == 16 && "Bad type for intrinsic!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009979
Chris Lattner989ba312008-06-18 04:33:20 +00009980 // Check that all of the elements are integer constants or undefs.
9981 bool AllEltsOk = true;
9982 for (unsigned i = 0; i != 16; ++i) {
9983 if (!isa<ConstantInt>(Mask->getOperand(i)) &&
9984 !isa<UndefValue>(Mask->getOperand(i))) {
9985 AllEltsOk = false;
9986 break;
9987 }
9988 }
9989
9990 if (AllEltsOk) {
9991 // Cast the input vectors to byte vectors.
9992 Value *Op0 =InsertBitCastBefore(II->getOperand(1),Mask->getType(),CI);
9993 Value *Op1 =InsertBitCastBefore(II->getOperand(2),Mask->getType(),CI);
Owen Anderson24be4c12009-07-03 00:17:18 +00009994 Value *Result = Context->getUndef(Op0->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00009995
Chris Lattner989ba312008-06-18 04:33:20 +00009996 // Only extract each element once.
9997 Value *ExtractedElts[32];
9998 memset(ExtractedElts, 0, sizeof(ExtractedElts));
9999
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010000 for (unsigned i = 0; i != 16; ++i) {
Chris Lattner989ba312008-06-18 04:33:20 +000010001 if (isa<UndefValue>(Mask->getOperand(i)))
10002 continue;
10003 unsigned Idx=cast<ConstantInt>(Mask->getOperand(i))->getZExtValue();
10004 Idx &= 31; // Match the hardware behavior.
10005
10006 if (ExtractedElts[Idx] == 0) {
10007 Instruction *Elt =
10008 new ExtractElementInst(Idx < 16 ? Op0 : Op1, Idx&15, "tmp");
10009 InsertNewInstBefore(Elt, CI);
10010 ExtractedElts[Idx] = Elt;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010011 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010012
Chris Lattner989ba312008-06-18 04:33:20 +000010013 // Insert this value into the result vector.
10014 Result = InsertElementInst::Create(Result, ExtractedElts[Idx],
10015 i, "tmp");
10016 InsertNewInstBefore(cast<Instruction>(Result), CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010017 }
Chris Lattner989ba312008-06-18 04:33:20 +000010018 return CastInst::Create(Instruction::BitCast, Result, CI.getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010019 }
Chris Lattner989ba312008-06-18 04:33:20 +000010020 }
10021 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010022
Chris Lattner989ba312008-06-18 04:33:20 +000010023 case Intrinsic::stackrestore: {
10024 // If the save is right next to the restore, remove the restore. This can
10025 // happen when variable allocas are DCE'd.
10026 if (IntrinsicInst *SS = dyn_cast<IntrinsicInst>(II->getOperand(1))) {
10027 if (SS->getIntrinsicID() == Intrinsic::stacksave) {
10028 BasicBlock::iterator BI = SS;
10029 if (&*++BI == II)
10030 return EraseInstFromFunction(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010031 }
Chris Lattner989ba312008-06-18 04:33:20 +000010032 }
10033
10034 // Scan down this block to see if there is another stack restore in the
10035 // same block without an intervening call/alloca.
10036 BasicBlock::iterator BI = II;
10037 TerminatorInst *TI = II->getParent()->getTerminator();
10038 bool CannotRemove = false;
10039 for (++BI; &*BI != TI; ++BI) {
10040 if (isa<AllocaInst>(BI)) {
10041 CannotRemove = true;
10042 break;
10043 }
Chris Lattnera6b477c2008-06-25 05:59:28 +000010044 if (CallInst *BCI = dyn_cast<CallInst>(BI)) {
10045 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(BCI)) {
10046 // If there is a stackrestore below this one, remove this one.
10047 if (II->getIntrinsicID() == Intrinsic::stackrestore)
10048 return EraseInstFromFunction(CI);
10049 // Otherwise, ignore the intrinsic.
10050 } else {
10051 // If we found a non-intrinsic call, we can't remove the stack
10052 // restore.
Chris Lattner416d91c2008-02-18 06:12:38 +000010053 CannotRemove = true;
10054 break;
10055 }
Chris Lattner989ba312008-06-18 04:33:20 +000010056 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010057 }
Chris Lattner989ba312008-06-18 04:33:20 +000010058
10059 // If the stack restore is in a return/unwind block and if there are no
10060 // allocas or calls between the restore and the return, nuke the restore.
10061 if (!CannotRemove && (isa<ReturnInst>(TI) || isa<UnwindInst>(TI)))
10062 return EraseInstFromFunction(CI);
10063 break;
10064 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010065 }
10066
10067 return visitCallSite(II);
10068}
10069
10070// InvokeInst simplification
10071//
10072Instruction *InstCombiner::visitInvokeInst(InvokeInst &II) {
10073 return visitCallSite(&II);
10074}
10075
Dale Johannesen96021832008-04-25 21:16:07 +000010076/// isSafeToEliminateVarargsCast - If this cast does not affect the value
10077/// passed through the varargs area, we can eliminate the use of the cast.
Dale Johannesen35615462008-04-23 18:34:37 +000010078static bool isSafeToEliminateVarargsCast(const CallSite CS,
10079 const CastInst * const CI,
10080 const TargetData * const TD,
10081 const int ix) {
10082 if (!CI->isLosslessCast())
10083 return false;
10084
10085 // The size of ByVal arguments is derived from the type, so we
10086 // can't change to a type with a different size. If the size were
10087 // passed explicitly we could avoid this check.
Devang Pateld222f862008-09-25 21:00:45 +000010088 if (!CS.paramHasAttr(ix, Attribute::ByVal))
Dale Johannesen35615462008-04-23 18:34:37 +000010089 return true;
10090
10091 const Type* SrcTy =
10092 cast<PointerType>(CI->getOperand(0)->getType())->getElementType();
10093 const Type* DstTy = cast<PointerType>(CI->getType())->getElementType();
10094 if (!SrcTy->isSized() || !DstTy->isSized())
10095 return false;
Duncan Sandsec4f97d2009-05-09 07:06:46 +000010096 if (TD->getTypeAllocSize(SrcTy) != TD->getTypeAllocSize(DstTy))
Dale Johannesen35615462008-04-23 18:34:37 +000010097 return false;
10098 return true;
10099}
10100
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010101// visitCallSite - Improvements for call and invoke instructions.
10102//
10103Instruction *InstCombiner::visitCallSite(CallSite CS) {
10104 bool Changed = false;
10105
10106 // If the callee is a constexpr cast of a function, attempt to move the cast
10107 // to the arguments of the call/invoke.
10108 if (transformConstExprCastCall(CS)) return 0;
10109
10110 Value *Callee = CS.getCalledValue();
10111
10112 if (Function *CalleeF = dyn_cast<Function>(Callee))
10113 if (CalleeF->getCallingConv() != CS.getCallingConv()) {
10114 Instruction *OldCall = CS.getInstruction();
10115 // If the call and callee calling conventions don't match, this call must
10116 // be unreachable, as the call is undefined.
Owen Anderson24be4c12009-07-03 00:17:18 +000010117 new StoreInst(Context->getConstantIntTrue(),
10118 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
10119 OldCall);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010120 if (!OldCall->use_empty())
Owen Anderson24be4c12009-07-03 00:17:18 +000010121 OldCall->replaceAllUsesWith(Context->getUndef(OldCall->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010122 if (isa<CallInst>(OldCall)) // Not worth removing an invoke here.
10123 return EraseInstFromFunction(*OldCall);
10124 return 0;
10125 }
10126
10127 if (isa<ConstantPointerNull>(Callee) || isa<UndefValue>(Callee)) {
10128 // This instruction is not reachable, just remove it. We insert a store to
10129 // undef so that we know that this code is not reachable, despite the fact
10130 // that we can't modify the CFG here.
Owen Anderson24be4c12009-07-03 00:17:18 +000010131 new StoreInst(Context->getConstantIntTrue(),
10132 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010133 CS.getInstruction());
10134
10135 if (!CS.getInstruction()->use_empty())
10136 CS.getInstruction()->
Owen Anderson24be4c12009-07-03 00:17:18 +000010137 replaceAllUsesWith(Context->getUndef(CS.getInstruction()->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010138
10139 if (InvokeInst *II = dyn_cast<InvokeInst>(CS.getInstruction())) {
10140 // Don't break the CFG, insert a dummy cond branch.
Gabor Greifd6da1d02008-04-06 20:25:17 +000010141 BranchInst::Create(II->getNormalDest(), II->getUnwindDest(),
Owen Anderson24be4c12009-07-03 00:17:18 +000010142 Context->getConstantIntTrue(), II);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010143 }
10144 return EraseInstFromFunction(*CS.getInstruction());
10145 }
10146
Duncan Sands74833f22007-09-17 10:26:40 +000010147 if (BitCastInst *BC = dyn_cast<BitCastInst>(Callee))
10148 if (IntrinsicInst *In = dyn_cast<IntrinsicInst>(BC->getOperand(0)))
10149 if (In->getIntrinsicID() == Intrinsic::init_trampoline)
10150 return transformCallThroughTrampoline(CS);
10151
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010152 const PointerType *PTy = cast<PointerType>(Callee->getType());
10153 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
10154 if (FTy->isVarArg()) {
Dale Johannesen502336c2008-04-23 01:03:05 +000010155 int ix = FTy->getNumParams() + (isa<InvokeInst>(Callee) ? 3 : 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010156 // See if we can optimize any arguments passed through the varargs area of
10157 // the call.
10158 for (CallSite::arg_iterator I = CS.arg_begin()+FTy->getNumParams(),
Dale Johannesen35615462008-04-23 18:34:37 +000010159 E = CS.arg_end(); I != E; ++I, ++ix) {
10160 CastInst *CI = dyn_cast<CastInst>(*I);
10161 if (CI && isSafeToEliminateVarargsCast(CS, CI, TD, ix)) {
10162 *I = CI->getOperand(0);
10163 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010164 }
Dale Johannesen35615462008-04-23 18:34:37 +000010165 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010166 }
10167
Duncan Sands2937e352007-12-19 21:13:37 +000010168 if (isa<InlineAsm>(Callee) && !CS.doesNotThrow()) {
Duncan Sands7868f3c2007-12-16 15:51:49 +000010169 // Inline asm calls cannot throw - mark them 'nounwind'.
Duncan Sands2937e352007-12-19 21:13:37 +000010170 CS.setDoesNotThrow();
Duncan Sands7868f3c2007-12-16 15:51:49 +000010171 Changed = true;
10172 }
10173
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010174 return Changed ? CS.getInstruction() : 0;
10175}
10176
10177// transformConstExprCastCall - If the callee is a constexpr cast of a function,
10178// attempt to move the cast to the arguments of the call/invoke.
10179//
10180bool InstCombiner::transformConstExprCastCall(CallSite CS) {
10181 if (!isa<ConstantExpr>(CS.getCalledValue())) return false;
10182 ConstantExpr *CE = cast<ConstantExpr>(CS.getCalledValue());
10183 if (CE->getOpcode() != Instruction::BitCast ||
10184 !isa<Function>(CE->getOperand(0)))
10185 return false;
10186 Function *Callee = cast<Function>(CE->getOperand(0));
10187 Instruction *Caller = CS.getInstruction();
Devang Pateld222f862008-09-25 21:00:45 +000010188 const AttrListPtr &CallerPAL = CS.getAttributes();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010189
10190 // Okay, this is a cast from a function to a different type. Unless doing so
10191 // would cause a type conversion of one of our arguments, change this call to
10192 // be a direct call with arguments casted to the appropriate types.
10193 //
10194 const FunctionType *FT = Callee->getFunctionType();
10195 const Type *OldRetTy = Caller->getType();
Duncan Sands7901ce12008-06-01 07:38:42 +000010196 const Type *NewRetTy = FT->getReturnType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010197
Duncan Sands7901ce12008-06-01 07:38:42 +000010198 if (isa<StructType>(NewRetTy))
Devang Pateld091d322008-03-11 18:04:06 +000010199 return false; // TODO: Handle multiple return values.
10200
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010201 // Check to see if we are changing the return type...
Duncan Sands7901ce12008-06-01 07:38:42 +000010202 if (OldRetTy != NewRetTy) {
Bill Wendlingd9644a42008-05-14 22:45:20 +000010203 if (Callee->isDeclaration() &&
Duncan Sands7901ce12008-06-01 07:38:42 +000010204 // Conversion is ok if changing from one pointer type to another or from
10205 // a pointer to an integer of the same size.
10206 !((isa<PointerType>(OldRetTy) || OldRetTy == TD->getIntPtrType()) &&
Duncan Sands886cadb2008-06-17 15:55:30 +000010207 (isa<PointerType>(NewRetTy) || NewRetTy == TD->getIntPtrType())))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010208 return false; // Cannot transform this return value.
10209
Duncan Sands5c489582008-01-06 10:12:28 +000010210 if (!Caller->use_empty() &&
Duncan Sands5c489582008-01-06 10:12:28 +000010211 // void -> non-void is handled specially
Duncan Sands7901ce12008-06-01 07:38:42 +000010212 NewRetTy != Type::VoidTy && !CastInst::isCastable(NewRetTy, OldRetTy))
Duncan Sands5c489582008-01-06 10:12:28 +000010213 return false; // Cannot transform this return value.
10214
Chris Lattner1c8733e2008-03-12 17:45:29 +000010215 if (!CallerPAL.isEmpty() && !Caller->use_empty()) {
Devang Patelf2a4a922008-09-26 22:53:05 +000010216 Attributes RAttrs = CallerPAL.getRetAttributes();
Devang Pateld222f862008-09-25 21:00:45 +000010217 if (RAttrs & Attribute::typeIncompatible(NewRetTy))
Duncan Sandsdbe97dc2008-01-07 17:16:06 +000010218 return false; // Attribute not compatible with transformed value.
10219 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010220
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010221 // If the callsite is an invoke instruction, and the return value is used by
10222 // a PHI node in a successor, we cannot change the return type of the call
10223 // because there is no place to put the cast instruction (without breaking
10224 // the critical edge). Bail out in this case.
10225 if (!Caller->use_empty())
10226 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller))
10227 for (Value::use_iterator UI = II->use_begin(), E = II->use_end();
10228 UI != E; ++UI)
10229 if (PHINode *PN = dyn_cast<PHINode>(*UI))
10230 if (PN->getParent() == II->getNormalDest() ||
10231 PN->getParent() == II->getUnwindDest())
10232 return false;
10233 }
10234
10235 unsigned NumActualArgs = unsigned(CS.arg_end()-CS.arg_begin());
10236 unsigned NumCommonArgs = std::min(FT->getNumParams(), NumActualArgs);
10237
10238 CallSite::arg_iterator AI = CS.arg_begin();
10239 for (unsigned i = 0, e = NumCommonArgs; i != e; ++i, ++AI) {
10240 const Type *ParamTy = FT->getParamType(i);
10241 const Type *ActTy = (*AI)->getType();
Duncan Sands5c489582008-01-06 10:12:28 +000010242
10243 if (!CastInst::isCastable(ActTy, ParamTy))
Duncan Sandsc849e662008-01-06 18:27:01 +000010244 return false; // Cannot transform this parameter value.
10245
Devang Patelf2a4a922008-09-26 22:53:05 +000010246 if (CallerPAL.getParamAttributes(i + 1)
10247 & Attribute::typeIncompatible(ParamTy))
Chris Lattner1c8733e2008-03-12 17:45:29 +000010248 return false; // Attribute not compatible with transformed value.
Duncan Sands5c489582008-01-06 10:12:28 +000010249
Duncan Sands7901ce12008-06-01 07:38:42 +000010250 // Converting from one pointer type to another or between a pointer and an
10251 // integer of the same size is safe even if we do not have a body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010252 bool isConvertible = ActTy == ParamTy ||
Duncan Sands7901ce12008-06-01 07:38:42 +000010253 ((isa<PointerType>(ParamTy) || ParamTy == TD->getIntPtrType()) &&
10254 (isa<PointerType>(ActTy) || ActTy == TD->getIntPtrType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010255 if (Callee->isDeclaration() && !isConvertible) return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010256 }
10257
10258 if (FT->getNumParams() < NumActualArgs && !FT->isVarArg() &&
10259 Callee->isDeclaration())
Chris Lattner1c8733e2008-03-12 17:45:29 +000010260 return false; // Do not delete arguments unless we have a function body.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010261
Chris Lattner1c8733e2008-03-12 17:45:29 +000010262 if (FT->getNumParams() < NumActualArgs && FT->isVarArg() &&
10263 !CallerPAL.isEmpty())
Duncan Sandsc849e662008-01-06 18:27:01 +000010264 // In this case we have more arguments than the new function type, but we
Duncan Sands4ced1f82008-01-13 08:02:44 +000010265 // won't be dropping them. Check that these extra arguments have attributes
10266 // that are compatible with being a vararg call argument.
Chris Lattner1c8733e2008-03-12 17:45:29 +000010267 for (unsigned i = CallerPAL.getNumSlots(); i; --i) {
10268 if (CallerPAL.getSlot(i - 1).Index <= FT->getNumParams())
Duncan Sands4ced1f82008-01-13 08:02:44 +000010269 break;
Devang Patele480dfa2008-09-23 23:03:40 +000010270 Attributes PAttrs = CallerPAL.getSlot(i - 1).Attrs;
Devang Pateld222f862008-09-25 21:00:45 +000010271 if (PAttrs & Attribute::VarArgsIncompatible)
Duncan Sands4ced1f82008-01-13 08:02:44 +000010272 return false;
10273 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010274
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010275 // Okay, we decided that this is a safe thing to do: go ahead and start
10276 // inserting cast instructions as necessary...
10277 std::vector<Value*> Args;
10278 Args.reserve(NumActualArgs);
Devang Pateld222f862008-09-25 21:00:45 +000010279 SmallVector<AttributeWithIndex, 8> attrVec;
Duncan Sandsc849e662008-01-06 18:27:01 +000010280 attrVec.reserve(NumCommonArgs);
10281
10282 // Get any return attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010283 Attributes RAttrs = CallerPAL.getRetAttributes();
Duncan Sandsc849e662008-01-06 18:27:01 +000010284
10285 // If the return value is not being used, the type may not be compatible
10286 // with the existing attributes. Wipe out any problematic attributes.
Devang Pateld222f862008-09-25 21:00:45 +000010287 RAttrs &= ~Attribute::typeIncompatible(NewRetTy);
Duncan Sandsc849e662008-01-06 18:27:01 +000010288
10289 // Add the new return attributes.
10290 if (RAttrs)
Devang Pateld222f862008-09-25 21:00:45 +000010291 attrVec.push_back(AttributeWithIndex::get(0, RAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010292
10293 AI = CS.arg_begin();
10294 for (unsigned i = 0; i != NumCommonArgs; ++i, ++AI) {
10295 const Type *ParamTy = FT->getParamType(i);
10296 if ((*AI)->getType() == ParamTy) {
10297 Args.push_back(*AI);
10298 } else {
10299 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI,
10300 false, ParamTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +000010301 CastInst *NewCast = CastInst::Create(opcode, *AI, ParamTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010302 Args.push_back(InsertNewInstBefore(NewCast, *Caller));
10303 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010304
10305 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010306 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +000010307 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010308 }
10309
10310 // If the function takes more arguments than the call was taking, add them
10311 // now...
10312 for (unsigned i = NumCommonArgs; i != FT->getNumParams(); ++i)
Owen Anderson24be4c12009-07-03 00:17:18 +000010313 Args.push_back(Context->getNullValue(FT->getParamType(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010314
10315 // If we are removing arguments to the function, emit an obnoxious warning...
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010316 if (FT->getNumParams() < NumActualArgs) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010317 if (!FT->isVarArg()) {
10318 cerr << "WARNING: While resolving call to function '"
10319 << Callee->getName() << "' arguments were dropped!\n";
10320 } else {
10321 // Add all of the arguments in their promoted form to the arg list...
10322 for (unsigned i = FT->getNumParams(); i != NumActualArgs; ++i, ++AI) {
10323 const Type *PTy = getPromotedType((*AI)->getType());
10324 if (PTy != (*AI)->getType()) {
10325 // Must promote to pass through va_arg area!
10326 Instruction::CastOps opcode = CastInst::getCastOpcode(*AI, false,
10327 PTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +000010328 Instruction *Cast = CastInst::Create(opcode, *AI, PTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010329 InsertNewInstBefore(Cast, *Caller);
10330 Args.push_back(Cast);
10331 } else {
10332 Args.push_back(*AI);
10333 }
Duncan Sandsc849e662008-01-06 18:27:01 +000010334
Duncan Sands4ced1f82008-01-13 08:02:44 +000010335 // Add any parameter attributes.
Devang Patelf2a4a922008-09-26 22:53:05 +000010336 if (Attributes PAttrs = CallerPAL.getParamAttributes(i + 1))
Devang Pateld222f862008-09-25 21:00:45 +000010337 attrVec.push_back(AttributeWithIndex::get(i + 1, PAttrs));
Duncan Sands4ced1f82008-01-13 08:02:44 +000010338 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010339 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000010340 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010341
Devang Patelf2a4a922008-09-26 22:53:05 +000010342 if (Attributes FnAttrs = CallerPAL.getFnAttributes())
10343 attrVec.push_back(AttributeWithIndex::get(~0, FnAttrs));
10344
Duncan Sands7901ce12008-06-01 07:38:42 +000010345 if (NewRetTy == Type::VoidTy)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010346 Caller->setName(""); // Void type should not have a name.
10347
Devang Pateld222f862008-09-25 21:00:45 +000010348 const AttrListPtr &NewCallerPAL = AttrListPtr::get(attrVec.begin(),attrVec.end());
Duncan Sandsc849e662008-01-06 18:27:01 +000010349
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010350 Instruction *NC;
10351 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010352 NC = InvokeInst::Create(Callee, II->getNormalDest(), II->getUnwindDest(),
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010353 Args.begin(), Args.end(),
10354 Caller->getName(), Caller);
Reid Spencer6b0b09a2007-07-30 19:53:57 +000010355 cast<InvokeInst>(NC)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010356 cast<InvokeInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010357 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010358 NC = CallInst::Create(Callee, Args.begin(), Args.end(),
10359 Caller->getName(), Caller);
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010360 CallInst *CI = cast<CallInst>(Caller);
10361 if (CI->isTailCall())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010362 cast<CallInst>(NC)->setTailCall();
Duncan Sandsf5588dc2007-11-27 13:23:08 +000010363 cast<CallInst>(NC)->setCallingConv(CI->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010364 cast<CallInst>(NC)->setAttributes(NewCallerPAL);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010365 }
10366
10367 // Insert a cast of the return type as necessary.
10368 Value *NV = NC;
Duncan Sands5c489582008-01-06 10:12:28 +000010369 if (OldRetTy != NV->getType() && !Caller->use_empty()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010370 if (NV->getType() != Type::VoidTy) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010371 Instruction::CastOps opcode = CastInst::getCastOpcode(NC, false,
Duncan Sands5c489582008-01-06 10:12:28 +000010372 OldRetTy, false);
Gabor Greifa645dd32008-05-16 19:29:10 +000010373 NV = NC = CastInst::Create(opcode, NC, OldRetTy, "tmp");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010374
10375 // If this is an invoke instruction, we should insert it after the first
10376 // non-phi, instruction in the normal successor block.
10377 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Dan Gohman514277c2008-05-23 21:05:58 +000010378 BasicBlock::iterator I = II->getNormalDest()->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010379 InsertNewInstBefore(NC, *I);
10380 } else {
10381 // Otherwise, it's a call, just insert cast right after the call instr
10382 InsertNewInstBefore(NC, *Caller);
10383 }
10384 AddUsersToWorkList(*Caller);
10385 } else {
Owen Anderson24be4c12009-07-03 00:17:18 +000010386 NV = Context->getUndef(Caller->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010387 }
10388 }
10389
10390 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10391 Caller->replaceAllUsesWith(NV);
10392 Caller->eraseFromParent();
10393 RemoveFromWorkList(Caller);
10394 return true;
10395}
10396
Duncan Sands74833f22007-09-17 10:26:40 +000010397// transformCallThroughTrampoline - Turn a call to a function created by the
10398// init_trampoline intrinsic into a direct call to the underlying function.
10399//
10400Instruction *InstCombiner::transformCallThroughTrampoline(CallSite CS) {
10401 Value *Callee = CS.getCalledValue();
10402 const PointerType *PTy = cast<PointerType>(Callee->getType());
10403 const FunctionType *FTy = cast<FunctionType>(PTy->getElementType());
Devang Pateld222f862008-09-25 21:00:45 +000010404 const AttrListPtr &Attrs = CS.getAttributes();
Duncan Sands48b81112008-01-14 19:52:09 +000010405
10406 // If the call already has the 'nest' attribute somewhere then give up -
10407 // otherwise 'nest' would occur twice after splicing in the chain.
Devang Pateld222f862008-09-25 21:00:45 +000010408 if (Attrs.hasAttrSomewhere(Attribute::Nest))
Duncan Sands48b81112008-01-14 19:52:09 +000010409 return 0;
Duncan Sands74833f22007-09-17 10:26:40 +000010410
10411 IntrinsicInst *Tramp =
10412 cast<IntrinsicInst>(cast<BitCastInst>(Callee)->getOperand(0));
10413
Anton Korobeynikov48fc88f2008-05-07 22:54:15 +000010414 Function *NestF = cast<Function>(Tramp->getOperand(2)->stripPointerCasts());
Duncan Sands74833f22007-09-17 10:26:40 +000010415 const PointerType *NestFPTy = cast<PointerType>(NestF->getType());
10416 const FunctionType *NestFTy = cast<FunctionType>(NestFPTy->getElementType());
10417
Devang Pateld222f862008-09-25 21:00:45 +000010418 const AttrListPtr &NestAttrs = NestF->getAttributes();
Chris Lattner1c8733e2008-03-12 17:45:29 +000010419 if (!NestAttrs.isEmpty()) {
Duncan Sands74833f22007-09-17 10:26:40 +000010420 unsigned NestIdx = 1;
10421 const Type *NestTy = 0;
Devang Pateld222f862008-09-25 21:00:45 +000010422 Attributes NestAttr = Attribute::None;
Duncan Sands74833f22007-09-17 10:26:40 +000010423
10424 // Look for a parameter marked with the 'nest' attribute.
10425 for (FunctionType::param_iterator I = NestFTy->param_begin(),
10426 E = NestFTy->param_end(); I != E; ++NestIdx, ++I)
Devang Pateld222f862008-09-25 21:00:45 +000010427 if (NestAttrs.paramHasAttr(NestIdx, Attribute::Nest)) {
Duncan Sands74833f22007-09-17 10:26:40 +000010428 // Record the parameter type and any other attributes.
10429 NestTy = *I;
Devang Patelf2a4a922008-09-26 22:53:05 +000010430 NestAttr = NestAttrs.getParamAttributes(NestIdx);
Duncan Sands74833f22007-09-17 10:26:40 +000010431 break;
10432 }
10433
10434 if (NestTy) {
10435 Instruction *Caller = CS.getInstruction();
10436 std::vector<Value*> NewArgs;
10437 NewArgs.reserve(unsigned(CS.arg_end()-CS.arg_begin())+1);
10438
Devang Pateld222f862008-09-25 21:00:45 +000010439 SmallVector<AttributeWithIndex, 8> NewAttrs;
Chris Lattner1c8733e2008-03-12 17:45:29 +000010440 NewAttrs.reserve(Attrs.getNumSlots() + 1);
Duncan Sands48b81112008-01-14 19:52:09 +000010441
Duncan Sands74833f22007-09-17 10:26:40 +000010442 // Insert the nest argument into the call argument list, which may
Duncan Sands48b81112008-01-14 19:52:09 +000010443 // mean appending it. Likewise for attributes.
10444
Devang Patelf2a4a922008-09-26 22:53:05 +000010445 // Add any result attributes.
10446 if (Attributes Attr = Attrs.getRetAttributes())
Devang Pateld222f862008-09-25 21:00:45 +000010447 NewAttrs.push_back(AttributeWithIndex::get(0, Attr));
Duncan Sands48b81112008-01-14 19:52:09 +000010448
Duncan Sands74833f22007-09-17 10:26:40 +000010449 {
10450 unsigned Idx = 1;
10451 CallSite::arg_iterator I = CS.arg_begin(), E = CS.arg_end();
10452 do {
10453 if (Idx == NestIdx) {
Duncan Sands48b81112008-01-14 19:52:09 +000010454 // Add the chain argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000010455 Value *NestVal = Tramp->getOperand(3);
10456 if (NestVal->getType() != NestTy)
10457 NestVal = new BitCastInst(NestVal, NestTy, "nest", Caller);
10458 NewArgs.push_back(NestVal);
Devang Pateld222f862008-09-25 21:00:45 +000010459 NewAttrs.push_back(AttributeWithIndex::get(NestIdx, NestAttr));
Duncan Sands74833f22007-09-17 10:26:40 +000010460 }
10461
10462 if (I == E)
10463 break;
10464
Duncan Sands48b81112008-01-14 19:52:09 +000010465 // Add the original argument and attributes.
Duncan Sands74833f22007-09-17 10:26:40 +000010466 NewArgs.push_back(*I);
Devang Patelf2a4a922008-09-26 22:53:05 +000010467 if (Attributes Attr = Attrs.getParamAttributes(Idx))
Duncan Sands48b81112008-01-14 19:52:09 +000010468 NewAttrs.push_back
Devang Pateld222f862008-09-25 21:00:45 +000010469 (AttributeWithIndex::get(Idx + (Idx >= NestIdx), Attr));
Duncan Sands74833f22007-09-17 10:26:40 +000010470
10471 ++Idx, ++I;
10472 } while (1);
10473 }
10474
Devang Patelf2a4a922008-09-26 22:53:05 +000010475 // Add any function attributes.
10476 if (Attributes Attr = Attrs.getFnAttributes())
10477 NewAttrs.push_back(AttributeWithIndex::get(~0, Attr));
10478
Duncan Sands74833f22007-09-17 10:26:40 +000010479 // The trampoline may have been bitcast to a bogus type (FTy).
10480 // Handle this by synthesizing a new function type, equal to FTy
Duncan Sands48b81112008-01-14 19:52:09 +000010481 // with the chain parameter inserted.
Duncan Sands74833f22007-09-17 10:26:40 +000010482
Duncan Sands74833f22007-09-17 10:26:40 +000010483 std::vector<const Type*> NewTypes;
Duncan Sands74833f22007-09-17 10:26:40 +000010484 NewTypes.reserve(FTy->getNumParams()+1);
10485
Duncan Sands74833f22007-09-17 10:26:40 +000010486 // Insert the chain's type into the list of parameter types, which may
Duncan Sands48b81112008-01-14 19:52:09 +000010487 // mean appending it.
Duncan Sands74833f22007-09-17 10:26:40 +000010488 {
10489 unsigned Idx = 1;
10490 FunctionType::param_iterator I = FTy->param_begin(),
10491 E = FTy->param_end();
10492
10493 do {
Duncan Sands48b81112008-01-14 19:52:09 +000010494 if (Idx == NestIdx)
10495 // Add the chain's type.
Duncan Sands74833f22007-09-17 10:26:40 +000010496 NewTypes.push_back(NestTy);
Duncan Sands74833f22007-09-17 10:26:40 +000010497
10498 if (I == E)
10499 break;
10500
Duncan Sands48b81112008-01-14 19:52:09 +000010501 // Add the original type.
Duncan Sands74833f22007-09-17 10:26:40 +000010502 NewTypes.push_back(*I);
Duncan Sands74833f22007-09-17 10:26:40 +000010503
10504 ++Idx, ++I;
10505 } while (1);
10506 }
10507
10508 // Replace the trampoline call with a direct call. Let the generic
10509 // code sort out any function type mismatches.
10510 FunctionType *NewFTy =
Owen Anderson24be4c12009-07-03 00:17:18 +000010511 Context->getFunctionType(FTy->getReturnType(), NewTypes,
10512 FTy->isVarArg());
10513 Constant *NewCallee =
10514 NestF->getType() == Context->getPointerTypeUnqual(NewFTy) ?
10515 NestF : Context->getConstantExprBitCast(NestF,
10516 Context->getPointerTypeUnqual(NewFTy));
Devang Pateld222f862008-09-25 21:00:45 +000010517 const AttrListPtr &NewPAL = AttrListPtr::get(NewAttrs.begin(),NewAttrs.end());
Duncan Sands74833f22007-09-17 10:26:40 +000010518
10519 Instruction *NewCaller;
10520 if (InvokeInst *II = dyn_cast<InvokeInst>(Caller)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010521 NewCaller = InvokeInst::Create(NewCallee,
10522 II->getNormalDest(), II->getUnwindDest(),
10523 NewArgs.begin(), NewArgs.end(),
10524 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010525 cast<InvokeInst>(NewCaller)->setCallingConv(II->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010526 cast<InvokeInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000010527 } else {
Gabor Greifd6da1d02008-04-06 20:25:17 +000010528 NewCaller = CallInst::Create(NewCallee, NewArgs.begin(), NewArgs.end(),
10529 Caller->getName(), Caller);
Duncan Sands74833f22007-09-17 10:26:40 +000010530 if (cast<CallInst>(Caller)->isTailCall())
10531 cast<CallInst>(NewCaller)->setTailCall();
10532 cast<CallInst>(NewCaller)->
10533 setCallingConv(cast<CallInst>(Caller)->getCallingConv());
Devang Pateld222f862008-09-25 21:00:45 +000010534 cast<CallInst>(NewCaller)->setAttributes(NewPAL);
Duncan Sands74833f22007-09-17 10:26:40 +000010535 }
10536 if (Caller->getType() != Type::VoidTy && !Caller->use_empty())
10537 Caller->replaceAllUsesWith(NewCaller);
10538 Caller->eraseFromParent();
10539 RemoveFromWorkList(Caller);
10540 return 0;
10541 }
10542 }
10543
10544 // Replace the trampoline call with a direct call. Since there is no 'nest'
10545 // parameter, there is no need to adjust the argument list. Let the generic
10546 // code sort out any function type mismatches.
10547 Constant *NewCallee =
Owen Anderson24be4c12009-07-03 00:17:18 +000010548 NestF->getType() == PTy ? NestF :
10549 Context->getConstantExprBitCast(NestF, PTy);
Duncan Sands74833f22007-09-17 10:26:40 +000010550 CS.setCalledFunction(NewCallee);
10551 return CS.getInstruction();
10552}
10553
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010554/// FoldPHIArgBinOpIntoPHI - If we have something like phi [add (a,b), add(c,d)]
10555/// and if a/b/c/d and the add's all have a single use, turn this into two phi's
10556/// and a single binop.
10557Instruction *InstCombiner::FoldPHIArgBinOpIntoPHI(PHINode &PN) {
10558 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
Chris Lattner30078012008-12-01 03:42:51 +000010559 assert(isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010560 unsigned Opc = FirstInst->getOpcode();
10561 Value *LHSVal = FirstInst->getOperand(0);
10562 Value *RHSVal = FirstInst->getOperand(1);
10563
10564 const Type *LHSType = LHSVal->getType();
10565 const Type *RHSType = RHSVal->getType();
10566
10567 // Scan to see if all operands are the same opcode, all have one use, and all
10568 // kill their operands (i.e. the operands have one use).
Chris Lattner9e1916e2008-12-01 02:34:36 +000010569 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010570 Instruction *I = dyn_cast<Instruction>(PN.getIncomingValue(i));
10571 if (!I || I->getOpcode() != Opc || !I->hasOneUse() ||
10572 // Verify type of the LHS matches so we don't fold cmp's of different
10573 // types or GEP's with different index types.
10574 I->getOperand(0)->getType() != LHSType ||
10575 I->getOperand(1)->getType() != RHSType)
10576 return 0;
10577
10578 // If they are CmpInst instructions, check their predicates
10579 if (Opc == Instruction::ICmp || Opc == Instruction::FCmp)
10580 if (cast<CmpInst>(I)->getPredicate() !=
10581 cast<CmpInst>(FirstInst)->getPredicate())
10582 return 0;
10583
10584 // Keep track of which operand needs a phi node.
10585 if (I->getOperand(0) != LHSVal) LHSVal = 0;
10586 if (I->getOperand(1) != RHSVal) RHSVal = 0;
10587 }
10588
Chris Lattner30078012008-12-01 03:42:51 +000010589 // Otherwise, this is safe to transform!
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010590
10591 Value *InLHS = FirstInst->getOperand(0);
10592 Value *InRHS = FirstInst->getOperand(1);
10593 PHINode *NewLHS = 0, *NewRHS = 0;
10594 if (LHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010595 NewLHS = PHINode::Create(LHSType,
10596 FirstInst->getOperand(0)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010597 NewLHS->reserveOperandSpace(PN.getNumOperands()/2);
10598 NewLHS->addIncoming(InLHS, PN.getIncomingBlock(0));
10599 InsertNewInstBefore(NewLHS, PN);
10600 LHSVal = NewLHS;
10601 }
10602
10603 if (RHSVal == 0) {
Gabor Greifb91ea9d2008-05-15 10:04:30 +000010604 NewRHS = PHINode::Create(RHSType,
10605 FirstInst->getOperand(1)->getName() + ".pn");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010606 NewRHS->reserveOperandSpace(PN.getNumOperands()/2);
10607 NewRHS->addIncoming(InRHS, PN.getIncomingBlock(0));
10608 InsertNewInstBefore(NewRHS, PN);
10609 RHSVal = NewRHS;
10610 }
10611
10612 // Add all operands to the new PHIs.
Chris Lattner9e1916e2008-12-01 02:34:36 +000010613 if (NewLHS || NewRHS) {
10614 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10615 Instruction *InInst = cast<Instruction>(PN.getIncomingValue(i));
10616 if (NewLHS) {
10617 Value *NewInLHS = InInst->getOperand(0);
10618 NewLHS->addIncoming(NewInLHS, PN.getIncomingBlock(i));
10619 }
10620 if (NewRHS) {
10621 Value *NewInRHS = InInst->getOperand(1);
10622 NewRHS->addIncoming(NewInRHS, PN.getIncomingBlock(i));
10623 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010624 }
10625 }
10626
10627 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010628 return BinaryOperator::Create(BinOp->getOpcode(), LHSVal, RHSVal);
Chris Lattner30078012008-12-01 03:42:51 +000010629 CmpInst *CIOp = cast<CmpInst>(FirstInst);
Owen Anderson6601fcd2009-07-09 23:48:35 +000010630 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
10631 LHSVal, RHSVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010632}
10633
Chris Lattner9e1916e2008-12-01 02:34:36 +000010634Instruction *InstCombiner::FoldPHIArgGEPIntoPHI(PHINode &PN) {
10635 GetElementPtrInst *FirstInst =cast<GetElementPtrInst>(PN.getIncomingValue(0));
10636
10637 SmallVector<Value*, 16> FixedOperands(FirstInst->op_begin(),
10638 FirstInst->op_end());
Chris Lattneradf354b2009-02-21 00:46:50 +000010639 // This is true if all GEP bases are allocas and if all indices into them are
10640 // constants.
10641 bool AllBasePointersAreAllocas = true;
Chris Lattner9e1916e2008-12-01 02:34:36 +000010642
10643 // Scan to see if all operands are the same opcode, all have one use, and all
10644 // kill their operands (i.e. the operands have one use).
10645 for (unsigned i = 1; i != PN.getNumIncomingValues(); ++i) {
10646 GetElementPtrInst *GEP= dyn_cast<GetElementPtrInst>(PN.getIncomingValue(i));
10647 if (!GEP || !GEP->hasOneUse() || GEP->getType() != FirstInst->getType() ||
10648 GEP->getNumOperands() != FirstInst->getNumOperands())
10649 return 0;
10650
Chris Lattneradf354b2009-02-21 00:46:50 +000010651 // Keep track of whether or not all GEPs are of alloca pointers.
10652 if (AllBasePointersAreAllocas &&
10653 (!isa<AllocaInst>(GEP->getOperand(0)) ||
10654 !GEP->hasAllConstantIndices()))
10655 AllBasePointersAreAllocas = false;
10656
Chris Lattner9e1916e2008-12-01 02:34:36 +000010657 // Compare the operand lists.
10658 for (unsigned op = 0, e = FirstInst->getNumOperands(); op != e; ++op) {
10659 if (FirstInst->getOperand(op) == GEP->getOperand(op))
10660 continue;
10661
10662 // Don't merge two GEPs when two operands differ (introducing phi nodes)
10663 // if one of the PHIs has a constant for the index. The index may be
10664 // substantially cheaper to compute for the constants, so making it a
10665 // variable index could pessimize the path. This also handles the case
10666 // for struct indices, which must always be constant.
10667 if (isa<ConstantInt>(FirstInst->getOperand(op)) ||
10668 isa<ConstantInt>(GEP->getOperand(op)))
10669 return 0;
10670
10671 if (FirstInst->getOperand(op)->getType() !=GEP->getOperand(op)->getType())
10672 return 0;
10673 FixedOperands[op] = 0; // Needs a PHI.
10674 }
10675 }
10676
Chris Lattneradf354b2009-02-21 00:46:50 +000010677 // If all of the base pointers of the PHI'd GEPs are from allocas, don't
Chris Lattnerf1e30c82009-02-23 05:56:17 +000010678 // bother doing this transformation. At best, this will just save a bit of
Chris Lattneradf354b2009-02-21 00:46:50 +000010679 // offset calculation, but all the predecessors will have to materialize the
10680 // stack address into a register anyway. We'd actually rather *clone* the
10681 // load up into the predecessors so that we have a load of a gep of an alloca,
10682 // which can usually all be folded into the load.
10683 if (AllBasePointersAreAllocas)
10684 return 0;
10685
Chris Lattner9e1916e2008-12-01 02:34:36 +000010686 // Otherwise, this is safe to transform. Insert PHI nodes for each operand
10687 // that is variable.
10688 SmallVector<PHINode*, 16> OperandPhis(FixedOperands.size());
10689
10690 bool HasAnyPHIs = false;
10691 for (unsigned i = 0, e = FixedOperands.size(); i != e; ++i) {
10692 if (FixedOperands[i]) continue; // operand doesn't need a phi.
10693 Value *FirstOp = FirstInst->getOperand(i);
10694 PHINode *NewPN = PHINode::Create(FirstOp->getType(),
10695 FirstOp->getName()+".pn");
10696 InsertNewInstBefore(NewPN, PN);
10697
10698 NewPN->reserveOperandSpace(e);
10699 NewPN->addIncoming(FirstOp, PN.getIncomingBlock(0));
10700 OperandPhis[i] = NewPN;
10701 FixedOperands[i] = NewPN;
10702 HasAnyPHIs = true;
10703 }
10704
10705
10706 // Add all operands to the new PHIs.
10707 if (HasAnyPHIs) {
10708 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10709 GetElementPtrInst *InGEP =cast<GetElementPtrInst>(PN.getIncomingValue(i));
10710 BasicBlock *InBB = PN.getIncomingBlock(i);
10711
10712 for (unsigned op = 0, e = OperandPhis.size(); op != e; ++op)
10713 if (PHINode *OpPhi = OperandPhis[op])
10714 OpPhi->addIncoming(InGEP->getOperand(op), InBB);
10715 }
10716 }
10717
10718 Value *Base = FixedOperands[0];
10719 return GetElementPtrInst::Create(Base, FixedOperands.begin()+1,
10720 FixedOperands.end());
10721}
10722
10723
Chris Lattnerf1e30c82009-02-23 05:56:17 +000010724/// isSafeAndProfitableToSinkLoad - Return true if we know that it is safe to
10725/// sink the load out of the block that defines it. This means that it must be
Chris Lattneradf354b2009-02-21 00:46:50 +000010726/// obvious the value of the load is not changed from the point of the load to
10727/// the end of the block it is in.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010728///
10729/// Finally, it is safe, but not profitable, to sink a load targetting a
10730/// non-address-taken alloca. Doing so will cause us to not promote the alloca
10731/// to a register.
Chris Lattneradf354b2009-02-21 00:46:50 +000010732static bool isSafeAndProfitableToSinkLoad(LoadInst *L) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010733 BasicBlock::iterator BBI = L, E = L->getParent()->end();
10734
10735 for (++BBI; BBI != E; ++BBI)
10736 if (BBI->mayWriteToMemory())
10737 return false;
10738
10739 // Check for non-address taken alloca. If not address-taken already, it isn't
10740 // profitable to do this xform.
10741 if (AllocaInst *AI = dyn_cast<AllocaInst>(L->getOperand(0))) {
10742 bool isAddressTaken = false;
10743 for (Value::use_iterator UI = AI->use_begin(), E = AI->use_end();
10744 UI != E; ++UI) {
10745 if (isa<LoadInst>(UI)) continue;
10746 if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
10747 // If storing TO the alloca, then the address isn't taken.
10748 if (SI->getOperand(1) == AI) continue;
10749 }
10750 isAddressTaken = true;
10751 break;
10752 }
10753
Chris Lattneradf354b2009-02-21 00:46:50 +000010754 if (!isAddressTaken && AI->isStaticAlloca())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010755 return false;
10756 }
10757
Chris Lattneradf354b2009-02-21 00:46:50 +000010758 // If this load is a load from a GEP with a constant offset from an alloca,
10759 // then we don't want to sink it. In its present form, it will be
10760 // load [constant stack offset]. Sinking it will cause us to have to
10761 // materialize the stack addresses in each predecessor in a register only to
10762 // do a shared load from register in the successor.
10763 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(L->getOperand(0)))
10764 if (AllocaInst *AI = dyn_cast<AllocaInst>(GEP->getOperand(0)))
10765 if (AI->isStaticAlloca() && GEP->hasAllConstantIndices())
10766 return false;
10767
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010768 return true;
10769}
10770
10771
10772// FoldPHIArgOpIntoPHI - If all operands to a PHI node are the same "unary"
10773// operator and they all are only used by the PHI, PHI together their
10774// inputs, and do the operation once, to the result of the PHI.
10775Instruction *InstCombiner::FoldPHIArgOpIntoPHI(PHINode &PN) {
10776 Instruction *FirstInst = cast<Instruction>(PN.getIncomingValue(0));
10777
10778 // Scan the instruction, looking for input operations that can be folded away.
10779 // If all input operands to the phi are the same instruction (e.g. a cast from
10780 // the same type or "+42") we can pull the operation through the PHI, reducing
10781 // code size and simplifying code.
10782 Constant *ConstantOp = 0;
10783 const Type *CastSrcTy = 0;
10784 bool isVolatile = false;
10785 if (isa<CastInst>(FirstInst)) {
10786 CastSrcTy = FirstInst->getOperand(0)->getType();
10787 } else if (isa<BinaryOperator>(FirstInst) || isa<CmpInst>(FirstInst)) {
10788 // Can fold binop, compare or shift here if the RHS is a constant,
10789 // otherwise call FoldPHIArgBinOpIntoPHI.
10790 ConstantOp = dyn_cast<Constant>(FirstInst->getOperand(1));
10791 if (ConstantOp == 0)
10792 return FoldPHIArgBinOpIntoPHI(PN);
10793 } else if (LoadInst *LI = dyn_cast<LoadInst>(FirstInst)) {
10794 isVolatile = LI->isVolatile();
10795 // We can't sink the load if the loaded value could be modified between the
10796 // load and the PHI.
10797 if (LI->getParent() != PN.getIncomingBlock(0) ||
Chris Lattneradf354b2009-02-21 00:46:50 +000010798 !isSafeAndProfitableToSinkLoad(LI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010799 return 0;
Chris Lattner2d9fdd82008-07-08 17:18:32 +000010800
10801 // If the PHI is of volatile loads and the load block has multiple
10802 // successors, sinking it would remove a load of the volatile value from
10803 // the path through the other successor.
10804 if (isVolatile &&
10805 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10806 return 0;
10807
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010808 } else if (isa<GetElementPtrInst>(FirstInst)) {
Chris Lattner9e1916e2008-12-01 02:34:36 +000010809 return FoldPHIArgGEPIntoPHI(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010810 } else {
10811 return 0; // Cannot fold this operation.
10812 }
10813
10814 // Check to see if all arguments are the same operation.
10815 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10816 if (!isa<Instruction>(PN.getIncomingValue(i))) return 0;
10817 Instruction *I = cast<Instruction>(PN.getIncomingValue(i));
10818 if (!I->hasOneUse() || !I->isSameOperationAs(FirstInst))
10819 return 0;
10820 if (CastSrcTy) {
10821 if (I->getOperand(0)->getType() != CastSrcTy)
10822 return 0; // Cast operation must match.
10823 } else if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
10824 // We can't sink the load if the loaded value could be modified between
10825 // the load and the PHI.
10826 if (LI->isVolatile() != isVolatile ||
10827 LI->getParent() != PN.getIncomingBlock(i) ||
Chris Lattneradf354b2009-02-21 00:46:50 +000010828 !isSafeAndProfitableToSinkLoad(LI))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010829 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +000010830
Chris Lattner2d9fdd82008-07-08 17:18:32 +000010831 // If the PHI is of volatile loads and the load block has multiple
10832 // successors, sinking it would remove a load of the volatile value from
10833 // the path through the other successor.
Chris Lattnerf7867012008-04-29 17:28:22 +000010834 if (isVolatile &&
10835 LI->getParent()->getTerminator()->getNumSuccessors() != 1)
10836 return 0;
Chris Lattnerf7867012008-04-29 17:28:22 +000010837
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010838 } else if (I->getOperand(1) != ConstantOp) {
10839 return 0;
10840 }
10841 }
10842
10843 // Okay, they are all the same operation. Create a new PHI node of the
10844 // correct type, and PHI together all of the LHS's of the instructions.
Gabor Greifd6da1d02008-04-06 20:25:17 +000010845 PHINode *NewPN = PHINode::Create(FirstInst->getOperand(0)->getType(),
10846 PN.getName()+".in");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010847 NewPN->reserveOperandSpace(PN.getNumOperands()/2);
10848
10849 Value *InVal = FirstInst->getOperand(0);
10850 NewPN->addIncoming(InVal, PN.getIncomingBlock(0));
10851
10852 // Add all operands to the new PHI.
10853 for (unsigned i = 1, e = PN.getNumIncomingValues(); i != e; ++i) {
10854 Value *NewInVal = cast<Instruction>(PN.getIncomingValue(i))->getOperand(0);
10855 if (NewInVal != InVal)
10856 InVal = 0;
10857 NewPN->addIncoming(NewInVal, PN.getIncomingBlock(i));
10858 }
10859
10860 Value *PhiVal;
10861 if (InVal) {
10862 // The new PHI unions all of the same values together. This is really
10863 // common, so we handle it intelligently here for compile-time speed.
10864 PhiVal = InVal;
10865 delete NewPN;
10866 } else {
10867 InsertNewInstBefore(NewPN, PN);
10868 PhiVal = NewPN;
10869 }
10870
10871 // Insert and return the new operation.
10872 if (CastInst* FirstCI = dyn_cast<CastInst>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010873 return CastInst::Create(FirstCI->getOpcode(), PhiVal, PN.getType());
Chris Lattnerfc984e92008-04-29 17:13:43 +000010874 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(FirstInst))
Gabor Greifa645dd32008-05-16 19:29:10 +000010875 return BinaryOperator::Create(BinOp->getOpcode(), PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +000010876 if (CmpInst *CIOp = dyn_cast<CmpInst>(FirstInst))
Owen Anderson6601fcd2009-07-09 23:48:35 +000010877 return CmpInst::Create(*Context, CIOp->getOpcode(), CIOp->getPredicate(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010878 PhiVal, ConstantOp);
Chris Lattnerfc984e92008-04-29 17:13:43 +000010879 assert(isa<LoadInst>(FirstInst) && "Unknown operation");
10880
10881 // If this was a volatile load that we are merging, make sure to loop through
10882 // and mark all the input loads as non-volatile. If we don't do this, we will
10883 // insert a new volatile load and the old ones will not be deletable.
10884 if (isVolatile)
10885 for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
10886 cast<LoadInst>(PN.getIncomingValue(i))->setVolatile(false);
10887
10888 return new LoadInst(PhiVal, "", isVolatile);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010889}
10890
10891/// DeadPHICycle - Return true if this PHI node is only used by a PHI node cycle
10892/// that is dead.
10893static bool DeadPHICycle(PHINode *PN,
10894 SmallPtrSet<PHINode*, 16> &PotentiallyDeadPHIs) {
10895 if (PN->use_empty()) return true;
10896 if (!PN->hasOneUse()) return false;
10897
10898 // Remember this node, and if we find the cycle, return.
10899 if (!PotentiallyDeadPHIs.insert(PN))
10900 return true;
Chris Lattneradf2e342007-08-28 04:23:55 +000010901
10902 // Don't scan crazily complex things.
10903 if (PotentiallyDeadPHIs.size() == 16)
10904 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010905
10906 if (PHINode *PU = dyn_cast<PHINode>(PN->use_back()))
10907 return DeadPHICycle(PU, PotentiallyDeadPHIs);
10908
10909 return false;
10910}
10911
Chris Lattner27b695d2007-11-06 21:52:06 +000010912/// PHIsEqualValue - Return true if this phi node is always equal to
10913/// NonPhiInVal. This happens with mutually cyclic phi nodes like:
10914/// z = some value; x = phi (y, z); y = phi (x, z)
10915static bool PHIsEqualValue(PHINode *PN, Value *NonPhiInVal,
10916 SmallPtrSet<PHINode*, 16> &ValueEqualPHIs) {
10917 // See if we already saw this PHI node.
10918 if (!ValueEqualPHIs.insert(PN))
10919 return true;
10920
10921 // Don't scan crazily complex things.
10922 if (ValueEqualPHIs.size() == 16)
10923 return false;
10924
10925 // Scan the operands to see if they are either phi nodes or are equal to
10926 // the value.
10927 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
10928 Value *Op = PN->getIncomingValue(i);
10929 if (PHINode *OpPN = dyn_cast<PHINode>(Op)) {
10930 if (!PHIsEqualValue(OpPN, NonPhiInVal, ValueEqualPHIs))
10931 return false;
10932 } else if (Op != NonPhiInVal)
10933 return false;
10934 }
10935
10936 return true;
10937}
10938
10939
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010940// PHINode simplification
10941//
10942Instruction *InstCombiner::visitPHINode(PHINode &PN) {
10943 // If LCSSA is around, don't mess with Phi nodes
10944 if (MustPreserveLCSSA) return 0;
10945
10946 if (Value *V = PN.hasConstantValue())
10947 return ReplaceInstUsesWith(PN, V);
10948
10949 // If all PHI operands are the same operation, pull them through the PHI,
10950 // reducing code size.
10951 if (isa<Instruction>(PN.getIncomingValue(0)) &&
Chris Lattner9e1916e2008-12-01 02:34:36 +000010952 isa<Instruction>(PN.getIncomingValue(1)) &&
10953 cast<Instruction>(PN.getIncomingValue(0))->getOpcode() ==
10954 cast<Instruction>(PN.getIncomingValue(1))->getOpcode() &&
10955 // FIXME: The hasOneUse check will fail for PHIs that use the value more
10956 // than themselves more than once.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010957 PN.getIncomingValue(0)->hasOneUse())
10958 if (Instruction *Result = FoldPHIArgOpIntoPHI(PN))
10959 return Result;
10960
10961 // If this is a trivial cycle in the PHI node graph, remove it. Basically, if
10962 // this PHI only has a single use (a PHI), and if that PHI only has one use (a
10963 // PHI)... break the cycle.
10964 if (PN.hasOneUse()) {
10965 Instruction *PHIUser = cast<Instruction>(PN.use_back());
10966 if (PHINode *PU = dyn_cast<PHINode>(PHIUser)) {
10967 SmallPtrSet<PHINode*, 16> PotentiallyDeadPHIs;
10968 PotentiallyDeadPHIs.insert(&PN);
10969 if (DeadPHICycle(PU, PotentiallyDeadPHIs))
Owen Anderson24be4c12009-07-03 00:17:18 +000010970 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010971 }
10972
10973 // If this phi has a single use, and if that use just computes a value for
10974 // the next iteration of a loop, delete the phi. This occurs with unused
10975 // induction variables, e.g. "for (int j = 0; ; ++j);". Detecting this
10976 // common case here is good because the only other things that catch this
10977 // are induction variable analysis (sometimes) and ADCE, which is only run
10978 // late.
10979 if (PHIUser->hasOneUse() &&
10980 (isa<BinaryOperator>(PHIUser) || isa<GetElementPtrInst>(PHIUser)) &&
10981 PHIUser->use_back() == &PN) {
Owen Anderson24be4c12009-07-03 00:17:18 +000010982 return ReplaceInstUsesWith(PN, Context->getUndef(PN.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000010983 }
10984 }
10985
Chris Lattner27b695d2007-11-06 21:52:06 +000010986 // We sometimes end up with phi cycles that non-obviously end up being the
10987 // same value, for example:
10988 // z = some value; x = phi (y, z); y = phi (x, z)
10989 // where the phi nodes don't necessarily need to be in the same block. Do a
10990 // quick check to see if the PHI node only contains a single non-phi value, if
10991 // so, scan to see if the phi cycle is actually equal to that value.
10992 {
10993 unsigned InValNo = 0, NumOperandVals = PN.getNumIncomingValues();
10994 // Scan for the first non-phi operand.
10995 while (InValNo != NumOperandVals &&
10996 isa<PHINode>(PN.getIncomingValue(InValNo)))
10997 ++InValNo;
10998
10999 if (InValNo != NumOperandVals) {
11000 Value *NonPhiInVal = PN.getOperand(InValNo);
11001
11002 // Scan the rest of the operands to see if there are any conflicts, if so
11003 // there is no need to recursively scan other phis.
11004 for (++InValNo; InValNo != NumOperandVals; ++InValNo) {
11005 Value *OpVal = PN.getIncomingValue(InValNo);
11006 if (OpVal != NonPhiInVal && !isa<PHINode>(OpVal))
11007 break;
11008 }
11009
11010 // If we scanned over all operands, then we have one unique value plus
11011 // phi values. Scan PHI nodes to see if they all merge in each other or
11012 // the value.
11013 if (InValNo == NumOperandVals) {
11014 SmallPtrSet<PHINode*, 16> ValueEqualPHIs;
11015 if (PHIsEqualValue(&PN, NonPhiInVal, ValueEqualPHIs))
11016 return ReplaceInstUsesWith(PN, NonPhiInVal);
11017 }
11018 }
11019 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011020 return 0;
11021}
11022
11023static Value *InsertCastToIntPtrTy(Value *V, const Type *DTy,
11024 Instruction *InsertPoint,
11025 InstCombiner *IC) {
Dan Gohman8fd520a2009-06-15 22:12:54 +000011026 unsigned PtrSize = DTy->getScalarSizeInBits();
11027 unsigned VTySize = V->getType()->getScalarSizeInBits();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011028 // We must cast correctly to the pointer type. Ensure that we
11029 // sign extend the integer value if it is smaller as this is
11030 // used for address computation.
11031 Instruction::CastOps opcode =
11032 (VTySize < PtrSize ? Instruction::SExt :
11033 (VTySize == PtrSize ? Instruction::BitCast : Instruction::Trunc));
11034 return IC->InsertCastBefore(opcode, V, DTy, *InsertPoint);
11035}
11036
11037
11038Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
11039 Value *PtrOp = GEP.getOperand(0);
11040 // Is it 'getelementptr %P, i32 0' or 'getelementptr %P'
11041 // If so, eliminate the noop.
11042 if (GEP.getNumOperands() == 1)
11043 return ReplaceInstUsesWith(GEP, PtrOp);
11044
11045 if (isa<UndefValue>(GEP.getOperand(0)))
Owen Anderson24be4c12009-07-03 00:17:18 +000011046 return ReplaceInstUsesWith(GEP, Context->getUndef(GEP.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011047
11048 bool HasZeroPointerIndex = false;
11049 if (Constant *C = dyn_cast<Constant>(GEP.getOperand(1)))
11050 HasZeroPointerIndex = C->isNullValue();
11051
11052 if (GEP.getNumOperands() == 2 && HasZeroPointerIndex)
11053 return ReplaceInstUsesWith(GEP, PtrOp);
11054
11055 // Eliminate unneeded casts for indices.
11056 bool MadeChange = false;
11057
11058 gep_type_iterator GTI = gep_type_begin(GEP);
Gabor Greif17396002008-06-12 21:37:33 +000011059 for (User::op_iterator i = GEP.op_begin() + 1, e = GEP.op_end();
11060 i != e; ++i, ++GTI) {
Sanjiv Gupta7f712d82009-04-24 02:37:54 +000011061 if (isa<SequentialType>(*GTI)) {
Gabor Greif17396002008-06-12 21:37:33 +000011062 if (CastInst *CI = dyn_cast<CastInst>(*i)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011063 if (CI->getOpcode() == Instruction::ZExt ||
11064 CI->getOpcode() == Instruction::SExt) {
11065 const Type *SrcTy = CI->getOperand(0)->getType();
11066 // We can eliminate a cast from i32 to i64 iff the target
11067 // is a 32-bit pointer target.
Dan Gohman8fd520a2009-06-15 22:12:54 +000011068 if (SrcTy->getScalarSizeInBits() >= TD->getPointerSizeInBits()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011069 MadeChange = true;
Gabor Greif17396002008-06-12 21:37:33 +000011070 *i = CI->getOperand(0);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011071 }
11072 }
11073 }
11074 // If we are using a wider index than needed for this platform, shrink it
Dan Gohman5d639ed2008-09-11 23:06:38 +000011075 // to what we need. If narrower, sign-extend it to what we need.
11076 // If the incoming value needs a cast instruction,
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011077 // insert it. This explicit cast can make subsequent optimizations more
11078 // obvious.
Gabor Greif17396002008-06-12 21:37:33 +000011079 Value *Op = *i;
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011080 if (TD->getTypeSizeInBits(Op->getType()) > TD->getPointerSizeInBits()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011081 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Anderson24be4c12009-07-03 00:17:18 +000011082 *i = Context->getConstantExprTrunc(C, TD->getIntPtrType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011083 MadeChange = true;
11084 } else {
11085 Op = InsertCastBefore(Instruction::Trunc, Op, TD->getIntPtrType(),
11086 GEP);
Gabor Greif17396002008-06-12 21:37:33 +000011087 *i = Op;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011088 MadeChange = true;
11089 }
Dan Gohman5d639ed2008-09-11 23:06:38 +000011090 } else if (TD->getTypeSizeInBits(Op->getType()) < TD->getPointerSizeInBits()) {
11091 if (Constant *C = dyn_cast<Constant>(Op)) {
Owen Anderson24be4c12009-07-03 00:17:18 +000011092 *i = Context->getConstantExprSExt(C, TD->getIntPtrType());
Dan Gohman5d639ed2008-09-11 23:06:38 +000011093 MadeChange = true;
11094 } else {
11095 Op = InsertCastBefore(Instruction::SExt, Op, TD->getIntPtrType(),
11096 GEP);
11097 *i = Op;
11098 MadeChange = true;
11099 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011100 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011101 }
11102 }
11103 if (MadeChange) return &GEP;
11104
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011105 // Combine Indices - If the source pointer to this getelementptr instruction
11106 // is a getelementptr instruction, combine the indices of the two
11107 // getelementptr instructions into a single instruction.
11108 //
11109 SmallVector<Value*, 8> SrcGEPOperands;
11110 if (User *Src = dyn_castGetElementPtr(PtrOp))
11111 SrcGEPOperands.append(Src->op_begin(), Src->op_end());
11112
11113 if (!SrcGEPOperands.empty()) {
11114 // Note that if our source is a gep chain itself that we wait for that
11115 // chain to be resolved before we perform this transformation. This
11116 // avoids us creating a TON of code in some cases.
11117 //
11118 if (isa<GetElementPtrInst>(SrcGEPOperands[0]) &&
11119 cast<Instruction>(SrcGEPOperands[0])->getNumOperands() == 2)
11120 return 0; // Wait until our source is folded to completion.
11121
11122 SmallVector<Value*, 8> Indices;
11123
11124 // Find out whether the last index in the source GEP is a sequential idx.
11125 bool EndsWithSequential = false;
11126 for (gep_type_iterator I = gep_type_begin(*cast<User>(PtrOp)),
11127 E = gep_type_end(*cast<User>(PtrOp)); I != E; ++I)
11128 EndsWithSequential = !isa<StructType>(*I);
11129
11130 // Can we combine the two pointer arithmetics offsets?
11131 if (EndsWithSequential) {
11132 // Replace: gep (gep %P, long B), long A, ...
11133 // With: T = long A+B; gep %P, T, ...
11134 //
11135 Value *Sum, *SO1 = SrcGEPOperands.back(), *GO1 = GEP.getOperand(1);
Owen Anderson24be4c12009-07-03 00:17:18 +000011136 if (SO1 == Context->getNullValue(SO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011137 Sum = GO1;
Owen Anderson24be4c12009-07-03 00:17:18 +000011138 } else if (GO1 == Context->getNullValue(GO1->getType())) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011139 Sum = SO1;
11140 } else {
11141 // If they aren't the same type, convert both to an integer of the
11142 // target's pointer size.
11143 if (SO1->getType() != GO1->getType()) {
11144 if (Constant *SO1C = dyn_cast<Constant>(SO1)) {
Owen Anderson24be4c12009-07-03 00:17:18 +000011145 SO1 =
11146 Context->getConstantExprIntegerCast(SO1C, GO1->getType(), true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011147 } else if (Constant *GO1C = dyn_cast<Constant>(GO1)) {
Owen Anderson24be4c12009-07-03 00:17:18 +000011148 GO1 =
11149 Context->getConstantExprIntegerCast(GO1C, SO1->getType(), true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011150 } else {
Duncan Sandsf99fdc62007-11-01 20:53:16 +000011151 unsigned PS = TD->getPointerSizeInBits();
11152 if (TD->getTypeSizeInBits(SO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011153 // Convert GO1 to SO1's type.
11154 GO1 = InsertCastToIntPtrTy(GO1, SO1->getType(), &GEP, this);
11155
Duncan Sandsf99fdc62007-11-01 20:53:16 +000011156 } else if (TD->getTypeSizeInBits(GO1->getType()) == PS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011157 // Convert SO1 to GO1's type.
11158 SO1 = InsertCastToIntPtrTy(SO1, GO1->getType(), &GEP, this);
11159 } else {
11160 const Type *PT = TD->getIntPtrType();
11161 SO1 = InsertCastToIntPtrTy(SO1, PT, &GEP, this);
11162 GO1 = InsertCastToIntPtrTy(GO1, PT, &GEP, this);
11163 }
11164 }
11165 }
11166 if (isa<Constant>(SO1) && isa<Constant>(GO1))
Owen Anderson24be4c12009-07-03 00:17:18 +000011167 Sum = Context->getConstantExprAdd(cast<Constant>(SO1),
11168 cast<Constant>(GO1));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011169 else {
Gabor Greifa645dd32008-05-16 19:29:10 +000011170 Sum = BinaryOperator::CreateAdd(SO1, GO1, PtrOp->getName()+".sum");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011171 InsertNewInstBefore(cast<Instruction>(Sum), GEP);
11172 }
11173 }
11174
11175 // Recycle the GEP we already have if possible.
11176 if (SrcGEPOperands.size() == 2) {
11177 GEP.setOperand(0, SrcGEPOperands[0]);
11178 GEP.setOperand(1, Sum);
11179 return &GEP;
11180 } else {
11181 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11182 SrcGEPOperands.end()-1);
11183 Indices.push_back(Sum);
11184 Indices.insert(Indices.end(), GEP.op_begin()+2, GEP.op_end());
11185 }
11186 } else if (isa<Constant>(*GEP.idx_begin()) &&
11187 cast<Constant>(*GEP.idx_begin())->isNullValue() &&
11188 SrcGEPOperands.size() != 1) {
11189 // Otherwise we can do the fold if the first index of the GEP is a zero
11190 Indices.insert(Indices.end(), SrcGEPOperands.begin()+1,
11191 SrcGEPOperands.end());
11192 Indices.insert(Indices.end(), GEP.idx_begin()+1, GEP.idx_end());
11193 }
11194
11195 if (!Indices.empty())
Gabor Greifd6da1d02008-04-06 20:25:17 +000011196 return GetElementPtrInst::Create(SrcGEPOperands[0], Indices.begin(),
11197 Indices.end(), GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011198
11199 } else if (GlobalValue *GV = dyn_cast<GlobalValue>(PtrOp)) {
11200 // GEP of global variable. If all of the indices for this GEP are
11201 // constants, we can promote this to a constexpr instead of an instruction.
11202
11203 // Scan for nonconstants...
11204 SmallVector<Constant*, 8> Indices;
11205 User::op_iterator I = GEP.idx_begin(), E = GEP.idx_end();
11206 for (; I != E && isa<Constant>(*I); ++I)
11207 Indices.push_back(cast<Constant>(*I));
11208
11209 if (I == E) { // If they are all constants...
Owen Anderson24be4c12009-07-03 00:17:18 +000011210 Constant *CE = Context->getConstantExprGetElementPtr(GV,
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011211 &Indices[0],Indices.size());
11212
11213 // Replace all uses of the GEP with the new constexpr...
11214 return ReplaceInstUsesWith(GEP, CE);
11215 }
11216 } else if (Value *X = getBitCastOperand(PtrOp)) { // Is the operand a cast?
11217 if (!isa<PointerType>(X->getType())) {
11218 // Not interesting. Source pointer must be a cast from pointer.
11219 } else if (HasZeroPointerIndex) {
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011220 // transform: GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ...
11221 // into : GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011222 //
Duncan Sandscf866e62009-03-02 09:18:21 +000011223 // Likewise, transform: GEP (bitcast i8* X to [0 x i8]*), i32 0, ...
11224 // into : GEP i8* X, ...
11225 //
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011226 // This occurs when the program declares an array extern like "int X[];"
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011227 const PointerType *CPTy = cast<PointerType>(PtrOp->getType());
11228 const PointerType *XTy = cast<PointerType>(X->getType());
Duncan Sandscf866e62009-03-02 09:18:21 +000011229 if (const ArrayType *CATy =
11230 dyn_cast<ArrayType>(CPTy->getElementType())) {
11231 // GEP (bitcast i8* X to [0 x i8]*), i32 0, ... ?
11232 if (CATy->getElementType() == XTy->getElementType()) {
11233 // -> GEP i8* X, ...
11234 SmallVector<Value*, 8> Indices(GEP.idx_begin()+1, GEP.idx_end());
11235 return GetElementPtrInst::Create(X, Indices.begin(), Indices.end(),
11236 GEP.getName());
11237 } else if (const ArrayType *XATy =
11238 dyn_cast<ArrayType>(XTy->getElementType())) {
11239 // GEP (bitcast [10 x i8]* X to [0 x i8]*), i32 0, ... ?
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011240 if (CATy->getElementType() == XATy->getElementType()) {
Duncan Sandscf866e62009-03-02 09:18:21 +000011241 // -> GEP [10 x i8]* X, i32 0, ...
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011242 // At this point, we know that the cast source type is a pointer
11243 // to an array of the same type as the destination pointer
11244 // array. Because the array type is never stepped over (there
11245 // is a leading zero) we can fold the cast into this GEP.
11246 GEP.setOperand(0, X);
11247 return &GEP;
11248 }
Duncan Sandscf866e62009-03-02 09:18:21 +000011249 }
11250 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011251 } else if (GEP.getNumOperands() == 2) {
11252 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011253 // %t = getelementptr i32* bitcast ([2 x i32]* %str to i32*), i32 %V
11254 // into: %t1 = getelementptr [2 x i32]* %str, i32 0, i32 %V; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011255 const Type *SrcElTy = cast<PointerType>(X->getType())->getElementType();
11256 const Type *ResElTy=cast<PointerType>(PtrOp->getType())->getElementType();
11257 if (isa<ArrayType>(SrcElTy) &&
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011258 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType()) ==
11259 TD->getTypeAllocSize(ResElTy)) {
David Greene393be882007-09-04 15:46:09 +000011260 Value *Idx[2];
Owen Anderson24be4c12009-07-03 00:17:18 +000011261 Idx[0] = Context->getNullValue(Type::Int32Ty);
David Greene393be882007-09-04 15:46:09 +000011262 Idx[1] = GEP.getOperand(1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011263 Value *V = InsertNewInstBefore(
Gabor Greifd6da1d02008-04-06 20:25:17 +000011264 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName()), GEP);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011265 // V and GEP are both pointer types --> BitCast
11266 return new BitCastInst(V, GEP.getType());
11267 }
11268
11269 // Transform things like:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011270 // getelementptr i8* bitcast ([100 x double]* X to i8*), i32 %tmp
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011271 // (where tmp = 8*tmp2) into:
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011272 // getelementptr [100 x double]* %arr, i32 0, i32 %tmp2; bitcast
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011273
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011274 if (isa<ArrayType>(SrcElTy) && ResElTy == Type::Int8Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011275 uint64_t ArrayEltSize =
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011276 TD->getTypeAllocSize(cast<ArrayType>(SrcElTy)->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011277
11278 // Check to see if "tmp" is a scale by a multiple of ArrayEltSize. We
11279 // allow either a mul, shift, or constant here.
11280 Value *NewIdx = 0;
11281 ConstantInt *Scale = 0;
11282 if (ArrayEltSize == 1) {
11283 NewIdx = GEP.getOperand(1);
Owen Anderson24be4c12009-07-03 00:17:18 +000011284 Scale =
11285 Context->getConstantInt(cast<IntegerType>(NewIdx->getType()), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011286 } else if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP.getOperand(1))) {
Owen Anderson24be4c12009-07-03 00:17:18 +000011287 NewIdx = Context->getConstantInt(CI->getType(), 1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011288 Scale = CI;
11289 } else if (Instruction *Inst =dyn_cast<Instruction>(GEP.getOperand(1))){
11290 if (Inst->getOpcode() == Instruction::Shl &&
11291 isa<ConstantInt>(Inst->getOperand(1))) {
11292 ConstantInt *ShAmt = cast<ConstantInt>(Inst->getOperand(1));
11293 uint32_t ShAmtVal = ShAmt->getLimitedValue(64);
Owen Anderson24be4c12009-07-03 00:17:18 +000011294 Scale = Context->getConstantInt(cast<IntegerType>(Inst->getType()),
Dan Gohman8fd520a2009-06-15 22:12:54 +000011295 1ULL << ShAmtVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011296 NewIdx = Inst->getOperand(0);
11297 } else if (Inst->getOpcode() == Instruction::Mul &&
11298 isa<ConstantInt>(Inst->getOperand(1))) {
11299 Scale = cast<ConstantInt>(Inst->getOperand(1));
11300 NewIdx = Inst->getOperand(0);
11301 }
11302 }
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011303
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011304 // If the index will be to exactly the right offset with the scale taken
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011305 // out, perform the transformation. Note, we don't know whether Scale is
11306 // signed or not. We'll use unsigned version of division/modulo
11307 // operation after making sure Scale doesn't have the sign bit set.
Chris Lattner02962712009-02-25 18:20:01 +000011308 if (ArrayEltSize && Scale && Scale->getSExtValue() >= 0LL &&
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011309 Scale->getZExtValue() % ArrayEltSize == 0) {
Owen Anderson24be4c12009-07-03 00:17:18 +000011310 Scale = Context->getConstantInt(Scale->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011311 Scale->getZExtValue() / ArrayEltSize);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011312 if (Scale->getZExtValue() != 1) {
Owen Anderson24be4c12009-07-03 00:17:18 +000011313 Constant *C =
11314 Context->getConstantExprIntegerCast(Scale, NewIdx->getType(),
Wojciech Matyjewicz5b5ab532007-12-12 15:21:32 +000011315 false /*ZExt*/);
Gabor Greifa645dd32008-05-16 19:29:10 +000011316 Instruction *Sc = BinaryOperator::CreateMul(NewIdx, C, "idxscale");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011317 NewIdx = InsertNewInstBefore(Sc, GEP);
11318 }
11319
11320 // Insert the new GEP instruction.
David Greene393be882007-09-04 15:46:09 +000011321 Value *Idx[2];
Owen Anderson24be4c12009-07-03 00:17:18 +000011322 Idx[0] = Context->getNullValue(Type::Int32Ty);
David Greene393be882007-09-04 15:46:09 +000011323 Idx[1] = NewIdx;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011324 Instruction *NewGEP =
Gabor Greifd6da1d02008-04-06 20:25:17 +000011325 GetElementPtrInst::Create(X, Idx, Idx + 2, GEP.getName());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011326 NewGEP = InsertNewInstBefore(NewGEP, GEP);
11327 // The NewGEP must be pointer typed, so must the old one -> BitCast
11328 return new BitCastInst(NewGEP, GEP.getType());
11329 }
11330 }
11331 }
11332 }
Chris Lattner111ea772009-01-09 04:53:57 +000011333
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011334 /// See if we can simplify:
11335 /// X = bitcast A to B*
11336 /// Y = gep X, <...constant indices...>
11337 /// into a gep of the original struct. This is important for SROA and alias
11338 /// analysis of unions. If "A" is also a bitcast, wait for A/X to be merged.
Chris Lattner111ea772009-01-09 04:53:57 +000011339 if (BitCastInst *BCI = dyn_cast<BitCastInst>(PtrOp)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011340 if (!isa<BitCastInst>(BCI->getOperand(0)) && GEP.hasAllConstantIndices()) {
11341 // Determine how much the GEP moves the pointer. We are guaranteed to get
11342 // a constant back from EmitGEPOffset.
Owen Anderson24be4c12009-07-03 00:17:18 +000011343 ConstantInt *OffsetV =
11344 cast<ConstantInt>(EmitGEPOffset(&GEP, GEP, *this));
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011345 int64_t Offset = OffsetV->getSExtValue();
11346
11347 // If this GEP instruction doesn't move the pointer, just replace the GEP
11348 // with a bitcast of the real input to the dest type.
11349 if (Offset == 0) {
11350 // If the bitcast is of an allocation, and the allocation will be
11351 // converted to match the type of the cast, don't touch this.
11352 if (isa<AllocationInst>(BCI->getOperand(0))) {
11353 // See if the bitcast simplifies, if so, don't nuke this GEP yet.
11354 if (Instruction *I = visitBitCast(*BCI)) {
11355 if (I != BCI) {
11356 I->takeName(BCI);
11357 BCI->getParent()->getInstList().insert(BCI, I);
11358 ReplaceInstUsesWith(*BCI, I);
11359 }
11360 return &GEP;
Chris Lattner111ea772009-01-09 04:53:57 +000011361 }
Chris Lattner111ea772009-01-09 04:53:57 +000011362 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011363 return new BitCastInst(BCI->getOperand(0), GEP.getType());
Chris Lattner111ea772009-01-09 04:53:57 +000011364 }
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011365
11366 // Otherwise, if the offset is non-zero, we need to find out if there is a
11367 // field at Offset in 'A's type. If so, we can pull the cast through the
11368 // GEP.
11369 SmallVector<Value*, 8> NewIndices;
11370 const Type *InTy =
11371 cast<PointerType>(BCI->getOperand(0)->getType())->getElementType();
Owen Anderson24be4c12009-07-03 00:17:18 +000011372 if (FindElementAtOffset(InTy, Offset, NewIndices, TD, Context)) {
Chris Lattner94ccd5f2009-01-09 05:44:56 +000011373 Instruction *NGEP =
11374 GetElementPtrInst::Create(BCI->getOperand(0), NewIndices.begin(),
11375 NewIndices.end());
11376 if (NGEP->getType() == GEP.getType()) return NGEP;
11377 InsertNewInstBefore(NGEP, GEP);
11378 NGEP->takeName(&GEP);
11379 return new BitCastInst(NGEP, GEP.getType());
11380 }
Chris Lattner111ea772009-01-09 04:53:57 +000011381 }
11382 }
11383
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011384 return 0;
11385}
11386
11387Instruction *InstCombiner::visitAllocationInst(AllocationInst &AI) {
11388 // Convert: malloc Ty, C - where C is a constant != 1 into: malloc [C x Ty], 1
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011389 if (AI.isArrayAllocation()) { // Check C != 1
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011390 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
11391 const Type *NewTy =
Owen Anderson24be4c12009-07-03 00:17:18 +000011392 Context->getArrayType(AI.getAllocatedType(), C->getZExtValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011393 AllocationInst *New = 0;
11394
11395 // Create and insert the replacement instruction...
11396 if (isa<MallocInst>(AI))
11397 New = new MallocInst(NewTy, 0, AI.getAlignment(), AI.getName());
11398 else {
11399 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
11400 New = new AllocaInst(NewTy, 0, AI.getAlignment(), AI.getName());
11401 }
11402
11403 InsertNewInstBefore(New, AI);
11404
11405 // Scan to the end of the allocation instructions, to skip over a block of
Dale Johannesena499d0d2009-03-11 22:19:43 +000011406 // allocas if possible...also skip interleaved debug info
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011407 //
11408 BasicBlock::iterator It = New;
Dale Johannesena499d0d2009-03-11 22:19:43 +000011409 while (isa<AllocationInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011410
11411 // Now that I is pointing to the first non-allocation-inst in the block,
11412 // insert our getelementptr instruction...
11413 //
Owen Anderson24be4c12009-07-03 00:17:18 +000011414 Value *NullIdx = Context->getNullValue(Type::Int32Ty);
David Greene393be882007-09-04 15:46:09 +000011415 Value *Idx[2];
11416 Idx[0] = NullIdx;
11417 Idx[1] = NullIdx;
Gabor Greifd6da1d02008-04-06 20:25:17 +000011418 Value *V = GetElementPtrInst::Create(New, Idx, Idx + 2,
11419 New->getName()+".sub", It);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011420
11421 // Now make everything use the getelementptr instead of the original
11422 // allocation.
11423 return ReplaceInstUsesWith(AI, V);
11424 } else if (isa<UndefValue>(AI.getArraySize())) {
Owen Anderson24be4c12009-07-03 00:17:18 +000011425 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011426 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011427 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011428
Dan Gohman28e78f02009-01-13 20:18:38 +000011429 if (isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
11430 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
Chris Lattner27cc5472009-03-17 17:55:15 +000011431 // Note that we only do this for alloca's, because malloc should allocate
11432 // and return a unique pointer, even for a zero byte allocation.
Duncan Sandsec4f97d2009-05-09 07:06:46 +000011433 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
Owen Anderson24be4c12009-07-03 00:17:18 +000011434 return ReplaceInstUsesWith(AI, Context->getNullValue(AI.getType()));
Dan Gohman28e78f02009-01-13 20:18:38 +000011435
11436 // If the alignment is 0 (unspecified), assign it the preferred alignment.
11437 if (AI.getAlignment() == 0)
11438 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
11439 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011440
11441 return 0;
11442}
11443
11444Instruction *InstCombiner::visitFreeInst(FreeInst &FI) {
11445 Value *Op = FI.getOperand(0);
11446
11447 // free undef -> unreachable.
11448 if (isa<UndefValue>(Op)) {
11449 // Insert a new store to null because we cannot modify the CFG here.
Owen Anderson24be4c12009-07-03 00:17:18 +000011450 new StoreInst(Context->getConstantIntTrue(),
11451 Context->getUndef(Context->getPointerTypeUnqual(Type::Int1Ty)), &FI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011452 return EraseInstFromFunction(FI);
11453 }
11454
11455 // If we have 'free null' delete the instruction. This can happen in stl code
11456 // when lots of inlining happens.
11457 if (isa<ConstantPointerNull>(Op))
11458 return EraseInstFromFunction(FI);
11459
11460 // Change free <ty>* (cast <ty2>* X to <ty>*) into free <ty2>* X
11461 if (BitCastInst *CI = dyn_cast<BitCastInst>(Op)) {
11462 FI.setOperand(0, CI->getOperand(0));
11463 return &FI;
11464 }
11465
11466 // Change free (gep X, 0,0,0,0) into free(X)
11467 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11468 if (GEPI->hasAllZeroIndices()) {
11469 AddToWorkList(GEPI);
11470 FI.setOperand(0, GEPI->getOperand(0));
11471 return &FI;
11472 }
11473 }
11474
11475 // Change free(malloc) into nothing, if the malloc has a single use.
11476 if (MallocInst *MI = dyn_cast<MallocInst>(Op))
11477 if (MI->hasOneUse()) {
11478 EraseInstFromFunction(FI);
11479 return EraseInstFromFunction(*MI);
11480 }
11481
11482 return 0;
11483}
11484
11485
11486/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
Devang Patela0f8ea82007-10-18 19:52:32 +000011487static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Bill Wendling44a36ea2008-02-26 10:53:30 +000011488 const TargetData *TD) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011489 User *CI = cast<User>(LI.getOperand(0));
11490 Value *CastOp = CI->getOperand(0);
Owen Anderson5349f052009-07-06 23:00:19 +000011491 LLVMContext *Context = IC.getContext();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011492
Nick Lewycky291c5942009-05-08 06:47:37 +000011493 if (TD) {
11494 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(CI)) {
11495 // Instead of loading constant c string, use corresponding integer value
11496 // directly if string length is small enough.
11497 std::string Str;
11498 if (GetConstantStringInfo(CE->getOperand(0), Str) && !Str.empty()) {
11499 unsigned len = Str.length();
11500 const Type *Ty = cast<PointerType>(CE->getType())->getElementType();
11501 unsigned numBits = Ty->getPrimitiveSizeInBits();
11502 // Replace LI with immediate integer store.
11503 if ((numBits >> 3) == len + 1) {
11504 APInt StrVal(numBits, 0);
11505 APInt SingleChar(numBits, 0);
11506 if (TD->isLittleEndian()) {
11507 for (signed i = len-1; i >= 0; i--) {
11508 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11509 StrVal = (StrVal << 8) | SingleChar;
11510 }
11511 } else {
11512 for (unsigned i = 0; i < len; i++) {
11513 SingleChar = (uint64_t) Str[i] & UCHAR_MAX;
11514 StrVal = (StrVal << 8) | SingleChar;
11515 }
11516 // Append NULL at the end.
11517 SingleChar = 0;
Bill Wendling44a36ea2008-02-26 10:53:30 +000011518 StrVal = (StrVal << 8) | SingleChar;
11519 }
Owen Anderson24be4c12009-07-03 00:17:18 +000011520 Value *NL = Context->getConstantInt(StrVal);
Nick Lewycky291c5942009-05-08 06:47:37 +000011521 return IC.ReplaceInstUsesWith(LI, NL);
Bill Wendling44a36ea2008-02-26 10:53:30 +000011522 }
Devang Patela0f8ea82007-10-18 19:52:32 +000011523 }
11524 }
11525 }
11526
Mon P Wangbd05ed82009-02-07 22:19:29 +000011527 const PointerType *DestTy = cast<PointerType>(CI->getType());
11528 const Type *DestPTy = DestTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011529 if (const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Mon P Wangbd05ed82009-02-07 22:19:29 +000011530
11531 // If the address spaces don't match, don't eliminate the cast.
11532 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
11533 return 0;
11534
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011535 const Type *SrcPTy = SrcTy->getElementType();
11536
11537 if (DestPTy->isInteger() || isa<PointerType>(DestPTy) ||
11538 isa<VectorType>(DestPTy)) {
11539 // If the source is an array, the code below will not succeed. Check to
11540 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11541 // constants.
11542 if (const ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
11543 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
11544 if (ASrcTy->getNumElements() != 0) {
11545 Value *Idxs[2];
Owen Anderson24be4c12009-07-03 00:17:18 +000011546 Idxs[0] = Idxs[1] = Context->getNullValue(Type::Int32Ty);
11547 CastOp = Context->getConstantExprGetElementPtr(CSrc, Idxs, 2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011548 SrcTy = cast<PointerType>(CastOp->getType());
11549 SrcPTy = SrcTy->getElementType();
11550 }
11551
11552 if ((SrcPTy->isInteger() || isa<PointerType>(SrcPTy) ||
11553 isa<VectorType>(SrcPTy)) &&
11554 // Do not allow turning this into a load of an integer, which is then
11555 // casted to a pointer, this pessimizes pointer analysis a lot.
11556 (isa<PointerType>(SrcPTy) == isa<PointerType>(LI.getType())) &&
11557 IC.getTargetData().getTypeSizeInBits(SrcPTy) ==
11558 IC.getTargetData().getTypeSizeInBits(DestPTy)) {
11559
11560 // Okay, we are casting from one integer or pointer type to another of
11561 // the same size. Instead of casting the pointer before the load, cast
11562 // the result of the loaded value.
11563 Value *NewLoad = IC.InsertNewInstBefore(new LoadInst(CastOp,
11564 CI->getName(),
11565 LI.isVolatile()),LI);
11566 // Now cast the result of the load.
11567 return new BitCastInst(NewLoad, LI.getType());
11568 }
11569 }
11570 }
11571 return 0;
11572}
11573
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011574Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
11575 Value *Op = LI.getOperand(0);
11576
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011577 // Attempt to improve the alignment.
Dan Gohman37192572009-02-16 00:44:23 +000011578 unsigned KnownAlign =
11579 GetOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()));
Dan Gohman2d648bb2008-04-10 18:43:06 +000011580 if (KnownAlign >
11581 (LI.getAlignment() == 0 ? TD->getABITypeAlignment(LI.getType()) :
11582 LI.getAlignment()))
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011583 LI.setAlignment(KnownAlign);
11584
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011585 // load (cast X) --> cast (load X) iff safe
11586 if (isa<CastInst>(Op))
Devang Patela0f8ea82007-10-18 19:52:32 +000011587 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011588 return Res;
11589
11590 // None of the following transforms are legal for volatile loads.
11591 if (LI.isVolatile()) return 0;
11592
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000011593 // Do really simple store-to-load forwarding and load CSE, to catch cases
11594 // where there are several consequtive memory accesses to the same location,
11595 // separated by a few arithmetic operations.
11596 BasicBlock::iterator BBI = &LI;
Chris Lattner6fd8c802008-11-27 08:56:30 +000011597 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
11598 return ReplaceInstUsesWith(LI, AvailableVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011599
Christopher Lamb2c175392007-12-29 07:56:53 +000011600 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
11601 const Value *GEPI0 = GEPI->getOperand(0);
11602 // TODO: Consider a target hook for valid address spaces for this xform.
11603 if (isa<ConstantPointerNull>(GEPI0) &&
11604 cast<PointerType>(GEPI0->getType())->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011605 // Insert a new store to null instruction before the load to indicate
11606 // that this code is not reachable. We do this instead of inserting
11607 // an unreachable instruction directly because we cannot modify the
11608 // CFG.
Owen Anderson24be4c12009-07-03 00:17:18 +000011609 new StoreInst(Context->getUndef(LI.getType()),
11610 Context->getNullValue(Op->getType()), &LI);
11611 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011612 }
Christopher Lamb2c175392007-12-29 07:56:53 +000011613 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011614
11615 if (Constant *C = dyn_cast<Constant>(Op)) {
11616 // load null/undef -> undef
Christopher Lamb2c175392007-12-29 07:56:53 +000011617 // TODO: Consider a target hook for valid address spaces for this xform.
11618 if (isa<UndefValue>(C) || (C->isNullValue() &&
11619 cast<PointerType>(Op->getType())->getAddressSpace() == 0)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011620 // Insert a new store to null instruction before the load to indicate that
11621 // this code is not reachable. We do this instead of inserting an
11622 // unreachable instruction directly because we cannot modify the CFG.
Owen Anderson24be4c12009-07-03 00:17:18 +000011623 new StoreInst(Context->getUndef(LI.getType()),
11624 Context->getNullValue(Op->getType()), &LI);
11625 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011626 }
11627
11628 // Instcombine load (constant global) into the value loaded.
11629 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op))
Duncan Sands54e70f62009-03-21 21:27:31 +000011630 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011631 return ReplaceInstUsesWith(LI, GV->getInitializer());
11632
11633 // Instcombine load (constantexpr_GEP global, 0, ...) into the value loaded.
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011634 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011635 if (CE->getOpcode() == Instruction::GetElementPtr) {
11636 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(CE->getOperand(0)))
Duncan Sands54e70f62009-03-21 21:27:31 +000011637 if (GV->isConstant() && GV->hasDefinitiveInitializer())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011638 if (Constant *V =
Owen Andersond4d90a02009-07-06 18:42:36 +000011639 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE,
11640 Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011641 return ReplaceInstUsesWith(LI, V);
11642 if (CE->getOperand(0)->isNullValue()) {
11643 // Insert a new store to null instruction before the load to indicate
11644 // that this code is not reachable. We do this instead of inserting
11645 // an unreachable instruction directly because we cannot modify the
11646 // CFG.
Owen Anderson24be4c12009-07-03 00:17:18 +000011647 new StoreInst(Context->getUndef(LI.getType()),
11648 Context->getNullValue(Op->getType()), &LI);
11649 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011650 }
11651
11652 } else if (CE->isCast()) {
Devang Patela0f8ea82007-10-18 19:52:32 +000011653 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011654 return Res;
11655 }
Anton Korobeynikov8522e1c2008-02-20 11:26:25 +000011656 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011657 }
Chris Lattner0270a112007-08-11 18:48:48 +000011658
11659 // If this load comes from anywhere in a constant global, and if the global
11660 // is all undef or zero, we know what it loads.
Duncan Sands52fb8732008-10-01 15:25:41 +000011661 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Op->getUnderlyingObject())){
Duncan Sands54e70f62009-03-21 21:27:31 +000011662 if (GV->isConstant() && GV->hasDefinitiveInitializer()) {
Chris Lattner0270a112007-08-11 18:48:48 +000011663 if (GV->getInitializer()->isNullValue())
Owen Anderson24be4c12009-07-03 00:17:18 +000011664 return ReplaceInstUsesWith(LI, Context->getNullValue(LI.getType()));
Chris Lattner0270a112007-08-11 18:48:48 +000011665 else if (isa<UndefValue>(GV->getInitializer()))
Owen Anderson24be4c12009-07-03 00:17:18 +000011666 return ReplaceInstUsesWith(LI, Context->getUndef(LI.getType()));
Chris Lattner0270a112007-08-11 18:48:48 +000011667 }
11668 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011669
11670 if (Op->hasOneUse()) {
11671 // Change select and PHI nodes to select values instead of addresses: this
11672 // helps alias analysis out a lot, allows many others simplifications, and
11673 // exposes redundancy in the code.
11674 //
11675 // Note that we cannot do the transformation unless we know that the
11676 // introduced loads cannot trap! Something like this is valid as long as
11677 // the condition is always false: load (select bool %C, int* null, int* %G),
11678 // but it would not be valid if we transformed it to load from null
11679 // unconditionally.
11680 //
11681 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
11682 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
11683 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI) &&
11684 isSafeToLoadUnconditionally(SI->getOperand(2), SI)) {
11685 Value *V1 = InsertNewInstBefore(new LoadInst(SI->getOperand(1),
11686 SI->getOperand(1)->getName()+".val"), LI);
11687 Value *V2 = InsertNewInstBefore(new LoadInst(SI->getOperand(2),
11688 SI->getOperand(2)->getName()+".val"), LI);
Gabor Greifd6da1d02008-04-06 20:25:17 +000011689 return SelectInst::Create(SI->getCondition(), V1, V2);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011690 }
11691
11692 // load (select (cond, null, P)) -> load P
11693 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
11694 if (C->isNullValue()) {
11695 LI.setOperand(0, SI->getOperand(2));
11696 return &LI;
11697 }
11698
11699 // load (select (cond, P, null)) -> load P
11700 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
11701 if (C->isNullValue()) {
11702 LI.setOperand(0, SI->getOperand(1));
11703 return &LI;
11704 }
11705 }
11706 }
11707 return 0;
11708}
11709
11710/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
Chris Lattner54dddc72009-01-24 01:00:13 +000011711/// when possible. This makes it generally easy to do alias analysis and/or
11712/// SROA/mem2reg of the memory object.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011713static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
11714 User *CI = cast<User>(SI.getOperand(1));
11715 Value *CastOp = CI->getOperand(0);
Owen Anderson5349f052009-07-06 23:00:19 +000011716 LLVMContext *Context = IC.getContext();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011717
11718 const Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
Chris Lattnera032c0e2009-01-16 20:08:59 +000011719 const PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
11720 if (SrcTy == 0) return 0;
11721
11722 const Type *SrcPTy = SrcTy->getElementType();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011723
Chris Lattnera032c0e2009-01-16 20:08:59 +000011724 if (!DestPTy->isInteger() && !isa<PointerType>(DestPTy))
11725 return 0;
11726
Chris Lattner54dddc72009-01-24 01:00:13 +000011727 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
11728 /// to its first element. This allows us to handle things like:
11729 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
11730 /// on 32-bit hosts.
11731 SmallVector<Value*, 4> NewGEPIndices;
11732
Chris Lattnera032c0e2009-01-16 20:08:59 +000011733 // If the source is an array, the code below will not succeed. Check to
11734 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
11735 // constants.
Chris Lattner54dddc72009-01-24 01:00:13 +000011736 if (isa<ArrayType>(SrcPTy) || isa<StructType>(SrcPTy)) {
11737 // Index through pointer.
Owen Anderson24be4c12009-07-03 00:17:18 +000011738 Constant *Zero = Context->getNullValue(Type::Int32Ty);
Chris Lattner54dddc72009-01-24 01:00:13 +000011739 NewGEPIndices.push_back(Zero);
11740
11741 while (1) {
11742 if (const StructType *STy = dyn_cast<StructType>(SrcPTy)) {
edwin7dc0aa32009-01-24 17:16:04 +000011743 if (!STy->getNumElements()) /* Struct can be empty {} */
edwin07d74e72009-01-24 11:30:49 +000011744 break;
Chris Lattner54dddc72009-01-24 01:00:13 +000011745 NewGEPIndices.push_back(Zero);
11746 SrcPTy = STy->getElementType(0);
11747 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
11748 NewGEPIndices.push_back(Zero);
11749 SrcPTy = ATy->getElementType();
11750 } else {
11751 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011752 }
Chris Lattner54dddc72009-01-24 01:00:13 +000011753 }
11754
Owen Anderson24be4c12009-07-03 00:17:18 +000011755 SrcTy = Context->getPointerType(SrcPTy, SrcTy->getAddressSpace());
Chris Lattner54dddc72009-01-24 01:00:13 +000011756 }
Chris Lattnera032c0e2009-01-16 20:08:59 +000011757
11758 if (!SrcPTy->isInteger() && !isa<PointerType>(SrcPTy))
11759 return 0;
11760
Chris Lattnerc73a0d12009-01-16 20:12:52 +000011761 // If the pointers point into different address spaces or if they point to
11762 // values with different sizes, we can't do the transformation.
11763 if (SrcTy->getAddressSpace() !=
11764 cast<PointerType>(CI->getType())->getAddressSpace() ||
11765 IC.getTargetData().getTypeSizeInBits(SrcPTy) !=
Chris Lattnera032c0e2009-01-16 20:08:59 +000011766 IC.getTargetData().getTypeSizeInBits(DestPTy))
11767 return 0;
11768
11769 // Okay, we are casting from one integer or pointer type to another of
11770 // the same size. Instead of casting the pointer before
11771 // the store, cast the value to be stored.
11772 Value *NewCast;
11773 Value *SIOp0 = SI.getOperand(0);
11774 Instruction::CastOps opcode = Instruction::BitCast;
11775 const Type* CastSrcTy = SIOp0->getType();
11776 const Type* CastDstTy = SrcPTy;
11777 if (isa<PointerType>(CastDstTy)) {
11778 if (CastSrcTy->isInteger())
11779 opcode = Instruction::IntToPtr;
11780 } else if (isa<IntegerType>(CastDstTy)) {
11781 if (isa<PointerType>(SIOp0->getType()))
11782 opcode = Instruction::PtrToInt;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011783 }
Chris Lattner54dddc72009-01-24 01:00:13 +000011784
11785 // SIOp0 is a pointer to aggregate and this is a store to the first field,
11786 // emit a GEP to index into its first field.
11787 if (!NewGEPIndices.empty()) {
11788 if (Constant *C = dyn_cast<Constant>(CastOp))
Owen Anderson24be4c12009-07-03 00:17:18 +000011789 CastOp = Context->getConstantExprGetElementPtr(C, &NewGEPIndices[0],
Chris Lattner54dddc72009-01-24 01:00:13 +000011790 NewGEPIndices.size());
11791 else
11792 CastOp = IC.InsertNewInstBefore(
11793 GetElementPtrInst::Create(CastOp, NewGEPIndices.begin(),
11794 NewGEPIndices.end()), SI);
11795 }
11796
Chris Lattnera032c0e2009-01-16 20:08:59 +000011797 if (Constant *C = dyn_cast<Constant>(SIOp0))
Owen Anderson24be4c12009-07-03 00:17:18 +000011798 NewCast = Context->getConstantExprCast(opcode, C, CastDstTy);
Chris Lattnera032c0e2009-01-16 20:08:59 +000011799 else
11800 NewCast = IC.InsertNewInstBefore(
11801 CastInst::Create(opcode, SIOp0, CastDstTy, SIOp0->getName()+".c"),
11802 SI);
11803 return new StoreInst(NewCast, CastOp);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011804}
11805
Chris Lattner6fd8c802008-11-27 08:56:30 +000011806/// equivalentAddressValues - Test if A and B will obviously have the same
11807/// value. This includes recognizing that %t0 and %t1 will have the same
11808/// value in code like this:
Dan Gohman8387bb32009-03-03 02:55:14 +000011809/// %t0 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000011810/// store i32 0, i32* %t0
Dan Gohman8387bb32009-03-03 02:55:14 +000011811/// %t1 = getelementptr \@a, 0, 3
Chris Lattner6fd8c802008-11-27 08:56:30 +000011812/// %t2 = load i32* %t1
11813///
11814static bool equivalentAddressValues(Value *A, Value *B) {
11815 // Test if the values are trivially equivalent.
11816 if (A == B) return true;
11817
11818 // Test if the values come form identical arithmetic instructions.
11819 if (isa<BinaryOperator>(A) ||
11820 isa<CastInst>(A) ||
11821 isa<PHINode>(A) ||
11822 isa<GetElementPtrInst>(A))
11823 if (Instruction *BI = dyn_cast<Instruction>(B))
11824 if (cast<Instruction>(A)->isIdenticalTo(BI))
11825 return true;
11826
11827 // Otherwise they may not be equivalent.
11828 return false;
11829}
11830
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011831// If this instruction has two uses, one of which is a llvm.dbg.declare,
11832// return the llvm.dbg.declare.
11833DbgDeclareInst *InstCombiner::hasOneUsePlusDeclare(Value *V) {
11834 if (!V->hasNUses(2))
11835 return 0;
11836 for (Value::use_iterator UI = V->use_begin(), E = V->use_end();
11837 UI != E; ++UI) {
11838 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI))
11839 return DI;
11840 if (isa<BitCastInst>(UI) && UI->hasOneUse()) {
11841 if (DbgDeclareInst *DI = dyn_cast<DbgDeclareInst>(UI->use_begin()))
11842 return DI;
11843 }
11844 }
11845 return 0;
11846}
11847
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011848Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
11849 Value *Val = SI.getOperand(0);
11850 Value *Ptr = SI.getOperand(1);
11851
11852 if (isa<UndefValue>(Ptr)) { // store X, undef -> noop (even if volatile)
11853 EraseInstFromFunction(SI);
11854 ++NumCombined;
11855 return 0;
11856 }
11857
11858 // If the RHS is an alloca with a single use, zapify the store, making the
11859 // alloca dead.
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011860 // If the RHS is an alloca with a two uses, the other one being a
11861 // llvm.dbg.declare, zapify the store and the declare, making the
11862 // alloca dead. We must do this to prevent declare's from affecting
11863 // codegen.
11864 if (!SI.isVolatile()) {
11865 if (Ptr->hasOneUse()) {
11866 if (isa<AllocaInst>(Ptr)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011867 EraseInstFromFunction(SI);
11868 ++NumCombined;
11869 return 0;
11870 }
Dale Johannesen2c11fe22009-03-03 21:26:39 +000011871 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
11872 if (isa<AllocaInst>(GEP->getOperand(0))) {
11873 if (GEP->getOperand(0)->hasOneUse()) {
11874 EraseInstFromFunction(SI);
11875 ++NumCombined;
11876 return 0;
11877 }
11878 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(GEP->getOperand(0))) {
11879 EraseInstFromFunction(*DI);
11880 EraseInstFromFunction(SI);
11881 ++NumCombined;
11882 return 0;
11883 }
11884 }
11885 }
11886 }
11887 if (DbgDeclareInst *DI = hasOneUsePlusDeclare(Ptr)) {
11888 EraseInstFromFunction(*DI);
11889 EraseInstFromFunction(SI);
11890 ++NumCombined;
11891 return 0;
11892 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011893 }
11894
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011895 // Attempt to improve the alignment.
Dan Gohman37192572009-02-16 00:44:23 +000011896 unsigned KnownAlign =
11897 GetOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()));
Dan Gohman2d648bb2008-04-10 18:43:06 +000011898 if (KnownAlign >
11899 (SI.getAlignment() == 0 ? TD->getABITypeAlignment(Val->getType()) :
11900 SI.getAlignment()))
Dan Gohman5c4d0e12007-07-20 16:34:21 +000011901 SI.setAlignment(KnownAlign);
11902
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011903 // Do really simple DSE, to catch cases where there are several consecutive
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011904 // stores to the same location, separated by a few arithmetic operations. This
11905 // situation often occurs with bitfield accesses.
11906 BasicBlock::iterator BBI = &SI;
11907 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
11908 --ScanInsts) {
Dale Johannesenb773a552009-03-04 01:20:34 +000011909 --BBI;
Dale Johannesenc9612322009-03-04 01:53:05 +000011910 // Don't count debug info directives, lest they affect codegen,
11911 // and we skip pointer-to-pointer bitcasts, which are NOPs.
11912 // It is necessary for correctness to skip those that feed into a
11913 // llvm.dbg.declare, as these are not present when debugging is off.
Dale Johannesen605879d2009-03-03 22:36:47 +000011914 if (isa<DbgInfoIntrinsic>(BBI) ||
Dale Johannesenc9612322009-03-04 01:53:05 +000011915 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011916 ScanInsts++;
Dale Johannesen2bf6a6b2009-03-03 01:43:03 +000011917 continue;
11918 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011919
11920 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
11921 // Prev store isn't volatile, and stores to the same location?
Chris Lattner6fd8c802008-11-27 08:56:30 +000011922 if (!PrevSI->isVolatile() &&equivalentAddressValues(PrevSI->getOperand(1),
11923 SI.getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011924 ++NumDeadStore;
11925 ++BBI;
11926 EraseInstFromFunction(*PrevSI);
11927 continue;
11928 }
11929 break;
11930 }
11931
11932 // If this is a load, we have to stop. However, if the loaded value is from
11933 // the pointer we're loading and is producing the pointer we're storing,
11934 // then *this* store is dead (X = load P; store X -> P).
11935 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Dan Gohman0ff5a1f2008-10-15 23:19:35 +000011936 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
11937 !SI.isVolatile()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011938 EraseInstFromFunction(SI);
11939 ++NumCombined;
11940 return 0;
11941 }
11942 // Otherwise, this is a load from some other location. Stores before it
11943 // may not be dead.
11944 break;
11945 }
11946
11947 // Don't skip over loads or things that can modify memory.
Chris Lattner84504282008-05-08 17:20:30 +000011948 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011949 break;
11950 }
11951
11952
11953 if (SI.isVolatile()) return 0; // Don't hack volatile stores.
11954
11955 // store X, null -> turns into 'unreachable' in SimplifyCFG
Chris Lattner96e0a652009-06-11 17:54:56 +000011956 if (isa<ConstantPointerNull>(Ptr) &&
11957 cast<PointerType>(Ptr->getType())->getAddressSpace() == 0) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011958 if (!isa<UndefValue>(Val)) {
Owen Anderson24be4c12009-07-03 00:17:18 +000011959 SI.setOperand(0, Context->getUndef(Val->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011960 if (Instruction *U = dyn_cast<Instruction>(Val))
11961 AddToWorkList(U); // Dropped a use.
11962 ++NumCombined;
11963 }
11964 return 0; // Do not modify these!
11965 }
11966
11967 // store undef, Ptr -> noop
11968 if (isa<UndefValue>(Val)) {
11969 EraseInstFromFunction(SI);
11970 ++NumCombined;
11971 return 0;
11972 }
11973
11974 // If the pointer destination is a cast, see if we can fold the cast into the
11975 // source instead.
11976 if (isa<CastInst>(Ptr))
11977 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11978 return Res;
11979 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
11980 if (CE->isCast())
11981 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
11982 return Res;
11983
11984
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000011985 // If this store is the last instruction in the basic block (possibly
11986 // excepting debug info instructions and the pointer bitcasts that feed
11987 // into them), and if the block ends with an unconditional branch, try
11988 // to move it to the successor block.
11989 BBI = &SI;
11990 do {
11991 ++BBI;
11992 } while (isa<DbgInfoIntrinsic>(BBI) ||
11993 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType())));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000011994 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
11995 if (BI->isUnconditional())
11996 if (SimplifyStoreAtEndOfBlock(SI))
11997 return 0; // xform done!
11998
11999 return 0;
12000}
12001
12002/// SimplifyStoreAtEndOfBlock - Turn things like:
12003/// if () { *P = v1; } else { *P = v2 }
12004/// into a phi node with a store in the successor.
12005///
12006/// Simplify things like:
12007/// *P = v1; if () { *P = v2; }
12008/// into a phi node with a store in the successor.
12009///
12010bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
12011 BasicBlock *StoreBB = SI.getParent();
12012
12013 // Check to see if the successor block has exactly two incoming edges. If
12014 // so, see if the other predecessor contains a store to the same location.
12015 // if so, insert a PHI node (if needed) and move the stores down.
12016 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
12017
12018 // Determine whether Dest has exactly two predecessors and, if so, compute
12019 // the other predecessor.
12020 pred_iterator PI = pred_begin(DestBB);
12021 BasicBlock *OtherBB = 0;
12022 if (*PI != StoreBB)
12023 OtherBB = *PI;
12024 ++PI;
12025 if (PI == pred_end(DestBB))
12026 return false;
12027
12028 if (*PI != StoreBB) {
12029 if (OtherBB)
12030 return false;
12031 OtherBB = *PI;
12032 }
12033 if (++PI != pred_end(DestBB))
12034 return false;
Eli Friedmanab39f9a2008-06-13 21:17:49 +000012035
12036 // Bail out if all the relevant blocks aren't distinct (this can happen,
12037 // for example, if SI is in an infinite loop)
12038 if (StoreBB == DestBB || OtherBB == DestBB)
12039 return false;
12040
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012041 // Verify that the other block ends in a branch and is not otherwise empty.
12042 BasicBlock::iterator BBI = OtherBB->getTerminator();
12043 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
12044 if (!OtherBr || BBI == OtherBB->begin())
12045 return false;
12046
12047 // If the other block ends in an unconditional branch, check for the 'if then
12048 // else' case. there is an instruction before the branch.
12049 StoreInst *OtherStore = 0;
12050 if (OtherBr->isUnconditional()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012051 --BBI;
Dale Johannesenb7a9e3e2009-03-05 02:06:48 +000012052 // Skip over debugging info.
12053 while (isa<DbgInfoIntrinsic>(BBI) ||
12054 (isa<BitCastInst>(BBI) && isa<PointerType>(BBI->getType()))) {
12055 if (BBI==OtherBB->begin())
12056 return false;
12057 --BBI;
12058 }
12059 // If this isn't a store, or isn't a store to the same location, bail out.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012060 OtherStore = dyn_cast<StoreInst>(BBI);
12061 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1))
12062 return false;
12063 } else {
12064 // Otherwise, the other block ended with a conditional branch. If one of the
12065 // destinations is StoreBB, then we have the if/then case.
12066 if (OtherBr->getSuccessor(0) != StoreBB &&
12067 OtherBr->getSuccessor(1) != StoreBB)
12068 return false;
12069
12070 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
12071 // if/then triangle. See if there is a store to the same ptr as SI that
12072 // lives in OtherBB.
12073 for (;; --BBI) {
12074 // Check to see if we find the matching store.
12075 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
12076 if (OtherStore->getOperand(1) != SI.getOperand(1))
12077 return false;
12078 break;
12079 }
Eli Friedman3a311d52008-06-13 22:02:12 +000012080 // If we find something that may be using or overwriting the stored
12081 // value, or if we run out of instructions, we can't do the xform.
12082 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012083 BBI == OtherBB->begin())
12084 return false;
12085 }
12086
12087 // In order to eliminate the store in OtherBr, we have to
Eli Friedman3a311d52008-06-13 22:02:12 +000012088 // make sure nothing reads or overwrites the stored value in
12089 // StoreBB.
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012090 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
12091 // FIXME: This should really be AA driven.
Eli Friedman3a311d52008-06-13 22:02:12 +000012092 if (I->mayReadFromMemory() || I->mayWriteToMemory())
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012093 return false;
12094 }
12095 }
12096
12097 // Insert a PHI node now if we need it.
12098 Value *MergedVal = OtherStore->getOperand(0);
12099 if (MergedVal != SI.getOperand(0)) {
Gabor Greifd6da1d02008-04-06 20:25:17 +000012100 PHINode *PN = PHINode::Create(MergedVal->getType(), "storemerge");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012101 PN->reserveOperandSpace(2);
12102 PN->addIncoming(SI.getOperand(0), SI.getParent());
12103 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
12104 MergedVal = InsertNewInstBefore(PN, DestBB->front());
12105 }
12106
12107 // Advance to a place where it is safe to insert the new store and
12108 // insert it.
Dan Gohman514277c2008-05-23 21:05:58 +000012109 BBI = DestBB->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012110 InsertNewInstBefore(new StoreInst(MergedVal, SI.getOperand(1),
12111 OtherStore->isVolatile()), *BBI);
12112
12113 // Nuke the old stores.
12114 EraseInstFromFunction(SI);
12115 EraseInstFromFunction(*OtherStore);
12116 ++NumCombined;
12117 return true;
12118}
12119
12120
12121Instruction *InstCombiner::visitBranchInst(BranchInst &BI) {
12122 // Change br (not X), label True, label False to: br X, label False, True
12123 Value *X = 0;
12124 BasicBlock *TrueDest;
12125 BasicBlock *FalseDest;
Owen Andersona21eb582009-07-10 17:35:01 +000012126 if (match(&BI, m_Br(m_Not(m_Value(X)), TrueDest, FalseDest), *Context) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012127 !isa<Constant>(X)) {
12128 // Swap Destinations and condition...
12129 BI.setCondition(X);
12130 BI.setSuccessor(0, FalseDest);
12131 BI.setSuccessor(1, TrueDest);
12132 return &BI;
12133 }
12134
12135 // Cannonicalize fcmp_one -> fcmp_oeq
12136 FCmpInst::Predicate FPred; Value *Y;
12137 if (match(&BI, m_Br(m_FCmp(FPred, m_Value(X), m_Value(Y)),
Owen Andersona21eb582009-07-10 17:35:01 +000012138 TrueDest, FalseDest), *Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012139 if ((FPred == FCmpInst::FCMP_ONE || FPred == FCmpInst::FCMP_OLE ||
12140 FPred == FCmpInst::FCMP_OGE) && BI.getCondition()->hasOneUse()) {
12141 FCmpInst *I = cast<FCmpInst>(BI.getCondition());
12142 FCmpInst::Predicate NewPred = FCmpInst::getInversePredicate(FPred);
Owen Anderson6601fcd2009-07-09 23:48:35 +000012143 Instruction *NewSCC = new FCmpInst(I, NewPred, X, Y, "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012144 NewSCC->takeName(I);
12145 // Swap Destinations and condition...
12146 BI.setCondition(NewSCC);
12147 BI.setSuccessor(0, FalseDest);
12148 BI.setSuccessor(1, TrueDest);
12149 RemoveFromWorkList(I);
12150 I->eraseFromParent();
12151 AddToWorkList(NewSCC);
12152 return &BI;
12153 }
12154
12155 // Cannonicalize icmp_ne -> icmp_eq
12156 ICmpInst::Predicate IPred;
12157 if (match(&BI, m_Br(m_ICmp(IPred, m_Value(X), m_Value(Y)),
Owen Andersona21eb582009-07-10 17:35:01 +000012158 TrueDest, FalseDest), *Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012159 if ((IPred == ICmpInst::ICMP_NE || IPred == ICmpInst::ICMP_ULE ||
12160 IPred == ICmpInst::ICMP_SLE || IPred == ICmpInst::ICMP_UGE ||
12161 IPred == ICmpInst::ICMP_SGE) && BI.getCondition()->hasOneUse()) {
12162 ICmpInst *I = cast<ICmpInst>(BI.getCondition());
12163 ICmpInst::Predicate NewPred = ICmpInst::getInversePredicate(IPred);
Owen Anderson6601fcd2009-07-09 23:48:35 +000012164 Instruction *NewSCC = new ICmpInst(I, NewPred, X, Y, "");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012165 NewSCC->takeName(I);
12166 // Swap Destinations and condition...
12167 BI.setCondition(NewSCC);
12168 BI.setSuccessor(0, FalseDest);
12169 BI.setSuccessor(1, TrueDest);
12170 RemoveFromWorkList(I);
12171 I->eraseFromParent();;
12172 AddToWorkList(NewSCC);
12173 return &BI;
12174 }
12175
12176 return 0;
12177}
12178
12179Instruction *InstCombiner::visitSwitchInst(SwitchInst &SI) {
12180 Value *Cond = SI.getCondition();
12181 if (Instruction *I = dyn_cast<Instruction>(Cond)) {
12182 if (I->getOpcode() == Instruction::Add)
12183 if (ConstantInt *AddRHS = dyn_cast<ConstantInt>(I->getOperand(1))) {
12184 // change 'switch (X+4) case 1:' into 'switch (X) case -3'
12185 for (unsigned i = 2, e = SI.getNumOperands(); i != e; i += 2)
Owen Anderson24be4c12009-07-03 00:17:18 +000012186 SI.setOperand(i,
12187 Context->getConstantExprSub(cast<Constant>(SI.getOperand(i)),
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012188 AddRHS));
12189 SI.setOperand(0, I->getOperand(0));
12190 AddToWorkList(I);
12191 return &SI;
12192 }
12193 }
12194 return 0;
12195}
12196
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012197Instruction *InstCombiner::visitExtractValueInst(ExtractValueInst &EV) {
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012198 Value *Agg = EV.getAggregateOperand();
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012199
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012200 if (!EV.hasIndices())
12201 return ReplaceInstUsesWith(EV, Agg);
12202
12203 if (Constant *C = dyn_cast<Constant>(Agg)) {
12204 if (isa<UndefValue>(C))
Owen Anderson24be4c12009-07-03 00:17:18 +000012205 return ReplaceInstUsesWith(EV, Context->getUndef(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012206
12207 if (isa<ConstantAggregateZero>(C))
Owen Anderson24be4c12009-07-03 00:17:18 +000012208 return ReplaceInstUsesWith(EV, Context->getNullValue(EV.getType()));
Matthijs Kooijman45e8eb42008-07-16 12:55:45 +000012209
12210 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C)) {
12211 // Extract the element indexed by the first index out of the constant
12212 Value *V = C->getOperand(*EV.idx_begin());
12213 if (EV.getNumIndices() > 1)
12214 // Extract the remaining indices out of the constant indexed by the
12215 // first index
12216 return ExtractValueInst::Create(V, EV.idx_begin() + 1, EV.idx_end());
12217 else
12218 return ReplaceInstUsesWith(EV, V);
12219 }
12220 return 0; // Can't handle other constants
12221 }
12222 if (InsertValueInst *IV = dyn_cast<InsertValueInst>(Agg)) {
12223 // We're extracting from an insertvalue instruction, compare the indices
12224 const unsigned *exti, *exte, *insi, *inse;
12225 for (exti = EV.idx_begin(), insi = IV->idx_begin(),
12226 exte = EV.idx_end(), inse = IV->idx_end();
12227 exti != exte && insi != inse;
12228 ++exti, ++insi) {
12229 if (*insi != *exti)
12230 // The insert and extract both reference distinctly different elements.
12231 // This means the extract is not influenced by the insert, and we can
12232 // replace the aggregate operand of the extract with the aggregate
12233 // operand of the insert. i.e., replace
12234 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12235 // %E = extractvalue { i32, { i32 } } %I, 0
12236 // with
12237 // %E = extractvalue { i32, { i32 } } %A, 0
12238 return ExtractValueInst::Create(IV->getAggregateOperand(),
12239 EV.idx_begin(), EV.idx_end());
12240 }
12241 if (exti == exte && insi == inse)
12242 // Both iterators are at the end: Index lists are identical. Replace
12243 // %B = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12244 // %C = extractvalue { i32, { i32 } } %B, 1, 0
12245 // with "i32 42"
12246 return ReplaceInstUsesWith(EV, IV->getInsertedValueOperand());
12247 if (exti == exte) {
12248 // The extract list is a prefix of the insert list. i.e. replace
12249 // %I = insertvalue { i32, { i32 } } %A, i32 42, 1, 0
12250 // %E = extractvalue { i32, { i32 } } %I, 1
12251 // with
12252 // %X = extractvalue { i32, { i32 } } %A, 1
12253 // %E = insertvalue { i32 } %X, i32 42, 0
12254 // by switching the order of the insert and extract (though the
12255 // insertvalue should be left in, since it may have other uses).
12256 Value *NewEV = InsertNewInstBefore(
12257 ExtractValueInst::Create(IV->getAggregateOperand(),
12258 EV.idx_begin(), EV.idx_end()),
12259 EV);
12260 return InsertValueInst::Create(NewEV, IV->getInsertedValueOperand(),
12261 insi, inse);
12262 }
12263 if (insi == inse)
12264 // The insert list is a prefix of the extract list
12265 // We can simply remove the common indices from the extract and make it
12266 // operate on the inserted value instead of the insertvalue result.
12267 // i.e., replace
12268 // %I = insertvalue { i32, { i32 } } %A, { i32 } { i32 42 }, 1
12269 // %E = extractvalue { i32, { i32 } } %I, 1, 0
12270 // with
12271 // %E extractvalue { i32 } { i32 42 }, 0
12272 return ExtractValueInst::Create(IV->getInsertedValueOperand(),
12273 exti, exte);
12274 }
12275 // Can't simplify extracts from other values. Note that nested extracts are
12276 // already simplified implicitely by the above (extract ( extract (insert) )
12277 // will be translated into extract ( insert ( extract ) ) first and then just
12278 // the value inserted, if appropriate).
Matthijs Kooijmanda9ef702008-06-11 14:05:05 +000012279 return 0;
12280}
12281
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012282/// CheapToScalarize - Return true if the value is cheaper to scalarize than it
12283/// is to leave as a vector operation.
12284static bool CheapToScalarize(Value *V, bool isConstant) {
12285 if (isa<ConstantAggregateZero>(V))
12286 return true;
12287 if (ConstantVector *C = dyn_cast<ConstantVector>(V)) {
12288 if (isConstant) return true;
12289 // If all elts are the same, we can extract.
12290 Constant *Op0 = C->getOperand(0);
12291 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12292 if (C->getOperand(i) != Op0)
12293 return false;
12294 return true;
12295 }
12296 Instruction *I = dyn_cast<Instruction>(V);
12297 if (!I) return false;
12298
12299 // Insert element gets simplified to the inserted element or is deleted if
12300 // this is constant idx extract element and its a constant idx insertelt.
12301 if (I->getOpcode() == Instruction::InsertElement && isConstant &&
12302 isa<ConstantInt>(I->getOperand(2)))
12303 return true;
12304 if (I->getOpcode() == Instruction::Load && I->hasOneUse())
12305 return true;
12306 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I))
12307 if (BO->hasOneUse() &&
12308 (CheapToScalarize(BO->getOperand(0), isConstant) ||
12309 CheapToScalarize(BO->getOperand(1), isConstant)))
12310 return true;
12311 if (CmpInst *CI = dyn_cast<CmpInst>(I))
12312 if (CI->hasOneUse() &&
12313 (CheapToScalarize(CI->getOperand(0), isConstant) ||
12314 CheapToScalarize(CI->getOperand(1), isConstant)))
12315 return true;
12316
12317 return false;
12318}
12319
12320/// Read and decode a shufflevector mask.
12321///
12322/// It turns undef elements into values that are larger than the number of
12323/// elements in the input.
12324static std::vector<unsigned> getShuffleMask(const ShuffleVectorInst *SVI) {
12325 unsigned NElts = SVI->getType()->getNumElements();
12326 if (isa<ConstantAggregateZero>(SVI->getOperand(2)))
12327 return std::vector<unsigned>(NElts, 0);
12328 if (isa<UndefValue>(SVI->getOperand(2)))
12329 return std::vector<unsigned>(NElts, 2*NElts);
12330
12331 std::vector<unsigned> Result;
12332 const ConstantVector *CP = cast<ConstantVector>(SVI->getOperand(2));
Gabor Greif17396002008-06-12 21:37:33 +000012333 for (User::const_op_iterator i = CP->op_begin(), e = CP->op_end(); i!=e; ++i)
12334 if (isa<UndefValue>(*i))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012335 Result.push_back(NElts*2); // undef -> 8
12336 else
Gabor Greif17396002008-06-12 21:37:33 +000012337 Result.push_back(cast<ConstantInt>(*i)->getZExtValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012338 return Result;
12339}
12340
12341/// FindScalarElement - Given a vector and an element number, see if the scalar
12342/// value is already around as a register, for example if it were inserted then
12343/// extracted from the vector.
Owen Anderson24be4c12009-07-03 00:17:18 +000012344static Value *FindScalarElement(Value *V, unsigned EltNo,
Owen Anderson5349f052009-07-06 23:00:19 +000012345 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012346 assert(isa<VectorType>(V->getType()) && "Not looking at a vector?");
12347 const VectorType *PTy = cast<VectorType>(V->getType());
12348 unsigned Width = PTy->getNumElements();
12349 if (EltNo >= Width) // Out of range access.
Owen Anderson24be4c12009-07-03 00:17:18 +000012350 return Context->getUndef(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012351
12352 if (isa<UndefValue>(V))
Owen Anderson24be4c12009-07-03 00:17:18 +000012353 return Context->getUndef(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012354 else if (isa<ConstantAggregateZero>(V))
Owen Anderson24be4c12009-07-03 00:17:18 +000012355 return Context->getNullValue(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012356 else if (ConstantVector *CP = dyn_cast<ConstantVector>(V))
12357 return CP->getOperand(EltNo);
12358 else if (InsertElementInst *III = dyn_cast<InsertElementInst>(V)) {
12359 // If this is an insert to a variable element, we don't know what it is.
12360 if (!isa<ConstantInt>(III->getOperand(2)))
12361 return 0;
12362 unsigned IIElt = cast<ConstantInt>(III->getOperand(2))->getZExtValue();
12363
12364 // If this is an insert to the element we are looking for, return the
12365 // inserted value.
12366 if (EltNo == IIElt)
12367 return III->getOperand(1);
12368
12369 // Otherwise, the insertelement doesn't modify the value, recurse on its
12370 // vector input.
Owen Anderson24be4c12009-07-03 00:17:18 +000012371 return FindScalarElement(III->getOperand(0), EltNo, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012372 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(V)) {
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012373 unsigned LHSWidth =
12374 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012375 unsigned InEl = getShuffleMask(SVI)[EltNo];
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012376 if (InEl < LHSWidth)
Owen Anderson24be4c12009-07-03 00:17:18 +000012377 return FindScalarElement(SVI->getOperand(0), InEl, Context);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012378 else if (InEl < LHSWidth*2)
Owen Anderson24be4c12009-07-03 00:17:18 +000012379 return FindScalarElement(SVI->getOperand(1), InEl - LHSWidth, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012380 else
Owen Anderson24be4c12009-07-03 00:17:18 +000012381 return Context->getUndef(PTy->getElementType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012382 }
12383
12384 // Otherwise, we don't know.
12385 return 0;
12386}
12387
12388Instruction *InstCombiner::visitExtractElementInst(ExtractElementInst &EI) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012389 // If vector val is undef, replace extract with scalar undef.
12390 if (isa<UndefValue>(EI.getOperand(0)))
Owen Anderson24be4c12009-07-03 00:17:18 +000012391 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012392
12393 // If vector val is constant 0, replace extract with scalar 0.
12394 if (isa<ConstantAggregateZero>(EI.getOperand(0)))
Owen Anderson24be4c12009-07-03 00:17:18 +000012395 return ReplaceInstUsesWith(EI, Context->getNullValue(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012396
12397 if (ConstantVector *C = dyn_cast<ConstantVector>(EI.getOperand(0))) {
Matthijs Kooijmandd3425f2008-06-11 09:00:12 +000012398 // If vector val is constant with all elements the same, replace EI with
12399 // that element. When the elements are not identical, we cannot replace yet
12400 // (we do that below, but only when the index is constant).
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012401 Constant *op0 = C->getOperand(0);
12402 for (unsigned i = 1; i < C->getNumOperands(); ++i)
12403 if (C->getOperand(i) != op0) {
12404 op0 = 0;
12405 break;
12406 }
12407 if (op0)
12408 return ReplaceInstUsesWith(EI, op0);
12409 }
12410
12411 // If extracting a specified index from the vector, see if we can recursively
12412 // find a previously computed scalar that was inserted into the vector.
12413 if (ConstantInt *IdxC = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12414 unsigned IndexVal = IdxC->getZExtValue();
12415 unsigned VectorWidth =
12416 cast<VectorType>(EI.getOperand(0)->getType())->getNumElements();
12417
12418 // If this is extracting an invalid index, turn this into undef, to avoid
12419 // crashing the code below.
12420 if (IndexVal >= VectorWidth)
Owen Anderson24be4c12009-07-03 00:17:18 +000012421 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012422
12423 // This instruction only demands the single element from the input vector.
12424 // If the input vector has a single use, simplify it based on this use
12425 // property.
12426 if (EI.getOperand(0)->hasOneUse() && VectorWidth != 1) {
Evan Cheng63295ab2009-02-03 10:05:09 +000012427 APInt UndefElts(VectorWidth, 0);
12428 APInt DemandedMask(VectorWidth, 1 << IndexVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012429 if (Value *V = SimplifyDemandedVectorElts(EI.getOperand(0),
Evan Cheng63295ab2009-02-03 10:05:09 +000012430 DemandedMask, UndefElts)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012431 EI.setOperand(0, V);
12432 return &EI;
12433 }
12434 }
12435
Owen Anderson24be4c12009-07-03 00:17:18 +000012436 if (Value *Elt = FindScalarElement(EI.getOperand(0), IndexVal, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012437 return ReplaceInstUsesWith(EI, Elt);
12438
12439 // If the this extractelement is directly using a bitcast from a vector of
12440 // the same number of elements, see if we can find the source element from
12441 // it. In this case, we will end up needing to bitcast the scalars.
12442 if (BitCastInst *BCI = dyn_cast<BitCastInst>(EI.getOperand(0))) {
12443 if (const VectorType *VT =
12444 dyn_cast<VectorType>(BCI->getOperand(0)->getType()))
12445 if (VT->getNumElements() == VectorWidth)
Owen Anderson24be4c12009-07-03 00:17:18 +000012446 if (Value *Elt = FindScalarElement(BCI->getOperand(0),
12447 IndexVal, Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012448 return new BitCastInst(Elt, EI.getType());
12449 }
12450 }
12451
12452 if (Instruction *I = dyn_cast<Instruction>(EI.getOperand(0))) {
12453 if (I->hasOneUse()) {
12454 // Push extractelement into predecessor operation if legal and
12455 // profitable to do so
12456 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
12457 bool isConstantElt = isa<ConstantInt>(EI.getOperand(1));
12458 if (CheapToScalarize(BO, isConstantElt)) {
12459 ExtractElementInst *newEI0 =
12460 new ExtractElementInst(BO->getOperand(0), EI.getOperand(1),
12461 EI.getName()+".lhs");
12462 ExtractElementInst *newEI1 =
12463 new ExtractElementInst(BO->getOperand(1), EI.getOperand(1),
12464 EI.getName()+".rhs");
12465 InsertNewInstBefore(newEI0, EI);
12466 InsertNewInstBefore(newEI1, EI);
Gabor Greifa645dd32008-05-16 19:29:10 +000012467 return BinaryOperator::Create(BO->getOpcode(), newEI0, newEI1);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012468 }
12469 } else if (isa<LoadInst>(I)) {
Christopher Lambbb2f2222007-12-17 01:12:55 +000012470 unsigned AS =
12471 cast<PointerType>(I->getOperand(0)->getType())->getAddressSpace();
Chris Lattner13c2d6e2008-01-13 22:23:22 +000012472 Value *Ptr = InsertBitCastBefore(I->getOperand(0),
Owen Anderson24be4c12009-07-03 00:17:18 +000012473 Context->getPointerType(EI.getType(), AS),EI);
Gabor Greifb91ea9d2008-05-15 10:04:30 +000012474 GetElementPtrInst *GEP =
12475 GetElementPtrInst::Create(Ptr, EI.getOperand(1), I->getName()+".gep");
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012476 InsertNewInstBefore(GEP, EI);
12477 return new LoadInst(GEP);
12478 }
12479 }
12480 if (InsertElementInst *IE = dyn_cast<InsertElementInst>(I)) {
12481 // Extracting the inserted element?
12482 if (IE->getOperand(2) == EI.getOperand(1))
12483 return ReplaceInstUsesWith(EI, IE->getOperand(1));
12484 // If the inserted and extracted elements are constants, they must not
12485 // be the same value, extract from the pre-inserted value instead.
12486 if (isa<Constant>(IE->getOperand(2)) &&
12487 isa<Constant>(EI.getOperand(1))) {
12488 AddUsesToWorkList(EI);
12489 EI.setOperand(0, IE->getOperand(0));
12490 return &EI;
12491 }
12492 } else if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I)) {
12493 // If this is extracting an element from a shufflevector, figure out where
12494 // it came from and extract from the appropriate input element instead.
12495 if (ConstantInt *Elt = dyn_cast<ConstantInt>(EI.getOperand(1))) {
12496 unsigned SrcIdx = getShuffleMask(SVI)[Elt->getZExtValue()];
12497 Value *Src;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012498 unsigned LHSWidth =
12499 cast<VectorType>(SVI->getOperand(0)->getType())->getNumElements();
12500
12501 if (SrcIdx < LHSWidth)
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012502 Src = SVI->getOperand(0);
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012503 else if (SrcIdx < LHSWidth*2) {
12504 SrcIdx -= LHSWidth;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012505 Src = SVI->getOperand(1);
12506 } else {
Owen Anderson24be4c12009-07-03 00:17:18 +000012507 return ReplaceInstUsesWith(EI, Context->getUndef(EI.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012508 }
12509 return new ExtractElementInst(Src, SrcIdx);
12510 }
12511 }
12512 }
12513 return 0;
12514}
12515
12516/// CollectSingleShuffleElements - If V is a shuffle of values that ONLY returns
12517/// elements from either LHS or RHS, return the shuffle mask and true.
12518/// Otherwise, return false.
12519static bool CollectSingleShuffleElements(Value *V, Value *LHS, Value *RHS,
Owen Anderson24be4c12009-07-03 00:17:18 +000012520 std::vector<Constant*> &Mask,
Owen Anderson5349f052009-07-06 23:00:19 +000012521 LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012522 assert(V->getType() == LHS->getType() && V->getType() == RHS->getType() &&
12523 "Invalid CollectSingleShuffleElements");
12524 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12525
12526 if (isa<UndefValue>(V)) {
Owen Anderson24be4c12009-07-03 00:17:18 +000012527 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012528 return true;
12529 } else if (V == LHS) {
12530 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson24be4c12009-07-03 00:17:18 +000012531 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012532 return true;
12533 } else if (V == RHS) {
12534 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson24be4c12009-07-03 00:17:18 +000012535 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i+NumElts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012536 return true;
12537 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12538 // If this is an insert of an extract from some other vector, include it.
12539 Value *VecOp = IEI->getOperand(0);
12540 Value *ScalarOp = IEI->getOperand(1);
12541 Value *IdxOp = IEI->getOperand(2);
12542
12543 if (!isa<ConstantInt>(IdxOp))
12544 return false;
12545 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12546
12547 if (isa<UndefValue>(ScalarOp)) { // inserting undef into vector.
12548 // Okay, we can handle this if the vector we are insertinting into is
12549 // transitively ok.
Owen Anderson24be4c12009-07-03 00:17:18 +000012550 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012551 // If so, update the mask to reflect the inserted undef.
Owen Anderson24be4c12009-07-03 00:17:18 +000012552 Mask[InsertedIdx] = Context->getUndef(Type::Int32Ty);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012553 return true;
12554 }
12555 } else if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)){
12556 if (isa<ConstantInt>(EI->getOperand(1)) &&
12557 EI->getOperand(0)->getType() == V->getType()) {
12558 unsigned ExtractedIdx =
12559 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12560
12561 // This must be extracting from either LHS or RHS.
12562 if (EI->getOperand(0) == LHS || EI->getOperand(0) == RHS) {
12563 // Okay, we can handle this if the vector we are insertinting into is
12564 // transitively ok.
Owen Anderson24be4c12009-07-03 00:17:18 +000012565 if (CollectSingleShuffleElements(VecOp, LHS, RHS, Mask, Context)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012566 // If so, update the mask to reflect the inserted value.
12567 if (EI->getOperand(0) == LHS) {
Mon P Wang6bf3c592008-08-20 02:23:25 +000012568 Mask[InsertedIdx % NumElts] =
Owen Anderson24be4c12009-07-03 00:17:18 +000012569 Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012570 } else {
12571 assert(EI->getOperand(0) == RHS);
Mon P Wang6bf3c592008-08-20 02:23:25 +000012572 Mask[InsertedIdx % NumElts] =
Owen Anderson24be4c12009-07-03 00:17:18 +000012573 Context->getConstantInt(Type::Int32Ty, ExtractedIdx+NumElts);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012574
12575 }
12576 return true;
12577 }
12578 }
12579 }
12580 }
12581 }
12582 // TODO: Handle shufflevector here!
12583
12584 return false;
12585}
12586
12587/// CollectShuffleElements - We are building a shuffle of V, using RHS as the
12588/// RHS of the shuffle instruction, if it is not null. Return a shuffle mask
12589/// that computes V and the LHS value of the shuffle.
12590static Value *CollectShuffleElements(Value *V, std::vector<Constant*> &Mask,
Owen Anderson5349f052009-07-06 23:00:19 +000012591 Value *&RHS, LLVMContext *Context) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012592 assert(isa<VectorType>(V->getType()) &&
12593 (RHS == 0 || V->getType() == RHS->getType()) &&
12594 "Invalid shuffle!");
12595 unsigned NumElts = cast<VectorType>(V->getType())->getNumElements();
12596
12597 if (isa<UndefValue>(V)) {
Owen Anderson24be4c12009-07-03 00:17:18 +000012598 Mask.assign(NumElts, Context->getUndef(Type::Int32Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012599 return V;
12600 } else if (isa<ConstantAggregateZero>(V)) {
Owen Anderson24be4c12009-07-03 00:17:18 +000012601 Mask.assign(NumElts, Context->getConstantInt(Type::Int32Ty, 0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012602 return V;
12603 } else if (InsertElementInst *IEI = dyn_cast<InsertElementInst>(V)) {
12604 // If this is an insert of an extract from some other vector, include it.
12605 Value *VecOp = IEI->getOperand(0);
12606 Value *ScalarOp = IEI->getOperand(1);
12607 Value *IdxOp = IEI->getOperand(2);
12608
12609 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12610 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12611 EI->getOperand(0)->getType() == V->getType()) {
12612 unsigned ExtractedIdx =
12613 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12614 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12615
12616 // Either the extracted from or inserted into vector must be RHSVec,
12617 // otherwise we'd end up with a shuffle of three inputs.
12618 if (EI->getOperand(0) == RHS || RHS == 0) {
12619 RHS = EI->getOperand(0);
Owen Anderson24be4c12009-07-03 00:17:18 +000012620 Value *V = CollectShuffleElements(VecOp, Mask, RHS, Context);
Mon P Wang6bf3c592008-08-20 02:23:25 +000012621 Mask[InsertedIdx % NumElts] =
Owen Anderson24be4c12009-07-03 00:17:18 +000012622 Context->getConstantInt(Type::Int32Ty, NumElts+ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012623 return V;
12624 }
12625
12626 if (VecOp == RHS) {
Owen Anderson24be4c12009-07-03 00:17:18 +000012627 Value *V = CollectShuffleElements(EI->getOperand(0), Mask,
12628 RHS, Context);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012629 // Everything but the extracted element is replaced with the RHS.
12630 for (unsigned i = 0; i != NumElts; ++i) {
12631 if (i != InsertedIdx)
Owen Anderson24be4c12009-07-03 00:17:18 +000012632 Mask[i] = Context->getConstantInt(Type::Int32Ty, NumElts+i);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012633 }
12634 return V;
12635 }
12636
12637 // If this insertelement is a chain that comes from exactly these two
12638 // vectors, return the vector and the effective shuffle.
Owen Anderson24be4c12009-07-03 00:17:18 +000012639 if (CollectSingleShuffleElements(IEI, EI->getOperand(0), RHS, Mask,
12640 Context))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012641 return EI->getOperand(0);
12642
12643 }
12644 }
12645 }
12646 // TODO: Handle shufflevector here!
12647
12648 // Otherwise, can't do anything fancy. Return an identity vector.
12649 for (unsigned i = 0; i != NumElts; ++i)
Owen Anderson24be4c12009-07-03 00:17:18 +000012650 Mask.push_back(Context->getConstantInt(Type::Int32Ty, i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012651 return V;
12652}
12653
12654Instruction *InstCombiner::visitInsertElementInst(InsertElementInst &IE) {
12655 Value *VecOp = IE.getOperand(0);
12656 Value *ScalarOp = IE.getOperand(1);
12657 Value *IdxOp = IE.getOperand(2);
12658
12659 // Inserting an undef or into an undefined place, remove this.
12660 if (isa<UndefValue>(ScalarOp) || isa<UndefValue>(IdxOp))
12661 ReplaceInstUsesWith(IE, VecOp);
12662
12663 // If the inserted element was extracted from some other vector, and if the
12664 // indexes are constant, try to turn this into a shufflevector operation.
12665 if (ExtractElementInst *EI = dyn_cast<ExtractElementInst>(ScalarOp)) {
12666 if (isa<ConstantInt>(EI->getOperand(1)) && isa<ConstantInt>(IdxOp) &&
12667 EI->getOperand(0)->getType() == IE.getType()) {
12668 unsigned NumVectorElts = IE.getType()->getNumElements();
12669 unsigned ExtractedIdx =
12670 cast<ConstantInt>(EI->getOperand(1))->getZExtValue();
12671 unsigned InsertedIdx = cast<ConstantInt>(IdxOp)->getZExtValue();
12672
12673 if (ExtractedIdx >= NumVectorElts) // Out of range extract.
12674 return ReplaceInstUsesWith(IE, VecOp);
12675
12676 if (InsertedIdx >= NumVectorElts) // Out of range insert.
Owen Anderson24be4c12009-07-03 00:17:18 +000012677 return ReplaceInstUsesWith(IE, Context->getUndef(IE.getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012678
12679 // If we are extracting a value from a vector, then inserting it right
12680 // back into the same place, just use the input vector.
12681 if (EI->getOperand(0) == VecOp && ExtractedIdx == InsertedIdx)
12682 return ReplaceInstUsesWith(IE, VecOp);
12683
12684 // We could theoretically do this for ANY input. However, doing so could
12685 // turn chains of insertelement instructions into a chain of shufflevector
12686 // instructions, and right now we do not merge shufflevectors. As such,
12687 // only do this in a situation where it is clear that there is benefit.
12688 if (isa<UndefValue>(VecOp) || isa<ConstantAggregateZero>(VecOp)) {
12689 // Turn this into shuffle(EIOp0, VecOp, Mask). The result has all of
12690 // the values of VecOp, except then one read from EIOp0.
12691 // Build a new shuffle mask.
12692 std::vector<Constant*> Mask;
12693 if (isa<UndefValue>(VecOp))
Owen Anderson24be4c12009-07-03 00:17:18 +000012694 Mask.assign(NumVectorElts, Context->getUndef(Type::Int32Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012695 else {
12696 assert(isa<ConstantAggregateZero>(VecOp) && "Unknown thing");
Owen Anderson24be4c12009-07-03 00:17:18 +000012697 Mask.assign(NumVectorElts, Context->getConstantInt(Type::Int32Ty,
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012698 NumVectorElts));
12699 }
Owen Anderson24be4c12009-07-03 00:17:18 +000012700 Mask[InsertedIdx] =
12701 Context->getConstantInt(Type::Int32Ty, ExtractedIdx);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012702 return new ShuffleVectorInst(EI->getOperand(0), VecOp,
Owen Anderson24be4c12009-07-03 00:17:18 +000012703 Context->getConstantVector(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012704 }
12705
12706 // If this insertelement isn't used by some other insertelement, turn it
12707 // (and any insertelements it points to), into one big shuffle.
12708 if (!IE.hasOneUse() || !isa<InsertElementInst>(IE.use_back())) {
12709 std::vector<Constant*> Mask;
12710 Value *RHS = 0;
Owen Anderson24be4c12009-07-03 00:17:18 +000012711 Value *LHS = CollectShuffleElements(&IE, Mask, RHS, Context);
12712 if (RHS == 0) RHS = Context->getUndef(LHS->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012713 // We now have a shuffle of LHS, RHS, Mask.
Owen Anderson24be4c12009-07-03 00:17:18 +000012714 return new ShuffleVectorInst(LHS, RHS,
12715 Context->getConstantVector(Mask));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012716 }
12717 }
12718 }
12719
Eli Friedmanbefee262009-06-06 20:08:03 +000012720 unsigned VWidth = cast<VectorType>(VecOp->getType())->getNumElements();
12721 APInt UndefElts(VWidth, 0);
12722 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12723 if (SimplifyDemandedVectorElts(&IE, AllOnesEltMask, UndefElts))
12724 return &IE;
12725
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012726 return 0;
12727}
12728
12729
12730Instruction *InstCombiner::visitShuffleVectorInst(ShuffleVectorInst &SVI) {
12731 Value *LHS = SVI.getOperand(0);
12732 Value *RHS = SVI.getOperand(1);
12733 std::vector<unsigned> Mask = getShuffleMask(&SVI);
12734
12735 bool MadeChange = false;
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012736
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012737 // Undefined shuffle mask -> undefined value.
12738 if (isa<UndefValue>(SVI.getOperand(2)))
Owen Anderson24be4c12009-07-03 00:17:18 +000012739 return ReplaceInstUsesWith(SVI, Context->getUndef(SVI.getType()));
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012740
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012741 unsigned VWidth = cast<VectorType>(SVI.getType())->getNumElements();
Mon P Wangbff5d9c2008-11-10 04:46:22 +000012742
12743 if (VWidth != cast<VectorType>(LHS->getType())->getNumElements())
12744 return 0;
12745
Evan Cheng63295ab2009-02-03 10:05:09 +000012746 APInt UndefElts(VWidth, 0);
12747 APInt AllOnesEltMask(APInt::getAllOnesValue(VWidth));
12748 if (SimplifyDemandedVectorElts(&SVI, AllOnesEltMask, UndefElts)) {
Dan Gohman83b702d2008-09-11 22:47:57 +000012749 LHS = SVI.getOperand(0);
12750 RHS = SVI.getOperand(1);
Dan Gohmanda93bbe2008-09-09 18:11:14 +000012751 MadeChange = true;
Dan Gohman83b702d2008-09-11 22:47:57 +000012752 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012753
12754 // Canonicalize shuffle(x ,x,mask) -> shuffle(x, undef,mask')
12755 // Canonicalize shuffle(undef,x,mask) -> shuffle(x, undef,mask').
12756 if (LHS == RHS || isa<UndefValue>(LHS)) {
12757 if (isa<UndefValue>(LHS) && LHS == RHS) {
12758 // shuffle(undef,undef,mask) -> undef.
12759 return ReplaceInstUsesWith(SVI, LHS);
12760 }
12761
12762 // Remap any references to RHS to use LHS.
12763 std::vector<Constant*> Elts;
12764 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12765 if (Mask[i] >= 2*e)
Owen Anderson24be4c12009-07-03 00:17:18 +000012766 Elts.push_back(Context->getUndef(Type::Int32Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012767 else {
12768 if ((Mask[i] >= e && isa<UndefValue>(RHS)) ||
Dan Gohmanbba96b92008-08-06 18:17:32 +000012769 (Mask[i] < e && isa<UndefValue>(LHS))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012770 Mask[i] = 2*e; // Turn into undef.
Owen Anderson24be4c12009-07-03 00:17:18 +000012771 Elts.push_back(Context->getUndef(Type::Int32Ty));
Dan Gohmanbba96b92008-08-06 18:17:32 +000012772 } else {
Mon P Wang6bf3c592008-08-20 02:23:25 +000012773 Mask[i] = Mask[i] % e; // Force to LHS.
Owen Anderson24be4c12009-07-03 00:17:18 +000012774 Elts.push_back(Context->getConstantInt(Type::Int32Ty, Mask[i]));
Dan Gohmanbba96b92008-08-06 18:17:32 +000012775 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012776 }
12777 }
12778 SVI.setOperand(0, SVI.getOperand(1));
Owen Anderson24be4c12009-07-03 00:17:18 +000012779 SVI.setOperand(1, Context->getUndef(RHS->getType()));
12780 SVI.setOperand(2, Context->getConstantVector(Elts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012781 LHS = SVI.getOperand(0);
12782 RHS = SVI.getOperand(1);
12783 MadeChange = true;
12784 }
12785
12786 // Analyze the shuffle, are the LHS or RHS and identity shuffles?
12787 bool isLHSID = true, isRHSID = true;
12788
12789 for (unsigned i = 0, e = Mask.size(); i != e; ++i) {
12790 if (Mask[i] >= e*2) continue; // Ignore undef values.
12791 // Is this an identity shuffle of the LHS value?
12792 isLHSID &= (Mask[i] == i);
12793
12794 // Is this an identity shuffle of the RHS value?
12795 isRHSID &= (Mask[i]-e == i);
12796 }
12797
12798 // Eliminate identity shuffles.
12799 if (isLHSID) return ReplaceInstUsesWith(SVI, LHS);
12800 if (isRHSID) return ReplaceInstUsesWith(SVI, RHS);
12801
12802 // If the LHS is a shufflevector itself, see if we can combine it with this
12803 // one without producing an unusual shuffle. Here we are really conservative:
12804 // we are absolutely afraid of producing a shuffle mask not in the input
12805 // program, because the code gen may not be smart enough to turn a merged
12806 // shuffle into two specific shuffles: it may produce worse code. As such,
12807 // we only merge two shuffles if the result is one of the two input shuffle
12808 // masks. In this case, merging the shuffles just removes one instruction,
12809 // which we know is safe. This is good for things like turning:
12810 // (splat(splat)) -> splat.
12811 if (ShuffleVectorInst *LHSSVI = dyn_cast<ShuffleVectorInst>(LHS)) {
12812 if (isa<UndefValue>(RHS)) {
12813 std::vector<unsigned> LHSMask = getShuffleMask(LHSSVI);
12814
12815 std::vector<unsigned> NewMask;
12816 for (unsigned i = 0, e = Mask.size(); i != e; ++i)
12817 if (Mask[i] >= 2*e)
12818 NewMask.push_back(2*e);
12819 else
12820 NewMask.push_back(LHSMask[Mask[i]]);
12821
12822 // If the result mask is equal to the src shuffle or this shuffle mask, do
12823 // the replacement.
12824 if (NewMask == LHSMask || NewMask == Mask) {
wangmp496a76d2009-01-26 04:39:00 +000012825 unsigned LHSInNElts =
12826 cast<VectorType>(LHSSVI->getOperand(0)->getType())->getNumElements();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012827 std::vector<Constant*> Elts;
12828 for (unsigned i = 0, e = NewMask.size(); i != e; ++i) {
wangmp496a76d2009-01-26 04:39:00 +000012829 if (NewMask[i] >= LHSInNElts*2) {
Owen Anderson24be4c12009-07-03 00:17:18 +000012830 Elts.push_back(Context->getUndef(Type::Int32Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012831 } else {
Owen Anderson24be4c12009-07-03 00:17:18 +000012832 Elts.push_back(Context->getConstantInt(Type::Int32Ty, NewMask[i]));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012833 }
12834 }
12835 return new ShuffleVectorInst(LHSSVI->getOperand(0),
12836 LHSSVI->getOperand(1),
Owen Anderson24be4c12009-07-03 00:17:18 +000012837 Context->getConstantVector(Elts));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012838 }
12839 }
12840 }
12841
12842 return MadeChange ? &SVI : 0;
12843}
12844
12845
12846
12847
12848/// TryToSinkInstruction - Try to move the specified instruction from its
12849/// current block into the beginning of DestBlock, which can only happen if it's
12850/// safe to move the instruction past all of the instructions between it and the
12851/// end of its block.
12852static bool TryToSinkInstruction(Instruction *I, BasicBlock *DestBlock) {
12853 assert(I->hasOneUse() && "Invariants didn't hold!");
12854
12855 // Cannot move control-flow-involving, volatile loads, vaarg, etc.
Duncan Sands2f500832009-05-06 06:49:50 +000012856 if (isa<PHINode>(I) || I->mayHaveSideEffects() || isa<TerminatorInst>(I))
Chris Lattnercb19a1c2008-05-09 15:07:33 +000012857 return false;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012858
12859 // Do not sink alloca instructions out of the entry block.
12860 if (isa<AllocaInst>(I) && I->getParent() ==
12861 &DestBlock->getParent()->getEntryBlock())
12862 return false;
12863
12864 // We can only sink load instructions if there is nothing between the load and
12865 // the end of block that could change the value.
Chris Lattner0db40a62008-05-08 17:37:37 +000012866 if (I->mayReadFromMemory()) {
12867 for (BasicBlock::iterator Scan = I, E = I->getParent()->end();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012868 Scan != E; ++Scan)
12869 if (Scan->mayWriteToMemory())
12870 return false;
12871 }
12872
Dan Gohman514277c2008-05-23 21:05:58 +000012873 BasicBlock::iterator InsertPos = DestBlock->getFirstNonPHI();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012874
Dale Johannesen24339f12009-03-03 01:09:07 +000012875 CopyPrecedingStopPoint(I, InsertPos);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012876 I->moveBefore(InsertPos);
12877 ++NumSunkInst;
12878 return true;
12879}
12880
12881
12882/// AddReachableCodeToWorklist - Walk the function in depth-first order, adding
12883/// all reachable code to the worklist.
12884///
12885/// This has a couple of tricks to make the code faster and more powerful. In
12886/// particular, we constant fold and DCE instructions as we go, to avoid adding
12887/// them to the worklist (this significantly speeds up instcombine on code where
12888/// many instructions are dead or constant). Additionally, if we find a branch
12889/// whose condition is a known constant, we only visit the reachable successors.
12890///
12891static void AddReachableCodeToWorklist(BasicBlock *BB,
12892 SmallPtrSet<BasicBlock*, 64> &Visited,
12893 InstCombiner &IC,
12894 const TargetData *TD) {
Chris Lattnera06291a2008-08-15 04:03:01 +000012895 SmallVector<BasicBlock*, 256> Worklist;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012896 Worklist.push_back(BB);
12897
12898 while (!Worklist.empty()) {
12899 BB = Worklist.back();
12900 Worklist.pop_back();
12901
12902 // We have now visited this block! If we've already been here, ignore it.
12903 if (!Visited.insert(BB)) continue;
Devang Patel794140c2008-11-19 18:56:50 +000012904
12905 DbgInfoIntrinsic *DBI_Prev = NULL;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012906 for (BasicBlock::iterator BBI = BB->begin(), E = BB->end(); BBI != E; ) {
12907 Instruction *Inst = BBI++;
12908
12909 // DCE instruction if trivially dead.
12910 if (isInstructionTriviallyDead(Inst)) {
12911 ++NumDeadInst;
12912 DOUT << "IC: DCE: " << *Inst;
12913 Inst->eraseFromParent();
12914 continue;
12915 }
12916
12917 // ConstantProp instruction if trivially constant.
Owen Andersond4d90a02009-07-06 18:42:36 +000012918 if (Constant *C = ConstantFoldInstruction(Inst, BB->getContext(), TD)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012919 DOUT << "IC: ConstFold to: " << *C << " from: " << *Inst;
12920 Inst->replaceAllUsesWith(C);
12921 ++NumConstProp;
12922 Inst->eraseFromParent();
12923 continue;
12924 }
Chris Lattnere0f462d2007-07-20 22:06:41 +000012925
Devang Patel794140c2008-11-19 18:56:50 +000012926 // If there are two consecutive llvm.dbg.stoppoint calls then
12927 // it is likely that the optimizer deleted code in between these
12928 // two intrinsics.
12929 DbgInfoIntrinsic *DBI_Next = dyn_cast<DbgInfoIntrinsic>(Inst);
12930 if (DBI_Next) {
12931 if (DBI_Prev
12932 && DBI_Prev->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint
12933 && DBI_Next->getIntrinsicID() == llvm::Intrinsic::dbg_stoppoint) {
12934 IC.RemoveFromWorkList(DBI_Prev);
12935 DBI_Prev->eraseFromParent();
12936 }
12937 DBI_Prev = DBI_Next;
Zhou Sheng77e03b92009-02-23 10:14:11 +000012938 } else {
12939 DBI_Prev = 0;
Devang Patel794140c2008-11-19 18:56:50 +000012940 }
12941
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012942 IC.AddToWorkList(Inst);
12943 }
12944
12945 // Recursively visit successors. If this is a branch or switch on a
12946 // constant, only visit the reachable successor.
12947 TerminatorInst *TI = BB->getTerminator();
12948 if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
12949 if (BI->isConditional() && isa<ConstantInt>(BI->getCondition())) {
12950 bool CondVal = cast<ConstantInt>(BI->getCondition())->getZExtValue();
Nick Lewyckyd551cf12008-03-09 08:50:23 +000012951 BasicBlock *ReachableBB = BI->getSuccessor(!CondVal);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000012952 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012953 continue;
12954 }
12955 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
12956 if (ConstantInt *Cond = dyn_cast<ConstantInt>(SI->getCondition())) {
12957 // See if this is an explicit destination.
12958 for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i)
12959 if (SI->getCaseValue(i) == Cond) {
Nick Lewyckyd551cf12008-03-09 08:50:23 +000012960 BasicBlock *ReachableBB = SI->getSuccessor(i);
Nick Lewyckyd8aa33a2008-04-25 16:53:59 +000012961 Worklist.push_back(ReachableBB);
Dan Gohmanf17a25c2007-07-18 16:29:46 +000012962 continue;
12963 }
12964
12965 // Otherwise it is the default destination.
12966 Worklist.push_back(SI->getSuccessor(0));
12967 continue;
12968 }
12969 }
12970
12971 for (unsigned i = 0, e = TI->getNumSuccessors(); i != e; ++i)
12972 Worklist.push_back(TI->getSuccessor(i));
12973 }
12974}
12975
12976bool InstCombiner::DoOneIteration(Function &F, unsigned Iteration) {
12977 bool Changed = false;
12978 TD = &getAnalysis<TargetData>();
12979
12980 DEBUG(DOUT << "\n\nINSTCOMBINE ITERATION #" << Iteration << " on "
12981 << F.getNameStr() << "\n");
12982
12983 {
12984 // Do a depth-first traversal of the function, populate the worklist with
12985 // the reachable instructions. Ignore blocks that are not reachable. Keep
12986 // track of which blocks we visit.
12987 SmallPtrSet<BasicBlock*, 64> Visited;
12988 AddReachableCodeToWorklist(F.begin(), Visited, *this, TD);
12989
12990 // Do a quick scan over the function. If we find any blocks that are
12991 // unreachable, remove any instructions inside of them. This prevents
12992 // the instcombine code from having to deal with some bad special cases.
12993 for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB)
12994 if (!Visited.count(BB)) {
12995 Instruction *Term = BB->getTerminator();
12996 while (Term != BB->begin()) { // Remove instrs bottom-up
12997 BasicBlock::iterator I = Term; --I;
12998
12999 DOUT << "IC: DCE: " << *I;
Dale Johannesendf356c62009-03-10 21:19:49 +000013000 // A debug intrinsic shouldn't force another iteration if we weren't
13001 // going to do one without it.
13002 if (!isa<DbgInfoIntrinsic>(I)) {
13003 ++NumDeadInst;
13004 Changed = true;
13005 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013006 if (!I->use_empty())
Owen Anderson24be4c12009-07-03 00:17:18 +000013007 I->replaceAllUsesWith(Context->getUndef(I->getType()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013008 I->eraseFromParent();
13009 }
13010 }
13011 }
13012
13013 while (!Worklist.empty()) {
13014 Instruction *I = RemoveOneFromWorkList();
13015 if (I == 0) continue; // skip null values.
13016
13017 // Check to see if we can DCE the instruction.
13018 if (isInstructionTriviallyDead(I)) {
13019 // Add operands to the worklist.
13020 if (I->getNumOperands() < 4)
13021 AddUsesToWorkList(*I);
13022 ++NumDeadInst;
13023
13024 DOUT << "IC: DCE: " << *I;
13025
13026 I->eraseFromParent();
13027 RemoveFromWorkList(I);
Chris Lattnerf6d58862009-01-31 07:04:22 +000013028 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013029 continue;
13030 }
13031
13032 // Instruction isn't dead, see if we can constant propagate it.
Owen Andersond4d90a02009-07-06 18:42:36 +000013033 if (Constant *C = ConstantFoldInstruction(I, F.getContext(), TD)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013034 DOUT << "IC: ConstFold to: " << *C << " from: " << *I;
13035
13036 // Add operands to the worklist.
13037 AddUsesToWorkList(*I);
13038 ReplaceInstUsesWith(*I, C);
13039
13040 ++NumConstProp;
13041 I->eraseFromParent();
13042 RemoveFromWorkList(I);
Chris Lattnerf6d58862009-01-31 07:04:22 +000013043 Changed = true;
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013044 continue;
13045 }
13046
Dan Gohman95b95de2009-05-07 19:43:39 +000013047 if (TD &&
13048 (I->getType()->getTypeID() == Type::VoidTyID ||
13049 I->isTrapping())) {
Nick Lewyckyadb67922008-05-25 20:56:15 +000013050 // See if we can constant fold its operands.
Chris Lattnerf6d58862009-01-31 07:04:22 +000013051 for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
13052 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(i))
Owen Andersond4d90a02009-07-06 18:42:36 +000013053 if (Constant *NewC = ConstantFoldConstantExpression(CE,
13054 F.getContext(), TD))
Chris Lattnerf6d58862009-01-31 07:04:22 +000013055 if (NewC != CE) {
13056 i->set(NewC);
13057 Changed = true;
13058 }
Nick Lewyckyadb67922008-05-25 20:56:15 +000013059 }
13060
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013061 // See if we can trivially sink this instruction to a successor basic block.
Dan Gohman29474e92008-07-23 00:34:11 +000013062 if (I->hasOneUse()) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013063 BasicBlock *BB = I->getParent();
13064 BasicBlock *UserParent = cast<Instruction>(I->use_back())->getParent();
13065 if (UserParent != BB) {
13066 bool UserIsSuccessor = false;
13067 // See if the user is one of our successors.
13068 for (succ_iterator SI = succ_begin(BB), E = succ_end(BB); SI != E; ++SI)
13069 if (*SI == UserParent) {
13070 UserIsSuccessor = true;
13071 break;
13072 }
13073
13074 // If the user is one of our immediate successors, and if that successor
13075 // only has us as a predecessors (we'd have to split the critical edge
13076 // otherwise), we can keep going.
13077 if (UserIsSuccessor && !isa<PHINode>(I->use_back()) &&
13078 next(pred_begin(UserParent)) == pred_end(UserParent))
13079 // Okay, the CFG is simple enough, try to sink this instruction.
13080 Changed |= TryToSinkInstruction(I, UserParent);
13081 }
13082 }
13083
13084 // Now that we have an instruction, try combining it to simplify it...
13085#ifndef NDEBUG
13086 std::string OrigI;
13087#endif
13088 DEBUG(std::ostringstream SS; I->print(SS); OrigI = SS.str(););
13089 if (Instruction *Result = visit(*I)) {
13090 ++NumCombined;
13091 // Should we replace the old instruction with a new one?
13092 if (Result != I) {
13093 DOUT << "IC: Old = " << *I
13094 << " New = " << *Result;
13095
13096 // Everything uses the new instruction now.
13097 I->replaceAllUsesWith(Result);
13098
13099 // Push the new instruction and any users onto the worklist.
13100 AddToWorkList(Result);
13101 AddUsersToWorkList(*Result);
13102
13103 // Move the name to the new instruction first.
13104 Result->takeName(I);
13105
13106 // Insert the new instruction into the basic block...
13107 BasicBlock *InstParent = I->getParent();
13108 BasicBlock::iterator InsertPos = I;
13109
13110 if (!isa<PHINode>(Result)) // If combining a PHI, don't insert
13111 while (isa<PHINode>(InsertPos)) // middle of a block of PHIs.
13112 ++InsertPos;
13113
13114 InstParent->getInstList().insert(InsertPos, Result);
13115
13116 // Make sure that we reprocess all operands now that we reduced their
13117 // use counts.
13118 AddUsesToWorkList(*I);
13119
13120 // Instructions can end up on the worklist more than once. Make sure
13121 // we do not process an instruction that has been deleted.
13122 RemoveFromWorkList(I);
13123
13124 // Erase the old instruction.
13125 InstParent->getInstList().erase(I);
13126 } else {
13127#ifndef NDEBUG
13128 DOUT << "IC: Mod = " << OrigI
13129 << " New = " << *I;
13130#endif
13131
13132 // If the instruction was modified, it's possible that it is now dead.
13133 // if so, remove it.
13134 if (isInstructionTriviallyDead(I)) {
13135 // Make sure we process all operands now that we are reducing their
13136 // use counts.
13137 AddUsesToWorkList(*I);
13138
13139 // Instructions may end up in the worklist more than once. Erase all
13140 // occurrences of this instruction.
13141 RemoveFromWorkList(I);
13142 I->eraseFromParent();
13143 } else {
13144 AddToWorkList(I);
13145 AddUsersToWorkList(*I);
13146 }
13147 }
13148 Changed = true;
13149 }
13150 }
13151
13152 assert(WorklistMap.empty() && "Worklist empty, but map not?");
Chris Lattnerb933ea62007-08-05 08:47:58 +000013153
13154 // Do an explicit clear, this shrinks the map if needed.
13155 WorklistMap.clear();
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013156 return Changed;
13157}
13158
13159
13160bool InstCombiner::runOnFunction(Function &F) {
13161 MustPreserveLCSSA = mustPreserveAnalysisID(LCSSAID);
13162
13163 bool EverMadeChange = false;
13164
13165 // Iterate while there is work to do.
13166 unsigned Iteration = 0;
Bill Wendlingd9644a42008-05-14 22:45:20 +000013167 while (DoOneIteration(F, Iteration++))
Dan Gohmanf17a25c2007-07-18 16:29:46 +000013168 EverMadeChange = true;
13169 return EverMadeChange;
13170}
13171
13172FunctionPass *llvm::createInstructionCombiningPass() {
13173 return new InstCombiner();
13174}