blob: da7d5fb33d35cabb46173d33ac9d9d21e3c26178 [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 Carrutha9174582015-01-22 05:25:13 +000014#include "InstCombineInternal.h"
NAKAMURA Takumiec6b1fc2015-12-15 09:37:31 +000015#include "llvm/ADT/SmallString.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"
Chandler Carruthbc6378d2014-10-19 10:46:46 +000019#include "llvm/IR/LLVMContext.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000020#include "llvm/IR/IntrinsicInst.h"
Charles Davis33d1dc02015-02-25 05:10:25 +000021#include "llvm/IR/MDBuilder.h"
Chris Lattnera65e2f72010-01-05 05:57:49 +000022#include "llvm/Transforms/Utils/BasicBlockUtils.h"
23#include "llvm/Transforms/Utils/Local.h"
Chris Lattnera65e2f72010-01-05 05:57:49 +000024using namespace llvm;
25
Chandler Carruth964daaa2014-04-22 02:55:47 +000026#define DEBUG_TYPE "instcombine"
27
Chandler Carruthc908ca12012-08-21 08:39:44 +000028STATISTIC(NumDeadStore, "Number of dead stores eliminated");
29STATISTIC(NumGlobalCopies, "Number of allocas copied from constant global");
30
31/// pointsToConstantGlobal - Return true if V (possibly indirectly) points to
32/// some part of a constant global variable. This intentionally only accepts
33/// constant expressions because we can't rewrite arbitrary instructions.
34static bool pointsToConstantGlobal(Value *V) {
35 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
36 return GV->isConstant();
Matt Arsenault607281772014-04-24 00:01:09 +000037
38 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Chandler Carruthc908ca12012-08-21 08:39:44 +000039 if (CE->getOpcode() == Instruction::BitCast ||
Matt Arsenault607281772014-04-24 00:01:09 +000040 CE->getOpcode() == Instruction::AddrSpaceCast ||
Chandler Carruthc908ca12012-08-21 08:39:44 +000041 CE->getOpcode() == Instruction::GetElementPtr)
42 return pointsToConstantGlobal(CE->getOperand(0));
Matt Arsenault607281772014-04-24 00:01:09 +000043 }
Chandler Carruthc908ca12012-08-21 08:39:44 +000044 return false;
45}
46
47/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
48/// pointer to an alloca. Ignore any reads of the pointer, return false if we
49/// see any stores or other unknown uses. If we see pointer arithmetic, keep
50/// track of whether it moves the pointer (with IsOffset) but otherwise traverse
51/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
52/// the alloca, and if the source pointer is a pointer to a constant global, we
53/// can optimize this.
54static bool
55isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
Reid Kleckner813dab22014-07-01 21:36:20 +000056 SmallVectorImpl<Instruction *> &ToDelete) {
Chandler Carruthc908ca12012-08-21 08:39:44 +000057 // We track lifetime intrinsics as we encounter them. If we decide to go
58 // ahead and replace the value with the global, this lets the caller quickly
59 // eliminate the markers.
60
Reid Kleckner813dab22014-07-01 21:36:20 +000061 SmallVector<std::pair<Value *, bool>, 35> ValuesToInspect;
62 ValuesToInspect.push_back(std::make_pair(V, false));
63 while (!ValuesToInspect.empty()) {
64 auto ValuePair = ValuesToInspect.pop_back_val();
65 const bool IsOffset = ValuePair.second;
66 for (auto &U : ValuePair.first->uses()) {
67 Instruction *I = cast<Instruction>(U.getUser());
Chandler Carruthc908ca12012-08-21 08:39:44 +000068
Reid Kleckner813dab22014-07-01 21:36:20 +000069 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
70 // Ignore non-volatile loads, they are always ok.
71 if (!LI->isSimple()) return false;
Chandler Carruthc908ca12012-08-21 08:39:44 +000072 continue;
73 }
Reid Kleckner813dab22014-07-01 21:36:20 +000074
75 if (isa<BitCastInst>(I) || isa<AddrSpaceCastInst>(I)) {
76 // If uses of the bitcast are ok, we are ok.
77 ValuesToInspect.push_back(std::make_pair(I, IsOffset));
78 continue;
79 }
80 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
81 // If the GEP has all zero indices, it doesn't offset the pointer. If it
82 // doesn't, it does.
83 ValuesToInspect.push_back(
84 std::make_pair(I, IsOffset || !GEP->hasAllZeroIndices()));
85 continue;
86 }
87
Benjamin Kramer3a09ef62015-04-10 14:50:08 +000088 if (auto CS = CallSite(I)) {
Reid Kleckner813dab22014-07-01 21:36:20 +000089 // If this is the function being called then we treat it like a load and
90 // ignore it.
91 if (CS.isCallee(&U))
92 continue;
93
David Majnemer02f47872015-12-23 09:58:41 +000094 unsigned DataOpNo = CS.getDataOperandNo(&U);
95 bool IsArgOperand = CS.isArgOperand(&U);
96
Reid Kleckner813dab22014-07-01 21:36:20 +000097 // Inalloca arguments are clobbered by the call.
David Majnemer02f47872015-12-23 09:58:41 +000098 if (IsArgOperand && CS.isInAllocaArgument(DataOpNo))
Reid Kleckner813dab22014-07-01 21:36:20 +000099 return false;
100
101 // If this is a readonly/readnone call site, then we know it is just a
102 // load (but one that potentially returns the value itself), so we can
103 // ignore it if we know that the value isn't captured.
104 if (CS.onlyReadsMemory() &&
David Majnemer02f47872015-12-23 09:58:41 +0000105 (CS.getInstruction()->use_empty() || CS.doesNotCapture(DataOpNo)))
Reid Kleckner813dab22014-07-01 21:36:20 +0000106 continue;
107
108 // If this is being passed as a byval argument, the caller is making a
109 // copy, so it is only a read of the alloca.
David Majnemer02f47872015-12-23 09:58:41 +0000110 if (IsArgOperand && CS.isByValArgument(DataOpNo))
Reid Kleckner813dab22014-07-01 21:36:20 +0000111 continue;
112 }
113
114 // Lifetime intrinsics can be handled by the caller.
115 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
116 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
117 II->getIntrinsicID() == Intrinsic::lifetime_end) {
118 assert(II->use_empty() && "Lifetime markers have no result to use!");
119 ToDelete.push_back(II);
120 continue;
121 }
122 }
123
124 // If this is isn't our memcpy/memmove, reject it as something we can't
125 // handle.
126 MemTransferInst *MI = dyn_cast<MemTransferInst>(I);
127 if (!MI)
128 return false;
129
130 // If the transfer is using the alloca as a source of the transfer, then
131 // ignore it since it is a load (unless the transfer is volatile).
132 if (U.getOperandNo() == 1) {
133 if (MI->isVolatile()) return false;
134 continue;
135 }
136
137 // If we already have seen a copy, reject the second one.
138 if (TheCopy) return false;
139
140 // If the pointer has been offset from the start of the alloca, we can't
141 // safely handle this.
142 if (IsOffset) return false;
143
144 // If the memintrinsic isn't using the alloca as the dest, reject it.
145 if (U.getOperandNo() != 0) return false;
146
147 // If the source of the memcpy/move is not a constant global, reject it.
148 if (!pointsToConstantGlobal(MI->getSource()))
149 return false;
150
151 // Otherwise, the transform is safe. Remember the copy instruction.
152 TheCopy = MI;
Chandler Carruthc908ca12012-08-21 08:39:44 +0000153 }
Chandler Carruthc908ca12012-08-21 08:39:44 +0000154 }
155 return true;
156}
157
158/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
159/// modified by a copy from a constant global. If we can prove this, we can
160/// replace any uses of the alloca with uses of the global directly.
161static MemTransferInst *
162isOnlyCopiedFromConstantGlobal(AllocaInst *AI,
163 SmallVectorImpl<Instruction *> &ToDelete) {
Craig Topperf40110f2014-04-25 05:29:35 +0000164 MemTransferInst *TheCopy = nullptr;
Chandler Carruthc908ca12012-08-21 08:39:44 +0000165 if (isOnlyCopiedFromConstantGlobal(AI, TheCopy, ToDelete))
166 return TheCopy;
Craig Topperf40110f2014-04-25 05:29:35 +0000167 return nullptr;
Chandler Carruthc908ca12012-08-21 08:39:44 +0000168}
169
Duncan P. N. Exon Smithc6820ec2015-03-13 19:22:03 +0000170static Instruction *simplifyAllocaArraySize(InstCombiner &IC, AllocaInst &AI) {
Duncan P. N. Exon Smith720762e2015-03-13 19:30:44 +0000171 // Check for array size of 1 (scalar allocation).
Duncan P. N. Exon Smithbe95b4a2015-03-13 19:42:09 +0000172 if (!AI.isArrayAllocation()) {
173 // i32 1 is the canonical array size for scalar allocations.
174 if (AI.getArraySize()->getType()->isIntegerTy(32))
175 return nullptr;
176
177 // Canonicalize it.
178 Value *V = IC.Builder->getInt32(1);
179 AI.setOperand(0, V);
180 return &AI;
181 }
Duncan P. N. Exon Smith720762e2015-03-13 19:30:44 +0000182
Chris Lattnera65e2f72010-01-05 05:57:49 +0000183 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000184 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
185 Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
186 AllocaInst *New = IC.Builder->CreateAlloca(NewTy, nullptr, AI.getName());
187 New->setAlignment(AI.getAlignment());
Chris Lattnera65e2f72010-01-05 05:57:49 +0000188
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000189 // Scan to the end of the allocation instructions, to skip over a block of
190 // allocas if possible...also skip interleaved debug info
191 //
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000192 BasicBlock::iterator It(New);
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000193 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It))
194 ++It;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000195
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000196 // Now that I is pointing to the first non-allocation-inst in the block,
197 // insert our getelementptr instruction...
198 //
199 Type *IdxTy = IC.getDataLayout().getIntPtrType(AI.getType());
200 Value *NullIdx = Constant::getNullValue(IdxTy);
201 Value *Idx[2] = {NullIdx, NullIdx};
202 Instruction *GEP =
Matt Arsenault640ff9d2013-08-14 00:24:05 +0000203 GetElementPtrInst::CreateInBounds(New, Idx, New->getName() + ".sub");
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000204 IC.InsertNewInstBefore(GEP, *It);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000205
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000206 // Now make everything use the getelementptr instead of the original
207 // allocation.
Sanjay Patel4b198802016-02-01 22:23:39 +0000208 return IC.replaceInstUsesWith(AI, GEP);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000209 }
210
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000211 if (isa<UndefValue>(AI.getArraySize()))
Sanjay Patel4b198802016-02-01 22:23:39 +0000212 return IC.replaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000213
Duncan P. N. Exon Smith07ff9b02015-03-13 19:34:55 +0000214 // Ensure that the alloca array size argument has type intptr_t, so that
215 // any casting is exposed early.
216 Type *IntPtrTy = IC.getDataLayout().getIntPtrType(AI.getType());
217 if (AI.getArraySize()->getType() != IntPtrTy) {
218 Value *V = IC.Builder->CreateIntCast(AI.getArraySize(), IntPtrTy, false);
219 AI.setOperand(0, V);
220 return &AI;
221 }
222
Duncan P. N. Exon Smithc6820ec2015-03-13 19:22:03 +0000223 return nullptr;
224}
225
226Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
227 if (auto *I = simplifyAllocaArraySize(*this, AI))
228 return I;
229
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000230 if (AI.getAllocatedType()->isSized()) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000231 // If the alignment is 0 (unspecified), assign it the preferred alignment.
232 if (AI.getAlignment() == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000233 AI.setAlignment(DL.getPrefTypeAlignment(AI.getAllocatedType()));
Duncan Sands8bc764a2012-06-26 13:39:21 +0000234
235 // Move all alloca's of zero byte objects to the entry block and merge them
236 // together. Note that we only do this for alloca's, because malloc should
237 // allocate and return a unique pointer, even for a zero byte allocation.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000238 if (DL.getTypeAllocSize(AI.getAllocatedType()) == 0) {
Duncan Sands8bc764a2012-06-26 13:39:21 +0000239 // For a zero sized alloca there is no point in doing an array allocation.
240 // This is helpful if the array size is a complicated expression not used
241 // elsewhere.
242 if (AI.isArrayAllocation()) {
243 AI.setOperand(0, ConstantInt::get(AI.getArraySize()->getType(), 1));
244 return &AI;
245 }
246
247 // Get the first instruction in the entry block.
248 BasicBlock &EntryBlock = AI.getParent()->getParent()->getEntryBlock();
249 Instruction *FirstInst = EntryBlock.getFirstNonPHIOrDbg();
250 if (FirstInst != &AI) {
251 // If the entry block doesn't start with a zero-size alloca then move
252 // this one to the start of the entry block. There is no problem with
253 // dominance as the array size was forced to a constant earlier already.
254 AllocaInst *EntryAI = dyn_cast<AllocaInst>(FirstInst);
255 if (!EntryAI || !EntryAI->getAllocatedType()->isSized() ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000256 DL.getTypeAllocSize(EntryAI->getAllocatedType()) != 0) {
Duncan Sands8bc764a2012-06-26 13:39:21 +0000257 AI.moveBefore(FirstInst);
258 return &AI;
259 }
260
Richard Osborneb68053e2012-09-18 09:31:44 +0000261 // If the alignment of the entry block alloca is 0 (unspecified),
262 // assign it the preferred alignment.
263 if (EntryAI->getAlignment() == 0)
264 EntryAI->setAlignment(
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000265 DL.getPrefTypeAlignment(EntryAI->getAllocatedType()));
Duncan Sands8bc764a2012-06-26 13:39:21 +0000266 // Replace this zero-sized alloca with the one at the start of the entry
267 // block after ensuring that the address will be aligned enough for both
268 // types.
Richard Osborneb68053e2012-09-18 09:31:44 +0000269 unsigned MaxAlign = std::max(EntryAI->getAlignment(),
270 AI.getAlignment());
Duncan Sands8bc764a2012-06-26 13:39:21 +0000271 EntryAI->setAlignment(MaxAlign);
272 if (AI.getType() != EntryAI->getType())
273 return new BitCastInst(EntryAI, AI.getType());
Sanjay Patel4b198802016-02-01 22:23:39 +0000274 return replaceInstUsesWith(AI, EntryAI);
Duncan Sands8bc764a2012-06-26 13:39:21 +0000275 }
276 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000277 }
278
Eli Friedmanb14873c2012-11-26 23:04:53 +0000279 if (AI.getAlignment()) {
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000280 // Check to see if this allocation is only modified by a memcpy/memmove from
281 // a constant global whose alignment is equal to or exceeds that of the
282 // allocation. If this is the case, we can change all users to use
283 // the constant global instead. This is commonly produced by the CFE by
284 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
285 // is only subsequently read.
286 SmallVector<Instruction *, 4> ToDelete;
287 if (MemTransferInst *Copy = isOnlyCopiedFromConstantGlobal(&AI, ToDelete)) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000288 unsigned SourceAlign = getOrEnforceKnownAlignment(
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000289 Copy->getSource(), AI.getAlignment(), DL, &AI, AC, DT);
Eli Friedmanb14873c2012-11-26 23:04:53 +0000290 if (AI.getAlignment() <= SourceAlign) {
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000291 DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n');
292 DEBUG(dbgs() << " memcpy = " << *Copy << '\n');
293 for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
Sanjay Patel4b198802016-02-01 22:23:39 +0000294 eraseInstFromFunction(*ToDelete[i]);
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000295 Constant *TheSrc = cast<Constant>(Copy->getSource());
Matt Arsenaultbbf18c62013-12-07 02:58:45 +0000296 Constant *Cast
297 = ConstantExpr::getPointerBitCastOrAddrSpaceCast(TheSrc, AI.getType());
Sanjay Patel4b198802016-02-01 22:23:39 +0000298 Instruction *NewI = replaceInstUsesWith(AI, Cast);
299 eraseInstFromFunction(*Copy);
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000300 ++NumGlobalCopies;
301 return NewI;
302 }
Chandler Carruthc908ca12012-08-21 08:39:44 +0000303 }
304 }
305
Nuno Lopes95cc4f32012-07-09 18:38:20 +0000306 // At last, use the generic allocation site handler to aggressively remove
307 // unused allocas.
308 return visitAllocSite(AI);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000309}
310
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000311/// \brief Helper to combine a load to a new type.
312///
313/// This just does the work of combining a load to a new type. It handles
314/// metadata, etc., and returns the new instruction. The \c NewTy should be the
315/// loaded *value* type. This will convert it to a pointer, cast the operand to
316/// that pointer type, load it, etc.
317///
318/// Note that this will create all of the instructions with whatever insert
319/// point the \c InstCombiner currently is using.
Mehdi Amini2668a482015-05-07 05:52:40 +0000320static LoadInst *combineLoadToNewType(InstCombiner &IC, LoadInst &LI, Type *NewTy,
321 const Twine &Suffix = "") {
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000322 Value *Ptr = LI.getPointerOperand();
323 unsigned AS = LI.getPointerAddressSpace();
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000324 SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000325 LI.getAllMetadata(MD);
326
327 LoadInst *NewLoad = IC.Builder->CreateAlignedLoad(
328 IC.Builder->CreateBitCast(Ptr, NewTy->getPointerTo(AS)),
Mehdi Amini2668a482015-05-07 05:52:40 +0000329 LI.getAlignment(), LI.getName() + Suffix);
Charles Davis33d1dc02015-02-25 05:10:25 +0000330 MDBuilder MDB(NewLoad->getContext());
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000331 for (const auto &MDPair : MD) {
332 unsigned ID = MDPair.first;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000333 MDNode *N = MDPair.second;
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000334 // Note, essentially every kind of metadata should be preserved here! This
335 // routine is supposed to clone a load instruction changing *only its type*.
336 // The only metadata it makes sense to drop is metadata which is invalidated
337 // when the pointer type changes. This should essentially never be the case
338 // in LLVM, but we explicitly switch over only known metadata to be
339 // conservatively correct. If you are adding metadata to LLVM which pertains
340 // to loads, you almost certainly want to add it here.
341 switch (ID) {
342 case LLVMContext::MD_dbg:
343 case LLVMContext::MD_tbaa:
344 case LLVMContext::MD_prof:
345 case LLVMContext::MD_fpmath:
346 case LLVMContext::MD_tbaa_struct:
347 case LLVMContext::MD_invariant_load:
348 case LLVMContext::MD_alias_scope:
349 case LLVMContext::MD_noalias:
Philip Reames5a3f5f72014-10-21 00:13:20 +0000350 case LLVMContext::MD_nontemporal:
351 case LLVMContext::MD_mem_parallel_loop_access:
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000352 // All of these directly apply.
353 NewLoad->setMetadata(ID, N);
354 break;
355
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000356 case LLVMContext::MD_nonnull:
Charles Davis33d1dc02015-02-25 05:10:25 +0000357 // This only directly applies if the new type is also a pointer.
358 if (NewTy->isPointerTy()) {
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000359 NewLoad->setMetadata(ID, N);
Charles Davis33d1dc02015-02-25 05:10:25 +0000360 break;
361 }
362 // If it's integral now, translate it to !range metadata.
363 if (NewTy->isIntegerTy()) {
364 auto *ITy = cast<IntegerType>(NewTy);
365 auto *NullInt = ConstantExpr::getPtrToInt(
366 ConstantPointerNull::get(cast<PointerType>(Ptr->getType())), ITy);
367 auto *NonNullInt =
368 ConstantExpr::getAdd(NullInt, ConstantInt::get(ITy, 1));
369 NewLoad->setMetadata(LLVMContext::MD_range,
370 MDB.createRange(NonNullInt, NullInt));
371 }
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000372 break;
Artur Pilipenko5c5011d2015-11-02 17:53:51 +0000373 case LLVMContext::MD_align:
374 case LLVMContext::MD_dereferenceable:
375 case LLVMContext::MD_dereferenceable_or_null:
376 // These only directly apply if the new type is also a pointer.
377 if (NewTy->isPointerTy())
378 NewLoad->setMetadata(ID, N);
379 break;
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000380 case LLVMContext::MD_range:
381 // FIXME: It would be nice to propagate this in some way, but the type
Charles Davis33d1dc02015-02-25 05:10:25 +0000382 // conversions make it hard. If the new type is a pointer, we could
383 // translate it to !nonnull metadata.
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000384 break;
385 }
386 }
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000387 return NewLoad;
388}
389
Chandler Carruthfa11d832015-01-22 03:34:54 +0000390/// \brief Combine a store to a new type.
391///
392/// Returns the newly created store instruction.
393static StoreInst *combineStoreToNewValue(InstCombiner &IC, StoreInst &SI, Value *V) {
394 Value *Ptr = SI.getPointerOperand();
395 unsigned AS = SI.getPointerAddressSpace();
396 SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
397 SI.getAllMetadata(MD);
398
399 StoreInst *NewStore = IC.Builder->CreateAlignedStore(
400 V, IC.Builder->CreateBitCast(Ptr, V->getType()->getPointerTo(AS)),
401 SI.getAlignment());
402 for (const auto &MDPair : MD) {
403 unsigned ID = MDPair.first;
404 MDNode *N = MDPair.second;
405 // Note, essentially every kind of metadata should be preserved here! This
406 // routine is supposed to clone a store instruction changing *only its
407 // type*. The only metadata it makes sense to drop is metadata which is
408 // invalidated when the pointer type changes. This should essentially
409 // never be the case in LLVM, but we explicitly switch over only known
410 // metadata to be conservatively correct. If you are adding metadata to
411 // LLVM which pertains to stores, you almost certainly want to add it
412 // here.
413 switch (ID) {
414 case LLVMContext::MD_dbg:
415 case LLVMContext::MD_tbaa:
416 case LLVMContext::MD_prof:
417 case LLVMContext::MD_fpmath:
418 case LLVMContext::MD_tbaa_struct:
419 case LLVMContext::MD_alias_scope:
420 case LLVMContext::MD_noalias:
421 case LLVMContext::MD_nontemporal:
422 case LLVMContext::MD_mem_parallel_loop_access:
Chandler Carruthfa11d832015-01-22 03:34:54 +0000423 // All of these directly apply.
424 NewStore->setMetadata(ID, N);
425 break;
426
427 case LLVMContext::MD_invariant_load:
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000428 case LLVMContext::MD_nonnull:
Chandler Carruthfa11d832015-01-22 03:34:54 +0000429 case LLVMContext::MD_range:
Artur Pilipenko5c5011d2015-11-02 17:53:51 +0000430 case LLVMContext::MD_align:
431 case LLVMContext::MD_dereferenceable:
432 case LLVMContext::MD_dereferenceable_or_null:
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000433 // These don't apply for stores.
Chandler Carruthfa11d832015-01-22 03:34:54 +0000434 break;
435 }
436 }
437
438 return NewStore;
439}
440
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000441/// \brief Combine loads to match the type of value their uses after looking
442/// through intervening bitcasts.
443///
444/// The core idea here is that if the result of a load is used in an operation,
445/// we should load the type most conducive to that operation. For example, when
446/// loading an integer and converting that immediately to a pointer, we should
447/// instead directly load a pointer.
448///
449/// However, this routine must never change the width of a load or the number of
450/// loads as that would introduce a semantic change. This combine is expected to
451/// be a semantic no-op which just allows loads to more closely model the types
452/// of their consuming operations.
453///
454/// Currently, we also refuse to change the precise type used for an atomic load
455/// or a volatile load. This is debatable, and might be reasonable to change
456/// later. However, it is risky in case some backend or other part of LLVM is
457/// relying on the exact type loaded to select appropriate atomic operations.
458static Instruction *combineLoadToOperationType(InstCombiner &IC, LoadInst &LI) {
459 // FIXME: We could probably with some care handle both volatile and atomic
460 // loads here but it isn't clear that this is important.
461 if (!LI.isSimple())
462 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000463
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000464 if (LI.use_empty())
465 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000466
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000467 Type *Ty = LI.getType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000468 const DataLayout &DL = IC.getDataLayout();
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000469
470 // Try to canonicalize loads which are only ever stored to operate over
471 // integers instead of any other type. We only do this when the loaded type
472 // is sized and has a size exactly the same as its store size and the store
473 // size is a legal integer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000474 if (!Ty->isIntegerTy() && Ty->isSized() &&
475 DL.isLegalInteger(DL.getTypeStoreSizeInBits(Ty)) &&
476 DL.getTypeStoreSizeInBits(Ty) == DL.getTypeSizeInBits(Ty)) {
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000477 if (std::all_of(LI.user_begin(), LI.user_end(), [&LI](User *U) {
478 auto *SI = dyn_cast<StoreInst>(U);
479 return SI && SI->getPointerOperand() != &LI;
480 })) {
481 LoadInst *NewLoad = combineLoadToNewType(
482 IC, LI,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000483 Type::getIntNTy(LI.getContext(), DL.getTypeStoreSizeInBits(Ty)));
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000484 // Replace all the stores with stores of the newly loaded value.
485 for (auto UI = LI.user_begin(), UE = LI.user_end(); UI != UE;) {
486 auto *SI = cast<StoreInst>(*UI++);
487 IC.Builder->SetInsertPoint(SI);
488 combineStoreToNewValue(IC, *SI, NewLoad);
Sanjay Patel4b198802016-02-01 22:23:39 +0000489 IC.eraseInstFromFunction(*SI);
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000490 }
491 assert(LI.use_empty() && "Failed to remove all users of the load!");
492 // Return the old load so the combiner can delete it safely.
493 return &LI;
494 }
495 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000496
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000497 // Fold away bit casts of the loaded value by loading the desired type.
498 if (LI.hasOneUse())
Quentin Colombet7ec03dc2016-02-03 18:04:13 +0000499 if (auto *BC = dyn_cast<BitCastInst>(LI.user_back())) {
500 LoadInst *NewLoad = combineLoadToNewType(IC, LI, BC->getDestTy());
501 BC->replaceAllUsesWith(NewLoad);
502 IC.eraseInstFromFunction(*BC);
503 return &LI;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000504 }
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000505
Chandler Carrutha7f247e2014-12-09 19:21:16 +0000506 // FIXME: We should also canonicalize loads of vectors when their elements are
507 // cast to other types.
Craig Topperf40110f2014-04-25 05:29:35 +0000508 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000509}
510
Mehdi Amini2668a482015-05-07 05:52:40 +0000511static Instruction *unpackLoadToAggregate(InstCombiner &IC, LoadInst &LI) {
512 // FIXME: We could probably with some care handle both volatile and atomic
513 // stores here but it isn't clear that this is important.
514 if (!LI.isSimple())
515 return nullptr;
516
517 Type *T = LI.getType();
518 if (!T->isAggregateType())
519 return nullptr;
520
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000521 assert(LI.getAlignment() && "Alignment must be set at this point");
Mehdi Amini2668a482015-05-07 05:52:40 +0000522
523 if (auto *ST = dyn_cast<StructType>(T)) {
524 // If the struct only have one element, we unpack.
Mehdi Amini1c131b32015-12-15 01:44:07 +0000525 unsigned Count = ST->getNumElements();
526 if (Count == 1) {
Mehdi Amini2668a482015-05-07 05:52:40 +0000527 LoadInst *NewLoad = combineLoadToNewType(IC, LI, ST->getTypeAtIndex(0U),
528 ".unpack");
Sanjay Patel4b198802016-02-01 22:23:39 +0000529 return IC.replaceInstUsesWith(LI, IC.Builder->CreateInsertValue(
Mehdi Amini2668a482015-05-07 05:52:40 +0000530 UndefValue::get(T), NewLoad, 0, LI.getName()));
531 }
Mehdi Amini1c131b32015-12-15 01:44:07 +0000532
533 // We don't want to break loads with padding here as we'd loose
534 // the knowledge that padding exists for the rest of the pipeline.
535 const DataLayout &DL = IC.getDataLayout();
536 auto *SL = DL.getStructLayout(ST);
537 if (SL->hasPadding())
538 return nullptr;
539
540 auto Name = LI.getName();
NAKAMURA Takumiec6b1fc2015-12-15 09:37:31 +0000541 SmallString<16> LoadName = Name;
542 LoadName += ".unpack";
543 SmallString<16> EltName = Name;
544 EltName += ".elt";
Mehdi Amini1c131b32015-12-15 01:44:07 +0000545 auto *Addr = LI.getPointerOperand();
546 Value *V = UndefValue::get(T);
547 auto *IdxType = Type::getInt32Ty(ST->getContext());
548 auto *Zero = ConstantInt::get(IdxType, 0);
549 for (unsigned i = 0; i < Count; i++) {
550 Value *Indices[2] = {
551 Zero,
552 ConstantInt::get(IdxType, i),
553 };
554 auto *Ptr = IC.Builder->CreateInBoundsGEP(ST, Addr, makeArrayRef(Indices), EltName);
Pete Cooper5562c332016-02-11 21:10:40 +0000555 auto *L = IC.Builder->CreateAlignedLoad(Ptr, LI.getAlignment(),
556 LoadName);
Mehdi Amini1c131b32015-12-15 01:44:07 +0000557 V = IC.Builder->CreateInsertValue(V, L, i);
558 }
559
560 V->setName(Name);
Sanjay Patel4b198802016-02-01 22:23:39 +0000561 return IC.replaceInstUsesWith(LI, V);
Mehdi Amini2668a482015-05-07 05:52:40 +0000562 }
563
David Majnemer58fb0382015-05-11 05:04:22 +0000564 if (auto *AT = dyn_cast<ArrayType>(T)) {
565 // If the array only have one element, we unpack.
566 if (AT->getNumElements() == 1) {
567 LoadInst *NewLoad = combineLoadToNewType(IC, LI, AT->getElementType(),
568 ".unpack");
Sanjay Patel4b198802016-02-01 22:23:39 +0000569 return IC.replaceInstUsesWith(LI, IC.Builder->CreateInsertValue(
David Majnemer58fb0382015-05-11 05:04:22 +0000570 UndefValue::get(T), NewLoad, 0, LI.getName()));
571 }
572 }
573
Mehdi Amini2668a482015-05-07 05:52:40 +0000574 return nullptr;
575}
576
Hal Finkel847e05f2015-02-20 03:05:53 +0000577// If we can determine that all possible objects pointed to by the provided
578// pointer value are, not only dereferenceable, but also definitively less than
579// or equal to the provided maximum size, then return true. Otherwise, return
580// false (constant global values and allocas fall into this category).
581//
582// FIXME: This should probably live in ValueTracking (or similar).
583static bool isObjectSizeLessThanOrEq(Value *V, uint64_t MaxSize,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000584 const DataLayout &DL) {
Hal Finkel847e05f2015-02-20 03:05:53 +0000585 SmallPtrSet<Value *, 4> Visited;
586 SmallVector<Value *, 4> Worklist(1, V);
587
588 do {
589 Value *P = Worklist.pop_back_val();
590 P = P->stripPointerCasts();
591
592 if (!Visited.insert(P).second)
593 continue;
594
595 if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
596 Worklist.push_back(SI->getTrueValue());
597 Worklist.push_back(SI->getFalseValue());
598 continue;
599 }
600
601 if (PHINode *PN = dyn_cast<PHINode>(P)) {
Pete Cooper833f34d2015-05-12 20:05:31 +0000602 for (Value *IncValue : PN->incoming_values())
603 Worklist.push_back(IncValue);
Hal Finkel847e05f2015-02-20 03:05:53 +0000604 continue;
605 }
606
607 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(P)) {
608 if (GA->mayBeOverridden())
609 return false;
610 Worklist.push_back(GA->getAliasee());
611 continue;
612 }
613
614 // If we know how big this object is, and it is less than MaxSize, continue
615 // searching. Otherwise, return false.
616 if (AllocaInst *AI = dyn_cast<AllocaInst>(P)) {
617 if (!AI->getAllocatedType()->isSized())
618 return false;
619
620 ConstantInt *CS = dyn_cast<ConstantInt>(AI->getArraySize());
621 if (!CS)
622 return false;
623
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000624 uint64_t TypeSize = DL.getTypeAllocSize(AI->getAllocatedType());
Hal Finkel847e05f2015-02-20 03:05:53 +0000625 // Make sure that, even if the multiplication below would wrap as an
626 // uint64_t, we still do the right thing.
627 if ((CS->getValue().zextOrSelf(128)*APInt(128, TypeSize)).ugt(MaxSize))
628 return false;
629 continue;
630 }
631
632 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
633 if (!GV->hasDefinitiveInitializer() || !GV->isConstant())
634 return false;
635
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000636 uint64_t InitSize = DL.getTypeAllocSize(GV->getValueType());
Hal Finkel847e05f2015-02-20 03:05:53 +0000637 if (InitSize > MaxSize)
638 return false;
639 continue;
640 }
641
642 return false;
643 } while (!Worklist.empty());
644
645 return true;
646}
647
648// If we're indexing into an object of a known size, and the outer index is
649// not a constant, but having any value but zero would lead to undefined
650// behavior, replace it with zero.
651//
652// For example, if we have:
653// @f.a = private unnamed_addr constant [1 x i32] [i32 12], align 4
654// ...
655// %arrayidx = getelementptr inbounds [1 x i32]* @f.a, i64 0, i64 %x
656// ... = load i32* %arrayidx, align 4
657// Then we know that we can replace %x in the GEP with i64 0.
658//
659// FIXME: We could fold any GEP index to zero that would cause UB if it were
660// not zero. Currently, we only handle the first such index. Also, we could
661// also search through non-zero constant indices if we kept track of the
662// offsets those indices implied.
663static bool canReplaceGEPIdxWithZero(InstCombiner &IC, GetElementPtrInst *GEPI,
664 Instruction *MemI, unsigned &Idx) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000665 if (GEPI->getNumOperands() < 2)
Hal Finkel847e05f2015-02-20 03:05:53 +0000666 return false;
667
668 // Find the first non-zero index of a GEP. If all indices are zero, return
669 // one past the last index.
670 auto FirstNZIdx = [](const GetElementPtrInst *GEPI) {
671 unsigned I = 1;
672 for (unsigned IE = GEPI->getNumOperands(); I != IE; ++I) {
673 Value *V = GEPI->getOperand(I);
674 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
675 if (CI->isZero())
676 continue;
677
678 break;
679 }
680
681 return I;
682 };
683
684 // Skip through initial 'zero' indices, and find the corresponding pointer
685 // type. See if the next index is not a constant.
686 Idx = FirstNZIdx(GEPI);
687 if (Idx == GEPI->getNumOperands())
688 return false;
689 if (isa<Constant>(GEPI->getOperand(Idx)))
690 return false;
691
692 SmallVector<Value *, 4> Ops(GEPI->idx_begin(), GEPI->idx_begin() + Idx);
Eduard Burtescu19eb0312016-01-19 17:28:00 +0000693 Type *AllocTy =
694 GetElementPtrInst::getIndexedType(GEPI->getSourceElementType(), Ops);
Hal Finkel847e05f2015-02-20 03:05:53 +0000695 if (!AllocTy || !AllocTy->isSized())
696 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000697 const DataLayout &DL = IC.getDataLayout();
698 uint64_t TyAllocSize = DL.getTypeAllocSize(AllocTy);
Hal Finkel847e05f2015-02-20 03:05:53 +0000699
700 // If there are more indices after the one we might replace with a zero, make
701 // sure they're all non-negative. If any of them are negative, the overall
702 // address being computed might be before the base address determined by the
703 // first non-zero index.
704 auto IsAllNonNegative = [&]() {
705 for (unsigned i = Idx+1, e = GEPI->getNumOperands(); i != e; ++i) {
706 bool KnownNonNegative, KnownNegative;
707 IC.ComputeSignBit(GEPI->getOperand(i), KnownNonNegative,
708 KnownNegative, 0, MemI);
709 if (KnownNonNegative)
710 continue;
711 return false;
712 }
713
714 return true;
715 };
716
717 // FIXME: If the GEP is not inbounds, and there are extra indices after the
718 // one we'll replace, those could cause the address computation to wrap
719 // (rendering the IsAllNonNegative() check below insufficient). We can do
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000720 // better, ignoring zero indices (and other indices we can prove small
Hal Finkel847e05f2015-02-20 03:05:53 +0000721 // enough not to wrap).
722 if (Idx+1 != GEPI->getNumOperands() && !GEPI->isInBounds())
723 return false;
724
725 // Note that isObjectSizeLessThanOrEq will return true only if the pointer is
726 // also known to be dereferenceable.
727 return isObjectSizeLessThanOrEq(GEPI->getOperand(0), TyAllocSize, DL) &&
728 IsAllNonNegative();
729}
730
731// If we're indexing into an object with a variable index for the memory
732// access, but the object has only one element, we can assume that the index
733// will always be zero. If we replace the GEP, return it.
734template <typename T>
735static Instruction *replaceGEPIdxWithZero(InstCombiner &IC, Value *Ptr,
736 T &MemI) {
737 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr)) {
738 unsigned Idx;
739 if (canReplaceGEPIdxWithZero(IC, GEPI, &MemI, Idx)) {
740 Instruction *NewGEPI = GEPI->clone();
741 NewGEPI->setOperand(Idx,
742 ConstantInt::get(GEPI->getOperand(Idx)->getType(), 0));
743 NewGEPI->insertBefore(GEPI);
744 MemI.setOperand(MemI.getPointerOperandIndex(), NewGEPI);
745 return NewGEPI;
746 }
747 }
748
749 return nullptr;
750}
751
Chris Lattnera65e2f72010-01-05 05:57:49 +0000752Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
753 Value *Op = LI.getOperand(0);
754
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000755 // Try to canonicalize the loaded type.
756 if (Instruction *Res = combineLoadToOperationType(*this, LI))
757 return Res;
758
Chris Lattnera65e2f72010-01-05 05:57:49 +0000759 // Attempt to improve the alignment.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000760 unsigned KnownAlign = getOrEnforceKnownAlignment(
761 Op, DL.getPrefTypeAlignment(LI.getType()), DL, &LI, AC, DT);
762 unsigned LoadAlign = LI.getAlignment();
763 unsigned EffectiveLoadAlign =
764 LoadAlign != 0 ? LoadAlign : DL.getABITypeAlignment(LI.getType());
Dan Gohman36196602010-08-03 18:20:32 +0000765
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000766 if (KnownAlign > EffectiveLoadAlign)
767 LI.setAlignment(KnownAlign);
768 else if (LoadAlign == 0)
769 LI.setAlignment(EffectiveLoadAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000770
Hal Finkel847e05f2015-02-20 03:05:53 +0000771 // Replace GEP indices if possible.
772 if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Op, LI)) {
773 Worklist.Add(NewGEPI);
774 return &LI;
775 }
776
Eli Friedman8bc586e2011-08-15 22:09:40 +0000777 // None of the following transforms are legal for volatile/atomic loads.
778 // FIXME: Some of it is okay for atomic loads; needs refactoring.
Craig Topperf40110f2014-04-25 05:29:35 +0000779 if (!LI.isSimple()) return nullptr;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000780
Mehdi Amini2668a482015-05-07 05:52:40 +0000781 if (Instruction *Res = unpackLoadToAggregate(*this, LI))
782 return Res;
783
Chris Lattnera65e2f72010-01-05 05:57:49 +0000784 // Do really simple store-to-load forwarding and load CSE, to catch cases
Duncan Sands75b5d272011-02-15 09:23:02 +0000785 // where there are several consecutive memory accesses to the same location,
Chris Lattnera65e2f72010-01-05 05:57:49 +0000786 // separated by a few arithmetic operations.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000787 BasicBlock::iterator BBI(LI);
Bjorn Steinbrinka91fd092015-07-10 06:55:44 +0000788 AAMDNodes AATags;
Larisse Voufo532bf712015-09-18 19:14:35 +0000789 if (Value *AvailableVal =
Eduard Burtescue2a69172016-01-22 01:51:51 +0000790 FindAvailableLoadedValue(&LI, LI.getParent(), BBI,
Larisse Voufo532bf712015-09-18 19:14:35 +0000791 DefMaxInstsToScan, AA, &AATags)) {
Bjorn Steinbrinka91fd092015-07-10 06:55:44 +0000792 if (LoadInst *NLI = dyn_cast<LoadInst>(AvailableVal)) {
793 unsigned KnownIDs[] = {
Artur Pilipenko5c5011d2015-11-02 17:53:51 +0000794 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
795 LLVMContext::MD_noalias, LLVMContext::MD_range,
796 LLVMContext::MD_invariant_load, LLVMContext::MD_nonnull,
797 LLVMContext::MD_invariant_group, LLVMContext::MD_align,
798 LLVMContext::MD_dereferenceable,
799 LLVMContext::MD_dereferenceable_or_null};
Bjorn Steinbrinka91fd092015-07-10 06:55:44 +0000800 combineMetadata(NLI, &LI, KnownIDs);
Bjorn Steinbrinka91fd092015-07-10 06:55:44 +0000801 };
802
Sanjay Patel4b198802016-02-01 22:23:39 +0000803 return replaceInstUsesWith(
Chandler Carruth1a3c2c42014-11-25 08:20:27 +0000804 LI, Builder->CreateBitOrPointerCast(AvailableVal, LI.getType(),
805 LI.getName() + ".cast"));
Bjorn Steinbrinka91fd092015-07-10 06:55:44 +0000806 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000807
808 // load(gep null, ...) -> unreachable
809 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
810 const Value *GEPI0 = GEPI->getOperand(0);
811 // TODO: Consider a target hook for valid address spaces for this xform.
812 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
813 // Insert a new store to null instruction before the load to indicate
814 // that this code is not reachable. We do this instead of inserting
815 // an unreachable instruction directly because we cannot modify the
816 // CFG.
817 new StoreInst(UndefValue::get(LI.getType()),
818 Constant::getNullValue(Op->getType()), &LI);
Sanjay Patel4b198802016-02-01 22:23:39 +0000819 return replaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattnera65e2f72010-01-05 05:57:49 +0000820 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000821 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000822
823 // load null/undef -> unreachable
824 // TODO: Consider a target hook for valid address spaces for this xform.
825 if (isa<UndefValue>(Op) ||
826 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
827 // Insert a new store to null instruction before the load to indicate that
828 // this code is not reachable. We do this instead of inserting an
829 // unreachable instruction directly because we cannot modify the CFG.
830 new StoreInst(UndefValue::get(LI.getType()),
831 Constant::getNullValue(Op->getType()), &LI);
Sanjay Patel4b198802016-02-01 22:23:39 +0000832 return replaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattnera65e2f72010-01-05 05:57:49 +0000833 }
834
Chris Lattnera65e2f72010-01-05 05:57:49 +0000835 if (Op->hasOneUse()) {
836 // Change select and PHI nodes to select values instead of addresses: this
837 // helps alias analysis out a lot, allows many others simplifications, and
838 // exposes redundancy in the code.
839 //
840 // Note that we cannot do the transformation unless we know that the
841 // introduced loads cannot trap! Something like this is valid as long as
842 // the condition is always false: load (select bool %C, int* null, int* %G),
843 // but it would not be valid if we transformed it to load from null
844 // unconditionally.
845 //
846 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
847 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Bob Wilson56600a12010-01-30 04:42:39 +0000848 unsigned Align = LI.getAlignment();
Artur Pilipenko6dd69692016-01-15 15:27:46 +0000849 if (isSafeToLoadUnconditionally(SI->getOperand(1), Align, SI) &&
850 isSafeToLoadUnconditionally(SI->getOperand(2), Align, SI)) {
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000851 LoadInst *V1 = Builder->CreateLoad(SI->getOperand(1),
Bob Wilson56600a12010-01-30 04:42:39 +0000852 SI->getOperand(1)->getName()+".val");
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000853 LoadInst *V2 = Builder->CreateLoad(SI->getOperand(2),
Bob Wilson56600a12010-01-30 04:42:39 +0000854 SI->getOperand(2)->getName()+".val");
855 V1->setAlignment(Align);
856 V2->setAlignment(Align);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000857 return SelectInst::Create(SI->getCondition(), V1, V2);
858 }
859
860 // load (select (cond, null, P)) -> load P
Larisse Voufo532bf712015-09-18 19:14:35 +0000861 if (isa<ConstantPointerNull>(SI->getOperand(1)) &&
Philip Reames5ad26c32014-12-29 22:46:21 +0000862 LI.getPointerAddressSpace() == 0) {
863 LI.setOperand(0, SI->getOperand(2));
864 return &LI;
865 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000866
867 // load (select (cond, P, null)) -> load P
Philip Reames5ad26c32014-12-29 22:46:21 +0000868 if (isa<ConstantPointerNull>(SI->getOperand(2)) &&
869 LI.getPointerAddressSpace() == 0) {
870 LI.setOperand(0, SI->getOperand(1));
871 return &LI;
872 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000873 }
874 }
Craig Topperf40110f2014-04-25 05:29:35 +0000875 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000876}
877
Chandler Carruth816d26f2014-11-25 10:09:51 +0000878/// \brief Combine stores to match the type of value being stored.
879///
880/// The core idea here is that the memory does not have any intrinsic type and
881/// where we can we should match the type of a store to the type of value being
882/// stored.
883///
884/// However, this routine must never change the width of a store or the number of
885/// stores as that would introduce a semantic change. This combine is expected to
886/// be a semantic no-op which just allows stores to more closely model the types
887/// of their incoming values.
888///
889/// Currently, we also refuse to change the precise type used for an atomic or
890/// volatile store. This is debatable, and might be reasonable to change later.
891/// However, it is risky in case some backend or other part of LLVM is relying
892/// on the exact type stored to select appropriate atomic operations.
893///
894/// \returns true if the store was successfully combined away. This indicates
895/// the caller must erase the store instruction. We have to let the caller erase
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000896/// the store instruction as otherwise there is no way to signal whether it was
Chandler Carruth816d26f2014-11-25 10:09:51 +0000897/// combined or not: IC.EraseInstFromFunction returns a null pointer.
898static bool combineStoreToValueType(InstCombiner &IC, StoreInst &SI) {
899 // FIXME: We could probably with some care handle both volatile and atomic
900 // stores here but it isn't clear that this is important.
901 if (!SI.isSimple())
902 return false;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000903
Chandler Carruth816d26f2014-11-25 10:09:51 +0000904 Value *V = SI.getValueOperand();
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000905
Chandler Carruth816d26f2014-11-25 10:09:51 +0000906 // Fold away bit casts of the stored value by storing the original type.
907 if (auto *BC = dyn_cast<BitCastInst>(V)) {
Chandler Carrutha7f247e2014-12-09 19:21:16 +0000908 V = BC->getOperand(0);
Chandler Carruth2135b972015-01-21 23:45:01 +0000909 combineStoreToNewValue(IC, SI, V);
Chandler Carruth816d26f2014-11-25 10:09:51 +0000910 return true;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000911 }
912
Chandler Carruth816d26f2014-11-25 10:09:51 +0000913 // FIXME: We should also canonicalize loads of vectors when their elements are
914 // cast to other types.
915 return false;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000916}
917
Mehdi Aminib344ac92015-03-14 22:19:33 +0000918static bool unpackStoreToAggregate(InstCombiner &IC, StoreInst &SI) {
919 // FIXME: We could probably with some care handle both volatile and atomic
920 // stores here but it isn't clear that this is important.
921 if (!SI.isSimple())
922 return false;
923
924 Value *V = SI.getValueOperand();
925 Type *T = V->getType();
926
927 if (!T->isAggregateType())
928 return false;
929
Mehdi Amini2668a482015-05-07 05:52:40 +0000930 if (auto *ST = dyn_cast<StructType>(T)) {
Mehdi Aminib344ac92015-03-14 22:19:33 +0000931 // If the struct only have one element, we unpack.
Mehdi Amini1c131b32015-12-15 01:44:07 +0000932 unsigned Count = ST->getNumElements();
933 if (Count == 1) {
Mehdi Aminib344ac92015-03-14 22:19:33 +0000934 V = IC.Builder->CreateExtractValue(V, 0);
935 combineStoreToNewValue(IC, SI, V);
936 return true;
937 }
Mehdi Amini1c131b32015-12-15 01:44:07 +0000938
939 // We don't want to break loads with padding here as we'd loose
940 // the knowledge that padding exists for the rest of the pipeline.
941 const DataLayout &DL = IC.getDataLayout();
942 auto *SL = DL.getStructLayout(ST);
943 if (SL->hasPadding())
944 return false;
945
NAKAMURA Takumiec6b1fc2015-12-15 09:37:31 +0000946 SmallString<16> EltName = V->getName();
947 EltName += ".elt";
Mehdi Amini1c131b32015-12-15 01:44:07 +0000948 auto *Addr = SI.getPointerOperand();
NAKAMURA Takumiec6b1fc2015-12-15 09:37:31 +0000949 SmallString<16> AddrName = Addr->getName();
950 AddrName += ".repack";
Mehdi Amini1c131b32015-12-15 01:44:07 +0000951 auto *IdxType = Type::getInt32Ty(ST->getContext());
952 auto *Zero = ConstantInt::get(IdxType, 0);
953 for (unsigned i = 0; i < Count; i++) {
954 Value *Indices[2] = {
955 Zero,
956 ConstantInt::get(IdxType, i),
957 };
958 auto *Ptr = IC.Builder->CreateInBoundsGEP(ST, Addr, makeArrayRef(Indices), AddrName);
959 auto *Val = IC.Builder->CreateExtractValue(V, i, EltName);
960 IC.Builder->CreateStore(Val, Ptr);
961 }
962
963 return true;
Mehdi Aminib344ac92015-03-14 22:19:33 +0000964 }
965
David Majnemer75364602015-05-11 05:04:27 +0000966 if (auto *AT = dyn_cast<ArrayType>(T)) {
967 // If the array only have one element, we unpack.
968 if (AT->getNumElements() == 1) {
969 V = IC.Builder->CreateExtractValue(V, 0);
970 combineStoreToNewValue(IC, SI, V);
971 return true;
972 }
973 }
974
Mehdi Aminib344ac92015-03-14 22:19:33 +0000975 return false;
976}
977
Chris Lattnera65e2f72010-01-05 05:57:49 +0000978/// equivalentAddressValues - Test if A and B will obviously have the same
979/// value. This includes recognizing that %t0 and %t1 will have the same
980/// value in code like this:
981/// %t0 = getelementptr \@a, 0, 3
982/// store i32 0, i32* %t0
983/// %t1 = getelementptr \@a, 0, 3
984/// %t2 = load i32* %t1
985///
986static bool equivalentAddressValues(Value *A, Value *B) {
987 // Test if the values are trivially equivalent.
988 if (A == B) return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000989
Chris Lattnera65e2f72010-01-05 05:57:49 +0000990 // Test if the values come form identical arithmetic instructions.
991 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
992 // its only used to compare two uses within the same basic block, which
993 // means that they'll always either have the same value or one of them
994 // will have an undefined value.
995 if (isa<BinaryOperator>(A) ||
996 isa<CastInst>(A) ||
997 isa<PHINode>(A) ||
998 isa<GetElementPtrInst>(A))
999 if (Instruction *BI = dyn_cast<Instruction>(B))
1000 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
1001 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001002
Chris Lattnera65e2f72010-01-05 05:57:49 +00001003 // Otherwise they may not be equivalent.
1004 return false;
1005}
1006
Chris Lattnera65e2f72010-01-05 05:57:49 +00001007Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
1008 Value *Val = SI.getOperand(0);
1009 Value *Ptr = SI.getOperand(1);
1010
Chandler Carruth816d26f2014-11-25 10:09:51 +00001011 // Try to canonicalize the stored type.
1012 if (combineStoreToValueType(*this, SI))
Sanjay Patel4b198802016-02-01 22:23:39 +00001013 return eraseInstFromFunction(SI);
Chandler Carruth816d26f2014-11-25 10:09:51 +00001014
Chris Lattnera65e2f72010-01-05 05:57:49 +00001015 // Attempt to improve the alignment.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001016 unsigned KnownAlign = getOrEnforceKnownAlignment(
1017 Ptr, DL.getPrefTypeAlignment(Val->getType()), DL, &SI, AC, DT);
1018 unsigned StoreAlign = SI.getAlignment();
1019 unsigned EffectiveStoreAlign =
1020 StoreAlign != 0 ? StoreAlign : DL.getABITypeAlignment(Val->getType());
Dan Gohman36196602010-08-03 18:20:32 +00001021
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001022 if (KnownAlign > EffectiveStoreAlign)
1023 SI.setAlignment(KnownAlign);
1024 else if (StoreAlign == 0)
1025 SI.setAlignment(EffectiveStoreAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001026
Mehdi Aminib344ac92015-03-14 22:19:33 +00001027 // Try to canonicalize the stored type.
1028 if (unpackStoreToAggregate(*this, SI))
Sanjay Patel4b198802016-02-01 22:23:39 +00001029 return eraseInstFromFunction(SI);
Mehdi Aminib344ac92015-03-14 22:19:33 +00001030
Hal Finkel847e05f2015-02-20 03:05:53 +00001031 // Replace GEP indices if possible.
1032 if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Ptr, SI)) {
1033 Worklist.Add(NewGEPI);
1034 return &SI;
1035 }
1036
Philip Reamesd7a6cc82015-12-17 22:19:27 +00001037 // Don't hack volatile/ordered stores.
1038 // FIXME: Some bits are legal for ordered atomic stores; needs refactoring.
1039 if (!SI.isUnordered()) return nullptr;
Eli Friedman8bc586e2011-08-15 22:09:40 +00001040
1041 // If the RHS is an alloca with a single use, zapify the store, making the
1042 // alloca dead.
1043 if (Ptr->hasOneUse()) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001044 if (isa<AllocaInst>(Ptr))
Sanjay Patel4b198802016-02-01 22:23:39 +00001045 return eraseInstFromFunction(SI);
Eli Friedman8bc586e2011-08-15 22:09:40 +00001046 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
1047 if (isa<AllocaInst>(GEP->getOperand(0))) {
1048 if (GEP->getOperand(0)->hasOneUse())
Sanjay Patel4b198802016-02-01 22:23:39 +00001049 return eraseInstFromFunction(SI);
Eli Friedman8bc586e2011-08-15 22:09:40 +00001050 }
1051 }
1052 }
1053
Chris Lattnera65e2f72010-01-05 05:57:49 +00001054 // Do really simple DSE, to catch cases where there are several consecutive
1055 // stores to the same location, separated by a few arithmetic operations. This
1056 // situation often occurs with bitfield accesses.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00001057 BasicBlock::iterator BBI(SI);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001058 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
1059 --ScanInsts) {
1060 --BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +00001061 // Don't count debug info directives, lest they affect codegen,
1062 // and we skip pointer-to-pointer bitcasts, which are NOPs.
1063 if (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +00001064 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +00001065 ScanInsts++;
1066 continue;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001067 }
1068
Chris Lattnera65e2f72010-01-05 05:57:49 +00001069 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
1070 // Prev store isn't volatile, and stores to the same location?
Philip Reamesd7a6cc82015-12-17 22:19:27 +00001071 if (PrevSI->isUnordered() && equivalentAddressValues(PrevSI->getOperand(1),
Eli Friedman8bc586e2011-08-15 22:09:40 +00001072 SI.getOperand(1))) {
Chris Lattnera65e2f72010-01-05 05:57:49 +00001073 ++NumDeadStore;
1074 ++BBI;
Sanjay Patel4b198802016-02-01 22:23:39 +00001075 eraseInstFromFunction(*PrevSI);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001076 continue;
1077 }
1078 break;
1079 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001080
Chris Lattnera65e2f72010-01-05 05:57:49 +00001081 // If this is a load, we have to stop. However, if the loaded value is from
1082 // the pointer we're loading and is producing the pointer we're storing,
1083 // then *this* store is dead (X = load P; store X -> P).
1084 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Philip Reamesd7a6cc82015-12-17 22:19:27 +00001085 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr)) {
1086 assert(SI.isUnordered() && "can't eliminate ordering operation");
Sanjay Patel4b198802016-02-01 22:23:39 +00001087 return eraseInstFromFunction(SI);
Philip Reamesd7a6cc82015-12-17 22:19:27 +00001088 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001089
Chris Lattnera65e2f72010-01-05 05:57:49 +00001090 // Otherwise, this is a load from some other location. Stores before it
1091 // may not be dead.
1092 break;
1093 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001094
Chris Lattnera65e2f72010-01-05 05:57:49 +00001095 // Don't skip over loads or things that can modify memory.
1096 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
1097 break;
1098 }
Chris Lattnera65e2f72010-01-05 05:57:49 +00001099
1100 // store X, null -> turns into 'unreachable' in SimplifyCFG
1101 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
1102 if (!isa<UndefValue>(Val)) {
1103 SI.setOperand(0, UndefValue::get(Val->getType()));
1104 if (Instruction *U = dyn_cast<Instruction>(Val))
1105 Worklist.Add(U); // Dropped a use.
1106 }
Craig Topperf40110f2014-04-25 05:29:35 +00001107 return nullptr; // Do not modify these!
Chris Lattnera65e2f72010-01-05 05:57:49 +00001108 }
1109
1110 // store undef, Ptr -> noop
1111 if (isa<UndefValue>(Val))
Sanjay Patel4b198802016-02-01 22:23:39 +00001112 return eraseInstFromFunction(SI);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001113
Philip Reamesd7a6cc82015-12-17 22:19:27 +00001114 // The code below needs to be audited and adjusted for unordered atomics
1115 if (!SI.isSimple())
1116 return nullptr;
1117
Chris Lattnera65e2f72010-01-05 05:57:49 +00001118 // If this store is the last instruction in the basic block (possibly
Victor Hernandez5f5abd52010-01-21 23:07:15 +00001119 // excepting debug info instructions), and if the block ends with an
1120 // unconditional branch, try to move it to the successor block.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00001121 BBI = SI.getIterator();
Chris Lattnera65e2f72010-01-05 05:57:49 +00001122 do {
1123 ++BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +00001124 } while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +00001125 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()));
Chris Lattnera65e2f72010-01-05 05:57:49 +00001126 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
1127 if (BI->isUnconditional())
1128 if (SimplifyStoreAtEndOfBlock(SI))
Craig Topperf40110f2014-04-25 05:29:35 +00001129 return nullptr; // xform done!
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001130
Craig Topperf40110f2014-04-25 05:29:35 +00001131 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001132}
1133
1134/// SimplifyStoreAtEndOfBlock - Turn things like:
1135/// if () { *P = v1; } else { *P = v2 }
1136/// into a phi node with a store in the successor.
1137///
1138/// Simplify things like:
1139/// *P = v1; if () { *P = v2; }
1140/// into a phi node with a store in the successor.
1141///
1142bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
1143 BasicBlock *StoreBB = SI.getParent();
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001144
Chris Lattnera65e2f72010-01-05 05:57:49 +00001145 // Check to see if the successor block has exactly two incoming edges. If
1146 // so, see if the other predecessor contains a store to the same location.
1147 // if so, insert a PHI node (if needed) and move the stores down.
1148 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001149
Chris Lattnera65e2f72010-01-05 05:57:49 +00001150 // Determine whether Dest has exactly two predecessors and, if so, compute
1151 // the other predecessor.
1152 pred_iterator PI = pred_begin(DestBB);
Gabor Greif1b787df2010-07-12 15:48:26 +00001153 BasicBlock *P = *PI;
Craig Topperf40110f2014-04-25 05:29:35 +00001154 BasicBlock *OtherBB = nullptr;
Gabor Greif1b787df2010-07-12 15:48:26 +00001155
1156 if (P != StoreBB)
1157 OtherBB = P;
1158
1159 if (++PI == pred_end(DestBB))
Chris Lattnera65e2f72010-01-05 05:57:49 +00001160 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001161
Gabor Greif1b787df2010-07-12 15:48:26 +00001162 P = *PI;
1163 if (P != StoreBB) {
Chris Lattnera65e2f72010-01-05 05:57:49 +00001164 if (OtherBB)
1165 return false;
Gabor Greif1b787df2010-07-12 15:48:26 +00001166 OtherBB = P;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001167 }
1168 if (++PI != pred_end(DestBB))
1169 return false;
1170
1171 // Bail out if all the relevant blocks aren't distinct (this can happen,
1172 // for example, if SI is in an infinite loop)
1173 if (StoreBB == DestBB || OtherBB == DestBB)
1174 return false;
1175
1176 // Verify that the other block ends in a branch and is not otherwise empty.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00001177 BasicBlock::iterator BBI(OtherBB->getTerminator());
Chris Lattnera65e2f72010-01-05 05:57:49 +00001178 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
1179 if (!OtherBr || BBI == OtherBB->begin())
1180 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001181
Chris Lattnera65e2f72010-01-05 05:57:49 +00001182 // If the other block ends in an unconditional branch, check for the 'if then
1183 // else' case. there is an instruction before the branch.
Craig Topperf40110f2014-04-25 05:29:35 +00001184 StoreInst *OtherStore = nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001185 if (OtherBr->isUnconditional()) {
1186 --BBI;
1187 // Skip over debugging info.
Victor Hernandez5f8c8c02010-01-22 19:05:05 +00001188 while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +00001189 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +00001190 if (BBI==OtherBB->begin())
1191 return false;
1192 --BBI;
1193 }
Eli Friedman8bc586e2011-08-15 22:09:40 +00001194 // If this isn't a store, isn't a store to the same location, or is not the
1195 // right kind of store, bail out.
Chris Lattnera65e2f72010-01-05 05:57:49 +00001196 OtherStore = dyn_cast<StoreInst>(BBI);
1197 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +00001198 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +00001199 return false;
1200 } else {
1201 // Otherwise, the other block ended with a conditional branch. If one of the
1202 // destinations is StoreBB, then we have the if/then case.
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001203 if (OtherBr->getSuccessor(0) != StoreBB &&
Chris Lattnera65e2f72010-01-05 05:57:49 +00001204 OtherBr->getSuccessor(1) != StoreBB)
1205 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001206
Chris Lattnera65e2f72010-01-05 05:57:49 +00001207 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
1208 // if/then triangle. See if there is a store to the same ptr as SI that
1209 // lives in OtherBB.
1210 for (;; --BBI) {
1211 // Check to see if we find the matching store.
1212 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
1213 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +00001214 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +00001215 return false;
1216 break;
1217 }
1218 // If we find something that may be using or overwriting the stored
1219 // value, or if we run out of instructions, we can't do the xform.
1220 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
1221 BBI == OtherBB->begin())
1222 return false;
1223 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001224
Chris Lattnera65e2f72010-01-05 05:57:49 +00001225 // In order to eliminate the store in OtherBr, we have to
1226 // make sure nothing reads or overwrites the stored value in
1227 // StoreBB.
1228 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
1229 // FIXME: This should really be AA driven.
1230 if (I->mayReadFromMemory() || I->mayWriteToMemory())
1231 return false;
1232 }
1233 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001234
Chris Lattnera65e2f72010-01-05 05:57:49 +00001235 // Insert a PHI node now if we need it.
1236 Value *MergedVal = OtherStore->getOperand(0);
1237 if (MergedVal != SI.getOperand(0)) {
Jay Foad52131342011-03-30 11:28:46 +00001238 PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge");
Chris Lattnera65e2f72010-01-05 05:57:49 +00001239 PN->addIncoming(SI.getOperand(0), SI.getParent());
1240 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
1241 MergedVal = InsertNewInstBefore(PN, DestBB->front());
1242 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001243
Chris Lattnera65e2f72010-01-05 05:57:49 +00001244 // Advance to a place where it is safe to insert the new store and
1245 // insert it.
Bill Wendling8ddfc092011-08-16 20:45:24 +00001246 BBI = DestBB->getFirstInsertionPt();
Eli Friedman35211c62011-05-27 00:19:40 +00001247 StoreInst *NewSI = new StoreInst(MergedVal, SI.getOperand(1),
Eli Friedman8bc586e2011-08-15 22:09:40 +00001248 SI.isVolatile(),
1249 SI.getAlignment(),
1250 SI.getOrdering(),
1251 SI.getSynchScope());
Eli Friedman35211c62011-05-27 00:19:40 +00001252 InsertNewInstBefore(NewSI, *BBI);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001253 NewSI->setDebugLoc(OtherStore->getDebugLoc());
Eli Friedman35211c62011-05-27 00:19:40 +00001254
Hal Finkelcc39b672014-07-24 12:16:19 +00001255 // If the two stores had AA tags, merge them.
1256 AAMDNodes AATags;
1257 SI.getAAMetadata(AATags);
1258 if (AATags) {
1259 OtherStore->getAAMetadata(AATags, /* Merge = */ true);
1260 NewSI->setAAMetadata(AATags);
1261 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001262
Chris Lattnera65e2f72010-01-05 05:57:49 +00001263 // Nuke the old stores.
Sanjay Patel4b198802016-02-01 22:23:39 +00001264 eraseInstFromFunction(SI);
1265 eraseInstFromFunction(*OtherStore);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001266 return true;
1267}