blob: b2f2e248e41724c5b2e10b2ae1216cf149c2f421 [file] [log] [blame]
Chris Lattnera65e2f72010-01-05 05:57:49 +00001//===- InstCombineLoadStoreAlloca.cpp -------------------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the visit functions for load, store and alloca.
11//
12//===----------------------------------------------------------------------===//
13
14#include "InstCombine.h"
15#include "llvm/IntrinsicInst.h"
Dan Gohman826bdf82010-05-28 16:19:17 +000016#include "llvm/Analysis/Loads.h"
Chris Lattnera65e2f72010-01-05 05:57:49 +000017#include "llvm/Target/TargetData.h"
18#include "llvm/Transforms/Utils/BasicBlockUtils.h"
19#include "llvm/Transforms/Utils/Local.h"
20#include "llvm/ADT/Statistic.h"
21using namespace llvm;
22
23STATISTIC(NumDeadStore, "Number of dead stores eliminated");
24
Chandler Carruthf82b0e22012-04-08 14:36:56 +000025// Try to kill dead allocas by walking through its uses until we see some use
26// that could escape. This is a conservative analysis which tries to handle
27// GEPs, bitcasts, stores, and no-op intrinsics. These tend to be the things
28// left after inlining and SROA finish chewing on an alloca.
29static Instruction *removeDeadAlloca(InstCombiner &IC, AllocaInst &AI) {
30 SmallVector<Instruction *, 4> Worklist, DeadStores;
31 Worklist.push_back(&AI);
32 do {
33 Instruction *PI = Worklist.pop_back_val();
34 for (Value::use_iterator UI = PI->use_begin(), UE = PI->use_end();
35 UI != UE; ++UI) {
36 Instruction *I = cast<Instruction>(*UI);
37 switch (I->getOpcode()) {
38 default:
39 // Give up the moment we see something we can't handle.
40 return 0;
41
42 case Instruction::GetElementPtr:
43 case Instruction::BitCast:
44 Worklist.push_back(I);
45 continue;
46
47 case Instruction::Call:
48 // We can handle a limited subset of calls to no-op intrinsics.
49 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
50 switch (II->getIntrinsicID()) {
51 case Intrinsic::dbg_declare:
52 case Intrinsic::dbg_value:
53 case Intrinsic::invariant_start:
54 case Intrinsic::invariant_end:
55 case Intrinsic::lifetime_start:
56 case Intrinsic::lifetime_end:
57 continue;
58 default:
59 return 0;
60 }
61 }
62 // Reject everything else.
63 return 0;
64
65 case Instruction::Store: {
66 // Stores into the alloca are only live if the alloca is live.
67 StoreInst *SI = cast<StoreInst>(I);
68 // We can eliminate atomic stores, but not volatile.
69 if (SI->isVolatile())
70 return 0;
71 // The store is only trivially safe if the poniter is the destination
72 // as opposed to the value. We're conservative here and don't check for
73 // the case where we store the address of a dead alloca into a dead
74 // alloca.
75 if (SI->getPointerOperand() != PI)
76 return 0;
77 DeadStores.push_back(I);
78 continue;
79 }
80 }
81 }
82 } while (!Worklist.empty());
83
84 // The alloca is dead. Kill off all the stores to it, and then replace it
85 // with undef.
86 while (!DeadStores.empty())
87 IC.EraseInstFromFunction(*DeadStores.pop_back_val());
88 return IC.ReplaceInstUsesWith(AI, UndefValue::get(AI.getType()));
89}
90
Chris Lattnera65e2f72010-01-05 05:57:49 +000091Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
Dan Gohmandf5d7dc2010-05-28 15:09:00 +000092 // Ensure that the alloca array size argument has type intptr_t, so that
93 // any casting is exposed early.
94 if (TD) {
Chris Lattner229907c2011-07-18 04:54:35 +000095 Type *IntPtrTy = TD->getIntPtrType(AI.getContext());
Dan Gohmandf5d7dc2010-05-28 15:09:00 +000096 if (AI.getArraySize()->getType() != IntPtrTy) {
97 Value *V = Builder->CreateIntCast(AI.getArraySize(),
98 IntPtrTy, false);
99 AI.setOperand(0, V);
100 return &AI;
101 }
102 }
103
Chris Lattnera65e2f72010-01-05 05:57:49 +0000104 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
105 if (AI.isArrayAllocation()) { // Check C != 1
106 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
Chris Lattner229907c2011-07-18 04:54:35 +0000107 Type *NewTy =
Chris Lattnera65e2f72010-01-05 05:57:49 +0000108 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
109 assert(isa<AllocaInst>(AI) && "Unknown type of allocation inst!");
110 AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
111 New->setAlignment(AI.getAlignment());
112
113 // Scan to the end of the allocation instructions, to skip over a block of
114 // allocas if possible...also skip interleaved debug info
115 //
116 BasicBlock::iterator It = New;
117 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
118
119 // Now that I is pointing to the first non-allocation-inst in the block,
120 // insert our getelementptr instruction...
121 //
122 Value *NullIdx =Constant::getNullValue(Type::getInt32Ty(AI.getContext()));
123 Value *Idx[2];
124 Idx[0] = NullIdx;
125 Idx[1] = NullIdx;
Eli Friedman41e509a2011-05-18 23:58:37 +0000126 Instruction *GEP =
Jay Foadd1b78492011-07-25 09:48:08 +0000127 GetElementPtrInst::CreateInBounds(New, Idx, New->getName()+".sub");
Eli Friedman41e509a2011-05-18 23:58:37 +0000128 InsertNewInstBefore(GEP, *It);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000129
130 // Now make everything use the getelementptr instead of the original
131 // allocation.
Eli Friedman41e509a2011-05-18 23:58:37 +0000132 return ReplaceInstUsesWith(AI, GEP);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000133 } else if (isa<UndefValue>(AI.getArraySize())) {
134 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
135 }
136 }
137
138 if (TD && isa<AllocaInst>(AI) && AI.getAllocatedType()->isSized()) {
139 // If alloca'ing a zero byte object, replace the alloca with a null pointer.
140 // Note that we only do this for alloca's, because malloc should allocate
141 // and return a unique pointer, even for a zero byte allocation.
142 if (TD->getTypeAllocSize(AI.getAllocatedType()) == 0)
143 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
144
145 // If the alignment is 0 (unspecified), assign it the preferred alignment.
146 if (AI.getAlignment() == 0)
147 AI.setAlignment(TD->getPrefTypeAlignment(AI.getAllocatedType()));
148 }
149
Chandler Carruthf82b0e22012-04-08 14:36:56 +0000150 // Try to aggressively remove allocas which are only used for GEPs, lifetime
151 // markers, and stores. This happens when SROA iteratively promotes stores
152 // out of the alloca, and we need to cleanup after it.
153 return removeDeadAlloca(*this, AI);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000154}
155
156
157/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
158static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
159 const TargetData *TD) {
160 User *CI = cast<User>(LI.getOperand(0));
161 Value *CastOp = CI->getOperand(0);
162
Chris Lattner229907c2011-07-18 04:54:35 +0000163 PointerType *DestTy = cast<PointerType>(CI->getType());
164 Type *DestPTy = DestTy->getElementType();
165 if (PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000166
167 // If the address spaces don't match, don't eliminate the cast.
168 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
169 return 0;
170
Chris Lattner229907c2011-07-18 04:54:35 +0000171 Type *SrcPTy = SrcTy->getElementType();
Chris Lattnera65e2f72010-01-05 05:57:49 +0000172
Duncan Sands19d0b472010-02-16 11:11:14 +0000173 if (DestPTy->isIntegerTy() || DestPTy->isPointerTy() ||
174 DestPTy->isVectorTy()) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000175 // If the source is an array, the code below will not succeed. Check to
176 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
177 // constants.
Chris Lattner229907c2011-07-18 04:54:35 +0000178 if (ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000179 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
180 if (ASrcTy->getNumElements() != 0) {
181 Value *Idxs[2];
182 Idxs[0] = Constant::getNullValue(Type::getInt32Ty(LI.getContext()));
183 Idxs[1] = Idxs[0];
Jay Foad71f19ac2011-07-22 07:54:01 +0000184 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000185 SrcTy = cast<PointerType>(CastOp->getType());
186 SrcPTy = SrcTy->getElementType();
187 }
188
189 if (IC.getTargetData() &&
Duncan Sands19d0b472010-02-16 11:11:14 +0000190 (SrcPTy->isIntegerTy() || SrcPTy->isPointerTy() ||
191 SrcPTy->isVectorTy()) &&
Chris Lattnera65e2f72010-01-05 05:57:49 +0000192 // Do not allow turning this into a load of an integer, which is then
193 // casted to a pointer, this pessimizes pointer analysis a lot.
Duncan Sands19d0b472010-02-16 11:11:14 +0000194 (SrcPTy->isPointerTy() == LI.getType()->isPointerTy()) &&
Chris Lattnera65e2f72010-01-05 05:57:49 +0000195 IC.getTargetData()->getTypeSizeInBits(SrcPTy) ==
196 IC.getTargetData()->getTypeSizeInBits(DestPTy)) {
197
198 // Okay, we are casting from one integer or pointer type to another of
199 // the same size. Instead of casting the pointer before the load, cast
200 // the result of the loaded value.
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000201 LoadInst *NewLoad =
Chris Lattnera65e2f72010-01-05 05:57:49 +0000202 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000203 NewLoad->setAlignment(LI.getAlignment());
Eli Friedman8bc586e2011-08-15 22:09:40 +0000204 NewLoad->setAtomic(LI.getOrdering(), LI.getSynchScope());
Chris Lattnera65e2f72010-01-05 05:57:49 +0000205 // Now cast the result of the load.
206 return new BitCastInst(NewLoad, LI.getType());
207 }
208 }
209 }
210 return 0;
211}
212
213Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
214 Value *Op = LI.getOperand(0);
215
216 // Attempt to improve the alignment.
217 if (TD) {
218 unsigned KnownAlign =
Chris Lattner6fcd32e2010-12-25 20:37:57 +0000219 getOrEnforceKnownAlignment(Op, TD->getPrefTypeAlignment(LI.getType()),TD);
Dan Gohman36196602010-08-03 18:20:32 +0000220 unsigned LoadAlign = LI.getAlignment();
221 unsigned EffectiveLoadAlign = LoadAlign != 0 ? LoadAlign :
222 TD->getABITypeAlignment(LI.getType());
223
224 if (KnownAlign > EffectiveLoadAlign)
Chris Lattnera65e2f72010-01-05 05:57:49 +0000225 LI.setAlignment(KnownAlign);
Dan Gohman36196602010-08-03 18:20:32 +0000226 else if (LoadAlign == 0)
227 LI.setAlignment(EffectiveLoadAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000228 }
229
230 // load (cast X) --> cast (load X) iff safe.
231 if (isa<CastInst>(Op))
232 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
233 return Res;
234
Eli Friedman8bc586e2011-08-15 22:09:40 +0000235 // None of the following transforms are legal for volatile/atomic loads.
236 // FIXME: Some of it is okay for atomic loads; needs refactoring.
237 if (!LI.isSimple()) return 0;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000238
239 // Do really simple store-to-load forwarding and load CSE, to catch cases
Duncan Sands75b5d272011-02-15 09:23:02 +0000240 // where there are several consecutive memory accesses to the same location,
Chris Lattnera65e2f72010-01-05 05:57:49 +0000241 // separated by a few arithmetic operations.
242 BasicBlock::iterator BBI = &LI;
243 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
244 return ReplaceInstUsesWith(LI, AvailableVal);
245
246 // load(gep null, ...) -> unreachable
247 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
248 const Value *GEPI0 = GEPI->getOperand(0);
249 // TODO: Consider a target hook for valid address spaces for this xform.
250 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
251 // Insert a new store to null instruction before the load to indicate
252 // that this code is not reachable. We do this instead of inserting
253 // an unreachable instruction directly because we cannot modify the
254 // CFG.
255 new StoreInst(UndefValue::get(LI.getType()),
256 Constant::getNullValue(Op->getType()), &LI);
257 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
258 }
259 }
260
261 // load null/undef -> unreachable
262 // TODO: Consider a target hook for valid address spaces for this xform.
263 if (isa<UndefValue>(Op) ||
264 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
265 // Insert a new store to null instruction before the load to indicate that
266 // this code is not reachable. We do this instead of inserting an
267 // unreachable instruction directly because we cannot modify the CFG.
268 new StoreInst(UndefValue::get(LI.getType()),
269 Constant::getNullValue(Op->getType()), &LI);
270 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
271 }
272
273 // Instcombine load (constantexpr_cast global) -> cast (load global)
274 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
275 if (CE->isCast())
276 if (Instruction *Res = InstCombineLoadCast(*this, LI, TD))
277 return Res;
278
279 if (Op->hasOneUse()) {
280 // Change select and PHI nodes to select values instead of addresses: this
281 // helps alias analysis out a lot, allows many others simplifications, and
282 // exposes redundancy in the code.
283 //
284 // Note that we cannot do the transformation unless we know that the
285 // introduced loads cannot trap! Something like this is valid as long as
286 // the condition is always false: load (select bool %C, int* null, int* %G),
287 // but it would not be valid if we transformed it to load from null
288 // unconditionally.
289 //
290 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
291 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Bob Wilson56600a12010-01-30 04:42:39 +0000292 unsigned Align = LI.getAlignment();
293 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI, Align, TD) &&
294 isSafeToLoadUnconditionally(SI->getOperand(2), SI, Align, TD)) {
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000295 LoadInst *V1 = Builder->CreateLoad(SI->getOperand(1),
Bob Wilson56600a12010-01-30 04:42:39 +0000296 SI->getOperand(1)->getName()+".val");
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000297 LoadInst *V2 = Builder->CreateLoad(SI->getOperand(2),
Bob Wilson56600a12010-01-30 04:42:39 +0000298 SI->getOperand(2)->getName()+".val");
299 V1->setAlignment(Align);
300 V2->setAlignment(Align);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000301 return SelectInst::Create(SI->getCondition(), V1, V2);
302 }
303
304 // load (select (cond, null, P)) -> load P
305 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
306 if (C->isNullValue()) {
307 LI.setOperand(0, SI->getOperand(2));
308 return &LI;
309 }
310
311 // load (select (cond, P, null)) -> load P
312 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
313 if (C->isNullValue()) {
314 LI.setOperand(0, SI->getOperand(1));
315 return &LI;
316 }
317 }
318 }
319 return 0;
320}
321
322/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
323/// when possible. This makes it generally easy to do alias analysis and/or
324/// SROA/mem2reg of the memory object.
325static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
326 User *CI = cast<User>(SI.getOperand(1));
327 Value *CastOp = CI->getOperand(0);
328
Chris Lattner229907c2011-07-18 04:54:35 +0000329 Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
330 PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
Chris Lattnera65e2f72010-01-05 05:57:49 +0000331 if (SrcTy == 0) return 0;
332
Chris Lattner229907c2011-07-18 04:54:35 +0000333 Type *SrcPTy = SrcTy->getElementType();
Chris Lattnera65e2f72010-01-05 05:57:49 +0000334
Duncan Sands19d0b472010-02-16 11:11:14 +0000335 if (!DestPTy->isIntegerTy() && !DestPTy->isPointerTy())
Chris Lattnera65e2f72010-01-05 05:57:49 +0000336 return 0;
337
338 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
339 /// to its first element. This allows us to handle things like:
340 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
341 /// on 32-bit hosts.
342 SmallVector<Value*, 4> NewGEPIndices;
343
344 // If the source is an array, the code below will not succeed. Check to
345 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
346 // constants.
Duncan Sands19d0b472010-02-16 11:11:14 +0000347 if (SrcPTy->isArrayTy() || SrcPTy->isStructTy()) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000348 // Index through pointer.
349 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(SI.getContext()));
350 NewGEPIndices.push_back(Zero);
351
352 while (1) {
Chris Lattner229907c2011-07-18 04:54:35 +0000353 if (StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000354 if (!STy->getNumElements()) /* Struct can be empty {} */
355 break;
356 NewGEPIndices.push_back(Zero);
357 SrcPTy = STy->getElementType(0);
Chris Lattner229907c2011-07-18 04:54:35 +0000358 } else if (ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000359 NewGEPIndices.push_back(Zero);
360 SrcPTy = ATy->getElementType();
361 } else {
362 break;
363 }
364 }
365
366 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
367 }
368
Duncan Sands19d0b472010-02-16 11:11:14 +0000369 if (!SrcPTy->isIntegerTy() && !SrcPTy->isPointerTy())
Chris Lattnera65e2f72010-01-05 05:57:49 +0000370 return 0;
371
372 // If the pointers point into different address spaces or if they point to
373 // values with different sizes, we can't do the transformation.
374 if (!IC.getTargetData() ||
375 SrcTy->getAddressSpace() !=
376 cast<PointerType>(CI->getType())->getAddressSpace() ||
377 IC.getTargetData()->getTypeSizeInBits(SrcPTy) !=
378 IC.getTargetData()->getTypeSizeInBits(DestPTy))
379 return 0;
380
381 // Okay, we are casting from one integer or pointer type to another of
382 // the same size. Instead of casting the pointer before
383 // the store, cast the value to be stored.
384 Value *NewCast;
385 Value *SIOp0 = SI.getOperand(0);
386 Instruction::CastOps opcode = Instruction::BitCast;
Chris Lattner229907c2011-07-18 04:54:35 +0000387 Type* CastSrcTy = SIOp0->getType();
388 Type* CastDstTy = SrcPTy;
Duncan Sands19d0b472010-02-16 11:11:14 +0000389 if (CastDstTy->isPointerTy()) {
Duncan Sands9dff9be2010-02-15 16:12:20 +0000390 if (CastSrcTy->isIntegerTy())
Chris Lattnera65e2f72010-01-05 05:57:49 +0000391 opcode = Instruction::IntToPtr;
Duncan Sands19d0b472010-02-16 11:11:14 +0000392 } else if (CastDstTy->isIntegerTy()) {
393 if (SIOp0->getType()->isPointerTy())
Chris Lattnera65e2f72010-01-05 05:57:49 +0000394 opcode = Instruction::PtrToInt;
395 }
396
397 // SIOp0 is a pointer to aggregate and this is a store to the first field,
398 // emit a GEP to index into its first field.
399 if (!NewGEPIndices.empty())
Jay Foad040dd822011-07-22 08:16:57 +0000400 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000401
402 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
403 SIOp0->getName()+".c");
Dan Gohman2e20dfb2010-10-25 16:16:27 +0000404 SI.setOperand(0, NewCast);
405 SI.setOperand(1, CastOp);
406 return &SI;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000407}
408
409/// equivalentAddressValues - Test if A and B will obviously have the same
410/// value. This includes recognizing that %t0 and %t1 will have the same
411/// value in code like this:
412/// %t0 = getelementptr \@a, 0, 3
413/// store i32 0, i32* %t0
414/// %t1 = getelementptr \@a, 0, 3
415/// %t2 = load i32* %t1
416///
417static bool equivalentAddressValues(Value *A, Value *B) {
418 // Test if the values are trivially equivalent.
419 if (A == B) return true;
420
421 // Test if the values come form identical arithmetic instructions.
422 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
423 // its only used to compare two uses within the same basic block, which
424 // means that they'll always either have the same value or one of them
425 // will have an undefined value.
426 if (isa<BinaryOperator>(A) ||
427 isa<CastInst>(A) ||
428 isa<PHINode>(A) ||
429 isa<GetElementPtrInst>(A))
430 if (Instruction *BI = dyn_cast<Instruction>(B))
431 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
432 return true;
433
434 // Otherwise they may not be equivalent.
435 return false;
436}
437
Chris Lattnera65e2f72010-01-05 05:57:49 +0000438Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
439 Value *Val = SI.getOperand(0);
440 Value *Ptr = SI.getOperand(1);
441
Chris Lattnera65e2f72010-01-05 05:57:49 +0000442 // Attempt to improve the alignment.
443 if (TD) {
444 unsigned KnownAlign =
Chris Lattner6fcd32e2010-12-25 20:37:57 +0000445 getOrEnforceKnownAlignment(Ptr, TD->getPrefTypeAlignment(Val->getType()),
446 TD);
Dan Gohman36196602010-08-03 18:20:32 +0000447 unsigned StoreAlign = SI.getAlignment();
448 unsigned EffectiveStoreAlign = StoreAlign != 0 ? StoreAlign :
449 TD->getABITypeAlignment(Val->getType());
450
Bill Wendling55b6b2b2012-03-16 18:20:54 +0000451 if (KnownAlign > EffectiveStoreAlign)
Chris Lattnera65e2f72010-01-05 05:57:49 +0000452 SI.setAlignment(KnownAlign);
Bill Wendling55b6b2b2012-03-16 18:20:54 +0000453 else if (StoreAlign == 0)
454 SI.setAlignment(EffectiveStoreAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000455 }
456
Eli Friedman8bc586e2011-08-15 22:09:40 +0000457 // Don't hack volatile/atomic stores.
458 // FIXME: Some bits are legal for atomic stores; needs refactoring.
459 if (!SI.isSimple()) return 0;
460
461 // If the RHS is an alloca with a single use, zapify the store, making the
462 // alloca dead.
463 if (Ptr->hasOneUse()) {
464 if (isa<AllocaInst>(Ptr))
465 return EraseInstFromFunction(SI);
466 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
467 if (isa<AllocaInst>(GEP->getOperand(0))) {
468 if (GEP->getOperand(0)->hasOneUse())
469 return EraseInstFromFunction(SI);
470 }
471 }
472 }
473
Chris Lattnera65e2f72010-01-05 05:57:49 +0000474 // Do really simple DSE, to catch cases where there are several consecutive
475 // stores to the same location, separated by a few arithmetic operations. This
476 // situation often occurs with bitfield accesses.
477 BasicBlock::iterator BBI = &SI;
478 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
479 --ScanInsts) {
480 --BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +0000481 // Don't count debug info directives, lest they affect codegen,
482 // and we skip pointer-to-pointer bitcasts, which are NOPs.
483 if (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000484 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000485 ScanInsts++;
486 continue;
487 }
488
489 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
490 // Prev store isn't volatile, and stores to the same location?
Eli Friedman8bc586e2011-08-15 22:09:40 +0000491 if (PrevSI->isSimple() && equivalentAddressValues(PrevSI->getOperand(1),
492 SI.getOperand(1))) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000493 ++NumDeadStore;
494 ++BBI;
495 EraseInstFromFunction(*PrevSI);
496 continue;
497 }
498 break;
499 }
500
501 // If this is a load, we have to stop. However, if the loaded value is from
502 // the pointer we're loading and is producing the pointer we're storing,
503 // then *this* store is dead (X = load P; store X -> P).
504 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Jin-Gu Kangb452db02011-03-14 01:21:00 +0000505 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
Eli Friedman8bc586e2011-08-15 22:09:40 +0000506 LI->isSimple())
Jin-Gu Kangb452db02011-03-14 01:21:00 +0000507 return EraseInstFromFunction(SI);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000508
509 // Otherwise, this is a load from some other location. Stores before it
510 // may not be dead.
511 break;
512 }
513
514 // Don't skip over loads or things that can modify memory.
515 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
516 break;
517 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000518
519 // store X, null -> turns into 'unreachable' in SimplifyCFG
520 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
521 if (!isa<UndefValue>(Val)) {
522 SI.setOperand(0, UndefValue::get(Val->getType()));
523 if (Instruction *U = dyn_cast<Instruction>(Val))
524 Worklist.Add(U); // Dropped a use.
525 }
526 return 0; // Do not modify these!
527 }
528
529 // store undef, Ptr -> noop
530 if (isa<UndefValue>(Val))
531 return EraseInstFromFunction(SI);
532
533 // If the pointer destination is a cast, see if we can fold the cast into the
534 // source instead.
535 if (isa<CastInst>(Ptr))
536 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
537 return Res;
538 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
539 if (CE->isCast())
540 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
541 return Res;
542
543
544 // If this store is the last instruction in the basic block (possibly
Victor Hernandez5f5abd52010-01-21 23:07:15 +0000545 // excepting debug info instructions), and if the block ends with an
546 // unconditional branch, try to move it to the successor block.
Chris Lattnera65e2f72010-01-05 05:57:49 +0000547 BBI = &SI;
548 do {
549 ++BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +0000550 } while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000551 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()));
Chris Lattnera65e2f72010-01-05 05:57:49 +0000552 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
553 if (BI->isUnconditional())
554 if (SimplifyStoreAtEndOfBlock(SI))
555 return 0; // xform done!
556
557 return 0;
558}
559
560/// SimplifyStoreAtEndOfBlock - Turn things like:
561/// if () { *P = v1; } else { *P = v2 }
562/// into a phi node with a store in the successor.
563///
564/// Simplify things like:
565/// *P = v1; if () { *P = v2; }
566/// into a phi node with a store in the successor.
567///
568bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
569 BasicBlock *StoreBB = SI.getParent();
570
571 // Check to see if the successor block has exactly two incoming edges. If
572 // so, see if the other predecessor contains a store to the same location.
573 // if so, insert a PHI node (if needed) and move the stores down.
574 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
575
576 // Determine whether Dest has exactly two predecessors and, if so, compute
577 // the other predecessor.
578 pred_iterator PI = pred_begin(DestBB);
Gabor Greif1b787df2010-07-12 15:48:26 +0000579 BasicBlock *P = *PI;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000580 BasicBlock *OtherBB = 0;
Gabor Greif1b787df2010-07-12 15:48:26 +0000581
582 if (P != StoreBB)
583 OtherBB = P;
584
585 if (++PI == pred_end(DestBB))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000586 return false;
587
Gabor Greif1b787df2010-07-12 15:48:26 +0000588 P = *PI;
589 if (P != StoreBB) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000590 if (OtherBB)
591 return false;
Gabor Greif1b787df2010-07-12 15:48:26 +0000592 OtherBB = P;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000593 }
594 if (++PI != pred_end(DestBB))
595 return false;
596
597 // Bail out if all the relevant blocks aren't distinct (this can happen,
598 // for example, if SI is in an infinite loop)
599 if (StoreBB == DestBB || OtherBB == DestBB)
600 return false;
601
602 // Verify that the other block ends in a branch and is not otherwise empty.
603 BasicBlock::iterator BBI = OtherBB->getTerminator();
604 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
605 if (!OtherBr || BBI == OtherBB->begin())
606 return false;
607
608 // If the other block ends in an unconditional branch, check for the 'if then
609 // else' case. there is an instruction before the branch.
610 StoreInst *OtherStore = 0;
611 if (OtherBr->isUnconditional()) {
612 --BBI;
613 // Skip over debugging info.
Victor Hernandez5f8c8c02010-01-22 19:05:05 +0000614 while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000615 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000616 if (BBI==OtherBB->begin())
617 return false;
618 --BBI;
619 }
Eli Friedman8bc586e2011-08-15 22:09:40 +0000620 // If this isn't a store, isn't a store to the same location, or is not the
621 // right kind of store, bail out.
Chris Lattnera65e2f72010-01-05 05:57:49 +0000622 OtherStore = dyn_cast<StoreInst>(BBI);
623 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +0000624 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000625 return false;
626 } else {
627 // Otherwise, the other block ended with a conditional branch. If one of the
628 // destinations is StoreBB, then we have the if/then case.
629 if (OtherBr->getSuccessor(0) != StoreBB &&
630 OtherBr->getSuccessor(1) != StoreBB)
631 return false;
632
633 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
634 // if/then triangle. See if there is a store to the same ptr as SI that
635 // lives in OtherBB.
636 for (;; --BBI) {
637 // Check to see if we find the matching store.
638 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
639 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +0000640 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000641 return false;
642 break;
643 }
644 // If we find something that may be using or overwriting the stored
645 // value, or if we run out of instructions, we can't do the xform.
646 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
647 BBI == OtherBB->begin())
648 return false;
649 }
650
651 // In order to eliminate the store in OtherBr, we have to
652 // make sure nothing reads or overwrites the stored value in
653 // StoreBB.
654 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
655 // FIXME: This should really be AA driven.
656 if (I->mayReadFromMemory() || I->mayWriteToMemory())
657 return false;
658 }
659 }
660
661 // Insert a PHI node now if we need it.
662 Value *MergedVal = OtherStore->getOperand(0);
663 if (MergedVal != SI.getOperand(0)) {
Jay Foad52131342011-03-30 11:28:46 +0000664 PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge");
Chris Lattnera65e2f72010-01-05 05:57:49 +0000665 PN->addIncoming(SI.getOperand(0), SI.getParent());
666 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
667 MergedVal = InsertNewInstBefore(PN, DestBB->front());
668 }
669
670 // Advance to a place where it is safe to insert the new store and
671 // insert it.
Bill Wendling8ddfc092011-08-16 20:45:24 +0000672 BBI = DestBB->getFirstInsertionPt();
Eli Friedman35211c62011-05-27 00:19:40 +0000673 StoreInst *NewSI = new StoreInst(MergedVal, SI.getOperand(1),
Eli Friedman8bc586e2011-08-15 22:09:40 +0000674 SI.isVolatile(),
675 SI.getAlignment(),
676 SI.getOrdering(),
677 SI.getSynchScope());
Eli Friedman35211c62011-05-27 00:19:40 +0000678 InsertNewInstBefore(NewSI, *BBI);
679 NewSI->setDebugLoc(OtherStore->getDebugLoc());
680
Chris Lattnera65e2f72010-01-05 05:57:49 +0000681 // Nuke the old stores.
682 EraseInstFromFunction(SI);
683 EraseInstFromFunction(*OtherStore);
684 return true;
685}