blob: f39e2ad72b0ffd2476f0ffdd3ea7d28874868bc0 [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
Chandler Carruth5f1f26e2014-04-21 19:51:41 +000014#define DEBUG_TYPE "instcombine"
Chris Lattnera65e2f72010-01-05 05:57:49 +000015#include "InstCombine.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000016#include "llvm/ADT/Statistic.h"
Dan Gohman826bdf82010-05-28 16:19:17 +000017#include "llvm/Analysis/Loads.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000018#include "llvm/IR/DataLayout.h"
19#include "llvm/IR/IntrinsicInst.h"
Chris Lattnera65e2f72010-01-05 05:57:49 +000020#include "llvm/Transforms/Utils/BasicBlockUtils.h"
21#include "llvm/Transforms/Utils/Local.h"
Chris Lattnera65e2f72010-01-05 05:57:49 +000022using namespace llvm;
23
Chandler Carruthc908ca12012-08-21 08:39:44 +000024STATISTIC(NumDeadStore, "Number of dead stores eliminated");
25STATISTIC(NumGlobalCopies, "Number of allocas copied from constant global");
26
27/// pointsToConstantGlobal - Return true if V (possibly indirectly) points to
28/// some part of a constant global variable. This intentionally only accepts
29/// constant expressions because we can't rewrite arbitrary instructions.
30static bool pointsToConstantGlobal(Value *V) {
31 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
32 return GV->isConstant();
33 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
34 if (CE->getOpcode() == Instruction::BitCast ||
35 CE->getOpcode() == Instruction::GetElementPtr)
36 return pointsToConstantGlobal(CE->getOperand(0));
37 return false;
38}
39
40/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
41/// pointer to an alloca. Ignore any reads of the pointer, return false if we
42/// see any stores or other unknown uses. If we see pointer arithmetic, keep
43/// track of whether it moves the pointer (with IsOffset) but otherwise traverse
44/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
45/// the alloca, and if the source pointer is a pointer to a constant global, we
46/// can optimize this.
47static bool
48isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
49 SmallVectorImpl<Instruction *> &ToDelete,
50 bool IsOffset = false) {
51 // We track lifetime intrinsics as we encounter them. If we decide to go
52 // ahead and replace the value with the global, this lets the caller quickly
53 // eliminate the markers.
54
Chandler Carruthcdf47882014-03-09 03:16:01 +000055 for (Use &U : V->uses()) {
56 Instruction *I = cast<Instruction>(U.getUser());
Chandler Carruthc908ca12012-08-21 08:39:44 +000057
Chandler Carruthcdf47882014-03-09 03:16:01 +000058 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthc908ca12012-08-21 08:39:44 +000059 // Ignore non-volatile loads, they are always ok.
60 if (!LI->isSimple()) return false;
61 continue;
62 }
63
Chandler Carruthcdf47882014-03-09 03:16:01 +000064 if (BitCastInst *BCI = dyn_cast<BitCastInst>(I)) {
Chandler Carruthc908ca12012-08-21 08:39:44 +000065 // If uses of the bitcast are ok, we are ok.
66 if (!isOnlyCopiedFromConstantGlobal(BCI, TheCopy, ToDelete, IsOffset))
67 return false;
68 continue;
69 }
Chandler Carruthcdf47882014-03-09 03:16:01 +000070 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
Chandler Carruthc908ca12012-08-21 08:39:44 +000071 // If the GEP has all zero indices, it doesn't offset the pointer. If it
72 // doesn't, it does.
Jim Grosbachbdbd7342013-04-05 21:20:12 +000073 if (!isOnlyCopiedFromConstantGlobal(
74 GEP, TheCopy, ToDelete, IsOffset || !GEP->hasAllZeroIndices()))
Chandler Carruthc908ca12012-08-21 08:39:44 +000075 return false;
76 continue;
77 }
78
Chandler Carruthcdf47882014-03-09 03:16:01 +000079 if (CallSite CS = I) {
Chandler Carruthc908ca12012-08-21 08:39:44 +000080 // If this is the function being called then we treat it like a load and
81 // ignore it.
Chandler Carruthcdf47882014-03-09 03:16:01 +000082 if (CS.isCallee(&U))
Chandler Carruthc908ca12012-08-21 08:39:44 +000083 continue;
84
Reid Kleckner26af2ca2014-01-28 02:38:36 +000085 // Inalloca arguments are clobbered by the call.
Chandler Carruthcdf47882014-03-09 03:16:01 +000086 unsigned ArgNo = CS.getArgumentNo(&U);
Reid Kleckner26af2ca2014-01-28 02:38:36 +000087 if (CS.isInAllocaArgument(ArgNo))
88 return false;
89
Chandler Carruthc908ca12012-08-21 08:39:44 +000090 // If this is a readonly/readnone call site, then we know it is just a
91 // load (but one that potentially returns the value itself), so we can
92 // ignore it if we know that the value isn't captured.
Chandler Carruthc908ca12012-08-21 08:39:44 +000093 if (CS.onlyReadsMemory() &&
94 (CS.getInstruction()->use_empty() || CS.doesNotCapture(ArgNo)))
95 continue;
96
97 // If this is being passed as a byval argument, the caller is making a
98 // copy, so it is only a read of the alloca.
99 if (CS.isByValArgument(ArgNo))
100 continue;
101 }
102
103 // Lifetime intrinsics can be handled by the caller.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000104 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
Chandler Carruthc908ca12012-08-21 08:39:44 +0000105 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
106 II->getIntrinsicID() == Intrinsic::lifetime_end) {
107 assert(II->use_empty() && "Lifetime markers have no result to use!");
108 ToDelete.push_back(II);
109 continue;
110 }
111 }
112
113 // If this is isn't our memcpy/memmove, reject it as something we can't
114 // handle.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000115 MemTransferInst *MI = dyn_cast<MemTransferInst>(I);
Chandler Carruthc908ca12012-08-21 08:39:44 +0000116 if (MI == 0)
117 return false;
118
119 // If the transfer is using the alloca as a source of the transfer, then
120 // ignore it since it is a load (unless the transfer is volatile).
Chandler Carruthcdf47882014-03-09 03:16:01 +0000121 if (U.getOperandNo() == 1) {
Chandler Carruthc908ca12012-08-21 08:39:44 +0000122 if (MI->isVolatile()) return false;
123 continue;
124 }
125
126 // If we already have seen a copy, reject the second one.
127 if (TheCopy) return false;
128
129 // If the pointer has been offset from the start of the alloca, we can't
130 // safely handle this.
131 if (IsOffset) return false;
132
133 // If the memintrinsic isn't using the alloca as the dest, reject it.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000134 if (U.getOperandNo() != 0) return false;
Chandler Carruthc908ca12012-08-21 08:39:44 +0000135
136 // If the source of the memcpy/move is not a constant global, reject it.
137 if (!pointsToConstantGlobal(MI->getSource()))
138 return false;
139
140 // Otherwise, the transform is safe. Remember the copy instruction.
141 TheCopy = MI;
142 }
143 return true;
144}
145
146/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
147/// modified by a copy from a constant global. If we can prove this, we can
148/// replace any uses of the alloca with uses of the global directly.
149static MemTransferInst *
150isOnlyCopiedFromConstantGlobal(AllocaInst *AI,
151 SmallVectorImpl<Instruction *> &ToDelete) {
152 MemTransferInst *TheCopy = 0;
153 if (isOnlyCopiedFromConstantGlobal(AI, TheCopy, ToDelete))
154 return TheCopy;
155 return 0;
156}
157
Chris Lattnera65e2f72010-01-05 05:57:49 +0000158Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
Dan Gohmandf5d7dc2010-05-28 15:09:00 +0000159 // Ensure that the alloca array size argument has type intptr_t, so that
160 // any casting is exposed early.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000161 if (DL) {
162 Type *IntPtrTy = DL->getIntPtrType(AI.getType());
Dan Gohmandf5d7dc2010-05-28 15:09:00 +0000163 if (AI.getArraySize()->getType() != IntPtrTy) {
164 Value *V = Builder->CreateIntCast(AI.getArraySize(),
165 IntPtrTy, false);
166 AI.setOperand(0, V);
167 return &AI;
168 }
169 }
170
Chris Lattnera65e2f72010-01-05 05:57:49 +0000171 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
172 if (AI.isArrayAllocation()) { // Check C != 1
173 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000174 Type *NewTy =
Chris Lattnera65e2f72010-01-05 05:57:49 +0000175 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Chris Lattnera65e2f72010-01-05 05:57:49 +0000176 AllocaInst *New = Builder->CreateAlloca(NewTy, 0, AI.getName());
177 New->setAlignment(AI.getAlignment());
178
179 // Scan to the end of the allocation instructions, to skip over a block of
180 // allocas if possible...also skip interleaved debug info
181 //
182 BasicBlock::iterator It = New;
183 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
184
185 // Now that I is pointing to the first non-allocation-inst in the block,
186 // insert our getelementptr instruction...
187 //
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000188 Type *IdxTy = DL
189 ? DL->getIntPtrType(AI.getType())
Matt Arsenault9e3a6ca2013-08-14 00:24:38 +0000190 : Type::getInt64Ty(AI.getContext());
191 Value *NullIdx = Constant::getNullValue(IdxTy);
Matt Arsenault640ff9d2013-08-14 00:24:05 +0000192 Value *Idx[2] = { NullIdx, NullIdx };
Eli Friedman41e509a2011-05-18 23:58:37 +0000193 Instruction *GEP =
Matt Arsenault640ff9d2013-08-14 00:24:05 +0000194 GetElementPtrInst::CreateInBounds(New, Idx, New->getName() + ".sub");
Eli Friedman41e509a2011-05-18 23:58:37 +0000195 InsertNewInstBefore(GEP, *It);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000196
197 // Now make everything use the getelementptr instead of the original
198 // allocation.
Eli Friedman41e509a2011-05-18 23:58:37 +0000199 return ReplaceInstUsesWith(AI, GEP);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000200 } else if (isa<UndefValue>(AI.getArraySize())) {
201 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
202 }
203 }
204
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000205 if (DL && AI.getAllocatedType()->isSized()) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000206 // If the alignment is 0 (unspecified), assign it the preferred alignment.
207 if (AI.getAlignment() == 0)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000208 AI.setAlignment(DL->getPrefTypeAlignment(AI.getAllocatedType()));
Duncan Sands8bc764a2012-06-26 13:39:21 +0000209
210 // Move all alloca's of zero byte objects to the entry block and merge them
211 // together. Note that we only do this for alloca's, because malloc should
212 // allocate and return a unique pointer, even for a zero byte allocation.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000213 if (DL->getTypeAllocSize(AI.getAllocatedType()) == 0) {
Duncan Sands8bc764a2012-06-26 13:39:21 +0000214 // For a zero sized alloca there is no point in doing an array allocation.
215 // This is helpful if the array size is a complicated expression not used
216 // elsewhere.
217 if (AI.isArrayAllocation()) {
218 AI.setOperand(0, ConstantInt::get(AI.getArraySize()->getType(), 1));
219 return &AI;
220 }
221
222 // Get the first instruction in the entry block.
223 BasicBlock &EntryBlock = AI.getParent()->getParent()->getEntryBlock();
224 Instruction *FirstInst = EntryBlock.getFirstNonPHIOrDbg();
225 if (FirstInst != &AI) {
226 // If the entry block doesn't start with a zero-size alloca then move
227 // this one to the start of the entry block. There is no problem with
228 // dominance as the array size was forced to a constant earlier already.
229 AllocaInst *EntryAI = dyn_cast<AllocaInst>(FirstInst);
230 if (!EntryAI || !EntryAI->getAllocatedType()->isSized() ||
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000231 DL->getTypeAllocSize(EntryAI->getAllocatedType()) != 0) {
Duncan Sands8bc764a2012-06-26 13:39:21 +0000232 AI.moveBefore(FirstInst);
233 return &AI;
234 }
235
Richard Osborneb68053e2012-09-18 09:31:44 +0000236 // If the alignment of the entry block alloca is 0 (unspecified),
237 // assign it the preferred alignment.
238 if (EntryAI->getAlignment() == 0)
239 EntryAI->setAlignment(
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000240 DL->getPrefTypeAlignment(EntryAI->getAllocatedType()));
Duncan Sands8bc764a2012-06-26 13:39:21 +0000241 // Replace this zero-sized alloca with the one at the start of the entry
242 // block after ensuring that the address will be aligned enough for both
243 // types.
Richard Osborneb68053e2012-09-18 09:31:44 +0000244 unsigned MaxAlign = std::max(EntryAI->getAlignment(),
245 AI.getAlignment());
Duncan Sands8bc764a2012-06-26 13:39:21 +0000246 EntryAI->setAlignment(MaxAlign);
247 if (AI.getType() != EntryAI->getType())
248 return new BitCastInst(EntryAI, AI.getType());
249 return ReplaceInstUsesWith(AI, EntryAI);
250 }
251 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000252 }
253
Eli Friedmanb14873c2012-11-26 23:04:53 +0000254 if (AI.getAlignment()) {
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000255 // Check to see if this allocation is only modified by a memcpy/memmove from
256 // a constant global whose alignment is equal to or exceeds that of the
257 // allocation. If this is the case, we can change all users to use
258 // the constant global instead. This is commonly produced by the CFE by
259 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
260 // is only subsequently read.
261 SmallVector<Instruction *, 4> ToDelete;
262 if (MemTransferInst *Copy = isOnlyCopiedFromConstantGlobal(&AI, ToDelete)) {
Eli Friedmanb14873c2012-11-26 23:04:53 +0000263 unsigned SourceAlign = getOrEnforceKnownAlignment(Copy->getSource(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000264 AI.getAlignment(), DL);
Eli Friedmanb14873c2012-11-26 23:04:53 +0000265 if (AI.getAlignment() <= SourceAlign) {
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000266 DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n');
267 DEBUG(dbgs() << " memcpy = " << *Copy << '\n');
268 for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
269 EraseInstFromFunction(*ToDelete[i]);
270 Constant *TheSrc = cast<Constant>(Copy->getSource());
Matt Arsenaultbbf18c62013-12-07 02:58:45 +0000271 Constant *Cast
272 = ConstantExpr::getPointerBitCastOrAddrSpaceCast(TheSrc, AI.getType());
273 Instruction *NewI = ReplaceInstUsesWith(AI, Cast);
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000274 EraseInstFromFunction(*Copy);
275 ++NumGlobalCopies;
276 return NewI;
277 }
Chandler Carruthc908ca12012-08-21 08:39:44 +0000278 }
279 }
280
Nuno Lopes95cc4f32012-07-09 18:38:20 +0000281 // At last, use the generic allocation site handler to aggressively remove
282 // unused allocas.
283 return visitAllocSite(AI);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000284}
285
286
287/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
288static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000289 const DataLayout *DL) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000290 User *CI = cast<User>(LI.getOperand(0));
291 Value *CastOp = CI->getOperand(0);
292
Chris Lattner229907c2011-07-18 04:54:35 +0000293 PointerType *DestTy = cast<PointerType>(CI->getType());
294 Type *DestPTy = DestTy->getElementType();
295 if (PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000296
297 // If the address spaces don't match, don't eliminate the cast.
298 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
299 return 0;
300
Chris Lattner229907c2011-07-18 04:54:35 +0000301 Type *SrcPTy = SrcTy->getElementType();
Chris Lattnera65e2f72010-01-05 05:57:49 +0000302
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000303 if (DestPTy->isIntegerTy() || DestPTy->isPointerTy() ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000304 DestPTy->isVectorTy()) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000305 // If the source is an array, the code below will not succeed. Check to
306 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
307 // constants.
Chris Lattner229907c2011-07-18 04:54:35 +0000308 if (ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000309 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
310 if (ASrcTy->getNumElements() != 0) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000311 Type *IdxTy = DL
312 ? DL->getIntPtrType(SrcTy)
Matt Arsenault3dfe54e2013-09-03 21:05:48 +0000313 : Type::getInt64Ty(SrcTy->getContext());
Matt Arsenault9e3a6ca2013-08-14 00:24:38 +0000314 Value *Idx = Constant::getNullValue(IdxTy);
315 Value *Idxs[2] = { Idx, Idx };
Jay Foad71f19ac2011-07-22 07:54:01 +0000316 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000317 SrcTy = cast<PointerType>(CastOp->getType());
318 SrcPTy = SrcTy->getElementType();
319 }
320
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000321 if (IC.getDataLayout() &&
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000322 (SrcPTy->isIntegerTy() || SrcPTy->isPointerTy() ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000323 SrcPTy->isVectorTy()) &&
Chris Lattnera65e2f72010-01-05 05:57:49 +0000324 // Do not allow turning this into a load of an integer, which is then
325 // casted to a pointer, this pessimizes pointer analysis a lot.
Benjamin Kramer0b37cdf2013-09-19 20:59:04 +0000326 (SrcPTy->isPtrOrPtrVectorTy() ==
327 LI.getType()->isPtrOrPtrVectorTy()) &&
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000328 IC.getDataLayout()->getTypeSizeInBits(SrcPTy) ==
329 IC.getDataLayout()->getTypeSizeInBits(DestPTy)) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000330
331 // Okay, we are casting from one integer or pointer type to another of
332 // the same size. Instead of casting the pointer before the load, cast
333 // the result of the loaded value.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000334 LoadInst *NewLoad =
Chris Lattnera65e2f72010-01-05 05:57:49 +0000335 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000336 NewLoad->setAlignment(LI.getAlignment());
Eli Friedman8bc586e2011-08-15 22:09:40 +0000337 NewLoad->setAtomic(LI.getOrdering(), LI.getSynchScope());
Chris Lattnera65e2f72010-01-05 05:57:49 +0000338 // Now cast the result of the load.
Owen Anderson9b8f9c32014-03-13 22:51:43 +0000339 PointerType *OldTy = dyn_cast<PointerType>(NewLoad->getType());
340 PointerType *NewTy = dyn_cast<PointerType>(LI.getType());
341 if (OldTy && NewTy &&
342 OldTy->getAddressSpace() != NewTy->getAddressSpace()) {
343 return new AddrSpaceCastInst(NewLoad, LI.getType());
344 }
345
Chris Lattnera65e2f72010-01-05 05:57:49 +0000346 return new BitCastInst(NewLoad, LI.getType());
347 }
348 }
349 }
350 return 0;
351}
352
353Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
354 Value *Op = LI.getOperand(0);
355
356 // Attempt to improve the alignment.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000357 if (DL) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000358 unsigned KnownAlign =
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000359 getOrEnforceKnownAlignment(Op, DL->getPrefTypeAlignment(LI.getType()),DL);
Dan Gohman36196602010-08-03 18:20:32 +0000360 unsigned LoadAlign = LI.getAlignment();
361 unsigned EffectiveLoadAlign = LoadAlign != 0 ? LoadAlign :
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000362 DL->getABITypeAlignment(LI.getType());
Dan Gohman36196602010-08-03 18:20:32 +0000363
364 if (KnownAlign > EffectiveLoadAlign)
Chris Lattnera65e2f72010-01-05 05:57:49 +0000365 LI.setAlignment(KnownAlign);
Dan Gohman36196602010-08-03 18:20:32 +0000366 else if (LoadAlign == 0)
367 LI.setAlignment(EffectiveLoadAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000368 }
369
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000370 // load (cast X) --> cast (load X) iff safe.
Chris Lattnera65e2f72010-01-05 05:57:49 +0000371 if (isa<CastInst>(Op))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000372 if (Instruction *Res = InstCombineLoadCast(*this, LI, DL))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000373 return Res;
374
Eli Friedman8bc586e2011-08-15 22:09:40 +0000375 // None of the following transforms are legal for volatile/atomic loads.
376 // FIXME: Some of it is okay for atomic loads; needs refactoring.
377 if (!LI.isSimple()) return 0;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000378
Chris Lattnera65e2f72010-01-05 05:57:49 +0000379 // Do really simple store-to-load forwarding and load CSE, to catch cases
Duncan Sands75b5d272011-02-15 09:23:02 +0000380 // where there are several consecutive memory accesses to the same location,
Chris Lattnera65e2f72010-01-05 05:57:49 +0000381 // separated by a few arithmetic operations.
382 BasicBlock::iterator BBI = &LI;
383 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
384 return ReplaceInstUsesWith(LI, AvailableVal);
385
386 // load(gep null, ...) -> unreachable
387 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
388 const Value *GEPI0 = GEPI->getOperand(0);
389 // TODO: Consider a target hook for valid address spaces for this xform.
390 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
391 // Insert a new store to null instruction before the load to indicate
392 // that this code is not reachable. We do this instead of inserting
393 // an unreachable instruction directly because we cannot modify the
394 // CFG.
395 new StoreInst(UndefValue::get(LI.getType()),
396 Constant::getNullValue(Op->getType()), &LI);
397 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
398 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000399 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000400
401 // load null/undef -> unreachable
402 // TODO: Consider a target hook for valid address spaces for this xform.
403 if (isa<UndefValue>(Op) ||
404 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
405 // Insert a new store to null instruction before the load to indicate that
406 // this code is not reachable. We do this instead of inserting an
407 // unreachable instruction directly because we cannot modify the CFG.
408 new StoreInst(UndefValue::get(LI.getType()),
409 Constant::getNullValue(Op->getType()), &LI);
410 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
411 }
412
413 // Instcombine load (constantexpr_cast global) -> cast (load global)
414 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
415 if (CE->isCast())
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000416 if (Instruction *Res = InstCombineLoadCast(*this, LI, DL))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000417 return Res;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000418
Chris Lattnera65e2f72010-01-05 05:57:49 +0000419 if (Op->hasOneUse()) {
420 // Change select and PHI nodes to select values instead of addresses: this
421 // helps alias analysis out a lot, allows many others simplifications, and
422 // exposes redundancy in the code.
423 //
424 // Note that we cannot do the transformation unless we know that the
425 // introduced loads cannot trap! Something like this is valid as long as
426 // the condition is always false: load (select bool %C, int* null, int* %G),
427 // but it would not be valid if we transformed it to load from null
428 // unconditionally.
429 //
430 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
431 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Bob Wilson56600a12010-01-30 04:42:39 +0000432 unsigned Align = LI.getAlignment();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000433 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI, Align, DL) &&
434 isSafeToLoadUnconditionally(SI->getOperand(2), SI, Align, DL)) {
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000435 LoadInst *V1 = Builder->CreateLoad(SI->getOperand(1),
Bob Wilson56600a12010-01-30 04:42:39 +0000436 SI->getOperand(1)->getName()+".val");
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000437 LoadInst *V2 = Builder->CreateLoad(SI->getOperand(2),
Bob Wilson56600a12010-01-30 04:42:39 +0000438 SI->getOperand(2)->getName()+".val");
439 V1->setAlignment(Align);
440 V2->setAlignment(Align);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000441 return SelectInst::Create(SI->getCondition(), V1, V2);
442 }
443
444 // load (select (cond, null, P)) -> load P
445 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
446 if (C->isNullValue()) {
447 LI.setOperand(0, SI->getOperand(2));
448 return &LI;
449 }
450
451 // load (select (cond, P, null)) -> load P
452 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
453 if (C->isNullValue()) {
454 LI.setOperand(0, SI->getOperand(1));
455 return &LI;
456 }
457 }
458 }
459 return 0;
460}
461
462/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
463/// when possible. This makes it generally easy to do alias analysis and/or
464/// SROA/mem2reg of the memory object.
465static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
466 User *CI = cast<User>(SI.getOperand(1));
467 Value *CastOp = CI->getOperand(0);
468
Chris Lattner229907c2011-07-18 04:54:35 +0000469 Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
470 PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
Chris Lattnera65e2f72010-01-05 05:57:49 +0000471 if (SrcTy == 0) return 0;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000472
Chris Lattner229907c2011-07-18 04:54:35 +0000473 Type *SrcPTy = SrcTy->getElementType();
Chris Lattnera65e2f72010-01-05 05:57:49 +0000474
Duncan Sands19d0b472010-02-16 11:11:14 +0000475 if (!DestPTy->isIntegerTy() && !DestPTy->isPointerTy())
Chris Lattnera65e2f72010-01-05 05:57:49 +0000476 return 0;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000477
Chris Lattnera65e2f72010-01-05 05:57:49 +0000478 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
479 /// to its first element. This allows us to handle things like:
480 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
481 /// on 32-bit hosts.
482 SmallVector<Value*, 4> NewGEPIndices;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000483
Chris Lattnera65e2f72010-01-05 05:57:49 +0000484 // If the source is an array, the code below will not succeed. Check to
485 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
486 // constants.
Duncan Sands19d0b472010-02-16 11:11:14 +0000487 if (SrcPTy->isArrayTy() || SrcPTy->isStructTy()) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000488 // Index through pointer.
489 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(SI.getContext()));
490 NewGEPIndices.push_back(Zero);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000491
Chris Lattnera65e2f72010-01-05 05:57:49 +0000492 while (1) {
Chris Lattner229907c2011-07-18 04:54:35 +0000493 if (StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000494 if (!STy->getNumElements()) /* Struct can be empty {} */
495 break;
496 NewGEPIndices.push_back(Zero);
497 SrcPTy = STy->getElementType(0);
Chris Lattner229907c2011-07-18 04:54:35 +0000498 } else if (ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000499 NewGEPIndices.push_back(Zero);
500 SrcPTy = ATy->getElementType();
501 } else {
502 break;
503 }
504 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000505
Chris Lattnera65e2f72010-01-05 05:57:49 +0000506 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
507 }
508
Duncan Sands19d0b472010-02-16 11:11:14 +0000509 if (!SrcPTy->isIntegerTy() && !SrcPTy->isPointerTy())
Chris Lattnera65e2f72010-01-05 05:57:49 +0000510 return 0;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000511
Richard Osborne0af4aa92014-03-25 17:21:41 +0000512 // If the pointers point into different address spaces don't do the
513 // transformation.
514 if (SrcTy->getAddressSpace() !=
515 cast<PointerType>(CI->getType())->getAddressSpace())
516 return 0;
517
518 // If the pointers point to values of different sizes don't do the
519 // transformation.
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000520 if (!IC.getDataLayout() ||
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000521 IC.getDataLayout()->getTypeSizeInBits(SrcPTy) !=
522 IC.getDataLayout()->getTypeSizeInBits(DestPTy))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000523 return 0;
524
Richard Osborne0af4aa92014-03-25 17:21:41 +0000525 // If the pointers point to pointers to different address spaces don't do the
526 // transformation. It is not safe to introduce an addrspacecast instruction in
527 // this case since, depending on the target, addrspacecast may not be a no-op
528 // cast.
529 if (SrcPTy->isPointerTy() && DestPTy->isPointerTy() &&
530 SrcPTy->getPointerAddressSpace() != DestPTy->getPointerAddressSpace())
531 return 0;
532
Chris Lattnera65e2f72010-01-05 05:57:49 +0000533 // Okay, we are casting from one integer or pointer type to another of
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000534 // the same size. Instead of casting the pointer before
Chris Lattnera65e2f72010-01-05 05:57:49 +0000535 // the store, cast the value to be stored.
536 Value *NewCast;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000537 Instruction::CastOps opcode = Instruction::BitCast;
Richard Osborne9805ec42014-03-25 17:21:35 +0000538 Type* CastSrcTy = DestPTy;
Chris Lattner229907c2011-07-18 04:54:35 +0000539 Type* CastDstTy = SrcPTy;
Duncan Sands19d0b472010-02-16 11:11:14 +0000540 if (CastDstTy->isPointerTy()) {
Duncan Sands9dff9be2010-02-15 16:12:20 +0000541 if (CastSrcTy->isIntegerTy())
Chris Lattnera65e2f72010-01-05 05:57:49 +0000542 opcode = Instruction::IntToPtr;
Duncan Sands19d0b472010-02-16 11:11:14 +0000543 } else if (CastDstTy->isIntegerTy()) {
Richard Osborne9805ec42014-03-25 17:21:35 +0000544 if (CastSrcTy->isPointerTy())
Chris Lattnera65e2f72010-01-05 05:57:49 +0000545 opcode = Instruction::PtrToInt;
546 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000547
Chris Lattnera65e2f72010-01-05 05:57:49 +0000548 // SIOp0 is a pointer to aggregate and this is a store to the first field,
549 // emit a GEP to index into its first field.
550 if (!NewGEPIndices.empty())
Jay Foad040dd822011-07-22 08:16:57 +0000551 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000552
Richard Osborne9805ec42014-03-25 17:21:35 +0000553 Value *SIOp0 = SI.getOperand(0);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000554 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
555 SIOp0->getName()+".c");
Dan Gohman2e20dfb2010-10-25 16:16:27 +0000556 SI.setOperand(0, NewCast);
557 SI.setOperand(1, CastOp);
558 return &SI;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000559}
560
561/// equivalentAddressValues - Test if A and B will obviously have the same
562/// value. This includes recognizing that %t0 and %t1 will have the same
563/// value in code like this:
564/// %t0 = getelementptr \@a, 0, 3
565/// store i32 0, i32* %t0
566/// %t1 = getelementptr \@a, 0, 3
567/// %t2 = load i32* %t1
568///
569static bool equivalentAddressValues(Value *A, Value *B) {
570 // Test if the values are trivially equivalent.
571 if (A == B) return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000572
Chris Lattnera65e2f72010-01-05 05:57:49 +0000573 // Test if the values come form identical arithmetic instructions.
574 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
575 // its only used to compare two uses within the same basic block, which
576 // means that they'll always either have the same value or one of them
577 // will have an undefined value.
578 if (isa<BinaryOperator>(A) ||
579 isa<CastInst>(A) ||
580 isa<PHINode>(A) ||
581 isa<GetElementPtrInst>(A))
582 if (Instruction *BI = dyn_cast<Instruction>(B))
583 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
584 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000585
Chris Lattnera65e2f72010-01-05 05:57:49 +0000586 // Otherwise they may not be equivalent.
587 return false;
588}
589
Chris Lattnera65e2f72010-01-05 05:57:49 +0000590Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
591 Value *Val = SI.getOperand(0);
592 Value *Ptr = SI.getOperand(1);
593
Chris Lattnera65e2f72010-01-05 05:57:49 +0000594 // Attempt to improve the alignment.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000595 if (DL) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000596 unsigned KnownAlign =
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000597 getOrEnforceKnownAlignment(Ptr, DL->getPrefTypeAlignment(Val->getType()),
598 DL);
Dan Gohman36196602010-08-03 18:20:32 +0000599 unsigned StoreAlign = SI.getAlignment();
600 unsigned EffectiveStoreAlign = StoreAlign != 0 ? StoreAlign :
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000601 DL->getABITypeAlignment(Val->getType());
Dan Gohman36196602010-08-03 18:20:32 +0000602
Bill Wendling55b6b2b2012-03-16 18:20:54 +0000603 if (KnownAlign > EffectiveStoreAlign)
Chris Lattnera65e2f72010-01-05 05:57:49 +0000604 SI.setAlignment(KnownAlign);
Bill Wendling55b6b2b2012-03-16 18:20:54 +0000605 else if (StoreAlign == 0)
606 SI.setAlignment(EffectiveStoreAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000607 }
608
Eli Friedman8bc586e2011-08-15 22:09:40 +0000609 // Don't hack volatile/atomic stores.
610 // FIXME: Some bits are legal for atomic stores; needs refactoring.
611 if (!SI.isSimple()) return 0;
612
613 // If the RHS is an alloca with a single use, zapify the store, making the
614 // alloca dead.
615 if (Ptr->hasOneUse()) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000616 if (isa<AllocaInst>(Ptr))
Eli Friedman8bc586e2011-08-15 22:09:40 +0000617 return EraseInstFromFunction(SI);
618 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
619 if (isa<AllocaInst>(GEP->getOperand(0))) {
620 if (GEP->getOperand(0)->hasOneUse())
621 return EraseInstFromFunction(SI);
622 }
623 }
624 }
625
Chris Lattnera65e2f72010-01-05 05:57:49 +0000626 // Do really simple DSE, to catch cases where there are several consecutive
627 // stores to the same location, separated by a few arithmetic operations. This
628 // situation often occurs with bitfield accesses.
629 BasicBlock::iterator BBI = &SI;
630 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
631 --ScanInsts) {
632 --BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +0000633 // Don't count debug info directives, lest they affect codegen,
634 // and we skip pointer-to-pointer bitcasts, which are NOPs.
635 if (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000636 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000637 ScanInsts++;
638 continue;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000639 }
640
Chris Lattnera65e2f72010-01-05 05:57:49 +0000641 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
642 // Prev store isn't volatile, and stores to the same location?
Eli Friedman8bc586e2011-08-15 22:09:40 +0000643 if (PrevSI->isSimple() && equivalentAddressValues(PrevSI->getOperand(1),
644 SI.getOperand(1))) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000645 ++NumDeadStore;
646 ++BBI;
647 EraseInstFromFunction(*PrevSI);
648 continue;
649 }
650 break;
651 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000652
Chris Lattnera65e2f72010-01-05 05:57:49 +0000653 // If this is a load, we have to stop. However, if the loaded value is from
654 // the pointer we're loading and is producing the pointer we're storing,
655 // then *this* store is dead (X = load P; store X -> P).
656 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Jin-Gu Kangb452db02011-03-14 01:21:00 +0000657 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
Eli Friedman8bc586e2011-08-15 22:09:40 +0000658 LI->isSimple())
Jin-Gu Kangb452db02011-03-14 01:21:00 +0000659 return EraseInstFromFunction(SI);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000660
Chris Lattnera65e2f72010-01-05 05:57:49 +0000661 // Otherwise, this is a load from some other location. Stores before it
662 // may not be dead.
663 break;
664 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000665
Chris Lattnera65e2f72010-01-05 05:57:49 +0000666 // Don't skip over loads or things that can modify memory.
667 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
668 break;
669 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000670
671 // store X, null -> turns into 'unreachable' in SimplifyCFG
672 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
673 if (!isa<UndefValue>(Val)) {
674 SI.setOperand(0, UndefValue::get(Val->getType()));
675 if (Instruction *U = dyn_cast<Instruction>(Val))
676 Worklist.Add(U); // Dropped a use.
677 }
678 return 0; // Do not modify these!
679 }
680
681 // store undef, Ptr -> noop
682 if (isa<UndefValue>(Val))
683 return EraseInstFromFunction(SI);
684
685 // If the pointer destination is a cast, see if we can fold the cast into the
686 // source instead.
687 if (isa<CastInst>(Ptr))
688 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
689 return Res;
690 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
691 if (CE->isCast())
692 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
693 return Res;
694
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000695
Chris Lattnera65e2f72010-01-05 05:57:49 +0000696 // If this store is the last instruction in the basic block (possibly
Victor Hernandez5f5abd52010-01-21 23:07:15 +0000697 // excepting debug info instructions), and if the block ends with an
698 // unconditional branch, try to move it to the successor block.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000699 BBI = &SI;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000700 do {
701 ++BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +0000702 } while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000703 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()));
Chris Lattnera65e2f72010-01-05 05:57:49 +0000704 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
705 if (BI->isUnconditional())
706 if (SimplifyStoreAtEndOfBlock(SI))
707 return 0; // xform done!
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000708
Chris Lattnera65e2f72010-01-05 05:57:49 +0000709 return 0;
710}
711
712/// SimplifyStoreAtEndOfBlock - Turn things like:
713/// if () { *P = v1; } else { *P = v2 }
714/// into a phi node with a store in the successor.
715///
716/// Simplify things like:
717/// *P = v1; if () { *P = v2; }
718/// into a phi node with a store in the successor.
719///
720bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
721 BasicBlock *StoreBB = SI.getParent();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000722
Chris Lattnera65e2f72010-01-05 05:57:49 +0000723 // Check to see if the successor block has exactly two incoming edges. If
724 // so, see if the other predecessor contains a store to the same location.
725 // if so, insert a PHI node (if needed) and move the stores down.
726 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000727
Chris Lattnera65e2f72010-01-05 05:57:49 +0000728 // Determine whether Dest has exactly two predecessors and, if so, compute
729 // the other predecessor.
730 pred_iterator PI = pred_begin(DestBB);
Gabor Greif1b787df2010-07-12 15:48:26 +0000731 BasicBlock *P = *PI;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000732 BasicBlock *OtherBB = 0;
Gabor Greif1b787df2010-07-12 15:48:26 +0000733
734 if (P != StoreBB)
735 OtherBB = P;
736
737 if (++PI == pred_end(DestBB))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000738 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000739
Gabor Greif1b787df2010-07-12 15:48:26 +0000740 P = *PI;
741 if (P != StoreBB) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000742 if (OtherBB)
743 return false;
Gabor Greif1b787df2010-07-12 15:48:26 +0000744 OtherBB = P;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000745 }
746 if (++PI != pred_end(DestBB))
747 return false;
748
749 // Bail out if all the relevant blocks aren't distinct (this can happen,
750 // for example, if SI is in an infinite loop)
751 if (StoreBB == DestBB || OtherBB == DestBB)
752 return false;
753
754 // Verify that the other block ends in a branch and is not otherwise empty.
755 BasicBlock::iterator BBI = OtherBB->getTerminator();
756 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
757 if (!OtherBr || BBI == OtherBB->begin())
758 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000759
Chris Lattnera65e2f72010-01-05 05:57:49 +0000760 // If the other block ends in an unconditional branch, check for the 'if then
761 // else' case. there is an instruction before the branch.
762 StoreInst *OtherStore = 0;
763 if (OtherBr->isUnconditional()) {
764 --BBI;
765 // Skip over debugging info.
Victor Hernandez5f8c8c02010-01-22 19:05:05 +0000766 while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000767 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000768 if (BBI==OtherBB->begin())
769 return false;
770 --BBI;
771 }
Eli Friedman8bc586e2011-08-15 22:09:40 +0000772 // If this isn't a store, isn't a store to the same location, or is not the
773 // right kind of store, bail out.
Chris Lattnera65e2f72010-01-05 05:57:49 +0000774 OtherStore = dyn_cast<StoreInst>(BBI);
775 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +0000776 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000777 return false;
778 } else {
779 // Otherwise, the other block ended with a conditional branch. If one of the
780 // destinations is StoreBB, then we have the if/then case.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000781 if (OtherBr->getSuccessor(0) != StoreBB &&
Chris Lattnera65e2f72010-01-05 05:57:49 +0000782 OtherBr->getSuccessor(1) != StoreBB)
783 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000784
Chris Lattnera65e2f72010-01-05 05:57:49 +0000785 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
786 // if/then triangle. See if there is a store to the same ptr as SI that
787 // lives in OtherBB.
788 for (;; --BBI) {
789 // Check to see if we find the matching store.
790 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
791 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +0000792 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000793 return false;
794 break;
795 }
796 // If we find something that may be using or overwriting the stored
797 // value, or if we run out of instructions, we can't do the xform.
798 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
799 BBI == OtherBB->begin())
800 return false;
801 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000802
Chris Lattnera65e2f72010-01-05 05:57:49 +0000803 // In order to eliminate the store in OtherBr, we have to
804 // make sure nothing reads or overwrites the stored value in
805 // StoreBB.
806 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
807 // FIXME: This should really be AA driven.
808 if (I->mayReadFromMemory() || I->mayWriteToMemory())
809 return false;
810 }
811 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000812
Chris Lattnera65e2f72010-01-05 05:57:49 +0000813 // Insert a PHI node now if we need it.
814 Value *MergedVal = OtherStore->getOperand(0);
815 if (MergedVal != SI.getOperand(0)) {
Jay Foad52131342011-03-30 11:28:46 +0000816 PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge");
Chris Lattnera65e2f72010-01-05 05:57:49 +0000817 PN->addIncoming(SI.getOperand(0), SI.getParent());
818 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
819 MergedVal = InsertNewInstBefore(PN, DestBB->front());
820 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000821
Chris Lattnera65e2f72010-01-05 05:57:49 +0000822 // Advance to a place where it is safe to insert the new store and
823 // insert it.
Bill Wendling8ddfc092011-08-16 20:45:24 +0000824 BBI = DestBB->getFirstInsertionPt();
Eli Friedman35211c62011-05-27 00:19:40 +0000825 StoreInst *NewSI = new StoreInst(MergedVal, SI.getOperand(1),
Eli Friedman8bc586e2011-08-15 22:09:40 +0000826 SI.isVolatile(),
827 SI.getAlignment(),
828 SI.getOrdering(),
829 SI.getSynchScope());
Eli Friedman35211c62011-05-27 00:19:40 +0000830 InsertNewInstBefore(NewSI, *BBI);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000831 NewSI->setDebugLoc(OtherStore->getDebugLoc());
Eli Friedman35211c62011-05-27 00:19:40 +0000832
Chris Lattnereeefe1b2012-12-31 08:10:58 +0000833 // If the two stores had the same TBAA tag, preserve it.
Chris Lattner473988c2013-01-05 16:44:07 +0000834 if (MDNode *TBAATag = SI.getMetadata(LLVMContext::MD_tbaa))
835 if ((TBAATag = MDNode::getMostGenericTBAA(TBAATag,
836 OtherStore->getMetadata(LLVMContext::MD_tbaa))))
837 NewSI->setMetadata(LLVMContext::MD_tbaa, TBAATag);
Chris Lattnereeefe1b2012-12-31 08:10:58 +0000838
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000839
Chris Lattnera65e2f72010-01-05 05:57:49 +0000840 // Nuke the old stores.
841 EraseInstFromFunction(SI);
842 EraseInstFromFunction(*OtherStore);
843 return true;
844}