blob: 66d09388f460be083e065ab2b5bdcac202d33204 [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"
Chandler Carruthed0881b2012-12-03 16:50:05 +000015#include "llvm/ADT/Statistic.h"
Dan Gohman826bdf82010-05-28 16:19:17 +000016#include "llvm/Analysis/Loads.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#include "llvm/IR/DataLayout.h"
18#include "llvm/IR/IntrinsicInst.h"
Chris Lattnera65e2f72010-01-05 05:57:49 +000019#include "llvm/Transforms/Utils/BasicBlockUtils.h"
20#include "llvm/Transforms/Utils/Local.h"
Chris Lattnera65e2f72010-01-05 05:57:49 +000021using namespace llvm;
22
Chandler Carruth964daaa2014-04-22 02:55:47 +000023#define DEBUG_TYPE "instcombine"
24
Chandler Carruthc908ca12012-08-21 08:39:44 +000025STATISTIC(NumDeadStore, "Number of dead stores eliminated");
26STATISTIC(NumGlobalCopies, "Number of allocas copied from constant global");
27
28/// pointsToConstantGlobal - Return true if V (possibly indirectly) points to
29/// some part of a constant global variable. This intentionally only accepts
30/// constant expressions because we can't rewrite arbitrary instructions.
31static bool pointsToConstantGlobal(Value *V) {
32 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
33 return GV->isConstant();
Matt Arsenault607281772014-04-24 00:01:09 +000034
35 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Chandler Carruthc908ca12012-08-21 08:39:44 +000036 if (CE->getOpcode() == Instruction::BitCast ||
Matt Arsenault607281772014-04-24 00:01:09 +000037 CE->getOpcode() == Instruction::AddrSpaceCast ||
Chandler Carruthc908ca12012-08-21 08:39:44 +000038 CE->getOpcode() == Instruction::GetElementPtr)
39 return pointsToConstantGlobal(CE->getOperand(0));
Matt Arsenault607281772014-04-24 00:01:09 +000040 }
Chandler Carruthc908ca12012-08-21 08:39:44 +000041 return false;
42}
43
44/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
45/// pointer to an alloca. Ignore any reads of the pointer, return false if we
46/// see any stores or other unknown uses. If we see pointer arithmetic, keep
47/// track of whether it moves the pointer (with IsOffset) but otherwise traverse
48/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
49/// the alloca, and if the source pointer is a pointer to a constant global, we
50/// can optimize this.
51static bool
52isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
53 SmallVectorImpl<Instruction *> &ToDelete,
54 bool IsOffset = false) {
55 // We track lifetime intrinsics as we encounter them. If we decide to go
56 // ahead and replace the value with the global, this lets the caller quickly
57 // eliminate the markers.
58
Chandler Carruthcdf47882014-03-09 03:16:01 +000059 for (Use &U : V->uses()) {
60 Instruction *I = cast<Instruction>(U.getUser());
Chandler Carruthc908ca12012-08-21 08:39:44 +000061
Chandler Carruthcdf47882014-03-09 03:16:01 +000062 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
Chandler Carruthc908ca12012-08-21 08:39:44 +000063 // Ignore non-volatile loads, they are always ok.
64 if (!LI->isSimple()) return false;
65 continue;
66 }
67
Matt Arsenault607281772014-04-24 00:01:09 +000068 if (isa<BitCastInst>(I) || isa<AddrSpaceCastInst>(I)) {
Chandler Carruthc908ca12012-08-21 08:39:44 +000069 // If uses of the bitcast are ok, we are ok.
Matt Arsenault607281772014-04-24 00:01:09 +000070 if (!isOnlyCopiedFromConstantGlobal(I, TheCopy, ToDelete, IsOffset))
Chandler Carruthc908ca12012-08-21 08:39:44 +000071 return false;
72 continue;
73 }
Chandler Carruthcdf47882014-03-09 03:16:01 +000074 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
Chandler Carruthc908ca12012-08-21 08:39:44 +000075 // If the GEP has all zero indices, it doesn't offset the pointer. If it
76 // doesn't, it does.
Jim Grosbachbdbd7342013-04-05 21:20:12 +000077 if (!isOnlyCopiedFromConstantGlobal(
78 GEP, TheCopy, ToDelete, IsOffset || !GEP->hasAllZeroIndices()))
Chandler Carruthc908ca12012-08-21 08:39:44 +000079 return false;
80 continue;
81 }
82
Chandler Carruthcdf47882014-03-09 03:16:01 +000083 if (CallSite CS = I) {
Chandler Carruthc908ca12012-08-21 08:39:44 +000084 // If this is the function being called then we treat it like a load and
85 // ignore it.
Chandler Carruthcdf47882014-03-09 03:16:01 +000086 if (CS.isCallee(&U))
Chandler Carruthc908ca12012-08-21 08:39:44 +000087 continue;
88
Reid Kleckner26af2ca2014-01-28 02:38:36 +000089 // Inalloca arguments are clobbered by the call.
Chandler Carruthcdf47882014-03-09 03:16:01 +000090 unsigned ArgNo = CS.getArgumentNo(&U);
Reid Kleckner26af2ca2014-01-28 02:38:36 +000091 if (CS.isInAllocaArgument(ArgNo))
92 return false;
93
Chandler Carruthc908ca12012-08-21 08:39:44 +000094 // If this is a readonly/readnone call site, then we know it is just a
95 // load (but one that potentially returns the value itself), so we can
96 // ignore it if we know that the value isn't captured.
Chandler Carruthc908ca12012-08-21 08:39:44 +000097 if (CS.onlyReadsMemory() &&
98 (CS.getInstruction()->use_empty() || CS.doesNotCapture(ArgNo)))
99 continue;
100
101 // If this is being passed as a byval argument, the caller is making a
102 // copy, so it is only a read of the alloca.
103 if (CS.isByValArgument(ArgNo))
104 continue;
105 }
106
107 // Lifetime intrinsics can be handled by the caller.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000108 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
Chandler Carruthc908ca12012-08-21 08:39:44 +0000109 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
110 II->getIntrinsicID() == Intrinsic::lifetime_end) {
111 assert(II->use_empty() && "Lifetime markers have no result to use!");
112 ToDelete.push_back(II);
113 continue;
114 }
115 }
116
117 // If this is isn't our memcpy/memmove, reject it as something we can't
118 // handle.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000119 MemTransferInst *MI = dyn_cast<MemTransferInst>(I);
Craig Topperf40110f2014-04-25 05:29:35 +0000120 if (!MI)
Chandler Carruthc908ca12012-08-21 08:39:44 +0000121 return false;
122
123 // If the transfer is using the alloca as a source of the transfer, then
124 // ignore it since it is a load (unless the transfer is volatile).
Chandler Carruthcdf47882014-03-09 03:16:01 +0000125 if (U.getOperandNo() == 1) {
Chandler Carruthc908ca12012-08-21 08:39:44 +0000126 if (MI->isVolatile()) return false;
127 continue;
128 }
129
130 // If we already have seen a copy, reject the second one.
131 if (TheCopy) return false;
132
133 // If the pointer has been offset from the start of the alloca, we can't
134 // safely handle this.
135 if (IsOffset) return false;
136
137 // If the memintrinsic isn't using the alloca as the dest, reject it.
Chandler Carruthcdf47882014-03-09 03:16:01 +0000138 if (U.getOperandNo() != 0) return false;
Chandler Carruthc908ca12012-08-21 08:39:44 +0000139
140 // If the source of the memcpy/move is not a constant global, reject it.
141 if (!pointsToConstantGlobal(MI->getSource()))
142 return false;
143
144 // Otherwise, the transform is safe. Remember the copy instruction.
145 TheCopy = MI;
146 }
147 return true;
148}
149
150/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
151/// modified by a copy from a constant global. If we can prove this, we can
152/// replace any uses of the alloca with uses of the global directly.
153static MemTransferInst *
154isOnlyCopiedFromConstantGlobal(AllocaInst *AI,
155 SmallVectorImpl<Instruction *> &ToDelete) {
Craig Topperf40110f2014-04-25 05:29:35 +0000156 MemTransferInst *TheCopy = nullptr;
Chandler Carruthc908ca12012-08-21 08:39:44 +0000157 if (isOnlyCopiedFromConstantGlobal(AI, TheCopy, ToDelete))
158 return TheCopy;
Craig Topperf40110f2014-04-25 05:29:35 +0000159 return nullptr;
Chandler Carruthc908ca12012-08-21 08:39:44 +0000160}
161
Chris Lattnera65e2f72010-01-05 05:57:49 +0000162Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
Dan Gohmandf5d7dc2010-05-28 15:09:00 +0000163 // Ensure that the alloca array size argument has type intptr_t, so that
164 // any casting is exposed early.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000165 if (DL) {
166 Type *IntPtrTy = DL->getIntPtrType(AI.getType());
Dan Gohmandf5d7dc2010-05-28 15:09:00 +0000167 if (AI.getArraySize()->getType() != IntPtrTy) {
168 Value *V = Builder->CreateIntCast(AI.getArraySize(),
169 IntPtrTy, false);
170 AI.setOperand(0, V);
171 return &AI;
172 }
173 }
174
Chris Lattnera65e2f72010-01-05 05:57:49 +0000175 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
176 if (AI.isArrayAllocation()) { // Check C != 1
177 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000178 Type *NewTy =
Chris Lattnera65e2f72010-01-05 05:57:49 +0000179 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Craig Topperf40110f2014-04-25 05:29:35 +0000180 AllocaInst *New = Builder->CreateAlloca(NewTy, nullptr, AI.getName());
Chris Lattnera65e2f72010-01-05 05:57:49 +0000181 New->setAlignment(AI.getAlignment());
182
183 // Scan to the end of the allocation instructions, to skip over a block of
184 // allocas if possible...also skip interleaved debug info
185 //
186 BasicBlock::iterator It = New;
187 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
188
189 // Now that I is pointing to the first non-allocation-inst in the block,
190 // insert our getelementptr instruction...
191 //
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000192 Type *IdxTy = DL
193 ? DL->getIntPtrType(AI.getType())
Matt Arsenault9e3a6ca2013-08-14 00:24:38 +0000194 : Type::getInt64Ty(AI.getContext());
195 Value *NullIdx = Constant::getNullValue(IdxTy);
Matt Arsenault640ff9d2013-08-14 00:24:05 +0000196 Value *Idx[2] = { NullIdx, NullIdx };
Eli Friedman41e509a2011-05-18 23:58:37 +0000197 Instruction *GEP =
Matt Arsenault640ff9d2013-08-14 00:24:05 +0000198 GetElementPtrInst::CreateInBounds(New, Idx, New->getName() + ".sub");
Eli Friedman41e509a2011-05-18 23:58:37 +0000199 InsertNewInstBefore(GEP, *It);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000200
201 // Now make everything use the getelementptr instead of the original
202 // allocation.
Eli Friedman41e509a2011-05-18 23:58:37 +0000203 return ReplaceInstUsesWith(AI, GEP);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000204 } else if (isa<UndefValue>(AI.getArraySize())) {
205 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
206 }
207 }
208
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000209 if (DL && AI.getAllocatedType()->isSized()) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000210 // If the alignment is 0 (unspecified), assign it the preferred alignment.
211 if (AI.getAlignment() == 0)
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000212 AI.setAlignment(DL->getPrefTypeAlignment(AI.getAllocatedType()));
Duncan Sands8bc764a2012-06-26 13:39:21 +0000213
214 // Move all alloca's of zero byte objects to the entry block and merge them
215 // together. Note that we only do this for alloca's, because malloc should
216 // allocate and return a unique pointer, even for a zero byte allocation.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000217 if (DL->getTypeAllocSize(AI.getAllocatedType()) == 0) {
Duncan Sands8bc764a2012-06-26 13:39:21 +0000218 // For a zero sized alloca there is no point in doing an array allocation.
219 // This is helpful if the array size is a complicated expression not used
220 // elsewhere.
221 if (AI.isArrayAllocation()) {
222 AI.setOperand(0, ConstantInt::get(AI.getArraySize()->getType(), 1));
223 return &AI;
224 }
225
226 // Get the first instruction in the entry block.
227 BasicBlock &EntryBlock = AI.getParent()->getParent()->getEntryBlock();
228 Instruction *FirstInst = EntryBlock.getFirstNonPHIOrDbg();
229 if (FirstInst != &AI) {
230 // If the entry block doesn't start with a zero-size alloca then move
231 // this one to the start of the entry block. There is no problem with
232 // dominance as the array size was forced to a constant earlier already.
233 AllocaInst *EntryAI = dyn_cast<AllocaInst>(FirstInst);
234 if (!EntryAI || !EntryAI->getAllocatedType()->isSized() ||
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000235 DL->getTypeAllocSize(EntryAI->getAllocatedType()) != 0) {
Duncan Sands8bc764a2012-06-26 13:39:21 +0000236 AI.moveBefore(FirstInst);
237 return &AI;
238 }
239
Richard Osborneb68053e2012-09-18 09:31:44 +0000240 // If the alignment of the entry block alloca is 0 (unspecified),
241 // assign it the preferred alignment.
242 if (EntryAI->getAlignment() == 0)
243 EntryAI->setAlignment(
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000244 DL->getPrefTypeAlignment(EntryAI->getAllocatedType()));
Duncan Sands8bc764a2012-06-26 13:39:21 +0000245 // Replace this zero-sized alloca with the one at the start of the entry
246 // block after ensuring that the address will be aligned enough for both
247 // types.
Richard Osborneb68053e2012-09-18 09:31:44 +0000248 unsigned MaxAlign = std::max(EntryAI->getAlignment(),
249 AI.getAlignment());
Duncan Sands8bc764a2012-06-26 13:39:21 +0000250 EntryAI->setAlignment(MaxAlign);
251 if (AI.getType() != EntryAI->getType())
252 return new BitCastInst(EntryAI, AI.getType());
253 return ReplaceInstUsesWith(AI, EntryAI);
254 }
255 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000256 }
257
Eli Friedmanb14873c2012-11-26 23:04:53 +0000258 if (AI.getAlignment()) {
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000259 // Check to see if this allocation is only modified by a memcpy/memmove from
260 // a constant global whose alignment is equal to or exceeds that of the
261 // allocation. If this is the case, we can change all users to use
262 // the constant global instead. This is commonly produced by the CFE by
263 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
264 // is only subsequently read.
265 SmallVector<Instruction *, 4> ToDelete;
266 if (MemTransferInst *Copy = isOnlyCopiedFromConstantGlobal(&AI, ToDelete)) {
Eli Friedmanb14873c2012-11-26 23:04:53 +0000267 unsigned SourceAlign = getOrEnforceKnownAlignment(Copy->getSource(),
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000268 AI.getAlignment(), DL);
Eli Friedmanb14873c2012-11-26 23:04:53 +0000269 if (AI.getAlignment() <= SourceAlign) {
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000270 DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n');
271 DEBUG(dbgs() << " memcpy = " << *Copy << '\n');
272 for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
273 EraseInstFromFunction(*ToDelete[i]);
274 Constant *TheSrc = cast<Constant>(Copy->getSource());
Matt Arsenaultbbf18c62013-12-07 02:58:45 +0000275 Constant *Cast
276 = ConstantExpr::getPointerBitCastOrAddrSpaceCast(TheSrc, AI.getType());
277 Instruction *NewI = ReplaceInstUsesWith(AI, Cast);
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000278 EraseInstFromFunction(*Copy);
279 ++NumGlobalCopies;
280 return NewI;
281 }
Chandler Carruthc908ca12012-08-21 08:39:44 +0000282 }
283 }
284
Nuno Lopes95cc4f32012-07-09 18:38:20 +0000285 // At last, use the generic allocation site handler to aggressively remove
286 // unused allocas.
287 return visitAllocSite(AI);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000288}
289
290
291/// InstCombineLoadCast - Fold 'load (cast P)' -> cast (load P)' when possible.
292static Instruction *InstCombineLoadCast(InstCombiner &IC, LoadInst &LI,
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000293 const DataLayout *DL) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000294 User *CI = cast<User>(LI.getOperand(0));
295 Value *CastOp = CI->getOperand(0);
296
Chris Lattner229907c2011-07-18 04:54:35 +0000297 PointerType *DestTy = cast<PointerType>(CI->getType());
298 Type *DestPTy = DestTy->getElementType();
299 if (PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000300
301 // If the address spaces don't match, don't eliminate the cast.
302 if (DestTy->getAddressSpace() != SrcTy->getAddressSpace())
Craig Topperf40110f2014-04-25 05:29:35 +0000303 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000304
Chris Lattner229907c2011-07-18 04:54:35 +0000305 Type *SrcPTy = SrcTy->getElementType();
Chris Lattnera65e2f72010-01-05 05:57:49 +0000306
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000307 if (DestPTy->isIntegerTy() || DestPTy->isPointerTy() ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000308 DestPTy->isVectorTy()) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000309 // If the source is an array, the code below will not succeed. Check to
310 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
311 // constants.
Chris Lattner229907c2011-07-18 04:54:35 +0000312 if (ArrayType *ASrcTy = dyn_cast<ArrayType>(SrcPTy))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000313 if (Constant *CSrc = dyn_cast<Constant>(CastOp))
314 if (ASrcTy->getNumElements() != 0) {
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000315 Type *IdxTy = DL
316 ? DL->getIntPtrType(SrcTy)
Matt Arsenault3dfe54e2013-09-03 21:05:48 +0000317 : Type::getInt64Ty(SrcTy->getContext());
Matt Arsenault9e3a6ca2013-08-14 00:24:38 +0000318 Value *Idx = Constant::getNullValue(IdxTy);
319 Value *Idxs[2] = { Idx, Idx };
Jay Foad71f19ac2011-07-22 07:54:01 +0000320 CastOp = ConstantExpr::getGetElementPtr(CSrc, Idxs);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000321 SrcTy = cast<PointerType>(CastOp->getType());
322 SrcPTy = SrcTy->getElementType();
323 }
324
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000325 if (IC.getDataLayout() &&
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000326 (SrcPTy->isIntegerTy() || SrcPTy->isPointerTy() ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000327 SrcPTy->isVectorTy()) &&
Chris Lattnera65e2f72010-01-05 05:57:49 +0000328 // Do not allow turning this into a load of an integer, which is then
329 // casted to a pointer, this pessimizes pointer analysis a lot.
Benjamin Kramer0b37cdf2013-09-19 20:59:04 +0000330 (SrcPTy->isPtrOrPtrVectorTy() ==
331 LI.getType()->isPtrOrPtrVectorTy()) &&
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000332 IC.getDataLayout()->getTypeSizeInBits(SrcPTy) ==
333 IC.getDataLayout()->getTypeSizeInBits(DestPTy)) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000334
335 // Okay, we are casting from one integer or pointer type to another of
336 // the same size. Instead of casting the pointer before the load, cast
337 // the result of the loaded value.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000338 LoadInst *NewLoad =
Chris Lattnera65e2f72010-01-05 05:57:49 +0000339 IC.Builder->CreateLoad(CastOp, LI.isVolatile(), CI->getName());
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000340 NewLoad->setAlignment(LI.getAlignment());
Eli Friedman8bc586e2011-08-15 22:09:40 +0000341 NewLoad->setAtomic(LI.getOrdering(), LI.getSynchScope());
Chris Lattnera65e2f72010-01-05 05:57:49 +0000342 // Now cast the result of the load.
Owen Anderson9b8f9c32014-03-13 22:51:43 +0000343 PointerType *OldTy = dyn_cast<PointerType>(NewLoad->getType());
344 PointerType *NewTy = dyn_cast<PointerType>(LI.getType());
345 if (OldTy && NewTy &&
346 OldTy->getAddressSpace() != NewTy->getAddressSpace()) {
347 return new AddrSpaceCastInst(NewLoad, LI.getType());
348 }
349
Chris Lattnera65e2f72010-01-05 05:57:49 +0000350 return new BitCastInst(NewLoad, LI.getType());
351 }
352 }
353 }
Craig Topperf40110f2014-04-25 05:29:35 +0000354 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000355}
356
357Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
358 Value *Op = LI.getOperand(0);
359
360 // Attempt to improve the alignment.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000361 if (DL) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000362 unsigned KnownAlign =
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000363 getOrEnforceKnownAlignment(Op, DL->getPrefTypeAlignment(LI.getType()),DL);
Dan Gohman36196602010-08-03 18:20:32 +0000364 unsigned LoadAlign = LI.getAlignment();
365 unsigned EffectiveLoadAlign = LoadAlign != 0 ? LoadAlign :
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000366 DL->getABITypeAlignment(LI.getType());
Dan Gohman36196602010-08-03 18:20:32 +0000367
368 if (KnownAlign > EffectiveLoadAlign)
Chris Lattnera65e2f72010-01-05 05:57:49 +0000369 LI.setAlignment(KnownAlign);
Dan Gohman36196602010-08-03 18:20:32 +0000370 else if (LoadAlign == 0)
371 LI.setAlignment(EffectiveLoadAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000372 }
373
Sylvestre Ledru91ce36c2012-09-27 10:14:43 +0000374 // load (cast X) --> cast (load X) iff safe.
Chris Lattnera65e2f72010-01-05 05:57:49 +0000375 if (isa<CastInst>(Op))
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000376 if (Instruction *Res = InstCombineLoadCast(*this, LI, DL))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000377 return Res;
378
Eli Friedman8bc586e2011-08-15 22:09:40 +0000379 // None of the following transforms are legal for volatile/atomic loads.
380 // FIXME: Some of it is okay for atomic loads; needs refactoring.
Craig Topperf40110f2014-04-25 05:29:35 +0000381 if (!LI.isSimple()) return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000382
Chris Lattnera65e2f72010-01-05 05:57:49 +0000383 // Do really simple store-to-load forwarding and load CSE, to catch cases
Duncan Sands75b5d272011-02-15 09:23:02 +0000384 // where there are several consecutive memory accesses to the same location,
Chris Lattnera65e2f72010-01-05 05:57:49 +0000385 // separated by a few arithmetic operations.
386 BasicBlock::iterator BBI = &LI;
387 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
388 return ReplaceInstUsesWith(LI, AvailableVal);
389
390 // load(gep null, ...) -> unreachable
391 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
392 const Value *GEPI0 = GEPI->getOperand(0);
393 // TODO: Consider a target hook for valid address spaces for this xform.
394 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
395 // Insert a new store to null instruction before the load to indicate
396 // that this code is not reachable. We do this instead of inserting
397 // an unreachable instruction directly because we cannot modify the
398 // CFG.
399 new StoreInst(UndefValue::get(LI.getType()),
400 Constant::getNullValue(Op->getType()), &LI);
401 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
402 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000403 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000404
405 // load null/undef -> unreachable
406 // TODO: Consider a target hook for valid address spaces for this xform.
407 if (isa<UndefValue>(Op) ||
408 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
409 // Insert a new store to null instruction before the load to indicate that
410 // this code is not reachable. We do this instead of inserting an
411 // unreachable instruction directly because we cannot modify the CFG.
412 new StoreInst(UndefValue::get(LI.getType()),
413 Constant::getNullValue(Op->getType()), &LI);
414 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
415 }
416
417 // Instcombine load (constantexpr_cast global) -> cast (load global)
418 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Op))
419 if (CE->isCast())
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000420 if (Instruction *Res = InstCombineLoadCast(*this, LI, DL))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000421 return Res;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000422
Chris Lattnera65e2f72010-01-05 05:57:49 +0000423 if (Op->hasOneUse()) {
424 // Change select and PHI nodes to select values instead of addresses: this
425 // helps alias analysis out a lot, allows many others simplifications, and
426 // exposes redundancy in the code.
427 //
428 // Note that we cannot do the transformation unless we know that the
429 // introduced loads cannot trap! Something like this is valid as long as
430 // the condition is always false: load (select bool %C, int* null, int* %G),
431 // but it would not be valid if we transformed it to load from null
432 // unconditionally.
433 //
434 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
435 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Bob Wilson56600a12010-01-30 04:42:39 +0000436 unsigned Align = LI.getAlignment();
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000437 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI, Align, DL) &&
438 isSafeToLoadUnconditionally(SI->getOperand(2), SI, Align, DL)) {
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000439 LoadInst *V1 = Builder->CreateLoad(SI->getOperand(1),
Bob Wilson56600a12010-01-30 04:42:39 +0000440 SI->getOperand(1)->getName()+".val");
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000441 LoadInst *V2 = Builder->CreateLoad(SI->getOperand(2),
Bob Wilson56600a12010-01-30 04:42:39 +0000442 SI->getOperand(2)->getName()+".val");
443 V1->setAlignment(Align);
444 V2->setAlignment(Align);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000445 return SelectInst::Create(SI->getCondition(), V1, V2);
446 }
447
448 // load (select (cond, null, P)) -> load P
449 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
450 if (C->isNullValue()) {
451 LI.setOperand(0, SI->getOperand(2));
452 return &LI;
453 }
454
455 // load (select (cond, P, null)) -> load P
456 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
457 if (C->isNullValue()) {
458 LI.setOperand(0, SI->getOperand(1));
459 return &LI;
460 }
461 }
462 }
Craig Topperf40110f2014-04-25 05:29:35 +0000463 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000464}
465
466/// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
467/// when possible. This makes it generally easy to do alias analysis and/or
468/// SROA/mem2reg of the memory object.
469static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
470 User *CI = cast<User>(SI.getOperand(1));
471 Value *CastOp = CI->getOperand(0);
472
Chris Lattner229907c2011-07-18 04:54:35 +0000473 Type *DestPTy = cast<PointerType>(CI->getType())->getElementType();
474 PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
Craig Topperf40110f2014-04-25 05:29:35 +0000475 if (!SrcTy) return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000476
Chris Lattner229907c2011-07-18 04:54:35 +0000477 Type *SrcPTy = SrcTy->getElementType();
Chris Lattnera65e2f72010-01-05 05:57:49 +0000478
Duncan Sands19d0b472010-02-16 11:11:14 +0000479 if (!DestPTy->isIntegerTy() && !DestPTy->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000480 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000481
Chris Lattnera65e2f72010-01-05 05:57:49 +0000482 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
483 /// to its first element. This allows us to handle things like:
484 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
485 /// on 32-bit hosts.
486 SmallVector<Value*, 4> NewGEPIndices;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000487
Chris Lattnera65e2f72010-01-05 05:57:49 +0000488 // If the source is an array, the code below will not succeed. Check to
489 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
490 // constants.
Duncan Sands19d0b472010-02-16 11:11:14 +0000491 if (SrcPTy->isArrayTy() || SrcPTy->isStructTy()) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000492 // Index through pointer.
493 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(SI.getContext()));
494 NewGEPIndices.push_back(Zero);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000495
Chris Lattnera65e2f72010-01-05 05:57:49 +0000496 while (1) {
Chris Lattner229907c2011-07-18 04:54:35 +0000497 if (StructType *STy = dyn_cast<StructType>(SrcPTy)) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000498 if (!STy->getNumElements()) /* Struct can be empty {} */
499 break;
500 NewGEPIndices.push_back(Zero);
501 SrcPTy = STy->getElementType(0);
Chris Lattner229907c2011-07-18 04:54:35 +0000502 } else if (ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000503 NewGEPIndices.push_back(Zero);
504 SrcPTy = ATy->getElementType();
505 } else {
506 break;
507 }
508 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000509
Chris Lattnera65e2f72010-01-05 05:57:49 +0000510 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
511 }
512
Duncan Sands19d0b472010-02-16 11:11:14 +0000513 if (!SrcPTy->isIntegerTy() && !SrcPTy->isPointerTy())
Craig Topperf40110f2014-04-25 05:29:35 +0000514 return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000515
Richard Osborne0af4aa92014-03-25 17:21:41 +0000516 // If the pointers point into different address spaces don't do the
517 // transformation.
518 if (SrcTy->getAddressSpace() !=
519 cast<PointerType>(CI->getType())->getAddressSpace())
Craig Topperf40110f2014-04-25 05:29:35 +0000520 return nullptr;
Richard Osborne0af4aa92014-03-25 17:21:41 +0000521
522 // If the pointers point to values of different sizes don't do the
523 // transformation.
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000524 if (!IC.getDataLayout() ||
Micah Villmowcdfe20b2012-10-08 16:38:25 +0000525 IC.getDataLayout()->getTypeSizeInBits(SrcPTy) !=
526 IC.getDataLayout()->getTypeSizeInBits(DestPTy))
Craig Topperf40110f2014-04-25 05:29:35 +0000527 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000528
Richard Osborne0af4aa92014-03-25 17:21:41 +0000529 // If the pointers point to pointers to different address spaces don't do the
530 // transformation. It is not safe to introduce an addrspacecast instruction in
531 // this case since, depending on the target, addrspacecast may not be a no-op
532 // cast.
533 if (SrcPTy->isPointerTy() && DestPTy->isPointerTy() &&
534 SrcPTy->getPointerAddressSpace() != DestPTy->getPointerAddressSpace())
Craig Topperf40110f2014-04-25 05:29:35 +0000535 return nullptr;
Richard Osborne0af4aa92014-03-25 17:21:41 +0000536
Chris Lattnera65e2f72010-01-05 05:57:49 +0000537 // Okay, we are casting from one integer or pointer type to another of
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000538 // the same size. Instead of casting the pointer before
Chris Lattnera65e2f72010-01-05 05:57:49 +0000539 // the store, cast the value to be stored.
540 Value *NewCast;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000541 Instruction::CastOps opcode = Instruction::BitCast;
Richard Osborne9805ec42014-03-25 17:21:35 +0000542 Type* CastSrcTy = DestPTy;
Chris Lattner229907c2011-07-18 04:54:35 +0000543 Type* CastDstTy = SrcPTy;
Duncan Sands19d0b472010-02-16 11:11:14 +0000544 if (CastDstTy->isPointerTy()) {
Duncan Sands9dff9be2010-02-15 16:12:20 +0000545 if (CastSrcTy->isIntegerTy())
Chris Lattnera65e2f72010-01-05 05:57:49 +0000546 opcode = Instruction::IntToPtr;
Duncan Sands19d0b472010-02-16 11:11:14 +0000547 } else if (CastDstTy->isIntegerTy()) {
Richard Osborne9805ec42014-03-25 17:21:35 +0000548 if (CastSrcTy->isPointerTy())
Chris Lattnera65e2f72010-01-05 05:57:49 +0000549 opcode = Instruction::PtrToInt;
550 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000551
Chris Lattnera65e2f72010-01-05 05:57:49 +0000552 // SIOp0 is a pointer to aggregate and this is a store to the first field,
553 // emit a GEP to index into its first field.
554 if (!NewGEPIndices.empty())
Jay Foad040dd822011-07-22 08:16:57 +0000555 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000556
Richard Osborne9805ec42014-03-25 17:21:35 +0000557 Value *SIOp0 = SI.getOperand(0);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000558 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
559 SIOp0->getName()+".c");
Dan Gohman2e20dfb2010-10-25 16:16:27 +0000560 SI.setOperand(0, NewCast);
561 SI.setOperand(1, CastOp);
562 return &SI;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000563}
564
565/// equivalentAddressValues - Test if A and B will obviously have the same
566/// value. This includes recognizing that %t0 and %t1 will have the same
567/// value in code like this:
568/// %t0 = getelementptr \@a, 0, 3
569/// store i32 0, i32* %t0
570/// %t1 = getelementptr \@a, 0, 3
571/// %t2 = load i32* %t1
572///
573static bool equivalentAddressValues(Value *A, Value *B) {
574 // Test if the values are trivially equivalent.
575 if (A == B) return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000576
Chris Lattnera65e2f72010-01-05 05:57:49 +0000577 // Test if the values come form identical arithmetic instructions.
578 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
579 // its only used to compare two uses within the same basic block, which
580 // means that they'll always either have the same value or one of them
581 // will have an undefined value.
582 if (isa<BinaryOperator>(A) ||
583 isa<CastInst>(A) ||
584 isa<PHINode>(A) ||
585 isa<GetElementPtrInst>(A))
586 if (Instruction *BI = dyn_cast<Instruction>(B))
587 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
588 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000589
Chris Lattnera65e2f72010-01-05 05:57:49 +0000590 // Otherwise they may not be equivalent.
591 return false;
592}
593
Chris Lattnera65e2f72010-01-05 05:57:49 +0000594Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
595 Value *Val = SI.getOperand(0);
596 Value *Ptr = SI.getOperand(1);
597
Chris Lattnera65e2f72010-01-05 05:57:49 +0000598 // Attempt to improve the alignment.
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000599 if (DL) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000600 unsigned KnownAlign =
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000601 getOrEnforceKnownAlignment(Ptr, DL->getPrefTypeAlignment(Val->getType()),
602 DL);
Dan Gohman36196602010-08-03 18:20:32 +0000603 unsigned StoreAlign = SI.getAlignment();
604 unsigned EffectiveStoreAlign = StoreAlign != 0 ? StoreAlign :
Rafael Espindola37dc9e12014-02-21 00:06:31 +0000605 DL->getABITypeAlignment(Val->getType());
Dan Gohman36196602010-08-03 18:20:32 +0000606
Bill Wendling55b6b2b2012-03-16 18:20:54 +0000607 if (KnownAlign > EffectiveStoreAlign)
Chris Lattnera65e2f72010-01-05 05:57:49 +0000608 SI.setAlignment(KnownAlign);
Bill Wendling55b6b2b2012-03-16 18:20:54 +0000609 else if (StoreAlign == 0)
610 SI.setAlignment(EffectiveStoreAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000611 }
612
Eli Friedman8bc586e2011-08-15 22:09:40 +0000613 // Don't hack volatile/atomic stores.
614 // FIXME: Some bits are legal for atomic stores; needs refactoring.
Craig Topperf40110f2014-04-25 05:29:35 +0000615 if (!SI.isSimple()) return nullptr;
Eli Friedman8bc586e2011-08-15 22:09:40 +0000616
617 // If the RHS is an alloca with a single use, zapify the store, making the
618 // alloca dead.
619 if (Ptr->hasOneUse()) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000620 if (isa<AllocaInst>(Ptr))
Eli Friedman8bc586e2011-08-15 22:09:40 +0000621 return EraseInstFromFunction(SI);
622 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
623 if (isa<AllocaInst>(GEP->getOperand(0))) {
624 if (GEP->getOperand(0)->hasOneUse())
625 return EraseInstFromFunction(SI);
626 }
627 }
628 }
629
Chris Lattnera65e2f72010-01-05 05:57:49 +0000630 // Do really simple DSE, to catch cases where there are several consecutive
631 // stores to the same location, separated by a few arithmetic operations. This
632 // situation often occurs with bitfield accesses.
633 BasicBlock::iterator BBI = &SI;
634 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
635 --ScanInsts) {
636 --BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +0000637 // Don't count debug info directives, lest they affect codegen,
638 // and we skip pointer-to-pointer bitcasts, which are NOPs.
639 if (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000640 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000641 ScanInsts++;
642 continue;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000643 }
644
Chris Lattnera65e2f72010-01-05 05:57:49 +0000645 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
646 // Prev store isn't volatile, and stores to the same location?
Eli Friedman8bc586e2011-08-15 22:09:40 +0000647 if (PrevSI->isSimple() && equivalentAddressValues(PrevSI->getOperand(1),
648 SI.getOperand(1))) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000649 ++NumDeadStore;
650 ++BBI;
651 EraseInstFromFunction(*PrevSI);
652 continue;
653 }
654 break;
655 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000656
Chris Lattnera65e2f72010-01-05 05:57:49 +0000657 // If this is a load, we have to stop. However, if the loaded value is from
658 // the pointer we're loading and is producing the pointer we're storing,
659 // then *this* store is dead (X = load P; store X -> P).
660 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Jin-Gu Kangb452db02011-03-14 01:21:00 +0000661 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
Eli Friedman8bc586e2011-08-15 22:09:40 +0000662 LI->isSimple())
Jin-Gu Kangb452db02011-03-14 01:21:00 +0000663 return EraseInstFromFunction(SI);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000664
Chris Lattnera65e2f72010-01-05 05:57:49 +0000665 // Otherwise, this is a load from some other location. Stores before it
666 // may not be dead.
667 break;
668 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000669
Chris Lattnera65e2f72010-01-05 05:57:49 +0000670 // Don't skip over loads or things that can modify memory.
671 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
672 break;
673 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000674
675 // store X, null -> turns into 'unreachable' in SimplifyCFG
676 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
677 if (!isa<UndefValue>(Val)) {
678 SI.setOperand(0, UndefValue::get(Val->getType()));
679 if (Instruction *U = dyn_cast<Instruction>(Val))
680 Worklist.Add(U); // Dropped a use.
681 }
Craig Topperf40110f2014-04-25 05:29:35 +0000682 return nullptr; // Do not modify these!
Chris Lattnera65e2f72010-01-05 05:57:49 +0000683 }
684
685 // store undef, Ptr -> noop
686 if (isa<UndefValue>(Val))
687 return EraseInstFromFunction(SI);
688
689 // If the pointer destination is a cast, see if we can fold the cast into the
690 // source instead.
691 if (isa<CastInst>(Ptr))
692 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
693 return Res;
694 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
695 if (CE->isCast())
696 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
697 return Res;
698
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000699
Chris Lattnera65e2f72010-01-05 05:57:49 +0000700 // If this store is the last instruction in the basic block (possibly
Victor Hernandez5f5abd52010-01-21 23:07:15 +0000701 // excepting debug info instructions), and if the block ends with an
702 // unconditional branch, try to move it to the successor block.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000703 BBI = &SI;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000704 do {
705 ++BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +0000706 } while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000707 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()));
Chris Lattnera65e2f72010-01-05 05:57:49 +0000708 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
709 if (BI->isUnconditional())
710 if (SimplifyStoreAtEndOfBlock(SI))
Craig Topperf40110f2014-04-25 05:29:35 +0000711 return nullptr; // xform done!
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000712
Craig Topperf40110f2014-04-25 05:29:35 +0000713 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000714}
715
716/// SimplifyStoreAtEndOfBlock - Turn things like:
717/// if () { *P = v1; } else { *P = v2 }
718/// into a phi node with a store in the successor.
719///
720/// Simplify things like:
721/// *P = v1; if () { *P = v2; }
722/// into a phi node with a store in the successor.
723///
724bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
725 BasicBlock *StoreBB = SI.getParent();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000726
Chris Lattnera65e2f72010-01-05 05:57:49 +0000727 // Check to see if the successor block has exactly two incoming edges. If
728 // so, see if the other predecessor contains a store to the same location.
729 // if so, insert a PHI node (if needed) and move the stores down.
730 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000731
Chris Lattnera65e2f72010-01-05 05:57:49 +0000732 // Determine whether Dest has exactly two predecessors and, if so, compute
733 // the other predecessor.
734 pred_iterator PI = pred_begin(DestBB);
Gabor Greif1b787df2010-07-12 15:48:26 +0000735 BasicBlock *P = *PI;
Craig Topperf40110f2014-04-25 05:29:35 +0000736 BasicBlock *OtherBB = nullptr;
Gabor Greif1b787df2010-07-12 15:48:26 +0000737
738 if (P != StoreBB)
739 OtherBB = P;
740
741 if (++PI == pred_end(DestBB))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000742 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000743
Gabor Greif1b787df2010-07-12 15:48:26 +0000744 P = *PI;
745 if (P != StoreBB) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000746 if (OtherBB)
747 return false;
Gabor Greif1b787df2010-07-12 15:48:26 +0000748 OtherBB = P;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000749 }
750 if (++PI != pred_end(DestBB))
751 return false;
752
753 // Bail out if all the relevant blocks aren't distinct (this can happen,
754 // for example, if SI is in an infinite loop)
755 if (StoreBB == DestBB || OtherBB == DestBB)
756 return false;
757
758 // Verify that the other block ends in a branch and is not otherwise empty.
759 BasicBlock::iterator BBI = OtherBB->getTerminator();
760 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
761 if (!OtherBr || BBI == OtherBB->begin())
762 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000763
Chris Lattnera65e2f72010-01-05 05:57:49 +0000764 // If the other block ends in an unconditional branch, check for the 'if then
765 // else' case. there is an instruction before the branch.
Craig Topperf40110f2014-04-25 05:29:35 +0000766 StoreInst *OtherStore = nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000767 if (OtherBr->isUnconditional()) {
768 --BBI;
769 // Skip over debugging info.
Victor Hernandez5f8c8c02010-01-22 19:05:05 +0000770 while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +0000771 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000772 if (BBI==OtherBB->begin())
773 return false;
774 --BBI;
775 }
Eli Friedman8bc586e2011-08-15 22:09:40 +0000776 // If this isn't a store, isn't a store to the same location, or is not the
777 // right kind of store, bail out.
Chris Lattnera65e2f72010-01-05 05:57:49 +0000778 OtherStore = dyn_cast<StoreInst>(BBI);
779 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +0000780 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000781 return false;
782 } else {
783 // Otherwise, the other block ended with a conditional branch. If one of the
784 // destinations is StoreBB, then we have the if/then case.
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000785 if (OtherBr->getSuccessor(0) != StoreBB &&
Chris Lattnera65e2f72010-01-05 05:57:49 +0000786 OtherBr->getSuccessor(1) != StoreBB)
787 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000788
Chris Lattnera65e2f72010-01-05 05:57:49 +0000789 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
790 // if/then triangle. See if there is a store to the same ptr as SI that
791 // lives in OtherBB.
792 for (;; --BBI) {
793 // Check to see if we find the matching store.
794 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
795 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +0000796 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +0000797 return false;
798 break;
799 }
800 // If we find something that may be using or overwriting the stored
801 // value, or if we run out of instructions, we can't do the xform.
802 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
803 BBI == OtherBB->begin())
804 return false;
805 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000806
Chris Lattnera65e2f72010-01-05 05:57:49 +0000807 // In order to eliminate the store in OtherBr, we have to
808 // make sure nothing reads or overwrites the stored value in
809 // StoreBB.
810 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
811 // FIXME: This should really be AA driven.
812 if (I->mayReadFromMemory() || I->mayWriteToMemory())
813 return false;
814 }
815 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000816
Chris Lattnera65e2f72010-01-05 05:57:49 +0000817 // Insert a PHI node now if we need it.
818 Value *MergedVal = OtherStore->getOperand(0);
819 if (MergedVal != SI.getOperand(0)) {
Jay Foad52131342011-03-30 11:28:46 +0000820 PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge");
Chris Lattnera65e2f72010-01-05 05:57:49 +0000821 PN->addIncoming(SI.getOperand(0), SI.getParent());
822 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
823 MergedVal = InsertNewInstBefore(PN, DestBB->front());
824 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000825
Chris Lattnera65e2f72010-01-05 05:57:49 +0000826 // Advance to a place where it is safe to insert the new store and
827 // insert it.
Bill Wendling8ddfc092011-08-16 20:45:24 +0000828 BBI = DestBB->getFirstInsertionPt();
Eli Friedman35211c62011-05-27 00:19:40 +0000829 StoreInst *NewSI = new StoreInst(MergedVal, SI.getOperand(1),
Eli Friedman8bc586e2011-08-15 22:09:40 +0000830 SI.isVolatile(),
831 SI.getAlignment(),
832 SI.getOrdering(),
833 SI.getSynchScope());
Eli Friedman35211c62011-05-27 00:19:40 +0000834 InsertNewInstBefore(NewSI, *BBI);
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000835 NewSI->setDebugLoc(OtherStore->getDebugLoc());
Eli Friedman35211c62011-05-27 00:19:40 +0000836
Chris Lattnereeefe1b2012-12-31 08:10:58 +0000837 // If the two stores had the same TBAA tag, preserve it.
Chris Lattner473988c2013-01-05 16:44:07 +0000838 if (MDNode *TBAATag = SI.getMetadata(LLVMContext::MD_tbaa))
839 if ((TBAATag = MDNode::getMostGenericTBAA(TBAATag,
840 OtherStore->getMetadata(LLVMContext::MD_tbaa))))
841 NewSI->setMetadata(LLVMContext::MD_tbaa, TBAATag);
Chris Lattnereeefe1b2012-12-31 08:10:58 +0000842
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000843
Chris Lattnera65e2f72010-01-05 05:57:49 +0000844 // Nuke the old stores.
845 EraseInstFromFunction(SI);
846 EraseInstFromFunction(*OtherStore);
847 return true;
848}