blob: b9b1e7b6e8aec1b1678fd83c2ad680bb069843a1 [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"
Yaxun Liuba01ed02017-02-10 21:46:07 +000015#include "llvm/ADT/MapVector.h"
NAKAMURA Takumiec6b1fc2015-12-15 09:37:31 +000016#include "llvm/ADT/SmallString.h"
Chandler Carruthed0881b2012-12-03 16:50:05 +000017#include "llvm/ADT/Statistic.h"
Dan Gohman826bdf82010-05-28 16:19:17 +000018#include "llvm/Analysis/Loads.h"
David Blaikie31b98d22018-06-04 21:23:21 +000019#include "llvm/Transforms/Utils/Local.h"
Peter Collingbourneecdd58f2016-10-21 19:59:26 +000020#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000021#include "llvm/IR/DataLayout.h"
Vedant Kumar238533e2018-11-19 19:55:02 +000022#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000023#include "llvm/IR/IntrinsicInst.h"
Yaxun Liuba01ed02017-02-10 21:46:07 +000024#include "llvm/IR/LLVMContext.h"
Charles Davis33d1dc02015-02-25 05:10:25 +000025#include "llvm/IR/MDBuilder.h"
Alexey Bataevec95c6c2017-12-08 15:32:10 +000026#include "llvm/IR/PatternMatch.h"
Chris Lattnera65e2f72010-01-05 05:57:49 +000027#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnera65e2f72010-01-05 05:57:49 +000028using namespace llvm;
Alexey Bataevec95c6c2017-12-08 15:32:10 +000029using namespace PatternMatch;
Chris Lattnera65e2f72010-01-05 05:57:49 +000030
Chandler Carruth964daaa2014-04-22 02:55:47 +000031#define DEBUG_TYPE "instcombine"
32
Chandler Carruthc908ca12012-08-21 08:39:44 +000033STATISTIC(NumDeadStore, "Number of dead stores eliminated");
34STATISTIC(NumGlobalCopies, "Number of allocas copied from constant global");
35
36/// pointsToConstantGlobal - Return true if V (possibly indirectly) points to
37/// some part of a constant global variable. This intentionally only accepts
38/// constant expressions because we can't rewrite arbitrary instructions.
39static bool pointsToConstantGlobal(Value *V) {
40 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
41 return GV->isConstant();
Matt Arsenault607281772014-04-24 00:01:09 +000042
43 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Chandler Carruthc908ca12012-08-21 08:39:44 +000044 if (CE->getOpcode() == Instruction::BitCast ||
Matt Arsenault607281772014-04-24 00:01:09 +000045 CE->getOpcode() == Instruction::AddrSpaceCast ||
Chandler Carruthc908ca12012-08-21 08:39:44 +000046 CE->getOpcode() == Instruction::GetElementPtr)
47 return pointsToConstantGlobal(CE->getOperand(0));
Matt Arsenault607281772014-04-24 00:01:09 +000048 }
Chandler Carruthc908ca12012-08-21 08:39:44 +000049 return false;
50}
51
52/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
53/// pointer to an alloca. Ignore any reads of the pointer, return false if we
54/// see any stores or other unknown uses. If we see pointer arithmetic, keep
55/// track of whether it moves the pointer (with IsOffset) but otherwise traverse
56/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
57/// the alloca, and if the source pointer is a pointer to a constant global, we
58/// can optimize this.
59static bool
60isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
Reid Kleckner813dab22014-07-01 21:36:20 +000061 SmallVectorImpl<Instruction *> &ToDelete) {
Chandler Carruthc908ca12012-08-21 08:39:44 +000062 // We track lifetime intrinsics as we encounter them. If we decide to go
63 // ahead and replace the value with the global, this lets the caller quickly
64 // eliminate the markers.
65
Reid Kleckner813dab22014-07-01 21:36:20 +000066 SmallVector<std::pair<Value *, bool>, 35> ValuesToInspect;
David Majnemer0a16c222016-08-11 21:15:00 +000067 ValuesToInspect.emplace_back(V, false);
Reid Kleckner813dab22014-07-01 21:36:20 +000068 while (!ValuesToInspect.empty()) {
69 auto ValuePair = ValuesToInspect.pop_back_val();
70 const bool IsOffset = ValuePair.second;
71 for (auto &U : ValuePair.first->uses()) {
David Majnemer0a16c222016-08-11 21:15:00 +000072 auto *I = cast<Instruction>(U.getUser());
Chandler Carruthc908ca12012-08-21 08:39:44 +000073
David Majnemer0a16c222016-08-11 21:15:00 +000074 if (auto *LI = dyn_cast<LoadInst>(I)) {
Reid Kleckner813dab22014-07-01 21:36:20 +000075 // Ignore non-volatile loads, they are always ok.
76 if (!LI->isSimple()) return false;
Chandler Carruthc908ca12012-08-21 08:39:44 +000077 continue;
78 }
Reid Kleckner813dab22014-07-01 21:36:20 +000079
80 if (isa<BitCastInst>(I) || isa<AddrSpaceCastInst>(I)) {
81 // If uses of the bitcast are ok, we are ok.
David Majnemer0a16c222016-08-11 21:15:00 +000082 ValuesToInspect.emplace_back(I, IsOffset);
Reid Kleckner813dab22014-07-01 21:36:20 +000083 continue;
84 }
David Majnemer0a16c222016-08-11 21:15:00 +000085 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
Reid Kleckner813dab22014-07-01 21:36:20 +000086 // If the GEP has all zero indices, it doesn't offset the pointer. If it
87 // doesn't, it does.
David Majnemer0a16c222016-08-11 21:15:00 +000088 ValuesToInspect.emplace_back(I, IsOffset || !GEP->hasAllZeroIndices());
Reid Kleckner813dab22014-07-01 21:36:20 +000089 continue;
90 }
91
Benjamin Kramer3a09ef62015-04-10 14:50:08 +000092 if (auto CS = CallSite(I)) {
Reid Kleckner813dab22014-07-01 21:36:20 +000093 // If this is the function being called then we treat it like a load and
94 // ignore it.
95 if (CS.isCallee(&U))
96 continue;
97
David Majnemer02f47872015-12-23 09:58:41 +000098 unsigned DataOpNo = CS.getDataOperandNo(&U);
99 bool IsArgOperand = CS.isArgOperand(&U);
100
Reid Kleckner813dab22014-07-01 21:36:20 +0000101 // Inalloca arguments are clobbered by the call.
David Majnemer02f47872015-12-23 09:58:41 +0000102 if (IsArgOperand && CS.isInAllocaArgument(DataOpNo))
Reid Kleckner813dab22014-07-01 21:36:20 +0000103 return false;
104
105 // If this is a readonly/readnone call site, then we know it is just a
106 // load (but one that potentially returns the value itself), so we can
107 // ignore it if we know that the value isn't captured.
108 if (CS.onlyReadsMemory() &&
David Majnemer02f47872015-12-23 09:58:41 +0000109 (CS.getInstruction()->use_empty() || CS.doesNotCapture(DataOpNo)))
Reid Kleckner813dab22014-07-01 21:36:20 +0000110 continue;
111
112 // If this is being passed as a byval argument, the caller is making a
113 // copy, so it is only a read of the alloca.
David Majnemer02f47872015-12-23 09:58:41 +0000114 if (IsArgOperand && CS.isByValArgument(DataOpNo))
Reid Kleckner813dab22014-07-01 21:36:20 +0000115 continue;
116 }
117
118 // Lifetime intrinsics can be handled by the caller.
119 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
120 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
121 II->getIntrinsicID() == Intrinsic::lifetime_end) {
122 assert(II->use_empty() && "Lifetime markers have no result to use!");
123 ToDelete.push_back(II);
124 continue;
125 }
126 }
127
128 // If this is isn't our memcpy/memmove, reject it as something we can't
129 // handle.
130 MemTransferInst *MI = dyn_cast<MemTransferInst>(I);
131 if (!MI)
132 return false;
133
134 // If the transfer is using the alloca as a source of the transfer, then
135 // ignore it since it is a load (unless the transfer is volatile).
136 if (U.getOperandNo() == 1) {
137 if (MI->isVolatile()) return false;
138 continue;
139 }
140
141 // If we already have seen a copy, reject the second one.
142 if (TheCopy) return false;
143
144 // If the pointer has been offset from the start of the alloca, we can't
145 // safely handle this.
146 if (IsOffset) return false;
147
148 // If the memintrinsic isn't using the alloca as the dest, reject it.
149 if (U.getOperandNo() != 0) return false;
150
151 // If the source of the memcpy/move is not a constant global, reject it.
152 if (!pointsToConstantGlobal(MI->getSource()))
153 return false;
154
155 // Otherwise, the transform is safe. Remember the copy instruction.
156 TheCopy = MI;
Chandler Carruthc908ca12012-08-21 08:39:44 +0000157 }
Chandler Carruthc908ca12012-08-21 08:39:44 +0000158 }
159 return true;
160}
161
162/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
163/// modified by a copy from a constant global. If we can prove this, we can
164/// replace any uses of the alloca with uses of the global directly.
165static MemTransferInst *
166isOnlyCopiedFromConstantGlobal(AllocaInst *AI,
167 SmallVectorImpl<Instruction *> &ToDelete) {
Craig Topperf40110f2014-04-25 05:29:35 +0000168 MemTransferInst *TheCopy = nullptr;
Chandler Carruthc908ca12012-08-21 08:39:44 +0000169 if (isOnlyCopiedFromConstantGlobal(AI, TheCopy, ToDelete))
170 return TheCopy;
Craig Topperf40110f2014-04-25 05:29:35 +0000171 return nullptr;
Chandler Carruthc908ca12012-08-21 08:39:44 +0000172}
173
Vitaly Bukadf19ad42017-06-24 01:35:19 +0000174/// Returns true if V is dereferenceable for size of alloca.
175static bool isDereferenceableForAllocaSize(const Value *V, const AllocaInst *AI,
176 const DataLayout &DL) {
177 if (AI->isArrayAllocation())
178 return false;
179 uint64_t AllocaSize = DL.getTypeStoreSize(AI->getAllocatedType());
180 if (!AllocaSize)
181 return false;
182 return isDereferenceableAndAlignedPointer(V, AI->getAlignment(),
183 APInt(64, AllocaSize), DL);
184}
185
Duncan P. N. Exon Smithc6820ec2015-03-13 19:22:03 +0000186static Instruction *simplifyAllocaArraySize(InstCombiner &IC, AllocaInst &AI) {
Duncan P. N. Exon Smith720762e2015-03-13 19:30:44 +0000187 // Check for array size of 1 (scalar allocation).
Duncan P. N. Exon Smithbe95b4a2015-03-13 19:42:09 +0000188 if (!AI.isArrayAllocation()) {
189 // i32 1 is the canonical array size for scalar allocations.
190 if (AI.getArraySize()->getType()->isIntegerTy(32))
191 return nullptr;
192
193 // Canonicalize it.
Craig Topperbb4069e2017-07-07 23:16:26 +0000194 Value *V = IC.Builder.getInt32(1);
Duncan P. N. Exon Smithbe95b4a2015-03-13 19:42:09 +0000195 AI.setOperand(0, V);
196 return &AI;
197 }
Duncan P. N. Exon Smith720762e2015-03-13 19:30:44 +0000198
Chris Lattnera65e2f72010-01-05 05:57:49 +0000199 // 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 +0000200 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
Simon Pilgrim82edf8d2018-08-13 16:50:20 +0000201 if (C->getValue().getActiveBits() <= 64) {
202 Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
203 AllocaInst *New = IC.Builder.CreateAlloca(NewTy, nullptr, AI.getName());
204 New->setAlignment(AI.getAlignment());
Chris Lattnera65e2f72010-01-05 05:57:49 +0000205
Simon Pilgrim82edf8d2018-08-13 16:50:20 +0000206 // Scan to the end of the allocation instructions, to skip over a block of
207 // allocas if possible...also skip interleaved debug info
208 //
209 BasicBlock::iterator It(New);
210 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It))
211 ++It;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000212
Simon Pilgrim82edf8d2018-08-13 16:50:20 +0000213 // Now that I is pointing to the first non-allocation-inst in the block,
214 // insert our getelementptr instruction...
215 //
216 Type *IdxTy = IC.getDataLayout().getIntPtrType(AI.getType());
217 Value *NullIdx = Constant::getNullValue(IdxTy);
218 Value *Idx[2] = {NullIdx, NullIdx};
219 Instruction *GEP =
220 GetElementPtrInst::CreateInBounds(New, Idx, New->getName() + ".sub");
221 IC.InsertNewInstBefore(GEP, *It);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000222
Simon Pilgrim82edf8d2018-08-13 16:50:20 +0000223 // Now make everything use the getelementptr instead of the original
224 // allocation.
225 return IC.replaceInstUsesWith(AI, GEP);
226 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000227 }
228
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000229 if (isa<UndefValue>(AI.getArraySize()))
Sanjay Patel4b198802016-02-01 22:23:39 +0000230 return IC.replaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000231
Duncan P. N. Exon Smith07ff9b02015-03-13 19:34:55 +0000232 // Ensure that the alloca array size argument has type intptr_t, so that
233 // any casting is exposed early.
234 Type *IntPtrTy = IC.getDataLayout().getIntPtrType(AI.getType());
235 if (AI.getArraySize()->getType() != IntPtrTy) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000236 Value *V = IC.Builder.CreateIntCast(AI.getArraySize(), IntPtrTy, false);
Duncan P. N. Exon Smith07ff9b02015-03-13 19:34:55 +0000237 AI.setOperand(0, V);
238 return &AI;
239 }
240
Duncan P. N. Exon Smithc6820ec2015-03-13 19:22:03 +0000241 return nullptr;
242}
243
Benjamin Kramer03ab8a32017-02-10 22:26:35 +0000244namespace {
Yaxun Liuba01ed02017-02-10 21:46:07 +0000245// If I and V are pointers in different address space, it is not allowed to
246// use replaceAllUsesWith since I and V have different types. A
247// non-target-specific transformation should not use addrspacecast on V since
248// the two address space may be disjoint depending on target.
249//
250// This class chases down uses of the old pointer until reaching the load
251// instructions, then replaces the old pointer in the load instructions with
252// the new pointer. If during the chasing it sees bitcast or GEP, it will
253// create new bitcast or GEP with the new pointer and use them in the load
254// instruction.
255class PointerReplacer {
256public:
257 PointerReplacer(InstCombiner &IC) : IC(IC) {}
258 void replacePointer(Instruction &I, Value *V);
259
260private:
261 void findLoadAndReplace(Instruction &I);
262 void replace(Instruction *I);
263 Value *getReplacement(Value *I);
264
265 SmallVector<Instruction *, 4> Path;
266 MapVector<Value *, Value *> WorkMap;
267 InstCombiner &IC;
268};
Benjamin Kramer03ab8a32017-02-10 22:26:35 +0000269} // end anonymous namespace
Yaxun Liuba01ed02017-02-10 21:46:07 +0000270
271void PointerReplacer::findLoadAndReplace(Instruction &I) {
272 for (auto U : I.users()) {
273 auto *Inst = dyn_cast<Instruction>(&*U);
274 if (!Inst)
275 return;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000276 LLVM_DEBUG(dbgs() << "Found pointer user: " << *U << '\n');
Yaxun Liuba01ed02017-02-10 21:46:07 +0000277 if (isa<LoadInst>(Inst)) {
278 for (auto P : Path)
279 replace(P);
280 replace(Inst);
281 } else if (isa<GetElementPtrInst>(Inst) || isa<BitCastInst>(Inst)) {
282 Path.push_back(Inst);
283 findLoadAndReplace(*Inst);
284 Path.pop_back();
285 } else {
286 return;
287 }
288 }
289}
290
291Value *PointerReplacer::getReplacement(Value *V) {
292 auto Loc = WorkMap.find(V);
293 if (Loc != WorkMap.end())
294 return Loc->second;
295 return nullptr;
296}
297
298void PointerReplacer::replace(Instruction *I) {
299 if (getReplacement(I))
300 return;
301
302 if (auto *LT = dyn_cast<LoadInst>(I)) {
303 auto *V = getReplacement(LT->getPointerOperand());
304 assert(V && "Operand not replaced");
305 auto *NewI = new LoadInst(V);
306 NewI->takeName(LT);
307 IC.InsertNewInstWith(NewI, *LT);
308 IC.replaceInstUsesWith(*LT, NewI);
309 WorkMap[LT] = NewI;
310 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
311 auto *V = getReplacement(GEP->getPointerOperand());
312 assert(V && "Operand not replaced");
313 SmallVector<Value *, 8> Indices;
314 Indices.append(GEP->idx_begin(), GEP->idx_end());
315 auto *NewI = GetElementPtrInst::Create(
316 V->getType()->getPointerElementType(), V, Indices);
317 IC.InsertNewInstWith(NewI, *GEP);
318 NewI->takeName(GEP);
319 WorkMap[GEP] = NewI;
320 } else if (auto *BC = dyn_cast<BitCastInst>(I)) {
321 auto *V = getReplacement(BC->getOperand(0));
322 assert(V && "Operand not replaced");
323 auto *NewT = PointerType::get(BC->getType()->getPointerElementType(),
324 V->getType()->getPointerAddressSpace());
325 auto *NewI = new BitCastInst(V, NewT);
326 IC.InsertNewInstWith(NewI, *BC);
327 NewI->takeName(BC);
Yaxun Liue6d1ce52017-02-24 20:27:25 +0000328 WorkMap[BC] = NewI;
Yaxun Liuba01ed02017-02-10 21:46:07 +0000329 } else {
330 llvm_unreachable("should never reach here");
331 }
332}
333
334void PointerReplacer::replacePointer(Instruction &I, Value *V) {
Benjamin Kramer684c87b2017-02-10 22:04:17 +0000335#ifndef NDEBUG
Yaxun Liuba01ed02017-02-10 21:46:07 +0000336 auto *PT = cast<PointerType>(I.getType());
337 auto *NT = cast<PointerType>(V->getType());
338 assert(PT != NT && PT->getElementType() == NT->getElementType() &&
339 "Invalid usage");
Benjamin Kramer684c87b2017-02-10 22:04:17 +0000340#endif
Yaxun Liuba01ed02017-02-10 21:46:07 +0000341 WorkMap[&I] = V;
342 findLoadAndReplace(I);
343}
344
Duncan P. N. Exon Smithc6820ec2015-03-13 19:22:03 +0000345Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
346 if (auto *I = simplifyAllocaArraySize(*this, AI))
347 return I;
348
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000349 if (AI.getAllocatedType()->isSized()) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000350 // If the alignment is 0 (unspecified), assign it the preferred alignment.
351 if (AI.getAlignment() == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000352 AI.setAlignment(DL.getPrefTypeAlignment(AI.getAllocatedType()));
Duncan Sands8bc764a2012-06-26 13:39:21 +0000353
354 // Move all alloca's of zero byte objects to the entry block and merge them
355 // together. Note that we only do this for alloca's, because malloc should
356 // allocate and return a unique pointer, even for a zero byte allocation.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000357 if (DL.getTypeAllocSize(AI.getAllocatedType()) == 0) {
Duncan Sands8bc764a2012-06-26 13:39:21 +0000358 // For a zero sized alloca there is no point in doing an array allocation.
359 // This is helpful if the array size is a complicated expression not used
360 // elsewhere.
361 if (AI.isArrayAllocation()) {
362 AI.setOperand(0, ConstantInt::get(AI.getArraySize()->getType(), 1));
363 return &AI;
364 }
365
366 // Get the first instruction in the entry block.
367 BasicBlock &EntryBlock = AI.getParent()->getParent()->getEntryBlock();
368 Instruction *FirstInst = EntryBlock.getFirstNonPHIOrDbg();
369 if (FirstInst != &AI) {
370 // If the entry block doesn't start with a zero-size alloca then move
371 // this one to the start of the entry block. There is no problem with
372 // dominance as the array size was forced to a constant earlier already.
373 AllocaInst *EntryAI = dyn_cast<AllocaInst>(FirstInst);
374 if (!EntryAI || !EntryAI->getAllocatedType()->isSized() ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000375 DL.getTypeAllocSize(EntryAI->getAllocatedType()) != 0) {
Duncan Sands8bc764a2012-06-26 13:39:21 +0000376 AI.moveBefore(FirstInst);
377 return &AI;
378 }
379
Richard Osborneb68053e2012-09-18 09:31:44 +0000380 // If the alignment of the entry block alloca is 0 (unspecified),
381 // assign it the preferred alignment.
382 if (EntryAI->getAlignment() == 0)
383 EntryAI->setAlignment(
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000384 DL.getPrefTypeAlignment(EntryAI->getAllocatedType()));
Duncan Sands8bc764a2012-06-26 13:39:21 +0000385 // Replace this zero-sized alloca with the one at the start of the entry
386 // block after ensuring that the address will be aligned enough for both
387 // types.
Richard Osborneb68053e2012-09-18 09:31:44 +0000388 unsigned MaxAlign = std::max(EntryAI->getAlignment(),
389 AI.getAlignment());
Duncan Sands8bc764a2012-06-26 13:39:21 +0000390 EntryAI->setAlignment(MaxAlign);
391 if (AI.getType() != EntryAI->getType())
392 return new BitCastInst(EntryAI, AI.getType());
Sanjay Patel4b198802016-02-01 22:23:39 +0000393 return replaceInstUsesWith(AI, EntryAI);
Duncan Sands8bc764a2012-06-26 13:39:21 +0000394 }
395 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000396 }
397
Eli Friedmanb14873c2012-11-26 23:04:53 +0000398 if (AI.getAlignment()) {
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000399 // Check to see if this allocation is only modified by a memcpy/memmove from
400 // a constant global whose alignment is equal to or exceeds that of the
401 // allocation. If this is the case, we can change all users to use
402 // the constant global instead. This is commonly produced by the CFE by
403 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
404 // is only subsequently read.
405 SmallVector<Instruction *, 4> ToDelete;
406 if (MemTransferInst *Copy = isOnlyCopiedFromConstantGlobal(&AI, ToDelete)) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000407 unsigned SourceAlign = getOrEnforceKnownAlignment(
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000408 Copy->getSource(), AI.getAlignment(), DL, &AI, &AC, &DT);
Vitaly Bukadf19ad42017-06-24 01:35:19 +0000409 if (AI.getAlignment() <= SourceAlign &&
410 isDereferenceableForAllocaSize(Copy->getSource(), &AI, DL)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000411 LLVM_DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n');
412 LLVM_DEBUG(dbgs() << " memcpy = " << *Copy << '\n');
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000413 for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
Sanjay Patel4b198802016-02-01 22:23:39 +0000414 eraseInstFromFunction(*ToDelete[i]);
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000415 Constant *TheSrc = cast<Constant>(Copy->getSource());
Yaxun Liuba01ed02017-02-10 21:46:07 +0000416 auto *SrcTy = TheSrc->getType();
417 auto *DestTy = PointerType::get(AI.getType()->getPointerElementType(),
418 SrcTy->getPointerAddressSpace());
419 Constant *Cast =
420 ConstantExpr::getPointerBitCastOrAddrSpaceCast(TheSrc, DestTy);
421 if (AI.getType()->getPointerAddressSpace() ==
422 SrcTy->getPointerAddressSpace()) {
423 Instruction *NewI = replaceInstUsesWith(AI, Cast);
424 eraseInstFromFunction(*Copy);
425 ++NumGlobalCopies;
426 return NewI;
427 } else {
428 PointerReplacer PtrReplacer(*this);
429 PtrReplacer.replacePointer(AI, Cast);
430 ++NumGlobalCopies;
431 }
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000432 }
Chandler Carruthc908ca12012-08-21 08:39:44 +0000433 }
434 }
435
Nuno Lopes95cc4f32012-07-09 18:38:20 +0000436 // At last, use the generic allocation site handler to aggressively remove
437 // unused allocas.
438 return visitAllocSite(AI);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000439}
440
Philip Reames89e92d22016-12-01 20:17:06 +0000441// Are we allowed to form a atomic load or store of this type?
442static bool isSupportedAtomicType(Type *Ty) {
Vedant Kumarb3091da2018-07-06 20:17:42 +0000443 return Ty->isIntOrPtrTy() || Ty->isFloatingPointTy();
Philip Reames89e92d22016-12-01 20:17:06 +0000444}
445
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000446/// Helper to combine a load to a new type.
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000447///
448/// This just does the work of combining a load to a new type. It handles
449/// metadata, etc., and returns the new instruction. The \c NewTy should be the
450/// loaded *value* type. This will convert it to a pointer, cast the operand to
451/// that pointer type, load it, etc.
452///
453/// Note that this will create all of the instructions with whatever insert
454/// point the \c InstCombiner currently is using.
Mehdi Amini2668a482015-05-07 05:52:40 +0000455static LoadInst *combineLoadToNewType(InstCombiner &IC, LoadInst &LI, Type *NewTy,
456 const Twine &Suffix = "") {
Philip Reames89e92d22016-12-01 20:17:06 +0000457 assert((!LI.isAtomic() || isSupportedAtomicType(NewTy)) &&
458 "can't fold an atomic load to requested type");
Alexey Bataev7c9ad0d2018-05-21 17:46:34 +0000459
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000460 Value *Ptr = LI.getPointerOperand();
461 unsigned AS = LI.getPointerAddressSpace();
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000462 SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000463 LI.getAllMetadata(MD);
464
Alexey Bataev7c9ad0d2018-05-21 17:46:34 +0000465 Value *NewPtr = nullptr;
466 if (!(match(Ptr, m_BitCast(m_Value(NewPtr))) &&
467 NewPtr->getType()->getPointerElementType() == NewTy &&
468 NewPtr->getType()->getPointerAddressSpace() == AS))
469 NewPtr = IC.Builder.CreateBitCast(Ptr, NewTy->getPointerTo(AS));
470
Craig Topperbb4069e2017-07-07 23:16:26 +0000471 LoadInst *NewLoad = IC.Builder.CreateAlignedLoad(
Alexey Bataev7c9ad0d2018-05-21 17:46:34 +0000472 NewPtr, LI.getAlignment(), LI.isVolatile(), LI.getName() + Suffix);
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +0000473 NewLoad->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
Charles Davis33d1dc02015-02-25 05:10:25 +0000474 MDBuilder MDB(NewLoad->getContext());
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000475 for (const auto &MDPair : MD) {
476 unsigned ID = MDPair.first;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000477 MDNode *N = MDPair.second;
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000478 // Note, essentially every kind of metadata should be preserved here! This
479 // routine is supposed to clone a load instruction changing *only its type*.
480 // The only metadata it makes sense to drop is metadata which is invalidated
481 // when the pointer type changes. This should essentially never be the case
482 // in LLVM, but we explicitly switch over only known metadata to be
483 // conservatively correct. If you are adding metadata to LLVM which pertains
484 // to loads, you almost certainly want to add it here.
485 switch (ID) {
486 case LLVMContext::MD_dbg:
487 case LLVMContext::MD_tbaa:
488 case LLVMContext::MD_prof:
489 case LLVMContext::MD_fpmath:
490 case LLVMContext::MD_tbaa_struct:
491 case LLVMContext::MD_invariant_load:
492 case LLVMContext::MD_alias_scope:
493 case LLVMContext::MD_noalias:
Philip Reames5a3f5f72014-10-21 00:13:20 +0000494 case LLVMContext::MD_nontemporal:
495 case LLVMContext::MD_mem_parallel_loop_access:
Michael Kruse978ba612018-12-20 04:58:07 +0000496 case LLVMContext::MD_access_group:
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000497 // All of these directly apply.
498 NewLoad->setMetadata(ID, N);
499 break;
500
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000501 case LLVMContext::MD_nonnull:
Chandler Carruth2abb65a2017-06-26 03:31:31 +0000502 copyNonnullMetadata(LI, N, *NewLoad);
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000503 break;
Artur Pilipenko5c5011d2015-11-02 17:53:51 +0000504 case LLVMContext::MD_align:
505 case LLVMContext::MD_dereferenceable:
506 case LLVMContext::MD_dereferenceable_or_null:
507 // These only directly apply if the new type is also a pointer.
508 if (NewTy->isPointerTy())
509 NewLoad->setMetadata(ID, N);
510 break;
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000511 case LLVMContext::MD_range:
Chandler Carruth2abb65a2017-06-26 03:31:31 +0000512 copyRangeMetadata(IC.getDataLayout(), LI, N, *NewLoad);
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000513 break;
514 }
515 }
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000516 return NewLoad;
517}
518
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000519/// Combine a store to a new type.
Chandler Carruthfa11d832015-01-22 03:34:54 +0000520///
521/// Returns the newly created store instruction.
522static StoreInst *combineStoreToNewValue(InstCombiner &IC, StoreInst &SI, Value *V) {
Philip Reames89e92d22016-12-01 20:17:06 +0000523 assert((!SI.isAtomic() || isSupportedAtomicType(V->getType())) &&
524 "can't fold an atomic store of requested type");
Fangrui Songf78650a2018-07-30 19:41:25 +0000525
Chandler Carruthfa11d832015-01-22 03:34:54 +0000526 Value *Ptr = SI.getPointerOperand();
527 unsigned AS = SI.getPointerAddressSpace();
528 SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
529 SI.getAllMetadata(MD);
530
Craig Topperbb4069e2017-07-07 23:16:26 +0000531 StoreInst *NewStore = IC.Builder.CreateAlignedStore(
532 V, IC.Builder.CreateBitCast(Ptr, V->getType()->getPointerTo(AS)),
Philip Reames6f4d0082016-05-06 22:17:01 +0000533 SI.getAlignment(), SI.isVolatile());
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +0000534 NewStore->setAtomic(SI.getOrdering(), SI.getSyncScopeID());
Chandler Carruthfa11d832015-01-22 03:34:54 +0000535 for (const auto &MDPair : MD) {
536 unsigned ID = MDPair.first;
537 MDNode *N = MDPair.second;
538 // Note, essentially every kind of metadata should be preserved here! This
539 // routine is supposed to clone a store instruction changing *only its
540 // type*. The only metadata it makes sense to drop is metadata which is
541 // invalidated when the pointer type changes. This should essentially
542 // never be the case in LLVM, but we explicitly switch over only known
543 // metadata to be conservatively correct. If you are adding metadata to
544 // LLVM which pertains to stores, you almost certainly want to add it
545 // here.
546 switch (ID) {
547 case LLVMContext::MD_dbg:
548 case LLVMContext::MD_tbaa:
549 case LLVMContext::MD_prof:
550 case LLVMContext::MD_fpmath:
551 case LLVMContext::MD_tbaa_struct:
552 case LLVMContext::MD_alias_scope:
553 case LLVMContext::MD_noalias:
554 case LLVMContext::MD_nontemporal:
555 case LLVMContext::MD_mem_parallel_loop_access:
Chandler Carruthfa11d832015-01-22 03:34:54 +0000556 // All of these directly apply.
557 NewStore->setMetadata(ID, N);
558 break;
559
560 case LLVMContext::MD_invariant_load:
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000561 case LLVMContext::MD_nonnull:
Chandler Carruthfa11d832015-01-22 03:34:54 +0000562 case LLVMContext::MD_range:
Artur Pilipenko5c5011d2015-11-02 17:53:51 +0000563 case LLVMContext::MD_align:
564 case LLVMContext::MD_dereferenceable:
565 case LLVMContext::MD_dereferenceable_or_null:
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000566 // These don't apply for stores.
Chandler Carruthfa11d832015-01-22 03:34:54 +0000567 break;
568 }
569 }
570
571 return NewStore;
572}
573
Alexey Bataevec95c6c2017-12-08 15:32:10 +0000574/// Returns true if instruction represent minmax pattern like:
575/// select ((cmp load V1, load V2), V1, V2).
576static bool isMinMaxWithLoads(Value *V) {
577 assert(V->getType()->isPointerTy() && "Expected pointer type.");
578 // Ignore possible ty* to ixx* bitcast.
579 V = peekThroughBitcast(V);
580 // Check that select is select ((cmp load V1, load V2), V1, V2) - minmax
581 // pattern.
582 CmpInst::Predicate Pred;
583 Instruction *L1;
584 Instruction *L2;
585 Value *LHS;
586 Value *RHS;
587 if (!match(V, m_Select(m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2)),
588 m_Value(LHS), m_Value(RHS))))
589 return false;
590 return (match(L1, m_Load(m_Specific(LHS))) &&
591 match(L2, m_Load(m_Specific(RHS)))) ||
592 (match(L1, m_Load(m_Specific(RHS))) &&
593 match(L2, m_Load(m_Specific(LHS))));
594}
595
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000596/// Combine loads to match the type of their uses' value after looking
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000597/// through intervening bitcasts.
598///
599/// The core idea here is that if the result of a load is used in an operation,
600/// we should load the type most conducive to that operation. For example, when
601/// loading an integer and converting that immediately to a pointer, we should
602/// instead directly load a pointer.
603///
604/// However, this routine must never change the width of a load or the number of
605/// loads as that would introduce a semantic change. This combine is expected to
606/// be a semantic no-op which just allows loads to more closely model the types
607/// of their consuming operations.
608///
609/// Currently, we also refuse to change the precise type used for an atomic load
610/// or a volatile load. This is debatable, and might be reasonable to change
611/// later. However, it is risky in case some backend or other part of LLVM is
612/// relying on the exact type loaded to select appropriate atomic operations.
613static Instruction *combineLoadToOperationType(InstCombiner &IC, LoadInst &LI) {
Philip Reames6f4d0082016-05-06 22:17:01 +0000614 // FIXME: We could probably with some care handle both volatile and ordered
615 // atomic loads here but it isn't clear that this is important.
616 if (!LI.isUnordered())
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000617 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000618
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000619 if (LI.use_empty())
620 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000621
Arnold Schwaighofer5d335552016-09-10 18:14:57 +0000622 // swifterror values can't be bitcasted.
623 if (LI.getPointerOperand()->isSwiftError())
624 return nullptr;
625
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000626 Type *Ty = LI.getType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000627 const DataLayout &DL = IC.getDataLayout();
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000628
629 // Try to canonicalize loads which are only ever stored to operate over
630 // integers instead of any other type. We only do this when the loaded type
631 // is sized and has a size exactly the same as its store size and the store
632 // size is a legal integer type.
Alexey Bataevec95c6c2017-12-08 15:32:10 +0000633 // Do not perform canonicalization if minmax pattern is found (to avoid
634 // infinite loop).
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000635 if (!Ty->isIntegerTy() && Ty->isSized() &&
636 DL.isLegalInteger(DL.getTypeStoreSizeInBits(Ty)) &&
Sanjoy Dasba04d3a2016-08-06 02:58:48 +0000637 DL.getTypeStoreSizeInBits(Ty) == DL.getTypeSizeInBits(Ty) &&
Alexey Bataevec95c6c2017-12-08 15:32:10 +0000638 !DL.isNonIntegralPointerType(Ty) &&
639 !isMinMaxWithLoads(
640 peekThroughBitcast(LI.getPointerOperand(), /*OneUseOnly=*/true))) {
David Majnemer0a16c222016-08-11 21:15:00 +0000641 if (all_of(LI.users(), [&LI](User *U) {
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000642 auto *SI = dyn_cast<StoreInst>(U);
Arnold Schwaighoferc3685632017-01-31 17:53:49 +0000643 return SI && SI->getPointerOperand() != &LI &&
644 !SI->getPointerOperand()->isSwiftError();
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000645 })) {
646 LoadInst *NewLoad = combineLoadToNewType(
647 IC, LI,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000648 Type::getIntNTy(LI.getContext(), DL.getTypeStoreSizeInBits(Ty)));
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000649 // Replace all the stores with stores of the newly loaded value.
650 for (auto UI = LI.user_begin(), UE = LI.user_end(); UI != UE;) {
651 auto *SI = cast<StoreInst>(*UI++);
Craig Topperbb4069e2017-07-07 23:16:26 +0000652 IC.Builder.SetInsertPoint(SI);
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000653 combineStoreToNewValue(IC, *SI, NewLoad);
Sanjay Patel4b198802016-02-01 22:23:39 +0000654 IC.eraseInstFromFunction(*SI);
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000655 }
656 assert(LI.use_empty() && "Failed to remove all users of the load!");
657 // Return the old load so the combiner can delete it safely.
658 return &LI;
659 }
660 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000661
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000662 // Fold away bit casts of the loaded value by loading the desired type.
Quentin Colombet490cfbe2016-02-11 22:30:41 +0000663 // We can do this for BitCastInsts as well as casts from and to pointer types,
664 // as long as those are noops (i.e., the source or dest type have the same
665 // bitwidth as the target's pointers).
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000666 if (LI.hasOneUse())
Philip Reames89e92d22016-12-01 20:17:06 +0000667 if (auto* CI = dyn_cast<CastInst>(LI.user_back()))
668 if (CI->isNoopCast(DL))
669 if (!LI.isAtomic() || isSupportedAtomicType(CI->getDestTy())) {
670 LoadInst *NewLoad = combineLoadToNewType(IC, LI, CI->getDestTy());
671 CI->replaceAllUsesWith(NewLoad);
672 IC.eraseInstFromFunction(*CI);
673 return &LI;
674 }
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000675
Chandler Carrutha7f247e2014-12-09 19:21:16 +0000676 // FIXME: We should also canonicalize loads of vectors when their elements are
677 // cast to other types.
Craig Topperf40110f2014-04-25 05:29:35 +0000678 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000679}
680
Mehdi Amini2668a482015-05-07 05:52:40 +0000681static Instruction *unpackLoadToAggregate(InstCombiner &IC, LoadInst &LI) {
682 // FIXME: We could probably with some care handle both volatile and atomic
683 // stores here but it isn't clear that this is important.
684 if (!LI.isSimple())
685 return nullptr;
686
687 Type *T = LI.getType();
688 if (!T->isAggregateType())
689 return nullptr;
690
Benjamin Kramerc1263532016-03-11 10:20:56 +0000691 StringRef Name = LI.getName();
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000692 assert(LI.getAlignment() && "Alignment must be set at this point");
Mehdi Amini2668a482015-05-07 05:52:40 +0000693
694 if (auto *ST = dyn_cast<StructType>(T)) {
695 // If the struct only have one element, we unpack.
Amaury Sechet61a7d622016-02-17 19:21:28 +0000696 auto NumElements = ST->getNumElements();
697 if (NumElements == 1) {
Mehdi Amini2668a482015-05-07 05:52:40 +0000698 LoadInst *NewLoad = combineLoadToNewType(IC, LI, ST->getTypeAtIndex(0U),
699 ".unpack");
Keno Fischera236dae2017-06-28 23:36:40 +0000700 AAMDNodes AAMD;
701 LI.getAAMetadata(AAMD);
702 NewLoad->setAAMetadata(AAMD);
Craig Topperbb4069e2017-07-07 23:16:26 +0000703 return IC.replaceInstUsesWith(LI, IC.Builder.CreateInsertValue(
Amaury Sechet61a7d622016-02-17 19:21:28 +0000704 UndefValue::get(T), NewLoad, 0, Name));
Mehdi Amini2668a482015-05-07 05:52:40 +0000705 }
Mehdi Amini1c131b32015-12-15 01:44:07 +0000706
707 // We don't want to break loads with padding here as we'd loose
708 // the knowledge that padding exists for the rest of the pipeline.
709 const DataLayout &DL = IC.getDataLayout();
710 auto *SL = DL.getStructLayout(ST);
711 if (SL->hasPadding())
712 return nullptr;
713
Amaury Sechet61a7d622016-02-17 19:21:28 +0000714 auto Align = LI.getAlignment();
715 if (!Align)
716 Align = DL.getABITypeAlignment(ST);
717
Mehdi Amini1c131b32015-12-15 01:44:07 +0000718 auto *Addr = LI.getPointerOperand();
Amaury Sechet61a7d622016-02-17 19:21:28 +0000719 auto *IdxType = Type::getInt32Ty(T->getContext());
Mehdi Amini1c131b32015-12-15 01:44:07 +0000720 auto *Zero = ConstantInt::get(IdxType, 0);
Amaury Sechet61a7d622016-02-17 19:21:28 +0000721
722 Value *V = UndefValue::get(T);
723 for (unsigned i = 0; i < NumElements; i++) {
Mehdi Amini1c131b32015-12-15 01:44:07 +0000724 Value *Indices[2] = {
725 Zero,
726 ConstantInt::get(IdxType, i),
727 };
Craig Topperbb4069e2017-07-07 23:16:26 +0000728 auto *Ptr = IC.Builder.CreateInBoundsGEP(ST, Addr, makeArrayRef(Indices),
729 Name + ".elt");
Amaury Sechet61a7d622016-02-17 19:21:28 +0000730 auto EltAlign = MinAlign(Align, SL->getElementOffset(i));
Craig Topperbb4069e2017-07-07 23:16:26 +0000731 auto *L = IC.Builder.CreateAlignedLoad(Ptr, EltAlign, Name + ".unpack");
Keno Fischera236dae2017-06-28 23:36:40 +0000732 // Propagate AA metadata. It'll still be valid on the narrowed load.
733 AAMDNodes AAMD;
734 LI.getAAMetadata(AAMD);
735 L->setAAMetadata(AAMD);
Craig Topperbb4069e2017-07-07 23:16:26 +0000736 V = IC.Builder.CreateInsertValue(V, L, i);
Mehdi Amini1c131b32015-12-15 01:44:07 +0000737 }
738
739 V->setName(Name);
Sanjay Patel4b198802016-02-01 22:23:39 +0000740 return IC.replaceInstUsesWith(LI, V);
Mehdi Amini2668a482015-05-07 05:52:40 +0000741 }
742
David Majnemer58fb0382015-05-11 05:04:22 +0000743 if (auto *AT = dyn_cast<ArrayType>(T)) {
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000744 auto *ET = AT->getElementType();
745 auto NumElements = AT->getNumElements();
746 if (NumElements == 1) {
747 LoadInst *NewLoad = combineLoadToNewType(IC, LI, ET, ".unpack");
Keno Fischera236dae2017-06-28 23:36:40 +0000748 AAMDNodes AAMD;
749 LI.getAAMetadata(AAMD);
750 NewLoad->setAAMetadata(AAMD);
Craig Topperbb4069e2017-07-07 23:16:26 +0000751 return IC.replaceInstUsesWith(LI, IC.Builder.CreateInsertValue(
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000752 UndefValue::get(T), NewLoad, 0, Name));
David Majnemer58fb0382015-05-11 05:04:22 +0000753 }
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000754
Davide Italianoda114122016-10-07 20:57:42 +0000755 // Bail out if the array is too large. Ideally we would like to optimize
756 // arrays of arbitrary size but this has a terrible impact on compile time.
757 // The threshold here is chosen arbitrarily, maybe needs a little bit of
758 // tuning.
Davide Italiano2133bf52017-02-07 17:56:50 +0000759 if (NumElements > IC.MaxArraySizeForCombine)
Davide Italianoda114122016-10-07 20:57:42 +0000760 return nullptr;
761
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000762 const DataLayout &DL = IC.getDataLayout();
763 auto EltSize = DL.getTypeAllocSize(ET);
764 auto Align = LI.getAlignment();
765 if (!Align)
766 Align = DL.getABITypeAlignment(T);
767
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000768 auto *Addr = LI.getPointerOperand();
769 auto *IdxType = Type::getInt64Ty(T->getContext());
770 auto *Zero = ConstantInt::get(IdxType, 0);
771
772 Value *V = UndefValue::get(T);
773 uint64_t Offset = 0;
774 for (uint64_t i = 0; i < NumElements; i++) {
775 Value *Indices[2] = {
776 Zero,
777 ConstantInt::get(IdxType, i),
778 };
Craig Topperbb4069e2017-07-07 23:16:26 +0000779 auto *Ptr = IC.Builder.CreateInBoundsGEP(AT, Addr, makeArrayRef(Indices),
780 Name + ".elt");
781 auto *L = IC.Builder.CreateAlignedLoad(Ptr, MinAlign(Align, Offset),
782 Name + ".unpack");
Keno Fischera236dae2017-06-28 23:36:40 +0000783 AAMDNodes AAMD;
784 LI.getAAMetadata(AAMD);
785 L->setAAMetadata(AAMD);
Craig Topperbb4069e2017-07-07 23:16:26 +0000786 V = IC.Builder.CreateInsertValue(V, L, i);
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000787 Offset += EltSize;
788 }
789
790 V->setName(Name);
791 return IC.replaceInstUsesWith(LI, V);
David Majnemer58fb0382015-05-11 05:04:22 +0000792 }
793
Mehdi Amini2668a482015-05-07 05:52:40 +0000794 return nullptr;
795}
796
Hal Finkel847e05f2015-02-20 03:05:53 +0000797// If we can determine that all possible objects pointed to by the provided
798// pointer value are, not only dereferenceable, but also definitively less than
799// or equal to the provided maximum size, then return true. Otherwise, return
800// false (constant global values and allocas fall into this category).
801//
802// FIXME: This should probably live in ValueTracking (or similar).
803static bool isObjectSizeLessThanOrEq(Value *V, uint64_t MaxSize,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000804 const DataLayout &DL) {
Hal Finkel847e05f2015-02-20 03:05:53 +0000805 SmallPtrSet<Value *, 4> Visited;
806 SmallVector<Value *, 4> Worklist(1, V);
807
808 do {
809 Value *P = Worklist.pop_back_val();
810 P = P->stripPointerCasts();
811
812 if (!Visited.insert(P).second)
813 continue;
814
815 if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
816 Worklist.push_back(SI->getTrueValue());
817 Worklist.push_back(SI->getFalseValue());
818 continue;
819 }
820
821 if (PHINode *PN = dyn_cast<PHINode>(P)) {
Pete Cooper833f34d2015-05-12 20:05:31 +0000822 for (Value *IncValue : PN->incoming_values())
823 Worklist.push_back(IncValue);
Hal Finkel847e05f2015-02-20 03:05:53 +0000824 continue;
825 }
826
827 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(P)) {
Sanjoy Das99042472016-04-17 04:30:43 +0000828 if (GA->isInterposable())
Hal Finkel847e05f2015-02-20 03:05:53 +0000829 return false;
830 Worklist.push_back(GA->getAliasee());
831 continue;
832 }
833
834 // If we know how big this object is, and it is less than MaxSize, continue
835 // searching. Otherwise, return false.
836 if (AllocaInst *AI = dyn_cast<AllocaInst>(P)) {
837 if (!AI->getAllocatedType()->isSized())
838 return false;
839
840 ConstantInt *CS = dyn_cast<ConstantInt>(AI->getArraySize());
841 if (!CS)
842 return false;
843
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000844 uint64_t TypeSize = DL.getTypeAllocSize(AI->getAllocatedType());
Hal Finkel847e05f2015-02-20 03:05:53 +0000845 // Make sure that, even if the multiplication below would wrap as an
846 // uint64_t, we still do the right thing.
847 if ((CS->getValue().zextOrSelf(128)*APInt(128, TypeSize)).ugt(MaxSize))
848 return false;
849 continue;
850 }
851
852 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
853 if (!GV->hasDefinitiveInitializer() || !GV->isConstant())
854 return false;
855
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000856 uint64_t InitSize = DL.getTypeAllocSize(GV->getValueType());
Hal Finkel847e05f2015-02-20 03:05:53 +0000857 if (InitSize > MaxSize)
858 return false;
859 continue;
860 }
861
862 return false;
863 } while (!Worklist.empty());
864
865 return true;
866}
867
868// If we're indexing into an object of a known size, and the outer index is
869// not a constant, but having any value but zero would lead to undefined
870// behavior, replace it with zero.
871//
872// For example, if we have:
873// @f.a = private unnamed_addr constant [1 x i32] [i32 12], align 4
874// ...
875// %arrayidx = getelementptr inbounds [1 x i32]* @f.a, i64 0, i64 %x
876// ... = load i32* %arrayidx, align 4
877// Then we know that we can replace %x in the GEP with i64 0.
878//
879// FIXME: We could fold any GEP index to zero that would cause UB if it were
880// not zero. Currently, we only handle the first such index. Also, we could
881// also search through non-zero constant indices if we kept track of the
882// offsets those indices implied.
883static bool canReplaceGEPIdxWithZero(InstCombiner &IC, GetElementPtrInst *GEPI,
884 Instruction *MemI, unsigned &Idx) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000885 if (GEPI->getNumOperands() < 2)
Hal Finkel847e05f2015-02-20 03:05:53 +0000886 return false;
887
888 // Find the first non-zero index of a GEP. If all indices are zero, return
889 // one past the last index.
890 auto FirstNZIdx = [](const GetElementPtrInst *GEPI) {
891 unsigned I = 1;
892 for (unsigned IE = GEPI->getNumOperands(); I != IE; ++I) {
893 Value *V = GEPI->getOperand(I);
894 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
895 if (CI->isZero())
896 continue;
897
898 break;
899 }
900
901 return I;
902 };
903
904 // Skip through initial 'zero' indices, and find the corresponding pointer
905 // type. See if the next index is not a constant.
906 Idx = FirstNZIdx(GEPI);
907 if (Idx == GEPI->getNumOperands())
908 return false;
909 if (isa<Constant>(GEPI->getOperand(Idx)))
910 return false;
911
912 SmallVector<Value *, 4> Ops(GEPI->idx_begin(), GEPI->idx_begin() + Idx);
Eduard Burtescu19eb0312016-01-19 17:28:00 +0000913 Type *AllocTy =
914 GetElementPtrInst::getIndexedType(GEPI->getSourceElementType(), Ops);
Hal Finkel847e05f2015-02-20 03:05:53 +0000915 if (!AllocTy || !AllocTy->isSized())
916 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000917 const DataLayout &DL = IC.getDataLayout();
918 uint64_t TyAllocSize = DL.getTypeAllocSize(AllocTy);
Hal Finkel847e05f2015-02-20 03:05:53 +0000919
920 // If there are more indices after the one we might replace with a zero, make
921 // sure they're all non-negative. If any of them are negative, the overall
922 // address being computed might be before the base address determined by the
923 // first non-zero index.
924 auto IsAllNonNegative = [&]() {
925 for (unsigned i = Idx+1, e = GEPI->getNumOperands(); i != e; ++i) {
Craig Topper1a36b7d2017-05-15 06:39:41 +0000926 KnownBits Known = IC.computeKnownBits(GEPI->getOperand(i), 0, MemI);
927 if (Known.isNonNegative())
Hal Finkel847e05f2015-02-20 03:05:53 +0000928 continue;
929 return false;
930 }
931
932 return true;
933 };
934
935 // FIXME: If the GEP is not inbounds, and there are extra indices after the
936 // one we'll replace, those could cause the address computation to wrap
937 // (rendering the IsAllNonNegative() check below insufficient). We can do
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000938 // better, ignoring zero indices (and other indices we can prove small
Hal Finkel847e05f2015-02-20 03:05:53 +0000939 // enough not to wrap).
940 if (Idx+1 != GEPI->getNumOperands() && !GEPI->isInBounds())
941 return false;
942
943 // Note that isObjectSizeLessThanOrEq will return true only if the pointer is
944 // also known to be dereferenceable.
945 return isObjectSizeLessThanOrEq(GEPI->getOperand(0), TyAllocSize, DL) &&
946 IsAllNonNegative();
947}
948
949// If we're indexing into an object with a variable index for the memory
950// access, but the object has only one element, we can assume that the index
951// will always be zero. If we replace the GEP, return it.
952template <typename T>
953static Instruction *replaceGEPIdxWithZero(InstCombiner &IC, Value *Ptr,
954 T &MemI) {
955 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr)) {
956 unsigned Idx;
957 if (canReplaceGEPIdxWithZero(IC, GEPI, &MemI, Idx)) {
958 Instruction *NewGEPI = GEPI->clone();
959 NewGEPI->setOperand(Idx,
960 ConstantInt::get(GEPI->getOperand(Idx)->getType(), 0));
961 NewGEPI->insertBefore(GEPI);
962 MemI.setOperand(MemI.getPointerOperandIndex(), NewGEPI);
963 return NewGEPI;
964 }
965 }
966
967 return nullptr;
968}
969
Anna Thomas2dd98352017-12-12 14:12:33 +0000970static bool canSimplifyNullStoreOrGEP(StoreInst &SI) {
Manoj Gupta77eeac32018-07-09 22:27:23 +0000971 if (NullPointerIsDefined(SI.getFunction(), SI.getPointerAddressSpace()))
Anna Thomas2dd98352017-12-12 14:12:33 +0000972 return false;
973
974 auto *Ptr = SI.getPointerOperand();
975 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr))
976 Ptr = GEPI->getOperand(0);
Manoj Gupta77eeac32018-07-09 22:27:23 +0000977 return (isa<ConstantPointerNull>(Ptr) &&
978 !NullPointerIsDefined(SI.getFunction(), SI.getPointerAddressSpace()));
Anna Thomas2dd98352017-12-12 14:12:33 +0000979}
980
Davide Italianoffcb4df2017-04-19 17:26:57 +0000981static bool canSimplifyNullLoadOrGEP(LoadInst &LI, Value *Op) {
982 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
983 const Value *GEPI0 = GEPI->getOperand(0);
Manoj Gupta77eeac32018-07-09 22:27:23 +0000984 if (isa<ConstantPointerNull>(GEPI0) &&
985 !NullPointerIsDefined(LI.getFunction(), GEPI->getPointerAddressSpace()))
Davide Italianoffcb4df2017-04-19 17:26:57 +0000986 return true;
987 }
988 if (isa<UndefValue>(Op) ||
Manoj Gupta77eeac32018-07-09 22:27:23 +0000989 (isa<ConstantPointerNull>(Op) &&
990 !NullPointerIsDefined(LI.getFunction(), LI.getPointerAddressSpace())))
Davide Italianoffcb4df2017-04-19 17:26:57 +0000991 return true;
992 return false;
993}
994
Chris Lattnera65e2f72010-01-05 05:57:49 +0000995Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
996 Value *Op = LI.getOperand(0);
997
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000998 // Try to canonicalize the loaded type.
999 if (Instruction *Res = combineLoadToOperationType(*this, LI))
1000 return Res;
1001
Chris Lattnera65e2f72010-01-05 05:57:49 +00001002 // Attempt to improve the alignment.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001003 unsigned KnownAlign = getOrEnforceKnownAlignment(
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001004 Op, DL.getPrefTypeAlignment(LI.getType()), DL, &LI, &AC, &DT);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001005 unsigned LoadAlign = LI.getAlignment();
1006 unsigned EffectiveLoadAlign =
1007 LoadAlign != 0 ? LoadAlign : DL.getABITypeAlignment(LI.getType());
Dan Gohman36196602010-08-03 18:20:32 +00001008
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001009 if (KnownAlign > EffectiveLoadAlign)
1010 LI.setAlignment(KnownAlign);
1011 else if (LoadAlign == 0)
1012 LI.setAlignment(EffectiveLoadAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001013
Hal Finkel847e05f2015-02-20 03:05:53 +00001014 // Replace GEP indices if possible.
1015 if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Op, LI)) {
1016 Worklist.Add(NewGEPI);
1017 return &LI;
1018 }
1019
Mehdi Amini2668a482015-05-07 05:52:40 +00001020 if (Instruction *Res = unpackLoadToAggregate(*this, LI))
1021 return Res;
1022
Chris Lattnera65e2f72010-01-05 05:57:49 +00001023 // Do really simple store-to-load forwarding and load CSE, to catch cases
Duncan Sands75b5d272011-02-15 09:23:02 +00001024 // where there are several consecutive memory accesses to the same location,
Chris Lattnera65e2f72010-01-05 05:57:49 +00001025 // separated by a few arithmetic operations.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00001026 BasicBlock::iterator BBI(LI);
Eli Friedmanbd254a62016-06-16 02:33:42 +00001027 bool IsLoadCSE = false;
Sanjay Patelb38ad88e2017-01-02 23:25:28 +00001028 if (Value *AvailableVal = FindAvailableLoadedValue(
1029 &LI, LI.getParent(), BBI, DefMaxInstsToScan, AA, &IsLoadCSE)) {
1030 if (IsLoadCSE)
Florian Hahn406f1ff2018-08-24 11:40:04 +00001031 combineMetadataForCSE(cast<LoadInst>(AvailableVal), &LI, false);
Bjorn Steinbrinka91fd092015-07-10 06:55:44 +00001032
Sanjay Patel4b198802016-02-01 22:23:39 +00001033 return replaceInstUsesWith(
Craig Topperbb4069e2017-07-07 23:16:26 +00001034 LI, Builder.CreateBitOrPointerCast(AvailableVal, LI.getType(),
1035 LI.getName() + ".cast"));
Bjorn Steinbrinka91fd092015-07-10 06:55:44 +00001036 }
Chris Lattnera65e2f72010-01-05 05:57:49 +00001037
Philip Reames3ac07182016-04-21 17:45:05 +00001038 // None of the following transforms are legal for volatile/ordered atomic
1039 // loads. Most of them do apply for unordered atomics.
1040 if (!LI.isUnordered()) return nullptr;
Philip Reamesac550902016-04-21 17:03:33 +00001041
Chris Lattnera65e2f72010-01-05 05:57:49 +00001042 // load(gep null, ...) -> unreachable
Chris Lattnera65e2f72010-01-05 05:57:49 +00001043 // load null/undef -> unreachable
Davide Italianoffcb4df2017-04-19 17:26:57 +00001044 // TODO: Consider a target hook for valid address spaces for this xforms.
1045 if (canSimplifyNullLoadOrGEP(LI, Op)) {
1046 // Insert a new store to null instruction before the load to indicate
1047 // that this code is not reachable. We do this instead of inserting
1048 // an unreachable instruction directly because we cannot modify the
1049 // CFG.
Weiming Zhao984f1dc2017-07-19 01:27:24 +00001050 StoreInst *SI = new StoreInst(UndefValue::get(LI.getType()),
1051 Constant::getNullValue(Op->getType()), &LI);
1052 SI->setDebugLoc(LI.getDebugLoc());
Sanjay Patel4b198802016-02-01 22:23:39 +00001053 return replaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattnera65e2f72010-01-05 05:57:49 +00001054 }
1055
Chris Lattnera65e2f72010-01-05 05:57:49 +00001056 if (Op->hasOneUse()) {
1057 // Change select and PHI nodes to select values instead of addresses: this
1058 // helps alias analysis out a lot, allows many others simplifications, and
1059 // exposes redundancy in the code.
1060 //
1061 // Note that we cannot do the transformation unless we know that the
1062 // introduced loads cannot trap! Something like this is valid as long as
1063 // the condition is always false: load (select bool %C, int* null, int* %G),
1064 // but it would not be valid if we transformed it to load from null
1065 // unconditionally.
1066 //
1067 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
1068 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Bob Wilson56600a12010-01-30 04:42:39 +00001069 unsigned Align = LI.getAlignment();
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001070 if (isSafeToLoadUnconditionally(SI->getOperand(1), Align, DL, SI) &&
1071 isSafeToLoadUnconditionally(SI->getOperand(2), Align, DL, SI)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001072 LoadInst *V1 = Builder.CreateLoad(SI->getOperand(1),
1073 SI->getOperand(1)->getName()+".val");
1074 LoadInst *V2 = Builder.CreateLoad(SI->getOperand(2),
1075 SI->getOperand(2)->getName()+".val");
Philip Reamesa98c7ea2016-04-21 17:59:40 +00001076 assert(LI.isUnordered() && "implied by above");
Bob Wilson56600a12010-01-30 04:42:39 +00001077 V1->setAlignment(Align);
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00001078 V1->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
Bob Wilson56600a12010-01-30 04:42:39 +00001079 V2->setAlignment(Align);
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00001080 V2->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
Chris Lattnera65e2f72010-01-05 05:57:49 +00001081 return SelectInst::Create(SI->getCondition(), V1, V2);
1082 }
1083
1084 // load (select (cond, null, P)) -> load P
Larisse Voufo532bf712015-09-18 19:14:35 +00001085 if (isa<ConstantPointerNull>(SI->getOperand(1)) &&
Manoj Gupta77eeac32018-07-09 22:27:23 +00001086 !NullPointerIsDefined(SI->getFunction(),
1087 LI.getPointerAddressSpace())) {
Philip Reames5ad26c32014-12-29 22:46:21 +00001088 LI.setOperand(0, SI->getOperand(2));
1089 return &LI;
1090 }
Chris Lattnera65e2f72010-01-05 05:57:49 +00001091
1092 // load (select (cond, P, null)) -> load P
Philip Reames5ad26c32014-12-29 22:46:21 +00001093 if (isa<ConstantPointerNull>(SI->getOperand(2)) &&
Manoj Gupta77eeac32018-07-09 22:27:23 +00001094 !NullPointerIsDefined(SI->getFunction(),
1095 LI.getPointerAddressSpace())) {
Philip Reames5ad26c32014-12-29 22:46:21 +00001096 LI.setOperand(0, SI->getOperand(1));
1097 return &LI;
1098 }
Chris Lattnera65e2f72010-01-05 05:57:49 +00001099 }
1100 }
Craig Topperf40110f2014-04-25 05:29:35 +00001101 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001102}
1103
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001104/// Look for extractelement/insertvalue sequence that acts like a bitcast.
Arch D. Robisonbe0490a2016-04-25 22:22:39 +00001105///
1106/// \returns underlying value that was "cast", or nullptr otherwise.
1107///
1108/// For example, if we have:
1109///
1110/// %E0 = extractelement <2 x double> %U, i32 0
1111/// %V0 = insertvalue [2 x double] undef, double %E0, 0
1112/// %E1 = extractelement <2 x double> %U, i32 1
1113/// %V1 = insertvalue [2 x double] %V0, double %E1, 1
1114///
1115/// and the layout of a <2 x double> is isomorphic to a [2 x double],
1116/// then %V1 can be safely approximated by a conceptual "bitcast" of %U.
1117/// Note that %U may contain non-undef values where %V1 has undef.
1118static Value *likeBitCastFromVector(InstCombiner &IC, Value *V) {
1119 Value *U = nullptr;
1120 while (auto *IV = dyn_cast<InsertValueInst>(V)) {
1121 auto *E = dyn_cast<ExtractElementInst>(IV->getInsertedValueOperand());
1122 if (!E)
1123 return nullptr;
1124 auto *W = E->getVectorOperand();
1125 if (!U)
1126 U = W;
1127 else if (U != W)
1128 return nullptr;
1129 auto *CI = dyn_cast<ConstantInt>(E->getIndexOperand());
1130 if (!CI || IV->getNumIndices() != 1 || CI->getZExtValue() != *IV->idx_begin())
1131 return nullptr;
1132 V = IV->getAggregateOperand();
1133 }
1134 if (!isa<UndefValue>(V) ||!U)
1135 return nullptr;
1136
1137 auto *UT = cast<VectorType>(U->getType());
1138 auto *VT = V->getType();
1139 // Check that types UT and VT are bitwise isomorphic.
1140 const auto &DL = IC.getDataLayout();
1141 if (DL.getTypeStoreSizeInBits(UT) != DL.getTypeStoreSizeInBits(VT)) {
1142 return nullptr;
1143 }
1144 if (auto *AT = dyn_cast<ArrayType>(VT)) {
1145 if (AT->getNumElements() != UT->getNumElements())
1146 return nullptr;
1147 } else {
1148 auto *ST = cast<StructType>(VT);
1149 if (ST->getNumElements() != UT->getNumElements())
1150 return nullptr;
1151 for (const auto *EltT : ST->elements()) {
1152 if (EltT != UT->getElementType())
1153 return nullptr;
1154 }
1155 }
1156 return U;
1157}
1158
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001159/// Combine stores to match the type of value being stored.
Chandler Carruth816d26f2014-11-25 10:09:51 +00001160///
1161/// The core idea here is that the memory does not have any intrinsic type and
1162/// where we can we should match the type of a store to the type of value being
1163/// stored.
1164///
1165/// However, this routine must never change the width of a store or the number of
1166/// stores as that would introduce a semantic change. This combine is expected to
1167/// be a semantic no-op which just allows stores to more closely model the types
1168/// of their incoming values.
1169///
1170/// Currently, we also refuse to change the precise type used for an atomic or
1171/// volatile store. This is debatable, and might be reasonable to change later.
1172/// However, it is risky in case some backend or other part of LLVM is relying
1173/// on the exact type stored to select appropriate atomic operations.
1174///
1175/// \returns true if the store was successfully combined away. This indicates
1176/// the caller must erase the store instruction. We have to let the caller erase
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00001177/// the store instruction as otherwise there is no way to signal whether it was
Chandler Carruth816d26f2014-11-25 10:09:51 +00001178/// combined or not: IC.EraseInstFromFunction returns a null pointer.
1179static bool combineStoreToValueType(InstCombiner &IC, StoreInst &SI) {
Philip Reames6f4d0082016-05-06 22:17:01 +00001180 // FIXME: We could probably with some care handle both volatile and ordered
1181 // atomic stores here but it isn't clear that this is important.
1182 if (!SI.isUnordered())
Chandler Carruth816d26f2014-11-25 10:09:51 +00001183 return false;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001184
Arnold Schwaighofer5d335552016-09-10 18:14:57 +00001185 // swifterror values can't be bitcasted.
1186 if (SI.getPointerOperand()->isSwiftError())
1187 return false;
1188
Chandler Carruth816d26f2014-11-25 10:09:51 +00001189 Value *V = SI.getValueOperand();
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001190
Chandler Carruth816d26f2014-11-25 10:09:51 +00001191 // Fold away bit casts of the stored value by storing the original type.
1192 if (auto *BC = dyn_cast<BitCastInst>(V)) {
Chandler Carrutha7f247e2014-12-09 19:21:16 +00001193 V = BC->getOperand(0);
Philip Reames89e92d22016-12-01 20:17:06 +00001194 if (!SI.isAtomic() || isSupportedAtomicType(V->getType())) {
1195 combineStoreToNewValue(IC, SI, V);
1196 return true;
1197 }
Chris Lattnera65e2f72010-01-05 05:57:49 +00001198 }
1199
Philip Reames89e92d22016-12-01 20:17:06 +00001200 if (Value *U = likeBitCastFromVector(IC, V))
1201 if (!SI.isAtomic() || isSupportedAtomicType(U->getType())) {
1202 combineStoreToNewValue(IC, SI, U);
1203 return true;
1204 }
Arch D. Robisonbe0490a2016-04-25 22:22:39 +00001205
JF Bastienc22d2992016-04-21 19:53:39 +00001206 // FIXME: We should also canonicalize stores of vectors when their elements
1207 // are cast to other types.
Chandler Carruth816d26f2014-11-25 10:09:51 +00001208 return false;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001209}
1210
Mehdi Aminib344ac92015-03-14 22:19:33 +00001211static bool unpackStoreToAggregate(InstCombiner &IC, StoreInst &SI) {
1212 // FIXME: We could probably with some care handle both volatile and atomic
1213 // stores here but it isn't clear that this is important.
1214 if (!SI.isSimple())
1215 return false;
1216
1217 Value *V = SI.getValueOperand();
1218 Type *T = V->getType();
1219
1220 if (!T->isAggregateType())
1221 return false;
1222
Mehdi Amini2668a482015-05-07 05:52:40 +00001223 if (auto *ST = dyn_cast<StructType>(T)) {
Mehdi Aminib344ac92015-03-14 22:19:33 +00001224 // If the struct only have one element, we unpack.
Mehdi Amini1c131b32015-12-15 01:44:07 +00001225 unsigned Count = ST->getNumElements();
1226 if (Count == 1) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001227 V = IC.Builder.CreateExtractValue(V, 0);
Mehdi Aminib344ac92015-03-14 22:19:33 +00001228 combineStoreToNewValue(IC, SI, V);
1229 return true;
1230 }
Mehdi Amini1c131b32015-12-15 01:44:07 +00001231
1232 // We don't want to break loads with padding here as we'd loose
1233 // the knowledge that padding exists for the rest of the pipeline.
1234 const DataLayout &DL = IC.getDataLayout();
1235 auto *SL = DL.getStructLayout(ST);
1236 if (SL->hasPadding())
1237 return false;
1238
Amaury Sechet61a7d622016-02-17 19:21:28 +00001239 auto Align = SI.getAlignment();
1240 if (!Align)
1241 Align = DL.getABITypeAlignment(ST);
1242
NAKAMURA Takumiec6b1fc2015-12-15 09:37:31 +00001243 SmallString<16> EltName = V->getName();
1244 EltName += ".elt";
Mehdi Amini1c131b32015-12-15 01:44:07 +00001245 auto *Addr = SI.getPointerOperand();
NAKAMURA Takumiec6b1fc2015-12-15 09:37:31 +00001246 SmallString<16> AddrName = Addr->getName();
1247 AddrName += ".repack";
Amaury Sechet61a7d622016-02-17 19:21:28 +00001248
Mehdi Amini1c131b32015-12-15 01:44:07 +00001249 auto *IdxType = Type::getInt32Ty(ST->getContext());
1250 auto *Zero = ConstantInt::get(IdxType, 0);
1251 for (unsigned i = 0; i < Count; i++) {
1252 Value *Indices[2] = {
1253 Zero,
1254 ConstantInt::get(IdxType, i),
1255 };
Craig Topperbb4069e2017-07-07 23:16:26 +00001256 auto *Ptr = IC.Builder.CreateInBoundsGEP(ST, Addr, makeArrayRef(Indices),
1257 AddrName);
1258 auto *Val = IC.Builder.CreateExtractValue(V, i, EltName);
Amaury Sechet61a7d622016-02-17 19:21:28 +00001259 auto EltAlign = MinAlign(Align, SL->getElementOffset(i));
Craig Topperbb4069e2017-07-07 23:16:26 +00001260 llvm::Instruction *NS = IC.Builder.CreateAlignedStore(Val, Ptr, EltAlign);
Keno Fischera236dae2017-06-28 23:36:40 +00001261 AAMDNodes AAMD;
1262 SI.getAAMetadata(AAMD);
1263 NS->setAAMetadata(AAMD);
Mehdi Amini1c131b32015-12-15 01:44:07 +00001264 }
1265
1266 return true;
Mehdi Aminib344ac92015-03-14 22:19:33 +00001267 }
1268
David Majnemer75364602015-05-11 05:04:27 +00001269 if (auto *AT = dyn_cast<ArrayType>(T)) {
1270 // If the array only have one element, we unpack.
Amaury Sechet3b8b2ea2016-03-02 22:36:45 +00001271 auto NumElements = AT->getNumElements();
1272 if (NumElements == 1) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001273 V = IC.Builder.CreateExtractValue(V, 0);
David Majnemer75364602015-05-11 05:04:27 +00001274 combineStoreToNewValue(IC, SI, V);
1275 return true;
1276 }
Amaury Sechet3b8b2ea2016-03-02 22:36:45 +00001277
Davide Italianof6988d22016-10-07 21:53:09 +00001278 // Bail out if the array is too large. Ideally we would like to optimize
1279 // arrays of arbitrary size but this has a terrible impact on compile time.
1280 // The threshold here is chosen arbitrarily, maybe needs a little bit of
1281 // tuning.
Davide Italiano2133bf52017-02-07 17:56:50 +00001282 if (NumElements > IC.MaxArraySizeForCombine)
Davide Italianof6988d22016-10-07 21:53:09 +00001283 return false;
1284
Amaury Sechet3b8b2ea2016-03-02 22:36:45 +00001285 const DataLayout &DL = IC.getDataLayout();
1286 auto EltSize = DL.getTypeAllocSize(AT->getElementType());
1287 auto Align = SI.getAlignment();
1288 if (!Align)
1289 Align = DL.getABITypeAlignment(T);
1290
1291 SmallString<16> EltName = V->getName();
1292 EltName += ".elt";
1293 auto *Addr = SI.getPointerOperand();
1294 SmallString<16> AddrName = Addr->getName();
1295 AddrName += ".repack";
1296
1297 auto *IdxType = Type::getInt64Ty(T->getContext());
1298 auto *Zero = ConstantInt::get(IdxType, 0);
1299
1300 uint64_t Offset = 0;
1301 for (uint64_t i = 0; i < NumElements; i++) {
1302 Value *Indices[2] = {
1303 Zero,
1304 ConstantInt::get(IdxType, i),
1305 };
Craig Topperbb4069e2017-07-07 23:16:26 +00001306 auto *Ptr = IC.Builder.CreateInBoundsGEP(AT, Addr, makeArrayRef(Indices),
1307 AddrName);
1308 auto *Val = IC.Builder.CreateExtractValue(V, i, EltName);
Amaury Sechet3b8b2ea2016-03-02 22:36:45 +00001309 auto EltAlign = MinAlign(Align, Offset);
Craig Topperbb4069e2017-07-07 23:16:26 +00001310 Instruction *NS = IC.Builder.CreateAlignedStore(Val, Ptr, EltAlign);
Keno Fischera236dae2017-06-28 23:36:40 +00001311 AAMDNodes AAMD;
1312 SI.getAAMetadata(AAMD);
1313 NS->setAAMetadata(AAMD);
Amaury Sechet3b8b2ea2016-03-02 22:36:45 +00001314 Offset += EltSize;
1315 }
1316
1317 return true;
David Majnemer75364602015-05-11 05:04:27 +00001318 }
1319
Mehdi Aminib344ac92015-03-14 22:19:33 +00001320 return false;
1321}
1322
Chris Lattnera65e2f72010-01-05 05:57:49 +00001323/// equivalentAddressValues - Test if A and B will obviously have the same
1324/// value. This includes recognizing that %t0 and %t1 will have the same
1325/// value in code like this:
1326/// %t0 = getelementptr \@a, 0, 3
1327/// store i32 0, i32* %t0
1328/// %t1 = getelementptr \@a, 0, 3
1329/// %t2 = load i32* %t1
1330///
1331static bool equivalentAddressValues(Value *A, Value *B) {
1332 // Test if the values are trivially equivalent.
1333 if (A == B) return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001334
Chris Lattnera65e2f72010-01-05 05:57:49 +00001335 // Test if the values come form identical arithmetic instructions.
1336 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
1337 // its only used to compare two uses within the same basic block, which
1338 // means that they'll always either have the same value or one of them
1339 // will have an undefined value.
1340 if (isa<BinaryOperator>(A) ||
1341 isa<CastInst>(A) ||
1342 isa<PHINode>(A) ||
1343 isa<GetElementPtrInst>(A))
1344 if (Instruction *BI = dyn_cast<Instruction>(B))
1345 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
1346 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001347
Chris Lattnera65e2f72010-01-05 05:57:49 +00001348 // Otherwise they may not be equivalent.
1349 return false;
1350}
1351
Alexey Bataevec95c6c2017-12-08 15:32:10 +00001352/// Converts store (bitcast (load (bitcast (select ...)))) to
1353/// store (load (select ...)), where select is minmax:
1354/// select ((cmp load V1, load V2), V1, V2).
Alexey Bataev83c15b12017-12-12 20:28:46 +00001355static bool removeBitcastsFromLoadStoreOnMinMax(InstCombiner &IC,
1356 StoreInst &SI) {
Alexey Bataevec95c6c2017-12-08 15:32:10 +00001357 // bitcast?
Alexey Bataev83c15b12017-12-12 20:28:46 +00001358 if (!match(SI.getPointerOperand(), m_BitCast(m_Value())))
Alexey Bataevfa0a76d2017-12-12 19:12:34 +00001359 return false;
Alexey Bataevec95c6c2017-12-08 15:32:10 +00001360 // load? integer?
1361 Value *LoadAddr;
1362 if (!match(SI.getValueOperand(), m_Load(m_BitCast(m_Value(LoadAddr)))))
Alexey Bataevfa0a76d2017-12-12 19:12:34 +00001363 return false;
Alexey Bataevec95c6c2017-12-08 15:32:10 +00001364 auto *LI = cast<LoadInst>(SI.getValueOperand());
1365 if (!LI->getType()->isIntegerTy())
Alexey Bataevfa0a76d2017-12-12 19:12:34 +00001366 return false;
Alexey Bataevec95c6c2017-12-08 15:32:10 +00001367 if (!isMinMaxWithLoads(LoadAddr))
Alexey Bataevfa0a76d2017-12-12 19:12:34 +00001368 return false;
Alexey Bataevec95c6c2017-12-08 15:32:10 +00001369
Alexey Bataev83c15b12017-12-12 20:28:46 +00001370 if (!all_of(LI->users(), [LI, LoadAddr](User *U) {
1371 auto *SI = dyn_cast<StoreInst>(U);
1372 return SI && SI->getPointerOperand() != LI &&
1373 peekThroughBitcast(SI->getPointerOperand()) != LoadAddr &&
1374 !SI->getPointerOperand()->isSwiftError();
1375 }))
1376 return false;
1377
1378 IC.Builder.SetInsertPoint(LI);
Alexey Bataevec95c6c2017-12-08 15:32:10 +00001379 LoadInst *NewLI = combineLoadToNewType(
1380 IC, *LI, LoadAddr->getType()->getPointerElementType());
Alexey Bataev83c15b12017-12-12 20:28:46 +00001381 // Replace all the stores with stores of the newly loaded value.
1382 for (auto *UI : LI->users()) {
1383 auto *USI = cast<StoreInst>(UI);
1384 IC.Builder.SetInsertPoint(USI);
1385 combineStoreToNewValue(IC, *USI, NewLI);
1386 }
1387 IC.replaceInstUsesWith(*LI, UndefValue::get(LI->getType()));
1388 IC.eraseInstFromFunction(*LI);
Alexey Bataevfa0a76d2017-12-12 19:12:34 +00001389 return true;
Alexey Bataevec95c6c2017-12-08 15:32:10 +00001390}
1391
Chris Lattnera65e2f72010-01-05 05:57:49 +00001392Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
1393 Value *Val = SI.getOperand(0);
1394 Value *Ptr = SI.getOperand(1);
1395
Chandler Carruth816d26f2014-11-25 10:09:51 +00001396 // Try to canonicalize the stored type.
1397 if (combineStoreToValueType(*this, SI))
Sanjay Patel4b198802016-02-01 22:23:39 +00001398 return eraseInstFromFunction(SI);
Chandler Carruth816d26f2014-11-25 10:09:51 +00001399
Chris Lattnera65e2f72010-01-05 05:57:49 +00001400 // Attempt to improve the alignment.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001401 unsigned KnownAlign = getOrEnforceKnownAlignment(
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001402 Ptr, DL.getPrefTypeAlignment(Val->getType()), DL, &SI, &AC, &DT);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001403 unsigned StoreAlign = SI.getAlignment();
1404 unsigned EffectiveStoreAlign =
1405 StoreAlign != 0 ? StoreAlign : DL.getABITypeAlignment(Val->getType());
Dan Gohman36196602010-08-03 18:20:32 +00001406
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001407 if (KnownAlign > EffectiveStoreAlign)
1408 SI.setAlignment(KnownAlign);
1409 else if (StoreAlign == 0)
1410 SI.setAlignment(EffectiveStoreAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001411
Mehdi Aminib344ac92015-03-14 22:19:33 +00001412 // Try to canonicalize the stored type.
1413 if (unpackStoreToAggregate(*this, SI))
Sanjay Patel4b198802016-02-01 22:23:39 +00001414 return eraseInstFromFunction(SI);
Mehdi Aminib344ac92015-03-14 22:19:33 +00001415
Alexey Bataevfa0a76d2017-12-12 19:12:34 +00001416 if (removeBitcastsFromLoadStoreOnMinMax(*this, SI))
1417 return eraseInstFromFunction(SI);
Alexey Bataevec95c6c2017-12-08 15:32:10 +00001418
Hal Finkel847e05f2015-02-20 03:05:53 +00001419 // Replace GEP indices if possible.
1420 if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Ptr, SI)) {
1421 Worklist.Add(NewGEPI);
1422 return &SI;
1423 }
1424
Philip Reamesd7a6cc82015-12-17 22:19:27 +00001425 // Don't hack volatile/ordered stores.
1426 // FIXME: Some bits are legal for ordered atomic stores; needs refactoring.
1427 if (!SI.isUnordered()) return nullptr;
Eli Friedman8bc586e2011-08-15 22:09:40 +00001428
1429 // If the RHS is an alloca with a single use, zapify the store, making the
1430 // alloca dead.
1431 if (Ptr->hasOneUse()) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001432 if (isa<AllocaInst>(Ptr))
Sanjay Patel4b198802016-02-01 22:23:39 +00001433 return eraseInstFromFunction(SI);
Eli Friedman8bc586e2011-08-15 22:09:40 +00001434 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
1435 if (isa<AllocaInst>(GEP->getOperand(0))) {
1436 if (GEP->getOperand(0)->hasOneUse())
Sanjay Patel4b198802016-02-01 22:23:39 +00001437 return eraseInstFromFunction(SI);
Eli Friedman8bc586e2011-08-15 22:09:40 +00001438 }
1439 }
1440 }
1441
Chris Lattnera65e2f72010-01-05 05:57:49 +00001442 // Do really simple DSE, to catch cases where there are several consecutive
1443 // stores to the same location, separated by a few arithmetic operations. This
1444 // situation often occurs with bitfield accesses.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00001445 BasicBlock::iterator BBI(SI);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001446 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
1447 --ScanInsts) {
1448 --BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +00001449 // Don't count debug info directives, lest they affect codegen,
1450 // and we skip pointer-to-pointer bitcasts, which are NOPs.
1451 if (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +00001452 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +00001453 ScanInsts++;
1454 continue;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001455 }
1456
Chris Lattnera65e2f72010-01-05 05:57:49 +00001457 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
1458 // Prev store isn't volatile, and stores to the same location?
Philip Reamesd7a6cc82015-12-17 22:19:27 +00001459 if (PrevSI->isUnordered() && equivalentAddressValues(PrevSI->getOperand(1),
Eli Friedman8bc586e2011-08-15 22:09:40 +00001460 SI.getOperand(1))) {
Chris Lattnera65e2f72010-01-05 05:57:49 +00001461 ++NumDeadStore;
1462 ++BBI;
Sanjay Patel4b198802016-02-01 22:23:39 +00001463 eraseInstFromFunction(*PrevSI);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001464 continue;
1465 }
1466 break;
1467 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001468
Chris Lattnera65e2f72010-01-05 05:57:49 +00001469 // If this is a load, we have to stop. However, if the loaded value is from
1470 // the pointer we're loading and is producing the pointer we're storing,
1471 // then *this* store is dead (X = load P; store X -> P).
1472 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Philip Reamesd7a6cc82015-12-17 22:19:27 +00001473 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr)) {
1474 assert(SI.isUnordered() && "can't eliminate ordering operation");
Sanjay Patel4b198802016-02-01 22:23:39 +00001475 return eraseInstFromFunction(SI);
Philip Reamesd7a6cc82015-12-17 22:19:27 +00001476 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001477
Chris Lattnera65e2f72010-01-05 05:57:49 +00001478 // Otherwise, this is a load from some other location. Stores before it
1479 // may not be dead.
1480 break;
1481 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001482
Sanjoy Das679bc322017-01-17 05:45:09 +00001483 // Don't skip over loads, throws or things that can modify memory.
1484 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory() || BBI->mayThrow())
Chris Lattnera65e2f72010-01-05 05:57:49 +00001485 break;
1486 }
Chris Lattnera65e2f72010-01-05 05:57:49 +00001487
1488 // store X, null -> turns into 'unreachable' in SimplifyCFG
Anna Thomas2dd98352017-12-12 14:12:33 +00001489 // store X, GEP(null, Y) -> turns into 'unreachable' in SimplifyCFG
1490 if (canSimplifyNullStoreOrGEP(SI)) {
Chris Lattnera65e2f72010-01-05 05:57:49 +00001491 if (!isa<UndefValue>(Val)) {
1492 SI.setOperand(0, UndefValue::get(Val->getType()));
1493 if (Instruction *U = dyn_cast<Instruction>(Val))
1494 Worklist.Add(U); // Dropped a use.
1495 }
Craig Topperf40110f2014-04-25 05:29:35 +00001496 return nullptr; // Do not modify these!
Chris Lattnera65e2f72010-01-05 05:57:49 +00001497 }
1498
1499 // store undef, Ptr -> noop
1500 if (isa<UndefValue>(Val))
Sanjay Patel4b198802016-02-01 22:23:39 +00001501 return eraseInstFromFunction(SI);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001502
Sanjay Patel4a12aa92018-11-10 20:29:25 +00001503 // If this store is the second-to-last instruction in the basic block
1504 // (excluding debug info and bitcasts of pointers) and if the block ends with
1505 // an unconditional branch, try to move the store to the successor block.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00001506 BBI = SI.getIterator();
Chris Lattnera65e2f72010-01-05 05:57:49 +00001507 do {
1508 ++BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +00001509 } while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +00001510 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()));
Sanjay Patel4a12aa92018-11-10 20:29:25 +00001511
Chris Lattnera65e2f72010-01-05 05:57:49 +00001512 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
1513 if (BI->isUnconditional())
Sanjay Patel4a12aa92018-11-10 20:29:25 +00001514 mergeStoreIntoSuccessor(SI);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001515
Craig Topperf40110f2014-04-25 05:29:35 +00001516 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001517}
1518
Sanjay Patel4a12aa92018-11-10 20:29:25 +00001519/// Try to transform:
Chris Lattnera65e2f72010-01-05 05:57:49 +00001520/// if () { *P = v1; } else { *P = v2 }
Sanjay Patel4a12aa92018-11-10 20:29:25 +00001521/// or:
Chris Lattnera65e2f72010-01-05 05:57:49 +00001522/// *P = v1; if () { *P = v2; }
1523/// into a phi node with a store in the successor.
Sanjay Patel4a12aa92018-11-10 20:29:25 +00001524bool InstCombiner::mergeStoreIntoSuccessor(StoreInst &SI) {
Philip Reames5f0e3692016-04-22 20:53:32 +00001525 assert(SI.isUnordered() &&
Sanjay Patel4a12aa92018-11-10 20:29:25 +00001526 "This code has not been audited for volatile or ordered store case.");
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00001527
Sanjay Patel4a12aa92018-11-10 20:29:25 +00001528 // Check if the successor block has exactly 2 incoming edges.
Chris Lattnera65e2f72010-01-05 05:57:49 +00001529 BasicBlock *StoreBB = SI.getParent();
Chris Lattnera65e2f72010-01-05 05:57:49 +00001530 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Vedant Kumar4de31bb2018-11-19 19:54:27 +00001531 if (!DestBB->hasNPredecessors(2))
Chris Lattnera65e2f72010-01-05 05:57:49 +00001532 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001533
Sanjay Patel4a12aa92018-11-10 20:29:25 +00001534 // Capture the other block (the block that doesn't contain our store).
1535 pred_iterator PredIter = pred_begin(DestBB);
1536 if (*PredIter == StoreBB)
1537 ++PredIter;
1538 BasicBlock *OtherBB = *PredIter;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001539
Sanjay Patel4a12aa92018-11-10 20:29:25 +00001540 // Bail out if all of the relevant blocks aren't distinct. This can happen,
1541 // for example, if SI is in an infinite loop.
Chris Lattnera65e2f72010-01-05 05:57:49 +00001542 if (StoreBB == DestBB || OtherBB == DestBB)
1543 return false;
1544
1545 // Verify that the other block ends in a branch and is not otherwise empty.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00001546 BasicBlock::iterator BBI(OtherBB->getTerminator());
Chris Lattnera65e2f72010-01-05 05:57:49 +00001547 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
1548 if (!OtherBr || BBI == OtherBB->begin())
1549 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001550
Chris Lattnera65e2f72010-01-05 05:57:49 +00001551 // If the other block ends in an unconditional branch, check for the 'if then
Sanjay Patel4a12aa92018-11-10 20:29:25 +00001552 // else' case. There is an instruction before the branch.
Craig Topperf40110f2014-04-25 05:29:35 +00001553 StoreInst *OtherStore = nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001554 if (OtherBr->isUnconditional()) {
1555 --BBI;
1556 // Skip over debugging info.
Victor Hernandez5f8c8c02010-01-22 19:05:05 +00001557 while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +00001558 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +00001559 if (BBI==OtherBB->begin())
1560 return false;
1561 --BBI;
1562 }
Eli Friedman8bc586e2011-08-15 22:09:40 +00001563 // If this isn't a store, isn't a store to the same location, or is not the
1564 // right kind of store, bail out.
Chris Lattnera65e2f72010-01-05 05:57:49 +00001565 OtherStore = dyn_cast<StoreInst>(BBI);
1566 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +00001567 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +00001568 return false;
1569 } else {
1570 // Otherwise, the other block ended with a conditional branch. If one of the
1571 // destinations is StoreBB, then we have the if/then case.
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001572 if (OtherBr->getSuccessor(0) != StoreBB &&
Chris Lattnera65e2f72010-01-05 05:57:49 +00001573 OtherBr->getSuccessor(1) != StoreBB)
1574 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001575
Chris Lattnera65e2f72010-01-05 05:57:49 +00001576 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Sanjay Patel4a12aa92018-11-10 20:29:25 +00001577 // if/then triangle. See if there is a store to the same ptr as SI that
Chris Lattnera65e2f72010-01-05 05:57:49 +00001578 // lives in OtherBB.
1579 for (;; --BBI) {
1580 // Check to see if we find the matching store.
1581 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
1582 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +00001583 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +00001584 return false;
1585 break;
1586 }
1587 // If we find something that may be using or overwriting the stored
Sanjay Patel4a12aa92018-11-10 20:29:25 +00001588 // value, or if we run out of instructions, we can't do the transform.
Sanjoy Das679bc322017-01-17 05:45:09 +00001589 if (BBI->mayReadFromMemory() || BBI->mayThrow() ||
1590 BBI->mayWriteToMemory() || BBI == OtherBB->begin())
Chris Lattnera65e2f72010-01-05 05:57:49 +00001591 return false;
1592 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001593
Sanjay Patel4a12aa92018-11-10 20:29:25 +00001594 // In order to eliminate the store in OtherBr, we have to make sure nothing
1595 // reads or overwrites the stored value in StoreBB.
Chris Lattnera65e2f72010-01-05 05:57:49 +00001596 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
1597 // FIXME: This should really be AA driven.
Sanjoy Das679bc322017-01-17 05:45:09 +00001598 if (I->mayReadFromMemory() || I->mayThrow() || I->mayWriteToMemory())
Chris Lattnera65e2f72010-01-05 05:57:49 +00001599 return false;
1600 }
1601 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001602
Chris Lattnera65e2f72010-01-05 05:57:49 +00001603 // Insert a PHI node now if we need it.
1604 Value *MergedVal = OtherStore->getOperand(0);
Vedant Kumar238533e2018-11-19 19:55:02 +00001605 // The debug locations of the original instructions might differ. Merge them.
1606 DebugLoc MergedLoc = DILocation::getMergedLocation(SI.getDebugLoc(),
1607 OtherStore->getDebugLoc());
Chris Lattnera65e2f72010-01-05 05:57:49 +00001608 if (MergedVal != SI.getOperand(0)) {
Jay Foad52131342011-03-30 11:28:46 +00001609 PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge");
Chris Lattnera65e2f72010-01-05 05:57:49 +00001610 PN->addIncoming(SI.getOperand(0), SI.getParent());
1611 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
1612 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Vedant Kumar238533e2018-11-19 19:55:02 +00001613 PN->setDebugLoc(MergedLoc);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001614 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001615
Sanjay Patel4a12aa92018-11-10 20:29:25 +00001616 // Advance to a place where it is safe to insert the new store and insert it.
Bill Wendling8ddfc092011-08-16 20:45:24 +00001617 BBI = DestBB->getFirstInsertionPt();
Eli Friedman35211c62011-05-27 00:19:40 +00001618 StoreInst *NewSI = new StoreInst(MergedVal, SI.getOperand(1),
Sanjay Patel4a12aa92018-11-10 20:29:25 +00001619 SI.isVolatile(), SI.getAlignment(),
1620 SI.getOrdering(), SI.getSyncScopeID());
Eli Friedman35211c62011-05-27 00:19:40 +00001621 InsertNewInstBefore(NewSI, *BBI);
Vedant Kumar238533e2018-11-19 19:55:02 +00001622 NewSI->setDebugLoc(MergedLoc);
Eli Friedman35211c62011-05-27 00:19:40 +00001623
Hal Finkelcc39b672014-07-24 12:16:19 +00001624 // If the two stores had AA tags, merge them.
1625 AAMDNodes AATags;
1626 SI.getAAMetadata(AATags);
1627 if (AATags) {
1628 OtherStore->getAAMetadata(AATags, /* Merge = */ true);
1629 NewSI->setAAMetadata(AATags);
1630 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001631
Chris Lattnera65e2f72010-01-05 05:57:49 +00001632 // Nuke the old stores.
Sanjay Patel4b198802016-02-01 22:23:39 +00001633 eraseInstFromFunction(SI);
1634 eraseInstFromFunction(*OtherStore);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001635 return true;
1636}