blob: 49edd540787192640efebaecf3b8501945147d09 [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;
David Majnemer0a16c222016-08-11 21:15:00 +000062 ValuesToInspect.emplace_back(V, false);
Reid Kleckner813dab22014-07-01 21:36:20 +000063 while (!ValuesToInspect.empty()) {
64 auto ValuePair = ValuesToInspect.pop_back_val();
65 const bool IsOffset = ValuePair.second;
66 for (auto &U : ValuePair.first->uses()) {
David Majnemer0a16c222016-08-11 21:15:00 +000067 auto *I = cast<Instruction>(U.getUser());
Chandler Carruthc908ca12012-08-21 08:39:44 +000068
David Majnemer0a16c222016-08-11 21:15:00 +000069 if (auto *LI = dyn_cast<LoadInst>(I)) {
Reid Kleckner813dab22014-07-01 21:36:20 +000070 // 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.
David Majnemer0a16c222016-08-11 21:15:00 +000077 ValuesToInspect.emplace_back(I, IsOffset);
Reid Kleckner813dab22014-07-01 21:36:20 +000078 continue;
79 }
David Majnemer0a16c222016-08-11 21:15:00 +000080 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
Reid Kleckner813dab22014-07-01 21:36:20 +000081 // If the GEP has all zero indices, it doesn't offset the pointer. If it
82 // doesn't, it does.
David Majnemer0a16c222016-08-11 21:15:00 +000083 ValuesToInspect.emplace_back(I, IsOffset || !GEP->hasAllZeroIndices());
Reid Kleckner813dab22014-07-01 21:36:20 +000084 continue;
85 }
86
Benjamin Kramer3a09ef62015-04-10 14:50:08 +000087 if (auto CS = CallSite(I)) {
Reid Kleckner813dab22014-07-01 21:36:20 +000088 // If this is the function being called then we treat it like a load and
89 // ignore it.
90 if (CS.isCallee(&U))
91 continue;
92
David Majnemer02f47872015-12-23 09:58:41 +000093 unsigned DataOpNo = CS.getDataOperandNo(&U);
94 bool IsArgOperand = CS.isArgOperand(&U);
95
Reid Kleckner813dab22014-07-01 21:36:20 +000096 // Inalloca arguments are clobbered by the call.
David Majnemer02f47872015-12-23 09:58:41 +000097 if (IsArgOperand && CS.isInAllocaArgument(DataOpNo))
Reid Kleckner813dab22014-07-01 21:36:20 +000098 return false;
99
100 // If this is a readonly/readnone call site, then we know it is just a
101 // load (but one that potentially returns the value itself), so we can
102 // ignore it if we know that the value isn't captured.
103 if (CS.onlyReadsMemory() &&
David Majnemer02f47872015-12-23 09:58:41 +0000104 (CS.getInstruction()->use_empty() || CS.doesNotCapture(DataOpNo)))
Reid Kleckner813dab22014-07-01 21:36:20 +0000105 continue;
106
107 // If this is being passed as a byval argument, the caller is making a
108 // copy, so it is only a read of the alloca.
David Majnemer02f47872015-12-23 09:58:41 +0000109 if (IsArgOperand && CS.isByValArgument(DataOpNo))
Reid Kleckner813dab22014-07-01 21:36:20 +0000110 continue;
111 }
112
113 // Lifetime intrinsics can be handled by the caller.
114 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
115 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
116 II->getIntrinsicID() == Intrinsic::lifetime_end) {
117 assert(II->use_empty() && "Lifetime markers have no result to use!");
118 ToDelete.push_back(II);
119 continue;
120 }
121 }
122
123 // If this is isn't our memcpy/memmove, reject it as something we can't
124 // handle.
125 MemTransferInst *MI = dyn_cast<MemTransferInst>(I);
126 if (!MI)
127 return false;
128
129 // If the transfer is using the alloca as a source of the transfer, then
130 // ignore it since it is a load (unless the transfer is volatile).
131 if (U.getOperandNo() == 1) {
132 if (MI->isVolatile()) return false;
133 continue;
134 }
135
136 // If we already have seen a copy, reject the second one.
137 if (TheCopy) return false;
138
139 // If the pointer has been offset from the start of the alloca, we can't
140 // safely handle this.
141 if (IsOffset) return false;
142
143 // If the memintrinsic isn't using the alloca as the dest, reject it.
144 if (U.getOperandNo() != 0) return false;
145
146 // If the source of the memcpy/move is not a constant global, reject it.
147 if (!pointsToConstantGlobal(MI->getSource()))
148 return false;
149
150 // Otherwise, the transform is safe. Remember the copy instruction.
151 TheCopy = MI;
Chandler Carruthc908ca12012-08-21 08:39:44 +0000152 }
Chandler Carruthc908ca12012-08-21 08:39:44 +0000153 }
154 return true;
155}
156
157/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
158/// modified by a copy from a constant global. If we can prove this, we can
159/// replace any uses of the alloca with uses of the global directly.
160static MemTransferInst *
161isOnlyCopiedFromConstantGlobal(AllocaInst *AI,
162 SmallVectorImpl<Instruction *> &ToDelete) {
Craig Topperf40110f2014-04-25 05:29:35 +0000163 MemTransferInst *TheCopy = nullptr;
Chandler Carruthc908ca12012-08-21 08:39:44 +0000164 if (isOnlyCopiedFromConstantGlobal(AI, TheCopy, ToDelete))
165 return TheCopy;
Craig Topperf40110f2014-04-25 05:29:35 +0000166 return nullptr;
Chandler Carruthc908ca12012-08-21 08:39:44 +0000167}
168
Duncan P. N. Exon Smithc6820ec2015-03-13 19:22:03 +0000169static Instruction *simplifyAllocaArraySize(InstCombiner &IC, AllocaInst &AI) {
Duncan P. N. Exon Smith720762e2015-03-13 19:30:44 +0000170 // Check for array size of 1 (scalar allocation).
Duncan P. N. Exon Smithbe95b4a2015-03-13 19:42:09 +0000171 if (!AI.isArrayAllocation()) {
172 // i32 1 is the canonical array size for scalar allocations.
173 if (AI.getArraySize()->getType()->isIntegerTy(32))
174 return nullptr;
175
176 // Canonicalize it.
177 Value *V = IC.Builder->getInt32(1);
178 AI.setOperand(0, V);
179 return &AI;
180 }
Duncan P. N. Exon Smith720762e2015-03-13 19:30:44 +0000181
Chris Lattnera65e2f72010-01-05 05:57:49 +0000182 // 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 +0000183 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
184 Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
185 AllocaInst *New = IC.Builder->CreateAlloca(NewTy, nullptr, AI.getName());
186 New->setAlignment(AI.getAlignment());
Chris Lattnera65e2f72010-01-05 05:57:49 +0000187
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000188 // Scan to the end of the allocation instructions, to skip over a block of
189 // allocas if possible...also skip interleaved debug info
190 //
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000191 BasicBlock::iterator It(New);
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000192 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It))
193 ++It;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000194
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000195 // Now that I is pointing to the first non-allocation-inst in the block,
196 // insert our getelementptr instruction...
197 //
198 Type *IdxTy = IC.getDataLayout().getIntPtrType(AI.getType());
199 Value *NullIdx = Constant::getNullValue(IdxTy);
200 Value *Idx[2] = {NullIdx, NullIdx};
201 Instruction *GEP =
Matt Arsenault640ff9d2013-08-14 00:24:05 +0000202 GetElementPtrInst::CreateInBounds(New, Idx, New->getName() + ".sub");
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000203 IC.InsertNewInstBefore(GEP, *It);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000204
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000205 // Now make everything use the getelementptr instead of the original
206 // allocation.
Sanjay Patel4b198802016-02-01 22:23:39 +0000207 return IC.replaceInstUsesWith(AI, GEP);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000208 }
209
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000210 if (isa<UndefValue>(AI.getArraySize()))
Sanjay Patel4b198802016-02-01 22:23:39 +0000211 return IC.replaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000212
Duncan P. N. Exon Smith07ff9b02015-03-13 19:34:55 +0000213 // Ensure that the alloca array size argument has type intptr_t, so that
214 // any casting is exposed early.
215 Type *IntPtrTy = IC.getDataLayout().getIntPtrType(AI.getType());
216 if (AI.getArraySize()->getType() != IntPtrTy) {
217 Value *V = IC.Builder->CreateIntCast(AI.getArraySize(), IntPtrTy, false);
218 AI.setOperand(0, V);
219 return &AI;
220 }
221
Duncan P. N. Exon Smithc6820ec2015-03-13 19:22:03 +0000222 return nullptr;
223}
224
225Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
226 if (auto *I = simplifyAllocaArraySize(*this, AI))
227 return I;
228
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000229 if (AI.getAllocatedType()->isSized()) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000230 // If the alignment is 0 (unspecified), assign it the preferred alignment.
231 if (AI.getAlignment() == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000232 AI.setAlignment(DL.getPrefTypeAlignment(AI.getAllocatedType()));
Duncan Sands8bc764a2012-06-26 13:39:21 +0000233
234 // Move all alloca's of zero byte objects to the entry block and merge them
235 // together. Note that we only do this for alloca's, because malloc should
236 // allocate and return a unique pointer, even for a zero byte allocation.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000237 if (DL.getTypeAllocSize(AI.getAllocatedType()) == 0) {
Duncan Sands8bc764a2012-06-26 13:39:21 +0000238 // For a zero sized alloca there is no point in doing an array allocation.
239 // This is helpful if the array size is a complicated expression not used
240 // elsewhere.
241 if (AI.isArrayAllocation()) {
242 AI.setOperand(0, ConstantInt::get(AI.getArraySize()->getType(), 1));
243 return &AI;
244 }
245
246 // Get the first instruction in the entry block.
247 BasicBlock &EntryBlock = AI.getParent()->getParent()->getEntryBlock();
248 Instruction *FirstInst = EntryBlock.getFirstNonPHIOrDbg();
249 if (FirstInst != &AI) {
250 // If the entry block doesn't start with a zero-size alloca then move
251 // this one to the start of the entry block. There is no problem with
252 // dominance as the array size was forced to a constant earlier already.
253 AllocaInst *EntryAI = dyn_cast<AllocaInst>(FirstInst);
254 if (!EntryAI || !EntryAI->getAllocatedType()->isSized() ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000255 DL.getTypeAllocSize(EntryAI->getAllocatedType()) != 0) {
Duncan Sands8bc764a2012-06-26 13:39:21 +0000256 AI.moveBefore(FirstInst);
257 return &AI;
258 }
259
Richard Osborneb68053e2012-09-18 09:31:44 +0000260 // If the alignment of the entry block alloca is 0 (unspecified),
261 // assign it the preferred alignment.
262 if (EntryAI->getAlignment() == 0)
263 EntryAI->setAlignment(
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000264 DL.getPrefTypeAlignment(EntryAI->getAllocatedType()));
Duncan Sands8bc764a2012-06-26 13:39:21 +0000265 // Replace this zero-sized alloca with the one at the start of the entry
266 // block after ensuring that the address will be aligned enough for both
267 // types.
Richard Osborneb68053e2012-09-18 09:31:44 +0000268 unsigned MaxAlign = std::max(EntryAI->getAlignment(),
269 AI.getAlignment());
Duncan Sands8bc764a2012-06-26 13:39:21 +0000270 EntryAI->setAlignment(MaxAlign);
271 if (AI.getType() != EntryAI->getType())
272 return new BitCastInst(EntryAI, AI.getType());
Sanjay Patel4b198802016-02-01 22:23:39 +0000273 return replaceInstUsesWith(AI, EntryAI);
Duncan Sands8bc764a2012-06-26 13:39:21 +0000274 }
275 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000276 }
277
Eli Friedmanb14873c2012-11-26 23:04:53 +0000278 if (AI.getAlignment()) {
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000279 // Check to see if this allocation is only modified by a memcpy/memmove from
280 // a constant global whose alignment is equal to or exceeds that of the
281 // allocation. If this is the case, we can change all users to use
282 // the constant global instead. This is commonly produced by the CFE by
283 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
284 // is only subsequently read.
285 SmallVector<Instruction *, 4> ToDelete;
286 if (MemTransferInst *Copy = isOnlyCopiedFromConstantGlobal(&AI, ToDelete)) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000287 unsigned SourceAlign = getOrEnforceKnownAlignment(
Justin Bogner99798402016-08-05 01:06:44 +0000288 Copy->getSource(), AI.getAlignment(), DL, &AI, &AC, &DT);
Eli Friedmanb14873c2012-11-26 23:04:53 +0000289 if (AI.getAlignment() <= SourceAlign) {
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000290 DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n');
291 DEBUG(dbgs() << " memcpy = " << *Copy << '\n');
292 for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
Sanjay Patel4b198802016-02-01 22:23:39 +0000293 eraseInstFromFunction(*ToDelete[i]);
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000294 Constant *TheSrc = cast<Constant>(Copy->getSource());
Matt Arsenaultbbf18c62013-12-07 02:58:45 +0000295 Constant *Cast
296 = ConstantExpr::getPointerBitCastOrAddrSpaceCast(TheSrc, AI.getType());
Sanjay Patel4b198802016-02-01 22:23:39 +0000297 Instruction *NewI = replaceInstUsesWith(AI, Cast);
298 eraseInstFromFunction(*Copy);
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000299 ++NumGlobalCopies;
300 return NewI;
301 }
Chandler Carruthc908ca12012-08-21 08:39:44 +0000302 }
303 }
304
Nuno Lopes95cc4f32012-07-09 18:38:20 +0000305 // At last, use the generic allocation site handler to aggressively remove
306 // unused allocas.
307 return visitAllocSite(AI);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000308}
309
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000310/// \brief Helper to combine a load to a new type.
311///
312/// This just does the work of combining a load to a new type. It handles
313/// metadata, etc., and returns the new instruction. The \c NewTy should be the
314/// loaded *value* type. This will convert it to a pointer, cast the operand to
315/// that pointer type, load it, etc.
316///
317/// Note that this will create all of the instructions with whatever insert
318/// point the \c InstCombiner currently is using.
Mehdi Amini2668a482015-05-07 05:52:40 +0000319static LoadInst *combineLoadToNewType(InstCombiner &IC, LoadInst &LI, Type *NewTy,
320 const Twine &Suffix = "") {
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000321 Value *Ptr = LI.getPointerOperand();
322 unsigned AS = LI.getPointerAddressSpace();
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000323 SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000324 LI.getAllMetadata(MD);
325
326 LoadInst *NewLoad = IC.Builder->CreateAlignedLoad(
327 IC.Builder->CreateBitCast(Ptr, NewTy->getPointerTo(AS)),
Philip Reames6f4d0082016-05-06 22:17:01 +0000328 LI.getAlignment(), LI.isVolatile(), LI.getName() + Suffix);
329 NewLoad->setAtomic(LI.getOrdering(), LI.getSynchScope());
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)),
Philip Reames6f4d0082016-05-06 22:17:01 +0000401 SI.getAlignment(), SI.isVolatile());
402 NewStore->setAtomic(SI.getOrdering(), SI.getSynchScope());
Chandler Carruthfa11d832015-01-22 03:34:54 +0000403 for (const auto &MDPair : MD) {
404 unsigned ID = MDPair.first;
405 MDNode *N = MDPair.second;
406 // Note, essentially every kind of metadata should be preserved here! This
407 // routine is supposed to clone a store instruction changing *only its
408 // type*. The only metadata it makes sense to drop is metadata which is
409 // invalidated when the pointer type changes. This should essentially
410 // never be the case in LLVM, but we explicitly switch over only known
411 // metadata to be conservatively correct. If you are adding metadata to
412 // LLVM which pertains to stores, you almost certainly want to add it
413 // here.
414 switch (ID) {
415 case LLVMContext::MD_dbg:
416 case LLVMContext::MD_tbaa:
417 case LLVMContext::MD_prof:
418 case LLVMContext::MD_fpmath:
419 case LLVMContext::MD_tbaa_struct:
420 case LLVMContext::MD_alias_scope:
421 case LLVMContext::MD_noalias:
422 case LLVMContext::MD_nontemporal:
423 case LLVMContext::MD_mem_parallel_loop_access:
Chandler Carruthfa11d832015-01-22 03:34:54 +0000424 // All of these directly apply.
425 NewStore->setMetadata(ID, N);
426 break;
427
428 case LLVMContext::MD_invariant_load:
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000429 case LLVMContext::MD_nonnull:
Chandler Carruthfa11d832015-01-22 03:34:54 +0000430 case LLVMContext::MD_range:
Artur Pilipenko5c5011d2015-11-02 17:53:51 +0000431 case LLVMContext::MD_align:
432 case LLVMContext::MD_dereferenceable:
433 case LLVMContext::MD_dereferenceable_or_null:
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000434 // These don't apply for stores.
Chandler Carruthfa11d832015-01-22 03:34:54 +0000435 break;
436 }
437 }
438
439 return NewStore;
440}
441
JF Bastien3e2e69f2016-04-21 19:41:48 +0000442/// \brief Combine loads to match the type of their uses' value after looking
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000443/// through intervening bitcasts.
444///
445/// The core idea here is that if the result of a load is used in an operation,
446/// we should load the type most conducive to that operation. For example, when
447/// loading an integer and converting that immediately to a pointer, we should
448/// instead directly load a pointer.
449///
450/// However, this routine must never change the width of a load or the number of
451/// loads as that would introduce a semantic change. This combine is expected to
452/// be a semantic no-op which just allows loads to more closely model the types
453/// of their consuming operations.
454///
455/// Currently, we also refuse to change the precise type used for an atomic load
456/// or a volatile load. This is debatable, and might be reasonable to change
457/// later. However, it is risky in case some backend or other part of LLVM is
458/// relying on the exact type loaded to select appropriate atomic operations.
459static Instruction *combineLoadToOperationType(InstCombiner &IC, LoadInst &LI) {
Philip Reames6f4d0082016-05-06 22:17:01 +0000460 // FIXME: We could probably with some care handle both volatile and ordered
461 // atomic loads here but it isn't clear that this is important.
462 if (!LI.isUnordered())
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000463 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000464
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000465 if (LI.use_empty())
466 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000467
Arnold Schwaighofer5d335552016-09-10 18:14:57 +0000468 // swifterror values can't be bitcasted.
469 if (LI.getPointerOperand()->isSwiftError())
470 return nullptr;
471
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000472 Type *Ty = LI.getType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000473 const DataLayout &DL = IC.getDataLayout();
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000474
475 // Try to canonicalize loads which are only ever stored to operate over
476 // integers instead of any other type. We only do this when the loaded type
477 // is sized and has a size exactly the same as its store size and the store
478 // size is a legal integer type.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000479 if (!Ty->isIntegerTy() && Ty->isSized() &&
480 DL.isLegalInteger(DL.getTypeStoreSizeInBits(Ty)) &&
Sanjoy Dasba04d3a2016-08-06 02:58:48 +0000481 DL.getTypeStoreSizeInBits(Ty) == DL.getTypeSizeInBits(Ty) &&
482 !DL.isNonIntegralPointerType(Ty)) {
David Majnemer0a16c222016-08-11 21:15:00 +0000483 if (all_of(LI.users(), [&LI](User *U) {
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000484 auto *SI = dyn_cast<StoreInst>(U);
485 return SI && SI->getPointerOperand() != &LI;
486 })) {
487 LoadInst *NewLoad = combineLoadToNewType(
488 IC, LI,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000489 Type::getIntNTy(LI.getContext(), DL.getTypeStoreSizeInBits(Ty)));
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000490 // Replace all the stores with stores of the newly loaded value.
491 for (auto UI = LI.user_begin(), UE = LI.user_end(); UI != UE;) {
492 auto *SI = cast<StoreInst>(*UI++);
493 IC.Builder->SetInsertPoint(SI);
494 combineStoreToNewValue(IC, *SI, NewLoad);
Sanjay Patel4b198802016-02-01 22:23:39 +0000495 IC.eraseInstFromFunction(*SI);
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000496 }
497 assert(LI.use_empty() && "Failed to remove all users of the load!");
498 // Return the old load so the combiner can delete it safely.
499 return &LI;
500 }
501 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000502
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000503 // Fold away bit casts of the loaded value by loading the desired type.
Quentin Colombet490cfbe2016-02-11 22:30:41 +0000504 // We can do this for BitCastInsts as well as casts from and to pointer types,
505 // as long as those are noops (i.e., the source or dest type have the same
506 // bitwidth as the target's pointers).
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000507 if (LI.hasOneUse())
Quentin Colombet490cfbe2016-02-11 22:30:41 +0000508 if (auto* CI = dyn_cast<CastInst>(LI.user_back())) {
509 if (CI->isNoopCast(DL)) {
510 LoadInst *NewLoad = combineLoadToNewType(IC, LI, CI->getDestTy());
511 CI->replaceAllUsesWith(NewLoad);
512 IC.eraseInstFromFunction(*CI);
513 return &LI;
514 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000515 }
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000516
Chandler Carrutha7f247e2014-12-09 19:21:16 +0000517 // FIXME: We should also canonicalize loads of vectors when their elements are
518 // cast to other types.
Craig Topperf40110f2014-04-25 05:29:35 +0000519 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000520}
521
Mehdi Amini2668a482015-05-07 05:52:40 +0000522static Instruction *unpackLoadToAggregate(InstCombiner &IC, LoadInst &LI) {
523 // FIXME: We could probably with some care handle both volatile and atomic
524 // stores here but it isn't clear that this is important.
525 if (!LI.isSimple())
526 return nullptr;
527
528 Type *T = LI.getType();
529 if (!T->isAggregateType())
530 return nullptr;
531
Benjamin Kramerc1263532016-03-11 10:20:56 +0000532 StringRef Name = LI.getName();
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000533 assert(LI.getAlignment() && "Alignment must be set at this point");
Mehdi Amini2668a482015-05-07 05:52:40 +0000534
535 if (auto *ST = dyn_cast<StructType>(T)) {
536 // If the struct only have one element, we unpack.
Amaury Sechet61a7d622016-02-17 19:21:28 +0000537 auto NumElements = ST->getNumElements();
538 if (NumElements == 1) {
Mehdi Amini2668a482015-05-07 05:52:40 +0000539 LoadInst *NewLoad = combineLoadToNewType(IC, LI, ST->getTypeAtIndex(0U),
540 ".unpack");
Sanjay Patel4b198802016-02-01 22:23:39 +0000541 return IC.replaceInstUsesWith(LI, IC.Builder->CreateInsertValue(
Amaury Sechet61a7d622016-02-17 19:21:28 +0000542 UndefValue::get(T), NewLoad, 0, Name));
Mehdi Amini2668a482015-05-07 05:52:40 +0000543 }
Mehdi Amini1c131b32015-12-15 01:44:07 +0000544
545 // We don't want to break loads with padding here as we'd loose
546 // the knowledge that padding exists for the rest of the pipeline.
547 const DataLayout &DL = IC.getDataLayout();
548 auto *SL = DL.getStructLayout(ST);
549 if (SL->hasPadding())
550 return nullptr;
551
Amaury Sechet61a7d622016-02-17 19:21:28 +0000552 auto Align = LI.getAlignment();
553 if (!Align)
554 Align = DL.getABITypeAlignment(ST);
555
Mehdi Amini1c131b32015-12-15 01:44:07 +0000556 auto *Addr = LI.getPointerOperand();
Amaury Sechet61a7d622016-02-17 19:21:28 +0000557 auto *IdxType = Type::getInt32Ty(T->getContext());
Mehdi Amini1c131b32015-12-15 01:44:07 +0000558 auto *Zero = ConstantInt::get(IdxType, 0);
Amaury Sechet61a7d622016-02-17 19:21:28 +0000559
560 Value *V = UndefValue::get(T);
561 for (unsigned i = 0; i < NumElements; i++) {
Mehdi Amini1c131b32015-12-15 01:44:07 +0000562 Value *Indices[2] = {
563 Zero,
564 ConstantInt::get(IdxType, i),
565 };
Amaury Sechetda71cb72016-02-17 21:21:29 +0000566 auto *Ptr = IC.Builder->CreateInBoundsGEP(ST, Addr, makeArrayRef(Indices),
Benjamin Kramerc1263532016-03-11 10:20:56 +0000567 Name + ".elt");
Amaury Sechet61a7d622016-02-17 19:21:28 +0000568 auto EltAlign = MinAlign(Align, SL->getElementOffset(i));
Benjamin Kramerc1263532016-03-11 10:20:56 +0000569 auto *L = IC.Builder->CreateAlignedLoad(Ptr, EltAlign, Name + ".unpack");
Mehdi Amini1c131b32015-12-15 01:44:07 +0000570 V = IC.Builder->CreateInsertValue(V, L, i);
571 }
572
573 V->setName(Name);
Sanjay Patel4b198802016-02-01 22:23:39 +0000574 return IC.replaceInstUsesWith(LI, V);
Mehdi Amini2668a482015-05-07 05:52:40 +0000575 }
576
David Majnemer58fb0382015-05-11 05:04:22 +0000577 if (auto *AT = dyn_cast<ArrayType>(T)) {
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000578 auto *ET = AT->getElementType();
579 auto NumElements = AT->getNumElements();
580 if (NumElements == 1) {
581 LoadInst *NewLoad = combineLoadToNewType(IC, LI, ET, ".unpack");
Sanjay Patel4b198802016-02-01 22:23:39 +0000582 return IC.replaceInstUsesWith(LI, IC.Builder->CreateInsertValue(
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000583 UndefValue::get(T), NewLoad, 0, Name));
David Majnemer58fb0382015-05-11 05:04:22 +0000584 }
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000585
Davide Italianoda114122016-10-07 20:57:42 +0000586 // Bail out if the array is too large. Ideally we would like to optimize
587 // arrays of arbitrary size but this has a terrible impact on compile time.
588 // The threshold here is chosen arbitrarily, maybe needs a little bit of
589 // tuning.
590 if (NumElements > 1024)
591 return nullptr;
592
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000593 const DataLayout &DL = IC.getDataLayout();
594 auto EltSize = DL.getTypeAllocSize(ET);
595 auto Align = LI.getAlignment();
596 if (!Align)
597 Align = DL.getABITypeAlignment(T);
598
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000599 auto *Addr = LI.getPointerOperand();
600 auto *IdxType = Type::getInt64Ty(T->getContext());
601 auto *Zero = ConstantInt::get(IdxType, 0);
602
603 Value *V = UndefValue::get(T);
604 uint64_t Offset = 0;
605 for (uint64_t i = 0; i < NumElements; i++) {
606 Value *Indices[2] = {
607 Zero,
608 ConstantInt::get(IdxType, i),
609 };
610 auto *Ptr = IC.Builder->CreateInBoundsGEP(AT, Addr, makeArrayRef(Indices),
Benjamin Kramerc1263532016-03-11 10:20:56 +0000611 Name + ".elt");
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000612 auto *L = IC.Builder->CreateAlignedLoad(Ptr, MinAlign(Align, Offset),
Benjamin Kramerc1263532016-03-11 10:20:56 +0000613 Name + ".unpack");
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000614 V = IC.Builder->CreateInsertValue(V, L, i);
615 Offset += EltSize;
616 }
617
618 V->setName(Name);
619 return IC.replaceInstUsesWith(LI, V);
David Majnemer58fb0382015-05-11 05:04:22 +0000620 }
621
Mehdi Amini2668a482015-05-07 05:52:40 +0000622 return nullptr;
623}
624
Hal Finkel847e05f2015-02-20 03:05:53 +0000625// If we can determine that all possible objects pointed to by the provided
626// pointer value are, not only dereferenceable, but also definitively less than
627// or equal to the provided maximum size, then return true. Otherwise, return
628// false (constant global values and allocas fall into this category).
629//
630// FIXME: This should probably live in ValueTracking (or similar).
631static bool isObjectSizeLessThanOrEq(Value *V, uint64_t MaxSize,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000632 const DataLayout &DL) {
Hal Finkel847e05f2015-02-20 03:05:53 +0000633 SmallPtrSet<Value *, 4> Visited;
634 SmallVector<Value *, 4> Worklist(1, V);
635
636 do {
637 Value *P = Worklist.pop_back_val();
638 P = P->stripPointerCasts();
639
640 if (!Visited.insert(P).second)
641 continue;
642
643 if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
644 Worklist.push_back(SI->getTrueValue());
645 Worklist.push_back(SI->getFalseValue());
646 continue;
647 }
648
649 if (PHINode *PN = dyn_cast<PHINode>(P)) {
Pete Cooper833f34d2015-05-12 20:05:31 +0000650 for (Value *IncValue : PN->incoming_values())
651 Worklist.push_back(IncValue);
Hal Finkel847e05f2015-02-20 03:05:53 +0000652 continue;
653 }
654
655 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(P)) {
Sanjoy Das99042472016-04-17 04:30:43 +0000656 if (GA->isInterposable())
Hal Finkel847e05f2015-02-20 03:05:53 +0000657 return false;
658 Worklist.push_back(GA->getAliasee());
659 continue;
660 }
661
662 // If we know how big this object is, and it is less than MaxSize, continue
663 // searching. Otherwise, return false.
664 if (AllocaInst *AI = dyn_cast<AllocaInst>(P)) {
665 if (!AI->getAllocatedType()->isSized())
666 return false;
667
668 ConstantInt *CS = dyn_cast<ConstantInt>(AI->getArraySize());
669 if (!CS)
670 return false;
671
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000672 uint64_t TypeSize = DL.getTypeAllocSize(AI->getAllocatedType());
Hal Finkel847e05f2015-02-20 03:05:53 +0000673 // Make sure that, even if the multiplication below would wrap as an
674 // uint64_t, we still do the right thing.
675 if ((CS->getValue().zextOrSelf(128)*APInt(128, TypeSize)).ugt(MaxSize))
676 return false;
677 continue;
678 }
679
680 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
681 if (!GV->hasDefinitiveInitializer() || !GV->isConstant())
682 return false;
683
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000684 uint64_t InitSize = DL.getTypeAllocSize(GV->getValueType());
Hal Finkel847e05f2015-02-20 03:05:53 +0000685 if (InitSize > MaxSize)
686 return false;
687 continue;
688 }
689
690 return false;
691 } while (!Worklist.empty());
692
693 return true;
694}
695
696// If we're indexing into an object of a known size, and the outer index is
697// not a constant, but having any value but zero would lead to undefined
698// behavior, replace it with zero.
699//
700// For example, if we have:
701// @f.a = private unnamed_addr constant [1 x i32] [i32 12], align 4
702// ...
703// %arrayidx = getelementptr inbounds [1 x i32]* @f.a, i64 0, i64 %x
704// ... = load i32* %arrayidx, align 4
705// Then we know that we can replace %x in the GEP with i64 0.
706//
707// FIXME: We could fold any GEP index to zero that would cause UB if it were
708// not zero. Currently, we only handle the first such index. Also, we could
709// also search through non-zero constant indices if we kept track of the
710// offsets those indices implied.
711static bool canReplaceGEPIdxWithZero(InstCombiner &IC, GetElementPtrInst *GEPI,
712 Instruction *MemI, unsigned &Idx) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000713 if (GEPI->getNumOperands() < 2)
Hal Finkel847e05f2015-02-20 03:05:53 +0000714 return false;
715
716 // Find the first non-zero index of a GEP. If all indices are zero, return
717 // one past the last index.
718 auto FirstNZIdx = [](const GetElementPtrInst *GEPI) {
719 unsigned I = 1;
720 for (unsigned IE = GEPI->getNumOperands(); I != IE; ++I) {
721 Value *V = GEPI->getOperand(I);
722 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
723 if (CI->isZero())
724 continue;
725
726 break;
727 }
728
729 return I;
730 };
731
732 // Skip through initial 'zero' indices, and find the corresponding pointer
733 // type. See if the next index is not a constant.
734 Idx = FirstNZIdx(GEPI);
735 if (Idx == GEPI->getNumOperands())
736 return false;
737 if (isa<Constant>(GEPI->getOperand(Idx)))
738 return false;
739
740 SmallVector<Value *, 4> Ops(GEPI->idx_begin(), GEPI->idx_begin() + Idx);
Eduard Burtescu19eb0312016-01-19 17:28:00 +0000741 Type *AllocTy =
742 GetElementPtrInst::getIndexedType(GEPI->getSourceElementType(), Ops);
Hal Finkel847e05f2015-02-20 03:05:53 +0000743 if (!AllocTy || !AllocTy->isSized())
744 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000745 const DataLayout &DL = IC.getDataLayout();
746 uint64_t TyAllocSize = DL.getTypeAllocSize(AllocTy);
Hal Finkel847e05f2015-02-20 03:05:53 +0000747
748 // If there are more indices after the one we might replace with a zero, make
749 // sure they're all non-negative. If any of them are negative, the overall
750 // address being computed might be before the base address determined by the
751 // first non-zero index.
752 auto IsAllNonNegative = [&]() {
753 for (unsigned i = Idx+1, e = GEPI->getNumOperands(); i != e; ++i) {
754 bool KnownNonNegative, KnownNegative;
755 IC.ComputeSignBit(GEPI->getOperand(i), KnownNonNegative,
756 KnownNegative, 0, MemI);
757 if (KnownNonNegative)
758 continue;
759 return false;
760 }
761
762 return true;
763 };
764
765 // FIXME: If the GEP is not inbounds, and there are extra indices after the
766 // one we'll replace, those could cause the address computation to wrap
767 // (rendering the IsAllNonNegative() check below insufficient). We can do
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000768 // better, ignoring zero indices (and other indices we can prove small
Hal Finkel847e05f2015-02-20 03:05:53 +0000769 // enough not to wrap).
770 if (Idx+1 != GEPI->getNumOperands() && !GEPI->isInBounds())
771 return false;
772
773 // Note that isObjectSizeLessThanOrEq will return true only if the pointer is
774 // also known to be dereferenceable.
775 return isObjectSizeLessThanOrEq(GEPI->getOperand(0), TyAllocSize, DL) &&
776 IsAllNonNegative();
777}
778
779// If we're indexing into an object with a variable index for the memory
780// access, but the object has only one element, we can assume that the index
781// will always be zero. If we replace the GEP, return it.
782template <typename T>
783static Instruction *replaceGEPIdxWithZero(InstCombiner &IC, Value *Ptr,
784 T &MemI) {
785 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr)) {
786 unsigned Idx;
787 if (canReplaceGEPIdxWithZero(IC, GEPI, &MemI, Idx)) {
788 Instruction *NewGEPI = GEPI->clone();
789 NewGEPI->setOperand(Idx,
790 ConstantInt::get(GEPI->getOperand(Idx)->getType(), 0));
791 NewGEPI->insertBefore(GEPI);
792 MemI.setOperand(MemI.getPointerOperandIndex(), NewGEPI);
793 return NewGEPI;
794 }
795 }
796
797 return nullptr;
798}
799
Chris Lattnera65e2f72010-01-05 05:57:49 +0000800Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
801 Value *Op = LI.getOperand(0);
802
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000803 // Try to canonicalize the loaded type.
804 if (Instruction *Res = combineLoadToOperationType(*this, LI))
805 return Res;
806
Chris Lattnera65e2f72010-01-05 05:57:49 +0000807 // Attempt to improve the alignment.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000808 unsigned KnownAlign = getOrEnforceKnownAlignment(
Justin Bogner99798402016-08-05 01:06:44 +0000809 Op, DL.getPrefTypeAlignment(LI.getType()), DL, &LI, &AC, &DT);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000810 unsigned LoadAlign = LI.getAlignment();
811 unsigned EffectiveLoadAlign =
812 LoadAlign != 0 ? LoadAlign : DL.getABITypeAlignment(LI.getType());
Dan Gohman36196602010-08-03 18:20:32 +0000813
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000814 if (KnownAlign > EffectiveLoadAlign)
815 LI.setAlignment(KnownAlign);
816 else if (LoadAlign == 0)
817 LI.setAlignment(EffectiveLoadAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000818
Hal Finkel847e05f2015-02-20 03:05:53 +0000819 // Replace GEP indices if possible.
820 if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Op, LI)) {
821 Worklist.Add(NewGEPI);
822 return &LI;
823 }
824
Mehdi Amini2668a482015-05-07 05:52:40 +0000825 if (Instruction *Res = unpackLoadToAggregate(*this, LI))
826 return Res;
827
Chris Lattnera65e2f72010-01-05 05:57:49 +0000828 // Do really simple store-to-load forwarding and load CSE, to catch cases
Duncan Sands75b5d272011-02-15 09:23:02 +0000829 // where there are several consecutive memory accesses to the same location,
Chris Lattnera65e2f72010-01-05 05:57:49 +0000830 // separated by a few arithmetic operations.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000831 BasicBlock::iterator BBI(LI);
Eli Friedmanbd254a62016-06-16 02:33:42 +0000832 bool IsLoadCSE = false;
Larisse Voufo532bf712015-09-18 19:14:35 +0000833 if (Value *AvailableVal =
Eduard Burtescue2a69172016-01-22 01:51:51 +0000834 FindAvailableLoadedValue(&LI, LI.getParent(), BBI,
Eli Friedman02419a92016-08-08 04:10:22 +0000835 DefMaxInstsToScan, AA, &IsLoadCSE)) {
Eli Friedmanbd254a62016-06-16 02:33:42 +0000836 if (IsLoadCSE) {
837 LoadInst *NLI = cast<LoadInst>(AvailableVal);
Bjorn Steinbrinka91fd092015-07-10 06:55:44 +0000838 unsigned KnownIDs[] = {
Artur Pilipenko5c5011d2015-11-02 17:53:51 +0000839 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
840 LLVMContext::MD_noalias, LLVMContext::MD_range,
841 LLVMContext::MD_invariant_load, LLVMContext::MD_nonnull,
842 LLVMContext::MD_invariant_group, LLVMContext::MD_align,
843 LLVMContext::MD_dereferenceable,
844 LLVMContext::MD_dereferenceable_or_null};
Bjorn Steinbrinka91fd092015-07-10 06:55:44 +0000845 combineMetadata(NLI, &LI, KnownIDs);
Bjorn Steinbrinka91fd092015-07-10 06:55:44 +0000846 };
847
Sanjay Patel4b198802016-02-01 22:23:39 +0000848 return replaceInstUsesWith(
Chandler Carruth1a3c2c42014-11-25 08:20:27 +0000849 LI, Builder->CreateBitOrPointerCast(AvailableVal, LI.getType(),
850 LI.getName() + ".cast"));
Bjorn Steinbrinka91fd092015-07-10 06:55:44 +0000851 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000852
Philip Reames3ac07182016-04-21 17:45:05 +0000853 // None of the following transforms are legal for volatile/ordered atomic
854 // loads. Most of them do apply for unordered atomics.
855 if (!LI.isUnordered()) return nullptr;
Philip Reamesac550902016-04-21 17:03:33 +0000856
Chris Lattnera65e2f72010-01-05 05:57:49 +0000857 // load(gep null, ...) -> unreachable
858 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
859 const Value *GEPI0 = GEPI->getOperand(0);
860 // TODO: Consider a target hook for valid address spaces for this xform.
861 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
862 // Insert a new store to null instruction before the load to indicate
863 // that this code is not reachable. We do this instead of inserting
864 // an unreachable instruction directly because we cannot modify the
865 // CFG.
866 new StoreInst(UndefValue::get(LI.getType()),
867 Constant::getNullValue(Op->getType()), &LI);
Sanjay Patel4b198802016-02-01 22:23:39 +0000868 return replaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattnera65e2f72010-01-05 05:57:49 +0000869 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +0000870 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000871
872 // load null/undef -> unreachable
873 // TODO: Consider a target hook for valid address spaces for this xform.
874 if (isa<UndefValue>(Op) ||
875 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
876 // Insert a new store to null instruction before the load to indicate that
877 // this code is not reachable. We do this instead of inserting an
878 // unreachable instruction directly because we cannot modify the CFG.
879 new StoreInst(UndefValue::get(LI.getType()),
880 Constant::getNullValue(Op->getType()), &LI);
Sanjay Patel4b198802016-02-01 22:23:39 +0000881 return replaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattnera65e2f72010-01-05 05:57:49 +0000882 }
883
Chris Lattnera65e2f72010-01-05 05:57:49 +0000884 if (Op->hasOneUse()) {
885 // Change select and PHI nodes to select values instead of addresses: this
886 // helps alias analysis out a lot, allows many others simplifications, and
887 // exposes redundancy in the code.
888 //
889 // Note that we cannot do the transformation unless we know that the
890 // introduced loads cannot trap! Something like this is valid as long as
891 // the condition is always false: load (select bool %C, int* null, int* %G),
892 // but it would not be valid if we transformed it to load from null
893 // unconditionally.
894 //
895 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
896 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Bob Wilson56600a12010-01-30 04:42:39 +0000897 unsigned Align = LI.getAlignment();
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +0000898 if (isSafeToLoadUnconditionally(SI->getOperand(1), Align, DL, SI) &&
899 isSafeToLoadUnconditionally(SI->getOperand(2), Align, DL, SI)) {
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000900 LoadInst *V1 = Builder->CreateLoad(SI->getOperand(1),
Bob Wilson56600a12010-01-30 04:42:39 +0000901 SI->getOperand(1)->getName()+".val");
Bob Wilson4b71b6c2010-01-30 00:41:10 +0000902 LoadInst *V2 = Builder->CreateLoad(SI->getOperand(2),
Bob Wilson56600a12010-01-30 04:42:39 +0000903 SI->getOperand(2)->getName()+".val");
Philip Reamesa98c7ea2016-04-21 17:59:40 +0000904 assert(LI.isUnordered() && "implied by above");
Bob Wilson56600a12010-01-30 04:42:39 +0000905 V1->setAlignment(Align);
Philip Reamesa98c7ea2016-04-21 17:59:40 +0000906 V1->setAtomic(LI.getOrdering(), LI.getSynchScope());
Bob Wilson56600a12010-01-30 04:42:39 +0000907 V2->setAlignment(Align);
Philip Reamesa98c7ea2016-04-21 17:59:40 +0000908 V2->setAtomic(LI.getOrdering(), LI.getSynchScope());
Chris Lattnera65e2f72010-01-05 05:57:49 +0000909 return SelectInst::Create(SI->getCondition(), V1, V2);
910 }
911
912 // load (select (cond, null, P)) -> load P
Larisse Voufo532bf712015-09-18 19:14:35 +0000913 if (isa<ConstantPointerNull>(SI->getOperand(1)) &&
Philip Reames5ad26c32014-12-29 22:46:21 +0000914 LI.getPointerAddressSpace() == 0) {
915 LI.setOperand(0, SI->getOperand(2));
916 return &LI;
917 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000918
919 // load (select (cond, P, null)) -> load P
Philip Reames5ad26c32014-12-29 22:46:21 +0000920 if (isa<ConstantPointerNull>(SI->getOperand(2)) &&
921 LI.getPointerAddressSpace() == 0) {
922 LI.setOperand(0, SI->getOperand(1));
923 return &LI;
924 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000925 }
926 }
Craig Topperf40110f2014-04-25 05:29:35 +0000927 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000928}
929
Arch D. Robisonbe0490a2016-04-25 22:22:39 +0000930/// \brief Look for extractelement/insertvalue sequence that acts like a bitcast.
931///
932/// \returns underlying value that was "cast", or nullptr otherwise.
933///
934/// For example, if we have:
935///
936/// %E0 = extractelement <2 x double> %U, i32 0
937/// %V0 = insertvalue [2 x double] undef, double %E0, 0
938/// %E1 = extractelement <2 x double> %U, i32 1
939/// %V1 = insertvalue [2 x double] %V0, double %E1, 1
940///
941/// and the layout of a <2 x double> is isomorphic to a [2 x double],
942/// then %V1 can be safely approximated by a conceptual "bitcast" of %U.
943/// Note that %U may contain non-undef values where %V1 has undef.
944static Value *likeBitCastFromVector(InstCombiner &IC, Value *V) {
945 Value *U = nullptr;
946 while (auto *IV = dyn_cast<InsertValueInst>(V)) {
947 auto *E = dyn_cast<ExtractElementInst>(IV->getInsertedValueOperand());
948 if (!E)
949 return nullptr;
950 auto *W = E->getVectorOperand();
951 if (!U)
952 U = W;
953 else if (U != W)
954 return nullptr;
955 auto *CI = dyn_cast<ConstantInt>(E->getIndexOperand());
956 if (!CI || IV->getNumIndices() != 1 || CI->getZExtValue() != *IV->idx_begin())
957 return nullptr;
958 V = IV->getAggregateOperand();
959 }
960 if (!isa<UndefValue>(V) ||!U)
961 return nullptr;
962
963 auto *UT = cast<VectorType>(U->getType());
964 auto *VT = V->getType();
965 // Check that types UT and VT are bitwise isomorphic.
966 const auto &DL = IC.getDataLayout();
967 if (DL.getTypeStoreSizeInBits(UT) != DL.getTypeStoreSizeInBits(VT)) {
968 return nullptr;
969 }
970 if (auto *AT = dyn_cast<ArrayType>(VT)) {
971 if (AT->getNumElements() != UT->getNumElements())
972 return nullptr;
973 } else {
974 auto *ST = cast<StructType>(VT);
975 if (ST->getNumElements() != UT->getNumElements())
976 return nullptr;
977 for (const auto *EltT : ST->elements()) {
978 if (EltT != UT->getElementType())
979 return nullptr;
980 }
981 }
982 return U;
983}
984
Chandler Carruth816d26f2014-11-25 10:09:51 +0000985/// \brief Combine stores to match the type of value being stored.
986///
987/// The core idea here is that the memory does not have any intrinsic type and
988/// where we can we should match the type of a store to the type of value being
989/// stored.
990///
991/// However, this routine must never change the width of a store or the number of
992/// stores as that would introduce a semantic change. This combine is expected to
993/// be a semantic no-op which just allows stores to more closely model the types
994/// of their incoming values.
995///
996/// Currently, we also refuse to change the precise type used for an atomic or
997/// volatile store. This is debatable, and might be reasonable to change later.
998/// However, it is risky in case some backend or other part of LLVM is relying
999/// on the exact type stored to select appropriate atomic operations.
1000///
1001/// \returns true if the store was successfully combined away. This indicates
1002/// the caller must erase the store instruction. We have to let the caller erase
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00001003/// the store instruction as otherwise there is no way to signal whether it was
Chandler Carruth816d26f2014-11-25 10:09:51 +00001004/// combined or not: IC.EraseInstFromFunction returns a null pointer.
1005static bool combineStoreToValueType(InstCombiner &IC, StoreInst &SI) {
Philip Reames6f4d0082016-05-06 22:17:01 +00001006 // FIXME: We could probably with some care handle both volatile and ordered
1007 // atomic stores here but it isn't clear that this is important.
1008 if (!SI.isUnordered())
Chandler Carruth816d26f2014-11-25 10:09:51 +00001009 return false;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001010
Arnold Schwaighofer5d335552016-09-10 18:14:57 +00001011 // swifterror values can't be bitcasted.
1012 if (SI.getPointerOperand()->isSwiftError())
1013 return false;
1014
Chandler Carruth816d26f2014-11-25 10:09:51 +00001015 Value *V = SI.getValueOperand();
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001016
Chandler Carruth816d26f2014-11-25 10:09:51 +00001017 // Fold away bit casts of the stored value by storing the original type.
1018 if (auto *BC = dyn_cast<BitCastInst>(V)) {
Chandler Carrutha7f247e2014-12-09 19:21:16 +00001019 V = BC->getOperand(0);
Chandler Carruth2135b972015-01-21 23:45:01 +00001020 combineStoreToNewValue(IC, SI, V);
Chandler Carruth816d26f2014-11-25 10:09:51 +00001021 return true;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001022 }
1023
Arch D. Robisonbe0490a2016-04-25 22:22:39 +00001024 if (Value *U = likeBitCastFromVector(IC, V)) {
1025 combineStoreToNewValue(IC, SI, U);
1026 return true;
1027 }
1028
JF Bastienc22d2992016-04-21 19:53:39 +00001029 // FIXME: We should also canonicalize stores of vectors when their elements
1030 // are cast to other types.
Chandler Carruth816d26f2014-11-25 10:09:51 +00001031 return false;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001032}
1033
Mehdi Aminib344ac92015-03-14 22:19:33 +00001034static bool unpackStoreToAggregate(InstCombiner &IC, StoreInst &SI) {
1035 // FIXME: We could probably with some care handle both volatile and atomic
1036 // stores here but it isn't clear that this is important.
1037 if (!SI.isSimple())
1038 return false;
1039
1040 Value *V = SI.getValueOperand();
1041 Type *T = V->getType();
1042
1043 if (!T->isAggregateType())
1044 return false;
1045
Mehdi Amini2668a482015-05-07 05:52:40 +00001046 if (auto *ST = dyn_cast<StructType>(T)) {
Mehdi Aminib344ac92015-03-14 22:19:33 +00001047 // If the struct only have one element, we unpack.
Mehdi Amini1c131b32015-12-15 01:44:07 +00001048 unsigned Count = ST->getNumElements();
1049 if (Count == 1) {
Mehdi Aminib344ac92015-03-14 22:19:33 +00001050 V = IC.Builder->CreateExtractValue(V, 0);
1051 combineStoreToNewValue(IC, SI, V);
1052 return true;
1053 }
Mehdi Amini1c131b32015-12-15 01:44:07 +00001054
1055 // We don't want to break loads with padding here as we'd loose
1056 // the knowledge that padding exists for the rest of the pipeline.
1057 const DataLayout &DL = IC.getDataLayout();
1058 auto *SL = DL.getStructLayout(ST);
1059 if (SL->hasPadding())
1060 return false;
1061
Amaury Sechet61a7d622016-02-17 19:21:28 +00001062 auto Align = SI.getAlignment();
1063 if (!Align)
1064 Align = DL.getABITypeAlignment(ST);
1065
NAKAMURA Takumiec6b1fc2015-12-15 09:37:31 +00001066 SmallString<16> EltName = V->getName();
1067 EltName += ".elt";
Mehdi Amini1c131b32015-12-15 01:44:07 +00001068 auto *Addr = SI.getPointerOperand();
NAKAMURA Takumiec6b1fc2015-12-15 09:37:31 +00001069 SmallString<16> AddrName = Addr->getName();
1070 AddrName += ".repack";
Amaury Sechet61a7d622016-02-17 19:21:28 +00001071
Mehdi Amini1c131b32015-12-15 01:44:07 +00001072 auto *IdxType = Type::getInt32Ty(ST->getContext());
1073 auto *Zero = ConstantInt::get(IdxType, 0);
1074 for (unsigned i = 0; i < Count; i++) {
1075 Value *Indices[2] = {
1076 Zero,
1077 ConstantInt::get(IdxType, i),
1078 };
Amaury Sechetda71cb72016-02-17 21:21:29 +00001079 auto *Ptr = IC.Builder->CreateInBoundsGEP(ST, Addr, makeArrayRef(Indices),
1080 AddrName);
Mehdi Amini1c131b32015-12-15 01:44:07 +00001081 auto *Val = IC.Builder->CreateExtractValue(V, i, EltName);
Amaury Sechet61a7d622016-02-17 19:21:28 +00001082 auto EltAlign = MinAlign(Align, SL->getElementOffset(i));
1083 IC.Builder->CreateAlignedStore(Val, Ptr, EltAlign);
Mehdi Amini1c131b32015-12-15 01:44:07 +00001084 }
1085
1086 return true;
Mehdi Aminib344ac92015-03-14 22:19:33 +00001087 }
1088
David Majnemer75364602015-05-11 05:04:27 +00001089 if (auto *AT = dyn_cast<ArrayType>(T)) {
1090 // If the array only have one element, we unpack.
Amaury Sechet3b8b2ea2016-03-02 22:36:45 +00001091 auto NumElements = AT->getNumElements();
1092 if (NumElements == 1) {
David Majnemer75364602015-05-11 05:04:27 +00001093 V = IC.Builder->CreateExtractValue(V, 0);
1094 combineStoreToNewValue(IC, SI, V);
1095 return true;
1096 }
Amaury Sechet3b8b2ea2016-03-02 22:36:45 +00001097
Davide Italianof6988d22016-10-07 21:53:09 +00001098 // Bail out if the array is too large. Ideally we would like to optimize
1099 // arrays of arbitrary size but this has a terrible impact on compile time.
1100 // The threshold here is chosen arbitrarily, maybe needs a little bit of
1101 // tuning.
1102 if (NumElements > 1024)
1103 return false;
1104
Amaury Sechet3b8b2ea2016-03-02 22:36:45 +00001105 const DataLayout &DL = IC.getDataLayout();
1106 auto EltSize = DL.getTypeAllocSize(AT->getElementType());
1107 auto Align = SI.getAlignment();
1108 if (!Align)
1109 Align = DL.getABITypeAlignment(T);
1110
1111 SmallString<16> EltName = V->getName();
1112 EltName += ".elt";
1113 auto *Addr = SI.getPointerOperand();
1114 SmallString<16> AddrName = Addr->getName();
1115 AddrName += ".repack";
1116
1117 auto *IdxType = Type::getInt64Ty(T->getContext());
1118 auto *Zero = ConstantInt::get(IdxType, 0);
1119
1120 uint64_t Offset = 0;
1121 for (uint64_t i = 0; i < NumElements; i++) {
1122 Value *Indices[2] = {
1123 Zero,
1124 ConstantInt::get(IdxType, i),
1125 };
1126 auto *Ptr = IC.Builder->CreateInBoundsGEP(AT, Addr, makeArrayRef(Indices),
1127 AddrName);
1128 auto *Val = IC.Builder->CreateExtractValue(V, i, EltName);
1129 auto EltAlign = MinAlign(Align, Offset);
1130 IC.Builder->CreateAlignedStore(Val, Ptr, EltAlign);
1131 Offset += EltSize;
1132 }
1133
1134 return true;
David Majnemer75364602015-05-11 05:04:27 +00001135 }
1136
Mehdi Aminib344ac92015-03-14 22:19:33 +00001137 return false;
1138}
1139
Chris Lattnera65e2f72010-01-05 05:57:49 +00001140/// equivalentAddressValues - Test if A and B will obviously have the same
1141/// value. This includes recognizing that %t0 and %t1 will have the same
1142/// value in code like this:
1143/// %t0 = getelementptr \@a, 0, 3
1144/// store i32 0, i32* %t0
1145/// %t1 = getelementptr \@a, 0, 3
1146/// %t2 = load i32* %t1
1147///
1148static bool equivalentAddressValues(Value *A, Value *B) {
1149 // Test if the values are trivially equivalent.
1150 if (A == B) return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001151
Chris Lattnera65e2f72010-01-05 05:57:49 +00001152 // Test if the values come form identical arithmetic instructions.
1153 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
1154 // its only used to compare two uses within the same basic block, which
1155 // means that they'll always either have the same value or one of them
1156 // will have an undefined value.
1157 if (isa<BinaryOperator>(A) ||
1158 isa<CastInst>(A) ||
1159 isa<PHINode>(A) ||
1160 isa<GetElementPtrInst>(A))
1161 if (Instruction *BI = dyn_cast<Instruction>(B))
1162 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
1163 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001164
Chris Lattnera65e2f72010-01-05 05:57:49 +00001165 // Otherwise they may not be equivalent.
1166 return false;
1167}
1168
Chris Lattnera65e2f72010-01-05 05:57:49 +00001169Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
1170 Value *Val = SI.getOperand(0);
1171 Value *Ptr = SI.getOperand(1);
1172
Chandler Carruth816d26f2014-11-25 10:09:51 +00001173 // Try to canonicalize the stored type.
1174 if (combineStoreToValueType(*this, SI))
Sanjay Patel4b198802016-02-01 22:23:39 +00001175 return eraseInstFromFunction(SI);
Chandler Carruth816d26f2014-11-25 10:09:51 +00001176
Chris Lattnera65e2f72010-01-05 05:57:49 +00001177 // Attempt to improve the alignment.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001178 unsigned KnownAlign = getOrEnforceKnownAlignment(
Justin Bogner99798402016-08-05 01:06:44 +00001179 Ptr, DL.getPrefTypeAlignment(Val->getType()), DL, &SI, &AC, &DT);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001180 unsigned StoreAlign = SI.getAlignment();
1181 unsigned EffectiveStoreAlign =
1182 StoreAlign != 0 ? StoreAlign : DL.getABITypeAlignment(Val->getType());
Dan Gohman36196602010-08-03 18:20:32 +00001183
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001184 if (KnownAlign > EffectiveStoreAlign)
1185 SI.setAlignment(KnownAlign);
1186 else if (StoreAlign == 0)
1187 SI.setAlignment(EffectiveStoreAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001188
Mehdi Aminib344ac92015-03-14 22:19:33 +00001189 // Try to canonicalize the stored type.
1190 if (unpackStoreToAggregate(*this, SI))
Sanjay Patel4b198802016-02-01 22:23:39 +00001191 return eraseInstFromFunction(SI);
Mehdi Aminib344ac92015-03-14 22:19:33 +00001192
Hal Finkel847e05f2015-02-20 03:05:53 +00001193 // Replace GEP indices if possible.
1194 if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Ptr, SI)) {
1195 Worklist.Add(NewGEPI);
1196 return &SI;
1197 }
1198
Philip Reamesd7a6cc82015-12-17 22:19:27 +00001199 // Don't hack volatile/ordered stores.
1200 // FIXME: Some bits are legal for ordered atomic stores; needs refactoring.
1201 if (!SI.isUnordered()) return nullptr;
Eli Friedman8bc586e2011-08-15 22:09:40 +00001202
1203 // If the RHS is an alloca with a single use, zapify the store, making the
1204 // alloca dead.
1205 if (Ptr->hasOneUse()) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001206 if (isa<AllocaInst>(Ptr))
Sanjay Patel4b198802016-02-01 22:23:39 +00001207 return eraseInstFromFunction(SI);
Eli Friedman8bc586e2011-08-15 22:09:40 +00001208 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
1209 if (isa<AllocaInst>(GEP->getOperand(0))) {
1210 if (GEP->getOperand(0)->hasOneUse())
Sanjay Patel4b198802016-02-01 22:23:39 +00001211 return eraseInstFromFunction(SI);
Eli Friedman8bc586e2011-08-15 22:09:40 +00001212 }
1213 }
1214 }
1215
Chris Lattnera65e2f72010-01-05 05:57:49 +00001216 // Do really simple DSE, to catch cases where there are several consecutive
1217 // stores to the same location, separated by a few arithmetic operations. This
1218 // situation often occurs with bitfield accesses.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00001219 BasicBlock::iterator BBI(SI);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001220 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
1221 --ScanInsts) {
1222 --BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +00001223 // Don't count debug info directives, lest they affect codegen,
1224 // and we skip pointer-to-pointer bitcasts, which are NOPs.
1225 if (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +00001226 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +00001227 ScanInsts++;
1228 continue;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001229 }
1230
Chris Lattnera65e2f72010-01-05 05:57:49 +00001231 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
1232 // Prev store isn't volatile, and stores to the same location?
Philip Reamesd7a6cc82015-12-17 22:19:27 +00001233 if (PrevSI->isUnordered() && equivalentAddressValues(PrevSI->getOperand(1),
Eli Friedman8bc586e2011-08-15 22:09:40 +00001234 SI.getOperand(1))) {
Chris Lattnera65e2f72010-01-05 05:57:49 +00001235 ++NumDeadStore;
1236 ++BBI;
Sanjay Patel4b198802016-02-01 22:23:39 +00001237 eraseInstFromFunction(*PrevSI);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001238 continue;
1239 }
1240 break;
1241 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001242
Chris Lattnera65e2f72010-01-05 05:57:49 +00001243 // If this is a load, we have to stop. However, if the loaded value is from
1244 // the pointer we're loading and is producing the pointer we're storing,
1245 // then *this* store is dead (X = load P; store X -> P).
1246 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Philip Reamesd7a6cc82015-12-17 22:19:27 +00001247 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr)) {
1248 assert(SI.isUnordered() && "can't eliminate ordering operation");
Sanjay Patel4b198802016-02-01 22:23:39 +00001249 return eraseInstFromFunction(SI);
Philip Reamesd7a6cc82015-12-17 22:19:27 +00001250 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001251
Chris Lattnera65e2f72010-01-05 05:57:49 +00001252 // Otherwise, this is a load from some other location. Stores before it
1253 // may not be dead.
1254 break;
1255 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001256
Chris Lattnera65e2f72010-01-05 05:57:49 +00001257 // Don't skip over loads or things that can modify memory.
1258 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
1259 break;
1260 }
Chris Lattnera65e2f72010-01-05 05:57:49 +00001261
1262 // store X, null -> turns into 'unreachable' in SimplifyCFG
1263 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
1264 if (!isa<UndefValue>(Val)) {
1265 SI.setOperand(0, UndefValue::get(Val->getType()));
1266 if (Instruction *U = dyn_cast<Instruction>(Val))
1267 Worklist.Add(U); // Dropped a use.
1268 }
Craig Topperf40110f2014-04-25 05:29:35 +00001269 return nullptr; // Do not modify these!
Chris Lattnera65e2f72010-01-05 05:57:49 +00001270 }
1271
1272 // store undef, Ptr -> noop
1273 if (isa<UndefValue>(Val))
Sanjay Patel4b198802016-02-01 22:23:39 +00001274 return eraseInstFromFunction(SI);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001275
Chris Lattnera65e2f72010-01-05 05:57:49 +00001276 // If this store is the last instruction in the basic block (possibly
Victor Hernandez5f5abd52010-01-21 23:07:15 +00001277 // excepting debug info instructions), and if the block ends with an
1278 // unconditional branch, try to move it to the successor block.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00001279 BBI = SI.getIterator();
Chris Lattnera65e2f72010-01-05 05:57:49 +00001280 do {
1281 ++BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +00001282 } while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +00001283 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()));
Chris Lattnera65e2f72010-01-05 05:57:49 +00001284 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
1285 if (BI->isUnconditional())
1286 if (SimplifyStoreAtEndOfBlock(SI))
Craig Topperf40110f2014-04-25 05:29:35 +00001287 return nullptr; // xform done!
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001288
Craig Topperf40110f2014-04-25 05:29:35 +00001289 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001290}
1291
1292/// SimplifyStoreAtEndOfBlock - Turn things like:
1293/// if () { *P = v1; } else { *P = v2 }
1294/// into a phi node with a store in the successor.
1295///
1296/// Simplify things like:
1297/// *P = v1; if () { *P = v2; }
1298/// into a phi node with a store in the successor.
1299///
1300bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
Philip Reames5f0e3692016-04-22 20:53:32 +00001301 assert(SI.isUnordered() &&
1302 "this code has not been auditted for volatile or ordered store case");
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00001303
Chris Lattnera65e2f72010-01-05 05:57:49 +00001304 BasicBlock *StoreBB = SI.getParent();
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001305
Chris Lattnera65e2f72010-01-05 05:57:49 +00001306 // Check to see if the successor block has exactly two incoming edges. If
1307 // so, see if the other predecessor contains a store to the same location.
1308 // if so, insert a PHI node (if needed) and move the stores down.
1309 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001310
Chris Lattnera65e2f72010-01-05 05:57:49 +00001311 // Determine whether Dest has exactly two predecessors and, if so, compute
1312 // the other predecessor.
1313 pred_iterator PI = pred_begin(DestBB);
Gabor Greif1b787df2010-07-12 15:48:26 +00001314 BasicBlock *P = *PI;
Craig Topperf40110f2014-04-25 05:29:35 +00001315 BasicBlock *OtherBB = nullptr;
Gabor Greif1b787df2010-07-12 15:48:26 +00001316
1317 if (P != StoreBB)
1318 OtherBB = P;
1319
1320 if (++PI == pred_end(DestBB))
Chris Lattnera65e2f72010-01-05 05:57:49 +00001321 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001322
Gabor Greif1b787df2010-07-12 15:48:26 +00001323 P = *PI;
1324 if (P != StoreBB) {
Chris Lattnera65e2f72010-01-05 05:57:49 +00001325 if (OtherBB)
1326 return false;
Gabor Greif1b787df2010-07-12 15:48:26 +00001327 OtherBB = P;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001328 }
1329 if (++PI != pred_end(DestBB))
1330 return false;
1331
1332 // Bail out if all the relevant blocks aren't distinct (this can happen,
1333 // for example, if SI is in an infinite loop)
1334 if (StoreBB == DestBB || OtherBB == DestBB)
1335 return false;
1336
1337 // Verify that the other block ends in a branch and is not otherwise empty.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00001338 BasicBlock::iterator BBI(OtherBB->getTerminator());
Chris Lattnera65e2f72010-01-05 05:57:49 +00001339 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
1340 if (!OtherBr || BBI == OtherBB->begin())
1341 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001342
Chris Lattnera65e2f72010-01-05 05:57:49 +00001343 // If the other block ends in an unconditional branch, check for the 'if then
1344 // else' case. there is an instruction before the branch.
Craig Topperf40110f2014-04-25 05:29:35 +00001345 StoreInst *OtherStore = nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001346 if (OtherBr->isUnconditional()) {
1347 --BBI;
1348 // Skip over debugging info.
Victor Hernandez5f8c8c02010-01-22 19:05:05 +00001349 while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +00001350 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +00001351 if (BBI==OtherBB->begin())
1352 return false;
1353 --BBI;
1354 }
Eli Friedman8bc586e2011-08-15 22:09:40 +00001355 // If this isn't a store, isn't a store to the same location, or is not the
1356 // right kind of store, bail out.
Chris Lattnera65e2f72010-01-05 05:57:49 +00001357 OtherStore = dyn_cast<StoreInst>(BBI);
1358 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +00001359 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +00001360 return false;
1361 } else {
1362 // Otherwise, the other block ended with a conditional branch. If one of the
1363 // destinations is StoreBB, then we have the if/then case.
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001364 if (OtherBr->getSuccessor(0) != StoreBB &&
Chris Lattnera65e2f72010-01-05 05:57:49 +00001365 OtherBr->getSuccessor(1) != StoreBB)
1366 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001367
Chris Lattnera65e2f72010-01-05 05:57:49 +00001368 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
1369 // if/then triangle. See if there is a store to the same ptr as SI that
1370 // lives in OtherBB.
1371 for (;; --BBI) {
1372 // Check to see if we find the matching store.
1373 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
1374 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +00001375 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +00001376 return false;
1377 break;
1378 }
1379 // If we find something that may be using or overwriting the stored
1380 // value, or if we run out of instructions, we can't do the xform.
1381 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
1382 BBI == OtherBB->begin())
1383 return false;
1384 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001385
Chris Lattnera65e2f72010-01-05 05:57:49 +00001386 // In order to eliminate the store in OtherBr, we have to
1387 // make sure nothing reads or overwrites the stored value in
1388 // StoreBB.
1389 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
1390 // FIXME: This should really be AA driven.
1391 if (I->mayReadFromMemory() || I->mayWriteToMemory())
1392 return false;
1393 }
1394 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001395
Chris Lattnera65e2f72010-01-05 05:57:49 +00001396 // Insert a PHI node now if we need it.
1397 Value *MergedVal = OtherStore->getOperand(0);
1398 if (MergedVal != SI.getOperand(0)) {
Jay Foad52131342011-03-30 11:28:46 +00001399 PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge");
Chris Lattnera65e2f72010-01-05 05:57:49 +00001400 PN->addIncoming(SI.getOperand(0), SI.getParent());
1401 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
1402 MergedVal = InsertNewInstBefore(PN, DestBB->front());
1403 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001404
Chris Lattnera65e2f72010-01-05 05:57:49 +00001405 // Advance to a place where it is safe to insert the new store and
1406 // insert it.
Bill Wendling8ddfc092011-08-16 20:45:24 +00001407 BBI = DestBB->getFirstInsertionPt();
Eli Friedman35211c62011-05-27 00:19:40 +00001408 StoreInst *NewSI = new StoreInst(MergedVal, SI.getOperand(1),
Eli Friedman8bc586e2011-08-15 22:09:40 +00001409 SI.isVolatile(),
1410 SI.getAlignment(),
1411 SI.getOrdering(),
1412 SI.getSynchScope());
Eli Friedman35211c62011-05-27 00:19:40 +00001413 InsertNewInstBefore(NewSI, *BBI);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001414 NewSI->setDebugLoc(OtherStore->getDebugLoc());
Eli Friedman35211c62011-05-27 00:19:40 +00001415
Hal Finkelcc39b672014-07-24 12:16:19 +00001416 // If the two stores had AA tags, merge them.
1417 AAMDNodes AATags;
1418 SI.getAAMetadata(AATags);
1419 if (AATags) {
1420 OtherStore->getAAMetadata(AATags, /* Merge = */ true);
1421 NewSI->setAAMetadata(AATags);
1422 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001423
Chris Lattnera65e2f72010-01-05 05:57:49 +00001424 // Nuke the old stores.
Sanjay Patel4b198802016-02-01 22:23:39 +00001425 eraseInstFromFunction(SI);
1426 eraseInstFromFunction(*OtherStore);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001427 return true;
1428}