blob: fcee6b00266e7de9aa76c0412a2434257480eb5b [file] [log] [blame]
Chris Lattnera65e2f72010-01-05 05:57:49 +00001//===- InstCombineLoadStoreAlloca.cpp -------------------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattnera65e2f72010-01-05 05:57:49 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the visit functions for load, store and alloca.
10//
11//===----------------------------------------------------------------------===//
12
Chandler Carrutha9174582015-01-22 05:25:13 +000013#include "InstCombineInternal.h"
Yaxun Liuba01ed02017-02-10 21:46:07 +000014#include "llvm/ADT/MapVector.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"
David Blaikie31b98d22018-06-04 21:23:21 +000018#include "llvm/Transforms/Utils/Local.h"
Peter Collingbourneecdd58f2016-10-21 19:59:26 +000019#include "llvm/IR/ConstantRange.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000020#include "llvm/IR/DataLayout.h"
Vedant Kumar238533e2018-11-19 19:55:02 +000021#include "llvm/IR/DebugInfoMetadata.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000022#include "llvm/IR/IntrinsicInst.h"
Yaxun Liuba01ed02017-02-10 21:46:07 +000023#include "llvm/IR/LLVMContext.h"
Charles Davis33d1dc02015-02-25 05:10:25 +000024#include "llvm/IR/MDBuilder.h"
Alexey Bataevec95c6c2017-12-08 15:32:10 +000025#include "llvm/IR/PatternMatch.h"
Chris Lattnera65e2f72010-01-05 05:57:49 +000026#include "llvm/Transforms/Utils/BasicBlockUtils.h"
Chris Lattnera65e2f72010-01-05 05:57:49 +000027using namespace llvm;
Alexey Bataevec95c6c2017-12-08 15:32:10 +000028using namespace PatternMatch;
Chris Lattnera65e2f72010-01-05 05:57:49 +000029
Chandler Carruth964daaa2014-04-22 02:55:47 +000030#define DEBUG_TYPE "instcombine"
31
Chandler Carruthc908ca12012-08-21 08:39:44 +000032STATISTIC(NumDeadStore, "Number of dead stores eliminated");
33STATISTIC(NumGlobalCopies, "Number of allocas copied from constant global");
34
35/// pointsToConstantGlobal - Return true if V (possibly indirectly) points to
36/// some part of a constant global variable. This intentionally only accepts
37/// constant expressions because we can't rewrite arbitrary instructions.
38static bool pointsToConstantGlobal(Value *V) {
39 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
40 return GV->isConstant();
Matt Arsenault607281772014-04-24 00:01:09 +000041
42 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
Chandler Carruthc908ca12012-08-21 08:39:44 +000043 if (CE->getOpcode() == Instruction::BitCast ||
Matt Arsenault607281772014-04-24 00:01:09 +000044 CE->getOpcode() == Instruction::AddrSpaceCast ||
Chandler Carruthc908ca12012-08-21 08:39:44 +000045 CE->getOpcode() == Instruction::GetElementPtr)
46 return pointsToConstantGlobal(CE->getOperand(0));
Matt Arsenault607281772014-04-24 00:01:09 +000047 }
Chandler Carruthc908ca12012-08-21 08:39:44 +000048 return false;
49}
50
51/// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
52/// pointer to an alloca. Ignore any reads of the pointer, return false if we
53/// see any stores or other unknown uses. If we see pointer arithmetic, keep
54/// track of whether it moves the pointer (with IsOffset) but otherwise traverse
55/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
56/// the alloca, and if the source pointer is a pointer to a constant global, we
57/// can optimize this.
58static bool
59isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
Reid Kleckner813dab22014-07-01 21:36:20 +000060 SmallVectorImpl<Instruction *> &ToDelete) {
Chandler Carruthc908ca12012-08-21 08:39:44 +000061 // We track lifetime intrinsics as we encounter them. If we decide to go
62 // ahead and replace the value with the global, this lets the caller quickly
63 // eliminate the markers.
64
Reid Kleckner813dab22014-07-01 21:36:20 +000065 SmallVector<std::pair<Value *, bool>, 35> ValuesToInspect;
David Majnemer0a16c222016-08-11 21:15:00 +000066 ValuesToInspect.emplace_back(V, false);
Reid Kleckner813dab22014-07-01 21:36:20 +000067 while (!ValuesToInspect.empty()) {
68 auto ValuePair = ValuesToInspect.pop_back_val();
69 const bool IsOffset = ValuePair.second;
70 for (auto &U : ValuePair.first->uses()) {
David Majnemer0a16c222016-08-11 21:15:00 +000071 auto *I = cast<Instruction>(U.getUser());
Chandler Carruthc908ca12012-08-21 08:39:44 +000072
David Majnemer0a16c222016-08-11 21:15:00 +000073 if (auto *LI = dyn_cast<LoadInst>(I)) {
Reid Kleckner813dab22014-07-01 21:36:20 +000074 // Ignore non-volatile loads, they are always ok.
75 if (!LI->isSimple()) return false;
Chandler Carruthc908ca12012-08-21 08:39:44 +000076 continue;
77 }
Reid Kleckner813dab22014-07-01 21:36:20 +000078
79 if (isa<BitCastInst>(I) || isa<AddrSpaceCastInst>(I)) {
80 // If uses of the bitcast are ok, we are ok.
David Majnemer0a16c222016-08-11 21:15:00 +000081 ValuesToInspect.emplace_back(I, IsOffset);
Reid Kleckner813dab22014-07-01 21:36:20 +000082 continue;
83 }
David Majnemer0a16c222016-08-11 21:15:00 +000084 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
Reid Kleckner813dab22014-07-01 21:36:20 +000085 // If the GEP has all zero indices, it doesn't offset the pointer. If it
86 // doesn't, it does.
David Majnemer0a16c222016-08-11 21:15:00 +000087 ValuesToInspect.emplace_back(I, IsOffset || !GEP->hasAllZeroIndices());
Reid Kleckner813dab22014-07-01 21:36:20 +000088 continue;
89 }
90
Craig Topperc1892ec2019-01-31 17:23:29 +000091 if (auto *Call = dyn_cast<CallBase>(I)) {
Reid Kleckner813dab22014-07-01 21:36:20 +000092 // If this is the function being called then we treat it like a load and
93 // ignore it.
Craig Topperc1892ec2019-01-31 17:23:29 +000094 if (Call->isCallee(&U))
Reid Kleckner813dab22014-07-01 21:36:20 +000095 continue;
96
Craig Topperc1892ec2019-01-31 17:23:29 +000097 unsigned DataOpNo = Call->getDataOperandNo(&U);
98 bool IsArgOperand = Call->isArgOperand(&U);
David Majnemer02f47872015-12-23 09:58:41 +000099
Reid Kleckner813dab22014-07-01 21:36:20 +0000100 // Inalloca arguments are clobbered by the call.
Craig Topperc1892ec2019-01-31 17:23:29 +0000101 if (IsArgOperand && Call->isInAllocaArgument(DataOpNo))
Reid Kleckner813dab22014-07-01 21:36:20 +0000102 return false;
103
104 // If this is a readonly/readnone call site, then we know it is just a
105 // load (but one that potentially returns the value itself), so we can
106 // ignore it if we know that the value isn't captured.
Craig Topperc1892ec2019-01-31 17:23:29 +0000107 if (Call->onlyReadsMemory() &&
108 (Call->use_empty() || Call->doesNotCapture(DataOpNo)))
Reid Kleckner813dab22014-07-01 21:36:20 +0000109 continue;
110
111 // If this is being passed as a byval argument, the caller is making a
112 // copy, so it is only a read of the alloca.
Craig Topperc1892ec2019-01-31 17:23:29 +0000113 if (IsArgOperand && Call->isByValArgument(DataOpNo))
Reid Kleckner813dab22014-07-01 21:36:20 +0000114 continue;
115 }
116
117 // Lifetime intrinsics can be handled by the caller.
Vedant Kumarb264d692018-12-21 21:49:40 +0000118 if (I->isLifetimeStartOrEnd()) {
119 assert(I->use_empty() && "Lifetime markers have no result to use!");
120 ToDelete.push_back(I);
121 continue;
Reid Kleckner813dab22014-07-01 21:36:20 +0000122 }
123
124 // If this is isn't our memcpy/memmove, reject it as something we can't
125 // handle.
126 MemTransferInst *MI = dyn_cast<MemTransferInst>(I);
127 if (!MI)
128 return false;
129
130 // If the transfer is using the alloca as a source of the transfer, then
131 // ignore it since it is a load (unless the transfer is volatile).
132 if (U.getOperandNo() == 1) {
133 if (MI->isVolatile()) return false;
134 continue;
135 }
136
137 // If we already have seen a copy, reject the second one.
138 if (TheCopy) return false;
139
140 // If the pointer has been offset from the start of the alloca, we can't
141 // safely handle this.
142 if (IsOffset) return false;
143
144 // If the memintrinsic isn't using the alloca as the dest, reject it.
145 if (U.getOperandNo() != 0) return false;
146
147 // If the source of the memcpy/move is not a constant global, reject it.
148 if (!pointsToConstantGlobal(MI->getSource()))
149 return false;
150
151 // Otherwise, the transform is safe. Remember the copy instruction.
152 TheCopy = MI;
Chandler Carruthc908ca12012-08-21 08:39:44 +0000153 }
Chandler Carruthc908ca12012-08-21 08:39:44 +0000154 }
155 return true;
156}
157
158/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
159/// modified by a copy from a constant global. If we can prove this, we can
160/// replace any uses of the alloca with uses of the global directly.
161static MemTransferInst *
162isOnlyCopiedFromConstantGlobal(AllocaInst *AI,
163 SmallVectorImpl<Instruction *> &ToDelete) {
Craig Topperf40110f2014-04-25 05:29:35 +0000164 MemTransferInst *TheCopy = nullptr;
Chandler Carruthc908ca12012-08-21 08:39:44 +0000165 if (isOnlyCopiedFromConstantGlobal(AI, TheCopy, ToDelete))
166 return TheCopy;
Craig Topperf40110f2014-04-25 05:29:35 +0000167 return nullptr;
Chandler Carruthc908ca12012-08-21 08:39:44 +0000168}
169
Vitaly Bukadf19ad42017-06-24 01:35:19 +0000170/// Returns true if V is dereferenceable for size of alloca.
171static bool isDereferenceableForAllocaSize(const Value *V, const AllocaInst *AI,
172 const DataLayout &DL) {
173 if (AI->isArrayAllocation())
174 return false;
175 uint64_t AllocaSize = DL.getTypeStoreSize(AI->getAllocatedType());
176 if (!AllocaSize)
177 return false;
178 return isDereferenceableAndAlignedPointer(V, AI->getAlignment(),
179 APInt(64, AllocaSize), DL);
180}
181
Duncan P. N. Exon Smithc6820ec2015-03-13 19:22:03 +0000182static Instruction *simplifyAllocaArraySize(InstCombiner &IC, AllocaInst &AI) {
Duncan P. N. Exon Smith720762e2015-03-13 19:30:44 +0000183 // Check for array size of 1 (scalar allocation).
Duncan P. N. Exon Smithbe95b4a2015-03-13 19:42:09 +0000184 if (!AI.isArrayAllocation()) {
185 // i32 1 is the canonical array size for scalar allocations.
186 if (AI.getArraySize()->getType()->isIntegerTy(32))
187 return nullptr;
188
189 // Canonicalize it.
Craig Topperbb4069e2017-07-07 23:16:26 +0000190 Value *V = IC.Builder.getInt32(1);
Duncan P. N. Exon Smithbe95b4a2015-03-13 19:42:09 +0000191 AI.setOperand(0, V);
192 return &AI;
193 }
Duncan P. N. Exon Smith720762e2015-03-13 19:30:44 +0000194
Chris Lattnera65e2f72010-01-05 05:57:49 +0000195 // 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 +0000196 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
Simon Pilgrim82edf8d2018-08-13 16:50:20 +0000197 if (C->getValue().getActiveBits() <= 64) {
198 Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
199 AllocaInst *New = IC.Builder.CreateAlloca(NewTy, nullptr, AI.getName());
200 New->setAlignment(AI.getAlignment());
Chris Lattnera65e2f72010-01-05 05:57:49 +0000201
Simon Pilgrim82edf8d2018-08-13 16:50:20 +0000202 // Scan to the end of the allocation instructions, to skip over a block of
203 // allocas if possible...also skip interleaved debug info
204 //
205 BasicBlock::iterator It(New);
206 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It))
207 ++It;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000208
Simon Pilgrim82edf8d2018-08-13 16:50:20 +0000209 // Now that I is pointing to the first non-allocation-inst in the block,
210 // insert our getelementptr instruction...
211 //
212 Type *IdxTy = IC.getDataLayout().getIntPtrType(AI.getType());
213 Value *NullIdx = Constant::getNullValue(IdxTy);
214 Value *Idx[2] = {NullIdx, NullIdx};
James Y Knight77160752019-02-01 20:44:47 +0000215 Instruction *GEP = GetElementPtrInst::CreateInBounds(
216 NewTy, New, Idx, New->getName() + ".sub");
Simon Pilgrim82edf8d2018-08-13 16:50:20 +0000217 IC.InsertNewInstBefore(GEP, *It);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000218
Simon Pilgrim82edf8d2018-08-13 16:50:20 +0000219 // Now make everything use the getelementptr instead of the original
220 // allocation.
221 return IC.replaceInstUsesWith(AI, GEP);
222 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000223 }
224
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000225 if (isa<UndefValue>(AI.getArraySize()))
Sanjay Patel4b198802016-02-01 22:23:39 +0000226 return IC.replaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000227
Duncan P. N. Exon Smith07ff9b02015-03-13 19:34:55 +0000228 // Ensure that the alloca array size argument has type intptr_t, so that
229 // any casting is exposed early.
230 Type *IntPtrTy = IC.getDataLayout().getIntPtrType(AI.getType());
231 if (AI.getArraySize()->getType() != IntPtrTy) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000232 Value *V = IC.Builder.CreateIntCast(AI.getArraySize(), IntPtrTy, false);
Duncan P. N. Exon Smith07ff9b02015-03-13 19:34:55 +0000233 AI.setOperand(0, V);
234 return &AI;
235 }
236
Duncan P. N. Exon Smithc6820ec2015-03-13 19:22:03 +0000237 return nullptr;
238}
239
Benjamin Kramer03ab8a32017-02-10 22:26:35 +0000240namespace {
Yaxun Liuba01ed02017-02-10 21:46:07 +0000241// If I and V are pointers in different address space, it is not allowed to
242// use replaceAllUsesWith since I and V have different types. A
243// non-target-specific transformation should not use addrspacecast on V since
244// the two address space may be disjoint depending on target.
245//
246// This class chases down uses of the old pointer until reaching the load
247// instructions, then replaces the old pointer in the load instructions with
248// the new pointer. If during the chasing it sees bitcast or GEP, it will
249// create new bitcast or GEP with the new pointer and use them in the load
250// instruction.
251class PointerReplacer {
252public:
253 PointerReplacer(InstCombiner &IC) : IC(IC) {}
254 void replacePointer(Instruction &I, Value *V);
255
256private:
257 void findLoadAndReplace(Instruction &I);
258 void replace(Instruction *I);
259 Value *getReplacement(Value *I);
260
261 SmallVector<Instruction *, 4> Path;
262 MapVector<Value *, Value *> WorkMap;
263 InstCombiner &IC;
264};
Benjamin Kramer03ab8a32017-02-10 22:26:35 +0000265} // end anonymous namespace
Yaxun Liuba01ed02017-02-10 21:46:07 +0000266
267void PointerReplacer::findLoadAndReplace(Instruction &I) {
268 for (auto U : I.users()) {
269 auto *Inst = dyn_cast<Instruction>(&*U);
270 if (!Inst)
271 return;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000272 LLVM_DEBUG(dbgs() << "Found pointer user: " << *U << '\n');
Yaxun Liuba01ed02017-02-10 21:46:07 +0000273 if (isa<LoadInst>(Inst)) {
274 for (auto P : Path)
275 replace(P);
276 replace(Inst);
277 } else if (isa<GetElementPtrInst>(Inst) || isa<BitCastInst>(Inst)) {
278 Path.push_back(Inst);
279 findLoadAndReplace(*Inst);
280 Path.pop_back();
281 } else {
282 return;
283 }
284 }
285}
286
287Value *PointerReplacer::getReplacement(Value *V) {
288 auto Loc = WorkMap.find(V);
289 if (Loc != WorkMap.end())
290 return Loc->second;
291 return nullptr;
292}
293
294void PointerReplacer::replace(Instruction *I) {
295 if (getReplacement(I))
296 return;
297
298 if (auto *LT = dyn_cast<LoadInst>(I)) {
299 auto *V = getReplacement(LT->getPointerOperand());
300 assert(V && "Operand not replaced");
James Y Knight14359ef2019-02-01 20:44:24 +0000301 auto *NewI = new LoadInst(I->getType(), V);
Yaxun Liuba01ed02017-02-10 21:46:07 +0000302 NewI->takeName(LT);
303 IC.InsertNewInstWith(NewI, *LT);
304 IC.replaceInstUsesWith(*LT, NewI);
305 WorkMap[LT] = NewI;
306 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
307 auto *V = getReplacement(GEP->getPointerOperand());
308 assert(V && "Operand not replaced");
309 SmallVector<Value *, 8> Indices;
310 Indices.append(GEP->idx_begin(), GEP->idx_end());
311 auto *NewI = GetElementPtrInst::Create(
312 V->getType()->getPointerElementType(), V, Indices);
313 IC.InsertNewInstWith(NewI, *GEP);
314 NewI->takeName(GEP);
315 WorkMap[GEP] = NewI;
316 } else if (auto *BC = dyn_cast<BitCastInst>(I)) {
317 auto *V = getReplacement(BC->getOperand(0));
318 assert(V && "Operand not replaced");
319 auto *NewT = PointerType::get(BC->getType()->getPointerElementType(),
320 V->getType()->getPointerAddressSpace());
321 auto *NewI = new BitCastInst(V, NewT);
322 IC.InsertNewInstWith(NewI, *BC);
323 NewI->takeName(BC);
Yaxun Liue6d1ce52017-02-24 20:27:25 +0000324 WorkMap[BC] = NewI;
Yaxun Liuba01ed02017-02-10 21:46:07 +0000325 } else {
326 llvm_unreachable("should never reach here");
327 }
328}
329
330void PointerReplacer::replacePointer(Instruction &I, Value *V) {
Benjamin Kramer684c87b2017-02-10 22:04:17 +0000331#ifndef NDEBUG
Yaxun Liuba01ed02017-02-10 21:46:07 +0000332 auto *PT = cast<PointerType>(I.getType());
333 auto *NT = cast<PointerType>(V->getType());
334 assert(PT != NT && PT->getElementType() == NT->getElementType() &&
335 "Invalid usage");
Benjamin Kramer684c87b2017-02-10 22:04:17 +0000336#endif
Yaxun Liuba01ed02017-02-10 21:46:07 +0000337 WorkMap[&I] = V;
338 findLoadAndReplace(I);
339}
340
Duncan P. N. Exon Smithc6820ec2015-03-13 19:22:03 +0000341Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
342 if (auto *I = simplifyAllocaArraySize(*this, AI))
343 return I;
344
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000345 if (AI.getAllocatedType()->isSized()) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000346 // If the alignment is 0 (unspecified), assign it the preferred alignment.
347 if (AI.getAlignment() == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000348 AI.setAlignment(DL.getPrefTypeAlignment(AI.getAllocatedType()));
Duncan Sands8bc764a2012-06-26 13:39:21 +0000349
350 // Move all alloca's of zero byte objects to the entry block and merge them
351 // together. Note that we only do this for alloca's, because malloc should
352 // allocate and return a unique pointer, even for a zero byte allocation.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000353 if (DL.getTypeAllocSize(AI.getAllocatedType()) == 0) {
Duncan Sands8bc764a2012-06-26 13:39:21 +0000354 // For a zero sized alloca there is no point in doing an array allocation.
355 // This is helpful if the array size is a complicated expression not used
356 // elsewhere.
357 if (AI.isArrayAllocation()) {
358 AI.setOperand(0, ConstantInt::get(AI.getArraySize()->getType(), 1));
359 return &AI;
360 }
361
362 // Get the first instruction in the entry block.
363 BasicBlock &EntryBlock = AI.getParent()->getParent()->getEntryBlock();
364 Instruction *FirstInst = EntryBlock.getFirstNonPHIOrDbg();
365 if (FirstInst != &AI) {
366 // If the entry block doesn't start with a zero-size alloca then move
367 // this one to the start of the entry block. There is no problem with
368 // dominance as the array size was forced to a constant earlier already.
369 AllocaInst *EntryAI = dyn_cast<AllocaInst>(FirstInst);
370 if (!EntryAI || !EntryAI->getAllocatedType()->isSized() ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000371 DL.getTypeAllocSize(EntryAI->getAllocatedType()) != 0) {
Duncan Sands8bc764a2012-06-26 13:39:21 +0000372 AI.moveBefore(FirstInst);
373 return &AI;
374 }
375
Richard Osborneb68053e2012-09-18 09:31:44 +0000376 // If the alignment of the entry block alloca is 0 (unspecified),
377 // assign it the preferred alignment.
378 if (EntryAI->getAlignment() == 0)
379 EntryAI->setAlignment(
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000380 DL.getPrefTypeAlignment(EntryAI->getAllocatedType()));
Duncan Sands8bc764a2012-06-26 13:39:21 +0000381 // Replace this zero-sized alloca with the one at the start of the entry
382 // block after ensuring that the address will be aligned enough for both
383 // types.
Richard Osborneb68053e2012-09-18 09:31:44 +0000384 unsigned MaxAlign = std::max(EntryAI->getAlignment(),
385 AI.getAlignment());
Duncan Sands8bc764a2012-06-26 13:39:21 +0000386 EntryAI->setAlignment(MaxAlign);
387 if (AI.getType() != EntryAI->getType())
388 return new BitCastInst(EntryAI, AI.getType());
Sanjay Patel4b198802016-02-01 22:23:39 +0000389 return replaceInstUsesWith(AI, EntryAI);
Duncan Sands8bc764a2012-06-26 13:39:21 +0000390 }
391 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000392 }
393
Eli Friedmanb14873c2012-11-26 23:04:53 +0000394 if (AI.getAlignment()) {
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000395 // Check to see if this allocation is only modified by a memcpy/memmove from
396 // a constant global whose alignment is equal to or exceeds that of the
397 // allocation. If this is the case, we can change all users to use
398 // the constant global instead. This is commonly produced by the CFE by
399 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
400 // is only subsequently read.
401 SmallVector<Instruction *, 4> ToDelete;
402 if (MemTransferInst *Copy = isOnlyCopiedFromConstantGlobal(&AI, ToDelete)) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000403 unsigned SourceAlign = getOrEnforceKnownAlignment(
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000404 Copy->getSource(), AI.getAlignment(), DL, &AI, &AC, &DT);
Vitaly Bukadf19ad42017-06-24 01:35:19 +0000405 if (AI.getAlignment() <= SourceAlign &&
406 isDereferenceableForAllocaSize(Copy->getSource(), &AI, DL)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000407 LLVM_DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n');
408 LLVM_DEBUG(dbgs() << " memcpy = " << *Copy << '\n');
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000409 for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
Sanjay Patel4b198802016-02-01 22:23:39 +0000410 eraseInstFromFunction(*ToDelete[i]);
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000411 Constant *TheSrc = cast<Constant>(Copy->getSource());
Yaxun Liuba01ed02017-02-10 21:46:07 +0000412 auto *SrcTy = TheSrc->getType();
413 auto *DestTy = PointerType::get(AI.getType()->getPointerElementType(),
414 SrcTy->getPointerAddressSpace());
415 Constant *Cast =
416 ConstantExpr::getPointerBitCastOrAddrSpaceCast(TheSrc, DestTy);
417 if (AI.getType()->getPointerAddressSpace() ==
418 SrcTy->getPointerAddressSpace()) {
419 Instruction *NewI = replaceInstUsesWith(AI, Cast);
420 eraseInstFromFunction(*Copy);
421 ++NumGlobalCopies;
422 return NewI;
423 } else {
424 PointerReplacer PtrReplacer(*this);
425 PtrReplacer.replacePointer(AI, Cast);
426 ++NumGlobalCopies;
427 }
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000428 }
Chandler Carruthc908ca12012-08-21 08:39:44 +0000429 }
430 }
431
Nuno Lopes95cc4f32012-07-09 18:38:20 +0000432 // At last, use the generic allocation site handler to aggressively remove
433 // unused allocas.
434 return visitAllocSite(AI);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000435}
436
Philip Reames89e92d22016-12-01 20:17:06 +0000437// Are we allowed to form a atomic load or store of this type?
438static bool isSupportedAtomicType(Type *Ty) {
Vedant Kumarb3091da2018-07-06 20:17:42 +0000439 return Ty->isIntOrPtrTy() || Ty->isFloatingPointTy();
Philip Reames89e92d22016-12-01 20:17:06 +0000440}
441
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000442/// Helper to combine a load to a new type.
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000443///
444/// This just does the work of combining a load to a new type. It handles
445/// metadata, etc., and returns the new instruction. The \c NewTy should be the
446/// loaded *value* type. This will convert it to a pointer, cast the operand to
447/// that pointer type, load it, etc.
448///
449/// Note that this will create all of the instructions with whatever insert
450/// point the \c InstCombiner currently is using.
Mehdi Amini2668a482015-05-07 05:52:40 +0000451static LoadInst *combineLoadToNewType(InstCombiner &IC, LoadInst &LI, Type *NewTy,
452 const Twine &Suffix = "") {
Philip Reames89e92d22016-12-01 20:17:06 +0000453 assert((!LI.isAtomic() || isSupportedAtomicType(NewTy)) &&
454 "can't fold an atomic load to requested type");
Alexey Bataev7c9ad0d2018-05-21 17:46:34 +0000455
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000456 Value *Ptr = LI.getPointerOperand();
457 unsigned AS = LI.getPointerAddressSpace();
Alexey Bataev7c9ad0d2018-05-21 17:46:34 +0000458 Value *NewPtr = nullptr;
459 if (!(match(Ptr, m_BitCast(m_Value(NewPtr))) &&
460 NewPtr->getType()->getPointerElementType() == NewTy &&
461 NewPtr->getType()->getPointerAddressSpace() == AS))
462 NewPtr = IC.Builder.CreateBitCast(Ptr, NewTy->getPointerTo(AS));
463
Craig Topperbb4069e2017-07-07 23:16:26 +0000464 LoadInst *NewLoad = IC.Builder.CreateAlignedLoad(
James Y Knight14359ef2019-02-01 20:44:24 +0000465 NewTy, NewPtr, LI.getAlignment(), LI.isVolatile(), LI.getName() + Suffix);
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +0000466 NewLoad->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
Sanjay Patel86e9f9d2019-07-24 22:11:11 +0000467 copyMetadataForLoad(*NewLoad, LI);
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000468 return NewLoad;
469}
470
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000471/// Combine a store to a new type.
Chandler Carruthfa11d832015-01-22 03:34:54 +0000472///
473/// Returns the newly created store instruction.
474static StoreInst *combineStoreToNewValue(InstCombiner &IC, StoreInst &SI, Value *V) {
Philip Reames89e92d22016-12-01 20:17:06 +0000475 assert((!SI.isAtomic() || isSupportedAtomicType(V->getType())) &&
476 "can't fold an atomic store of requested type");
Fangrui Songf78650a2018-07-30 19:41:25 +0000477
Chandler Carruthfa11d832015-01-22 03:34:54 +0000478 Value *Ptr = SI.getPointerOperand();
479 unsigned AS = SI.getPointerAddressSpace();
480 SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
481 SI.getAllMetadata(MD);
482
Craig Topperbb4069e2017-07-07 23:16:26 +0000483 StoreInst *NewStore = IC.Builder.CreateAlignedStore(
484 V, IC.Builder.CreateBitCast(Ptr, V->getType()->getPointerTo(AS)),
Philip Reames6f4d0082016-05-06 22:17:01 +0000485 SI.getAlignment(), SI.isVolatile());
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +0000486 NewStore->setAtomic(SI.getOrdering(), SI.getSyncScopeID());
Chandler Carruthfa11d832015-01-22 03:34:54 +0000487 for (const auto &MDPair : MD) {
488 unsigned ID = MDPair.first;
489 MDNode *N = MDPair.second;
490 // Note, essentially every kind of metadata should be preserved here! This
491 // routine is supposed to clone a store instruction changing *only its
492 // type*. The only metadata it makes sense to drop is metadata which is
493 // invalidated when the pointer type changes. This should essentially
494 // never be the case in LLVM, but we explicitly switch over only known
495 // metadata to be conservatively correct. If you are adding metadata to
496 // LLVM which pertains to stores, you almost certainly want to add it
497 // here.
498 switch (ID) {
499 case LLVMContext::MD_dbg:
500 case LLVMContext::MD_tbaa:
501 case LLVMContext::MD_prof:
502 case LLVMContext::MD_fpmath:
503 case LLVMContext::MD_tbaa_struct:
504 case LLVMContext::MD_alias_scope:
505 case LLVMContext::MD_noalias:
506 case LLVMContext::MD_nontemporal:
507 case LLVMContext::MD_mem_parallel_loop_access:
Michael Kruse19942712018-12-20 17:11:02 +0000508 case LLVMContext::MD_access_group:
Chandler Carruthfa11d832015-01-22 03:34:54 +0000509 // All of these directly apply.
510 NewStore->setMetadata(ID, N);
511 break;
Chandler Carruthfa11d832015-01-22 03:34:54 +0000512 case LLVMContext::MD_invariant_load:
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000513 case LLVMContext::MD_nonnull:
Chandler Carruthfa11d832015-01-22 03:34:54 +0000514 case LLVMContext::MD_range:
Artur Pilipenko5c5011d2015-11-02 17:53:51 +0000515 case LLVMContext::MD_align:
516 case LLVMContext::MD_dereferenceable:
517 case LLVMContext::MD_dereferenceable_or_null:
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000518 // These don't apply for stores.
Chandler Carruthfa11d832015-01-22 03:34:54 +0000519 break;
520 }
521 }
522
523 return NewStore;
524}
525
Alexey Bataevec95c6c2017-12-08 15:32:10 +0000526/// Returns true if instruction represent minmax pattern like:
527/// select ((cmp load V1, load V2), V1, V2).
528static bool isMinMaxWithLoads(Value *V) {
529 assert(V->getType()->isPointerTy() && "Expected pointer type.");
530 // Ignore possible ty* to ixx* bitcast.
531 V = peekThroughBitcast(V);
532 // Check that select is select ((cmp load V1, load V2), V1, V2) - minmax
533 // pattern.
534 CmpInst::Predicate Pred;
535 Instruction *L1;
536 Instruction *L2;
537 Value *LHS;
538 Value *RHS;
539 if (!match(V, m_Select(m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2)),
540 m_Value(LHS), m_Value(RHS))))
541 return false;
542 return (match(L1, m_Load(m_Specific(LHS))) &&
543 match(L2, m_Load(m_Specific(RHS)))) ||
544 (match(L1, m_Load(m_Specific(RHS))) &&
545 match(L2, m_Load(m_Specific(LHS))));
546}
547
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000548/// Combine loads to match the type of their uses' value after looking
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000549/// through intervening bitcasts.
550///
551/// The core idea here is that if the result of a load is used in an operation,
552/// we should load the type most conducive to that operation. For example, when
553/// loading an integer and converting that immediately to a pointer, we should
554/// instead directly load a pointer.
555///
556/// However, this routine must never change the width of a load or the number of
557/// loads as that would introduce a semantic change. This combine is expected to
558/// be a semantic no-op which just allows loads to more closely model the types
559/// of their consuming operations.
560///
561/// Currently, we also refuse to change the precise type used for an atomic load
562/// or a volatile load. This is debatable, and might be reasonable to change
563/// later. However, it is risky in case some backend or other part of LLVM is
564/// relying on the exact type loaded to select appropriate atomic operations.
565static Instruction *combineLoadToOperationType(InstCombiner &IC, LoadInst &LI) {
Philip Reames6f4d0082016-05-06 22:17:01 +0000566 // FIXME: We could probably with some care handle both volatile and ordered
567 // atomic loads here but it isn't clear that this is important.
568 if (!LI.isUnordered())
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000569 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000570
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000571 if (LI.use_empty())
572 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000573
Arnold Schwaighofer5d335552016-09-10 18:14:57 +0000574 // swifterror values can't be bitcasted.
575 if (LI.getPointerOperand()->isSwiftError())
576 return nullptr;
577
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000578 Type *Ty = LI.getType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000579 const DataLayout &DL = IC.getDataLayout();
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000580
581 // Try to canonicalize loads which are only ever stored to operate over
582 // integers instead of any other type. We only do this when the loaded type
583 // is sized and has a size exactly the same as its store size and the store
584 // size is a legal integer type.
Alexey Bataevec95c6c2017-12-08 15:32:10 +0000585 // Do not perform canonicalization if minmax pattern is found (to avoid
586 // infinite loop).
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000587 if (!Ty->isIntegerTy() && Ty->isSized() &&
588 DL.isLegalInteger(DL.getTypeStoreSizeInBits(Ty)) &&
Bjorn Petterssonb4771422019-05-24 09:20:20 +0000589 DL.typeSizeEqualsStoreSize(Ty) &&
Alexey Bataevec95c6c2017-12-08 15:32:10 +0000590 !DL.isNonIntegralPointerType(Ty) &&
591 !isMinMaxWithLoads(
592 peekThroughBitcast(LI.getPointerOperand(), /*OneUseOnly=*/true))) {
David Majnemer0a16c222016-08-11 21:15:00 +0000593 if (all_of(LI.users(), [&LI](User *U) {
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000594 auto *SI = dyn_cast<StoreInst>(U);
Arnold Schwaighoferc3685632017-01-31 17:53:49 +0000595 return SI && SI->getPointerOperand() != &LI &&
596 !SI->getPointerOperand()->isSwiftError();
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000597 })) {
598 LoadInst *NewLoad = combineLoadToNewType(
599 IC, LI,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000600 Type::getIntNTy(LI.getContext(), DL.getTypeStoreSizeInBits(Ty)));
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000601 // Replace all the stores with stores of the newly loaded value.
602 for (auto UI = LI.user_begin(), UE = LI.user_end(); UI != UE;) {
603 auto *SI = cast<StoreInst>(*UI++);
Craig Topperbb4069e2017-07-07 23:16:26 +0000604 IC.Builder.SetInsertPoint(SI);
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000605 combineStoreToNewValue(IC, *SI, NewLoad);
Sanjay Patel4b198802016-02-01 22:23:39 +0000606 IC.eraseInstFromFunction(*SI);
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000607 }
608 assert(LI.use_empty() && "Failed to remove all users of the load!");
609 // Return the old load so the combiner can delete it safely.
610 return &LI;
611 }
612 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000613
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000614 // Fold away bit casts of the loaded value by loading the desired type.
Quentin Colombet490cfbe2016-02-11 22:30:41 +0000615 // We can do this for BitCastInsts as well as casts from and to pointer types,
616 // as long as those are noops (i.e., the source or dest type have the same
617 // bitwidth as the target's pointers).
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000618 if (LI.hasOneUse())
Philip Reames89e92d22016-12-01 20:17:06 +0000619 if (auto* CI = dyn_cast<CastInst>(LI.user_back()))
620 if (CI->isNoopCast(DL))
621 if (!LI.isAtomic() || isSupportedAtomicType(CI->getDestTy())) {
622 LoadInst *NewLoad = combineLoadToNewType(IC, LI, CI->getDestTy());
623 CI->replaceAllUsesWith(NewLoad);
624 IC.eraseInstFromFunction(*CI);
625 return &LI;
626 }
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000627
Chandler Carrutha7f247e2014-12-09 19:21:16 +0000628 // FIXME: We should also canonicalize loads of vectors when their elements are
629 // cast to other types.
Craig Topperf40110f2014-04-25 05:29:35 +0000630 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000631}
632
Mehdi Amini2668a482015-05-07 05:52:40 +0000633static Instruction *unpackLoadToAggregate(InstCombiner &IC, LoadInst &LI) {
634 // FIXME: We could probably with some care handle both volatile and atomic
635 // stores here but it isn't clear that this is important.
636 if (!LI.isSimple())
637 return nullptr;
638
639 Type *T = LI.getType();
640 if (!T->isAggregateType())
641 return nullptr;
642
Benjamin Kramerc1263532016-03-11 10:20:56 +0000643 StringRef Name = LI.getName();
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000644 assert(LI.getAlignment() && "Alignment must be set at this point");
Mehdi Amini2668a482015-05-07 05:52:40 +0000645
646 if (auto *ST = dyn_cast<StructType>(T)) {
647 // If the struct only have one element, we unpack.
Amaury Sechet61a7d622016-02-17 19:21:28 +0000648 auto NumElements = ST->getNumElements();
649 if (NumElements == 1) {
Mehdi Amini2668a482015-05-07 05:52:40 +0000650 LoadInst *NewLoad = combineLoadToNewType(IC, LI, ST->getTypeAtIndex(0U),
651 ".unpack");
Keno Fischera236dae2017-06-28 23:36:40 +0000652 AAMDNodes AAMD;
653 LI.getAAMetadata(AAMD);
654 NewLoad->setAAMetadata(AAMD);
Craig Topperbb4069e2017-07-07 23:16:26 +0000655 return IC.replaceInstUsesWith(LI, IC.Builder.CreateInsertValue(
Amaury Sechet61a7d622016-02-17 19:21:28 +0000656 UndefValue::get(T), NewLoad, 0, Name));
Mehdi Amini2668a482015-05-07 05:52:40 +0000657 }
Mehdi Amini1c131b32015-12-15 01:44:07 +0000658
659 // We don't want to break loads with padding here as we'd loose
660 // the knowledge that padding exists for the rest of the pipeline.
661 const DataLayout &DL = IC.getDataLayout();
662 auto *SL = DL.getStructLayout(ST);
663 if (SL->hasPadding())
664 return nullptr;
665
Amaury Sechet61a7d622016-02-17 19:21:28 +0000666 auto Align = LI.getAlignment();
667 if (!Align)
668 Align = DL.getABITypeAlignment(ST);
669
Mehdi Amini1c131b32015-12-15 01:44:07 +0000670 auto *Addr = LI.getPointerOperand();
Amaury Sechet61a7d622016-02-17 19:21:28 +0000671 auto *IdxType = Type::getInt32Ty(T->getContext());
Mehdi Amini1c131b32015-12-15 01:44:07 +0000672 auto *Zero = ConstantInt::get(IdxType, 0);
Amaury Sechet61a7d622016-02-17 19:21:28 +0000673
674 Value *V = UndefValue::get(T);
675 for (unsigned i = 0; i < NumElements; i++) {
Mehdi Amini1c131b32015-12-15 01:44:07 +0000676 Value *Indices[2] = {
677 Zero,
678 ConstantInt::get(IdxType, i),
679 };
Craig Topperbb4069e2017-07-07 23:16:26 +0000680 auto *Ptr = IC.Builder.CreateInBoundsGEP(ST, Addr, makeArrayRef(Indices),
681 Name + ".elt");
Amaury Sechet61a7d622016-02-17 19:21:28 +0000682 auto EltAlign = MinAlign(Align, SL->getElementOffset(i));
James Y Knight14359ef2019-02-01 20:44:24 +0000683 auto *L = IC.Builder.CreateAlignedLoad(ST->getElementType(i), Ptr,
684 EltAlign, Name + ".unpack");
Keno Fischera236dae2017-06-28 23:36:40 +0000685 // Propagate AA metadata. It'll still be valid on the narrowed load.
686 AAMDNodes AAMD;
687 LI.getAAMetadata(AAMD);
688 L->setAAMetadata(AAMD);
Craig Topperbb4069e2017-07-07 23:16:26 +0000689 V = IC.Builder.CreateInsertValue(V, L, i);
Mehdi Amini1c131b32015-12-15 01:44:07 +0000690 }
691
692 V->setName(Name);
Sanjay Patel4b198802016-02-01 22:23:39 +0000693 return IC.replaceInstUsesWith(LI, V);
Mehdi Amini2668a482015-05-07 05:52:40 +0000694 }
695
David Majnemer58fb0382015-05-11 05:04:22 +0000696 if (auto *AT = dyn_cast<ArrayType>(T)) {
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000697 auto *ET = AT->getElementType();
698 auto NumElements = AT->getNumElements();
699 if (NumElements == 1) {
700 LoadInst *NewLoad = combineLoadToNewType(IC, LI, ET, ".unpack");
Keno Fischera236dae2017-06-28 23:36:40 +0000701 AAMDNodes AAMD;
702 LI.getAAMetadata(AAMD);
703 NewLoad->setAAMetadata(AAMD);
Craig Topperbb4069e2017-07-07 23:16:26 +0000704 return IC.replaceInstUsesWith(LI, IC.Builder.CreateInsertValue(
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000705 UndefValue::get(T), NewLoad, 0, Name));
David Majnemer58fb0382015-05-11 05:04:22 +0000706 }
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000707
Davide Italianoda114122016-10-07 20:57:42 +0000708 // Bail out if the array is too large. Ideally we would like to optimize
709 // arrays of arbitrary size but this has a terrible impact on compile time.
710 // The threshold here is chosen arbitrarily, maybe needs a little bit of
711 // tuning.
Davide Italiano2133bf52017-02-07 17:56:50 +0000712 if (NumElements > IC.MaxArraySizeForCombine)
Davide Italianoda114122016-10-07 20:57:42 +0000713 return nullptr;
714
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000715 const DataLayout &DL = IC.getDataLayout();
716 auto EltSize = DL.getTypeAllocSize(ET);
717 auto Align = LI.getAlignment();
718 if (!Align)
719 Align = DL.getABITypeAlignment(T);
720
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000721 auto *Addr = LI.getPointerOperand();
722 auto *IdxType = Type::getInt64Ty(T->getContext());
723 auto *Zero = ConstantInt::get(IdxType, 0);
724
725 Value *V = UndefValue::get(T);
726 uint64_t Offset = 0;
727 for (uint64_t i = 0; i < NumElements; i++) {
728 Value *Indices[2] = {
729 Zero,
730 ConstantInt::get(IdxType, i),
731 };
Craig Topperbb4069e2017-07-07 23:16:26 +0000732 auto *Ptr = IC.Builder.CreateInBoundsGEP(AT, Addr, makeArrayRef(Indices),
733 Name + ".elt");
James Y Knight14359ef2019-02-01 20:44:24 +0000734 auto *L = IC.Builder.CreateAlignedLoad(
735 AT->getElementType(), Ptr, MinAlign(Align, Offset), Name + ".unpack");
Keno Fischera236dae2017-06-28 23:36:40 +0000736 AAMDNodes AAMD;
737 LI.getAAMetadata(AAMD);
738 L->setAAMetadata(AAMD);
Craig Topperbb4069e2017-07-07 23:16:26 +0000739 V = IC.Builder.CreateInsertValue(V, L, i);
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000740 Offset += EltSize;
741 }
742
743 V->setName(Name);
744 return IC.replaceInstUsesWith(LI, V);
David Majnemer58fb0382015-05-11 05:04:22 +0000745 }
746
Mehdi Amini2668a482015-05-07 05:52:40 +0000747 return nullptr;
748}
749
Hal Finkel847e05f2015-02-20 03:05:53 +0000750// If we can determine that all possible objects pointed to by the provided
751// pointer value are, not only dereferenceable, but also definitively less than
752// or equal to the provided maximum size, then return true. Otherwise, return
753// false (constant global values and allocas fall into this category).
754//
755// FIXME: This should probably live in ValueTracking (or similar).
756static bool isObjectSizeLessThanOrEq(Value *V, uint64_t MaxSize,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000757 const DataLayout &DL) {
Hal Finkel847e05f2015-02-20 03:05:53 +0000758 SmallPtrSet<Value *, 4> Visited;
759 SmallVector<Value *, 4> Worklist(1, V);
760
761 do {
762 Value *P = Worklist.pop_back_val();
763 P = P->stripPointerCasts();
764
765 if (!Visited.insert(P).second)
766 continue;
767
768 if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
769 Worklist.push_back(SI->getTrueValue());
770 Worklist.push_back(SI->getFalseValue());
771 continue;
772 }
773
774 if (PHINode *PN = dyn_cast<PHINode>(P)) {
Pete Cooper833f34d2015-05-12 20:05:31 +0000775 for (Value *IncValue : PN->incoming_values())
776 Worklist.push_back(IncValue);
Hal Finkel847e05f2015-02-20 03:05:53 +0000777 continue;
778 }
779
780 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(P)) {
Sanjoy Das99042472016-04-17 04:30:43 +0000781 if (GA->isInterposable())
Hal Finkel847e05f2015-02-20 03:05:53 +0000782 return false;
783 Worklist.push_back(GA->getAliasee());
784 continue;
785 }
786
787 // If we know how big this object is, and it is less than MaxSize, continue
788 // searching. Otherwise, return false.
789 if (AllocaInst *AI = dyn_cast<AllocaInst>(P)) {
790 if (!AI->getAllocatedType()->isSized())
791 return false;
792
793 ConstantInt *CS = dyn_cast<ConstantInt>(AI->getArraySize());
794 if (!CS)
795 return false;
796
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000797 uint64_t TypeSize = DL.getTypeAllocSize(AI->getAllocatedType());
Hal Finkel847e05f2015-02-20 03:05:53 +0000798 // Make sure that, even if the multiplication below would wrap as an
799 // uint64_t, we still do the right thing.
800 if ((CS->getValue().zextOrSelf(128)*APInt(128, TypeSize)).ugt(MaxSize))
801 return false;
802 continue;
803 }
804
805 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
806 if (!GV->hasDefinitiveInitializer() || !GV->isConstant())
807 return false;
808
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000809 uint64_t InitSize = DL.getTypeAllocSize(GV->getValueType());
Hal Finkel847e05f2015-02-20 03:05:53 +0000810 if (InitSize > MaxSize)
811 return false;
812 continue;
813 }
814
815 return false;
816 } while (!Worklist.empty());
817
818 return true;
819}
820
821// If we're indexing into an object of a known size, and the outer index is
822// not a constant, but having any value but zero would lead to undefined
823// behavior, replace it with zero.
824//
825// For example, if we have:
826// @f.a = private unnamed_addr constant [1 x i32] [i32 12], align 4
827// ...
828// %arrayidx = getelementptr inbounds [1 x i32]* @f.a, i64 0, i64 %x
829// ... = load i32* %arrayidx, align 4
830// Then we know that we can replace %x in the GEP with i64 0.
831//
832// FIXME: We could fold any GEP index to zero that would cause UB if it were
833// not zero. Currently, we only handle the first such index. Also, we could
834// also search through non-zero constant indices if we kept track of the
835// offsets those indices implied.
836static bool canReplaceGEPIdxWithZero(InstCombiner &IC, GetElementPtrInst *GEPI,
837 Instruction *MemI, unsigned &Idx) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000838 if (GEPI->getNumOperands() < 2)
Hal Finkel847e05f2015-02-20 03:05:53 +0000839 return false;
840
841 // Find the first non-zero index of a GEP. If all indices are zero, return
842 // one past the last index.
843 auto FirstNZIdx = [](const GetElementPtrInst *GEPI) {
844 unsigned I = 1;
845 for (unsigned IE = GEPI->getNumOperands(); I != IE; ++I) {
846 Value *V = GEPI->getOperand(I);
847 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
848 if (CI->isZero())
849 continue;
850
851 break;
852 }
853
854 return I;
855 };
856
857 // Skip through initial 'zero' indices, and find the corresponding pointer
858 // type. See if the next index is not a constant.
859 Idx = FirstNZIdx(GEPI);
860 if (Idx == GEPI->getNumOperands())
861 return false;
862 if (isa<Constant>(GEPI->getOperand(Idx)))
863 return false;
864
865 SmallVector<Value *, 4> Ops(GEPI->idx_begin(), GEPI->idx_begin() + Idx);
Eduard Burtescu19eb0312016-01-19 17:28:00 +0000866 Type *AllocTy =
867 GetElementPtrInst::getIndexedType(GEPI->getSourceElementType(), Ops);
Hal Finkel847e05f2015-02-20 03:05:53 +0000868 if (!AllocTy || !AllocTy->isSized())
869 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000870 const DataLayout &DL = IC.getDataLayout();
871 uint64_t TyAllocSize = DL.getTypeAllocSize(AllocTy);
Hal Finkel847e05f2015-02-20 03:05:53 +0000872
873 // If there are more indices after the one we might replace with a zero, make
874 // sure they're all non-negative. If any of them are negative, the overall
875 // address being computed might be before the base address determined by the
876 // first non-zero index.
877 auto IsAllNonNegative = [&]() {
878 for (unsigned i = Idx+1, e = GEPI->getNumOperands(); i != e; ++i) {
Craig Topper1a36b7d2017-05-15 06:39:41 +0000879 KnownBits Known = IC.computeKnownBits(GEPI->getOperand(i), 0, MemI);
880 if (Known.isNonNegative())
Hal Finkel847e05f2015-02-20 03:05:53 +0000881 continue;
882 return false;
883 }
884
885 return true;
886 };
887
888 // FIXME: If the GEP is not inbounds, and there are extra indices after the
889 // one we'll replace, those could cause the address computation to wrap
890 // (rendering the IsAllNonNegative() check below insufficient). We can do
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000891 // better, ignoring zero indices (and other indices we can prove small
Hal Finkel847e05f2015-02-20 03:05:53 +0000892 // enough not to wrap).
893 if (Idx+1 != GEPI->getNumOperands() && !GEPI->isInBounds())
894 return false;
895
896 // Note that isObjectSizeLessThanOrEq will return true only if the pointer is
897 // also known to be dereferenceable.
898 return isObjectSizeLessThanOrEq(GEPI->getOperand(0), TyAllocSize, DL) &&
899 IsAllNonNegative();
900}
901
902// If we're indexing into an object with a variable index for the memory
903// access, but the object has only one element, we can assume that the index
904// will always be zero. If we replace the GEP, return it.
905template <typename T>
906static Instruction *replaceGEPIdxWithZero(InstCombiner &IC, Value *Ptr,
907 T &MemI) {
908 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr)) {
909 unsigned Idx;
910 if (canReplaceGEPIdxWithZero(IC, GEPI, &MemI, Idx)) {
911 Instruction *NewGEPI = GEPI->clone();
912 NewGEPI->setOperand(Idx,
913 ConstantInt::get(GEPI->getOperand(Idx)->getType(), 0));
914 NewGEPI->insertBefore(GEPI);
915 MemI.setOperand(MemI.getPointerOperandIndex(), NewGEPI);
916 return NewGEPI;
917 }
918 }
919
920 return nullptr;
921}
922
Anna Thomas2dd98352017-12-12 14:12:33 +0000923static bool canSimplifyNullStoreOrGEP(StoreInst &SI) {
Manoj Gupta77eeac32018-07-09 22:27:23 +0000924 if (NullPointerIsDefined(SI.getFunction(), SI.getPointerAddressSpace()))
Anna Thomas2dd98352017-12-12 14:12:33 +0000925 return false;
926
927 auto *Ptr = SI.getPointerOperand();
928 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr))
929 Ptr = GEPI->getOperand(0);
Manoj Gupta77eeac32018-07-09 22:27:23 +0000930 return (isa<ConstantPointerNull>(Ptr) &&
931 !NullPointerIsDefined(SI.getFunction(), SI.getPointerAddressSpace()));
Anna Thomas2dd98352017-12-12 14:12:33 +0000932}
933
Davide Italianoffcb4df2017-04-19 17:26:57 +0000934static bool canSimplifyNullLoadOrGEP(LoadInst &LI, Value *Op) {
935 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
936 const Value *GEPI0 = GEPI->getOperand(0);
Manoj Gupta77eeac32018-07-09 22:27:23 +0000937 if (isa<ConstantPointerNull>(GEPI0) &&
938 !NullPointerIsDefined(LI.getFunction(), GEPI->getPointerAddressSpace()))
Davide Italianoffcb4df2017-04-19 17:26:57 +0000939 return true;
940 }
941 if (isa<UndefValue>(Op) ||
Manoj Gupta77eeac32018-07-09 22:27:23 +0000942 (isa<ConstantPointerNull>(Op) &&
943 !NullPointerIsDefined(LI.getFunction(), LI.getPointerAddressSpace())))
Davide Italianoffcb4df2017-04-19 17:26:57 +0000944 return true;
945 return false;
946}
947
Chris Lattnera65e2f72010-01-05 05:57:49 +0000948Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
949 Value *Op = LI.getOperand(0);
950
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000951 // Try to canonicalize the loaded type.
952 if (Instruction *Res = combineLoadToOperationType(*this, LI))
953 return Res;
954
Chris Lattnera65e2f72010-01-05 05:57:49 +0000955 // Attempt to improve the alignment.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000956 unsigned KnownAlign = getOrEnforceKnownAlignment(
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000957 Op, DL.getPrefTypeAlignment(LI.getType()), DL, &LI, &AC, &DT);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000958 unsigned LoadAlign = LI.getAlignment();
959 unsigned EffectiveLoadAlign =
960 LoadAlign != 0 ? LoadAlign : DL.getABITypeAlignment(LI.getType());
Dan Gohman36196602010-08-03 18:20:32 +0000961
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000962 if (KnownAlign > EffectiveLoadAlign)
Guillaume Chatelet17380222019-09-30 09:37:05 +0000963 LI.setAlignment(MaybeAlign(KnownAlign));
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000964 else if (LoadAlign == 0)
Guillaume Chatelet17380222019-09-30 09:37:05 +0000965 LI.setAlignment(MaybeAlign(EffectiveLoadAlign));
Chris Lattnera65e2f72010-01-05 05:57:49 +0000966
Hal Finkel847e05f2015-02-20 03:05:53 +0000967 // Replace GEP indices if possible.
968 if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Op, LI)) {
969 Worklist.Add(NewGEPI);
970 return &LI;
971 }
972
Mehdi Amini2668a482015-05-07 05:52:40 +0000973 if (Instruction *Res = unpackLoadToAggregate(*this, LI))
974 return Res;
975
Chris Lattnera65e2f72010-01-05 05:57:49 +0000976 // Do really simple store-to-load forwarding and load CSE, to catch cases
Duncan Sands75b5d272011-02-15 09:23:02 +0000977 // where there are several consecutive memory accesses to the same location,
Chris Lattnera65e2f72010-01-05 05:57:49 +0000978 // separated by a few arithmetic operations.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000979 BasicBlock::iterator BBI(LI);
Eli Friedmanbd254a62016-06-16 02:33:42 +0000980 bool IsLoadCSE = false;
Sanjay Patelb38ad88e2017-01-02 23:25:28 +0000981 if (Value *AvailableVal = FindAvailableLoadedValue(
982 &LI, LI.getParent(), BBI, DefMaxInstsToScan, AA, &IsLoadCSE)) {
983 if (IsLoadCSE)
Florian Hahn406f1ff2018-08-24 11:40:04 +0000984 combineMetadataForCSE(cast<LoadInst>(AvailableVal), &LI, false);
Bjorn Steinbrinka91fd092015-07-10 06:55:44 +0000985
Sanjay Patel4b198802016-02-01 22:23:39 +0000986 return replaceInstUsesWith(
Craig Topperbb4069e2017-07-07 23:16:26 +0000987 LI, Builder.CreateBitOrPointerCast(AvailableVal, LI.getType(),
988 LI.getName() + ".cast"));
Bjorn Steinbrinka91fd092015-07-10 06:55:44 +0000989 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000990
Philip Reames3ac07182016-04-21 17:45:05 +0000991 // None of the following transforms are legal for volatile/ordered atomic
992 // loads. Most of them do apply for unordered atomics.
993 if (!LI.isUnordered()) return nullptr;
Philip Reamesac550902016-04-21 17:03:33 +0000994
Chris Lattnera65e2f72010-01-05 05:57:49 +0000995 // load(gep null, ...) -> unreachable
Chris Lattnera65e2f72010-01-05 05:57:49 +0000996 // load null/undef -> unreachable
Davide Italianoffcb4df2017-04-19 17:26:57 +0000997 // TODO: Consider a target hook for valid address spaces for this xforms.
998 if (canSimplifyNullLoadOrGEP(LI, Op)) {
999 // Insert a new store to null instruction before the load to indicate
1000 // that this code is not reachable. We do this instead of inserting
1001 // an unreachable instruction directly because we cannot modify the
1002 // CFG.
Weiming Zhao984f1dc2017-07-19 01:27:24 +00001003 StoreInst *SI = new StoreInst(UndefValue::get(LI.getType()),
1004 Constant::getNullValue(Op->getType()), &LI);
1005 SI->setDebugLoc(LI.getDebugLoc());
Sanjay Patel4b198802016-02-01 22:23:39 +00001006 return replaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattnera65e2f72010-01-05 05:57:49 +00001007 }
1008
Chris Lattnera65e2f72010-01-05 05:57:49 +00001009 if (Op->hasOneUse()) {
1010 // Change select and PHI nodes to select values instead of addresses: this
1011 // helps alias analysis out a lot, allows many others simplifications, and
1012 // exposes redundancy in the code.
1013 //
1014 // Note that we cannot do the transformation unless we know that the
1015 // introduced loads cannot trap! Something like this is valid as long as
1016 // the condition is always false: load (select bool %C, int* null, int* %G),
1017 // but it would not be valid if we transformed it to load from null
1018 // unconditionally.
1019 //
1020 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
1021 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Bob Wilson56600a12010-01-30 04:42:39 +00001022 unsigned Align = LI.getAlignment();
Tim Northover60afa492019-07-09 11:35:35 +00001023 if (isSafeToLoadUnconditionally(SI->getOperand(1), LI.getType(), Align,
1024 DL, SI) &&
1025 isSafeToLoadUnconditionally(SI->getOperand(2), LI.getType(), Align,
1026 DL, SI)) {
James Y Knight14359ef2019-02-01 20:44:24 +00001027 LoadInst *V1 =
1028 Builder.CreateLoad(LI.getType(), SI->getOperand(1),
1029 SI->getOperand(1)->getName() + ".val");
1030 LoadInst *V2 =
1031 Builder.CreateLoad(LI.getType(), SI->getOperand(2),
1032 SI->getOperand(2)->getName() + ".val");
Philip Reamesa98c7ea2016-04-21 17:59:40 +00001033 assert(LI.isUnordered() && "implied by above");
Guillaume Chatelet17380222019-09-30 09:37:05 +00001034 V1->setAlignment(MaybeAlign(Align));
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00001035 V1->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
Guillaume Chatelet17380222019-09-30 09:37:05 +00001036 V2->setAlignment(MaybeAlign(Align));
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00001037 V2->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
Chris Lattnera65e2f72010-01-05 05:57:49 +00001038 return SelectInst::Create(SI->getCondition(), V1, V2);
1039 }
1040
1041 // load (select (cond, null, P)) -> load P
Larisse Voufo532bf712015-09-18 19:14:35 +00001042 if (isa<ConstantPointerNull>(SI->getOperand(1)) &&
Manoj Gupta77eeac32018-07-09 22:27:23 +00001043 !NullPointerIsDefined(SI->getFunction(),
1044 LI.getPointerAddressSpace())) {
Philip Reames5ad26c32014-12-29 22:46:21 +00001045 LI.setOperand(0, SI->getOperand(2));
1046 return &LI;
1047 }
Chris Lattnera65e2f72010-01-05 05:57:49 +00001048
1049 // load (select (cond, P, null)) -> load P
Philip Reames5ad26c32014-12-29 22:46:21 +00001050 if (isa<ConstantPointerNull>(SI->getOperand(2)) &&
Manoj Gupta77eeac32018-07-09 22:27:23 +00001051 !NullPointerIsDefined(SI->getFunction(),
1052 LI.getPointerAddressSpace())) {
Philip Reames5ad26c32014-12-29 22:46:21 +00001053 LI.setOperand(0, SI->getOperand(1));
1054 return &LI;
1055 }
Chris Lattnera65e2f72010-01-05 05:57:49 +00001056 }
1057 }
Craig Topperf40110f2014-04-25 05:29:35 +00001058 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001059}
1060
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001061/// Look for extractelement/insertvalue sequence that acts like a bitcast.
Arch D. Robisonbe0490a2016-04-25 22:22:39 +00001062///
1063/// \returns underlying value that was "cast", or nullptr otherwise.
1064///
1065/// For example, if we have:
1066///
1067/// %E0 = extractelement <2 x double> %U, i32 0
1068/// %V0 = insertvalue [2 x double] undef, double %E0, 0
1069/// %E1 = extractelement <2 x double> %U, i32 1
1070/// %V1 = insertvalue [2 x double] %V0, double %E1, 1
1071///
1072/// and the layout of a <2 x double> is isomorphic to a [2 x double],
1073/// then %V1 can be safely approximated by a conceptual "bitcast" of %U.
1074/// Note that %U may contain non-undef values where %V1 has undef.
1075static Value *likeBitCastFromVector(InstCombiner &IC, Value *V) {
1076 Value *U = nullptr;
1077 while (auto *IV = dyn_cast<InsertValueInst>(V)) {
1078 auto *E = dyn_cast<ExtractElementInst>(IV->getInsertedValueOperand());
1079 if (!E)
1080 return nullptr;
1081 auto *W = E->getVectorOperand();
1082 if (!U)
1083 U = W;
1084 else if (U != W)
1085 return nullptr;
1086 auto *CI = dyn_cast<ConstantInt>(E->getIndexOperand());
1087 if (!CI || IV->getNumIndices() != 1 || CI->getZExtValue() != *IV->idx_begin())
1088 return nullptr;
1089 V = IV->getAggregateOperand();
1090 }
1091 if (!isa<UndefValue>(V) ||!U)
1092 return nullptr;
1093
1094 auto *UT = cast<VectorType>(U->getType());
1095 auto *VT = V->getType();
1096 // Check that types UT and VT are bitwise isomorphic.
1097 const auto &DL = IC.getDataLayout();
1098 if (DL.getTypeStoreSizeInBits(UT) != DL.getTypeStoreSizeInBits(VT)) {
1099 return nullptr;
1100 }
1101 if (auto *AT = dyn_cast<ArrayType>(VT)) {
1102 if (AT->getNumElements() != UT->getNumElements())
1103 return nullptr;
1104 } else {
1105 auto *ST = cast<StructType>(VT);
1106 if (ST->getNumElements() != UT->getNumElements())
1107 return nullptr;
1108 for (const auto *EltT : ST->elements()) {
1109 if (EltT != UT->getElementType())
1110 return nullptr;
1111 }
1112 }
1113 return U;
1114}
1115
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001116/// Combine stores to match the type of value being stored.
Chandler Carruth816d26f2014-11-25 10:09:51 +00001117///
1118/// The core idea here is that the memory does not have any intrinsic type and
1119/// where we can we should match the type of a store to the type of value being
1120/// stored.
1121///
1122/// However, this routine must never change the width of a store or the number of
1123/// stores as that would introduce a semantic change. This combine is expected to
1124/// be a semantic no-op which just allows stores to more closely model the types
1125/// of their incoming values.
1126///
1127/// Currently, we also refuse to change the precise type used for an atomic or
1128/// volatile store. This is debatable, and might be reasonable to change later.
1129/// However, it is risky in case some backend or other part of LLVM is relying
1130/// on the exact type stored to select appropriate atomic operations.
1131///
1132/// \returns true if the store was successfully combined away. This indicates
1133/// the caller must erase the store instruction. We have to let the caller erase
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00001134/// the store instruction as otherwise there is no way to signal whether it was
Chandler Carruth816d26f2014-11-25 10:09:51 +00001135/// combined or not: IC.EraseInstFromFunction returns a null pointer.
1136static bool combineStoreToValueType(InstCombiner &IC, StoreInst &SI) {
Philip Reames6f4d0082016-05-06 22:17:01 +00001137 // FIXME: We could probably with some care handle both volatile and ordered
1138 // atomic stores here but it isn't clear that this is important.
1139 if (!SI.isUnordered())
Chandler Carruth816d26f2014-11-25 10:09:51 +00001140 return false;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001141
Arnold Schwaighofer5d335552016-09-10 18:14:57 +00001142 // swifterror values can't be bitcasted.
1143 if (SI.getPointerOperand()->isSwiftError())
1144 return false;
1145
Chandler Carruth816d26f2014-11-25 10:09:51 +00001146 Value *V = SI.getValueOperand();
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001147
Chandler Carruth816d26f2014-11-25 10:09:51 +00001148 // Fold away bit casts of the stored value by storing the original type.
1149 if (auto *BC = dyn_cast<BitCastInst>(V)) {
Chandler Carrutha7f247e2014-12-09 19:21:16 +00001150 V = BC->getOperand(0);
Philip Reames89e92d22016-12-01 20:17:06 +00001151 if (!SI.isAtomic() || isSupportedAtomicType(V->getType())) {
1152 combineStoreToNewValue(IC, SI, V);
1153 return true;
1154 }
Chris Lattnera65e2f72010-01-05 05:57:49 +00001155 }
1156
Philip Reames89e92d22016-12-01 20:17:06 +00001157 if (Value *U = likeBitCastFromVector(IC, V))
1158 if (!SI.isAtomic() || isSupportedAtomicType(U->getType())) {
1159 combineStoreToNewValue(IC, SI, U);
1160 return true;
1161 }
Arch D. Robisonbe0490a2016-04-25 22:22:39 +00001162
JF Bastienc22d2992016-04-21 19:53:39 +00001163 // FIXME: We should also canonicalize stores of vectors when their elements
1164 // are cast to other types.
Chandler Carruth816d26f2014-11-25 10:09:51 +00001165 return false;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001166}
1167
Mehdi Aminib344ac92015-03-14 22:19:33 +00001168static bool unpackStoreToAggregate(InstCombiner &IC, StoreInst &SI) {
1169 // FIXME: We could probably with some care handle both volatile and atomic
1170 // stores here but it isn't clear that this is important.
1171 if (!SI.isSimple())
1172 return false;
1173
1174 Value *V = SI.getValueOperand();
1175 Type *T = V->getType();
1176
1177 if (!T->isAggregateType())
1178 return false;
1179
Mehdi Amini2668a482015-05-07 05:52:40 +00001180 if (auto *ST = dyn_cast<StructType>(T)) {
Mehdi Aminib344ac92015-03-14 22:19:33 +00001181 // If the struct only have one element, we unpack.
Mehdi Amini1c131b32015-12-15 01:44:07 +00001182 unsigned Count = ST->getNumElements();
1183 if (Count == 1) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001184 V = IC.Builder.CreateExtractValue(V, 0);
Mehdi Aminib344ac92015-03-14 22:19:33 +00001185 combineStoreToNewValue(IC, SI, V);
1186 return true;
1187 }
Mehdi Amini1c131b32015-12-15 01:44:07 +00001188
1189 // We don't want to break loads with padding here as we'd loose
1190 // the knowledge that padding exists for the rest of the pipeline.
1191 const DataLayout &DL = IC.getDataLayout();
1192 auto *SL = DL.getStructLayout(ST);
1193 if (SL->hasPadding())
1194 return false;
1195
Amaury Sechet61a7d622016-02-17 19:21:28 +00001196 auto Align = SI.getAlignment();
1197 if (!Align)
1198 Align = DL.getABITypeAlignment(ST);
1199
NAKAMURA Takumiec6b1fc2015-12-15 09:37:31 +00001200 SmallString<16> EltName = V->getName();
1201 EltName += ".elt";
Mehdi Amini1c131b32015-12-15 01:44:07 +00001202 auto *Addr = SI.getPointerOperand();
NAKAMURA Takumiec6b1fc2015-12-15 09:37:31 +00001203 SmallString<16> AddrName = Addr->getName();
1204 AddrName += ".repack";
Amaury Sechet61a7d622016-02-17 19:21:28 +00001205
Mehdi Amini1c131b32015-12-15 01:44:07 +00001206 auto *IdxType = Type::getInt32Ty(ST->getContext());
1207 auto *Zero = ConstantInt::get(IdxType, 0);
1208 for (unsigned i = 0; i < Count; i++) {
1209 Value *Indices[2] = {
1210 Zero,
1211 ConstantInt::get(IdxType, i),
1212 };
Craig Topperbb4069e2017-07-07 23:16:26 +00001213 auto *Ptr = IC.Builder.CreateInBoundsGEP(ST, Addr, makeArrayRef(Indices),
1214 AddrName);
1215 auto *Val = IC.Builder.CreateExtractValue(V, i, EltName);
Amaury Sechet61a7d622016-02-17 19:21:28 +00001216 auto EltAlign = MinAlign(Align, SL->getElementOffset(i));
Craig Topperbb4069e2017-07-07 23:16:26 +00001217 llvm::Instruction *NS = IC.Builder.CreateAlignedStore(Val, Ptr, EltAlign);
Keno Fischera236dae2017-06-28 23:36:40 +00001218 AAMDNodes AAMD;
1219 SI.getAAMetadata(AAMD);
1220 NS->setAAMetadata(AAMD);
Mehdi Amini1c131b32015-12-15 01:44:07 +00001221 }
1222
1223 return true;
Mehdi Aminib344ac92015-03-14 22:19:33 +00001224 }
1225
David Majnemer75364602015-05-11 05:04:27 +00001226 if (auto *AT = dyn_cast<ArrayType>(T)) {
1227 // If the array only have one element, we unpack.
Amaury Sechet3b8b2ea2016-03-02 22:36:45 +00001228 auto NumElements = AT->getNumElements();
1229 if (NumElements == 1) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001230 V = IC.Builder.CreateExtractValue(V, 0);
David Majnemer75364602015-05-11 05:04:27 +00001231 combineStoreToNewValue(IC, SI, V);
1232 return true;
1233 }
Amaury Sechet3b8b2ea2016-03-02 22:36:45 +00001234
Davide Italianof6988d22016-10-07 21:53:09 +00001235 // Bail out if the array is too large. Ideally we would like to optimize
1236 // arrays of arbitrary size but this has a terrible impact on compile time.
1237 // The threshold here is chosen arbitrarily, maybe needs a little bit of
1238 // tuning.
Davide Italiano2133bf52017-02-07 17:56:50 +00001239 if (NumElements > IC.MaxArraySizeForCombine)
Davide Italianof6988d22016-10-07 21:53:09 +00001240 return false;
1241
Amaury Sechet3b8b2ea2016-03-02 22:36:45 +00001242 const DataLayout &DL = IC.getDataLayout();
1243 auto EltSize = DL.getTypeAllocSize(AT->getElementType());
1244 auto Align = SI.getAlignment();
1245 if (!Align)
1246 Align = DL.getABITypeAlignment(T);
1247
1248 SmallString<16> EltName = V->getName();
1249 EltName += ".elt";
1250 auto *Addr = SI.getPointerOperand();
1251 SmallString<16> AddrName = Addr->getName();
1252 AddrName += ".repack";
1253
1254 auto *IdxType = Type::getInt64Ty(T->getContext());
1255 auto *Zero = ConstantInt::get(IdxType, 0);
1256
1257 uint64_t Offset = 0;
1258 for (uint64_t i = 0; i < NumElements; i++) {
1259 Value *Indices[2] = {
1260 Zero,
1261 ConstantInt::get(IdxType, i),
1262 };
Craig Topperbb4069e2017-07-07 23:16:26 +00001263 auto *Ptr = IC.Builder.CreateInBoundsGEP(AT, Addr, makeArrayRef(Indices),
1264 AddrName);
1265 auto *Val = IC.Builder.CreateExtractValue(V, i, EltName);
Amaury Sechet3b8b2ea2016-03-02 22:36:45 +00001266 auto EltAlign = MinAlign(Align, Offset);
Craig Topperbb4069e2017-07-07 23:16:26 +00001267 Instruction *NS = IC.Builder.CreateAlignedStore(Val, Ptr, EltAlign);
Keno Fischera236dae2017-06-28 23:36:40 +00001268 AAMDNodes AAMD;
1269 SI.getAAMetadata(AAMD);
1270 NS->setAAMetadata(AAMD);
Amaury Sechet3b8b2ea2016-03-02 22:36:45 +00001271 Offset += EltSize;
1272 }
1273
1274 return true;
David Majnemer75364602015-05-11 05:04:27 +00001275 }
1276
Mehdi Aminib344ac92015-03-14 22:19:33 +00001277 return false;
1278}
1279
Chris Lattnera65e2f72010-01-05 05:57:49 +00001280/// equivalentAddressValues - Test if A and B will obviously have the same
1281/// value. This includes recognizing that %t0 and %t1 will have the same
1282/// value in code like this:
1283/// %t0 = getelementptr \@a, 0, 3
1284/// store i32 0, i32* %t0
1285/// %t1 = getelementptr \@a, 0, 3
1286/// %t2 = load i32* %t1
1287///
1288static bool equivalentAddressValues(Value *A, Value *B) {
1289 // Test if the values are trivially equivalent.
1290 if (A == B) return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001291
Chris Lattnera65e2f72010-01-05 05:57:49 +00001292 // Test if the values come form identical arithmetic instructions.
1293 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
1294 // its only used to compare two uses within the same basic block, which
1295 // means that they'll always either have the same value or one of them
1296 // will have an undefined value.
1297 if (isa<BinaryOperator>(A) ||
1298 isa<CastInst>(A) ||
1299 isa<PHINode>(A) ||
1300 isa<GetElementPtrInst>(A))
1301 if (Instruction *BI = dyn_cast<Instruction>(B))
1302 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
1303 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001304
Chris Lattnera65e2f72010-01-05 05:57:49 +00001305 // Otherwise they may not be equivalent.
1306 return false;
1307}
1308
Alexey Bataevec95c6c2017-12-08 15:32:10 +00001309/// Converts store (bitcast (load (bitcast (select ...)))) to
1310/// store (load (select ...)), where select is minmax:
1311/// select ((cmp load V1, load V2), V1, V2).
Alexey Bataev83c15b12017-12-12 20:28:46 +00001312static bool removeBitcastsFromLoadStoreOnMinMax(InstCombiner &IC,
1313 StoreInst &SI) {
Alexey Bataevec95c6c2017-12-08 15:32:10 +00001314 // bitcast?
Alexey Bataev83c15b12017-12-12 20:28:46 +00001315 if (!match(SI.getPointerOperand(), m_BitCast(m_Value())))
Alexey Bataevfa0a76d2017-12-12 19:12:34 +00001316 return false;
Alexey Bataevec95c6c2017-12-08 15:32:10 +00001317 // load? integer?
1318 Value *LoadAddr;
1319 if (!match(SI.getValueOperand(), m_Load(m_BitCast(m_Value(LoadAddr)))))
Alexey Bataevfa0a76d2017-12-12 19:12:34 +00001320 return false;
Alexey Bataevec95c6c2017-12-08 15:32:10 +00001321 auto *LI = cast<LoadInst>(SI.getValueOperand());
1322 if (!LI->getType()->isIntegerTy())
Alexey Bataevfa0a76d2017-12-12 19:12:34 +00001323 return false;
Alexey Bataevec95c6c2017-12-08 15:32:10 +00001324 if (!isMinMaxWithLoads(LoadAddr))
Alexey Bataevfa0a76d2017-12-12 19:12:34 +00001325 return false;
Alexey Bataevec95c6c2017-12-08 15:32:10 +00001326
Alexey Bataev83c15b12017-12-12 20:28:46 +00001327 if (!all_of(LI->users(), [LI, LoadAddr](User *U) {
1328 auto *SI = dyn_cast<StoreInst>(U);
1329 return SI && SI->getPointerOperand() != LI &&
1330 peekThroughBitcast(SI->getPointerOperand()) != LoadAddr &&
1331 !SI->getPointerOperand()->isSwiftError();
1332 }))
1333 return false;
1334
1335 IC.Builder.SetInsertPoint(LI);
Alexey Bataevec95c6c2017-12-08 15:32:10 +00001336 LoadInst *NewLI = combineLoadToNewType(
1337 IC, *LI, LoadAddr->getType()->getPointerElementType());
Alexey Bataev83c15b12017-12-12 20:28:46 +00001338 // Replace all the stores with stores of the newly loaded value.
1339 for (auto *UI : LI->users()) {
1340 auto *USI = cast<StoreInst>(UI);
1341 IC.Builder.SetInsertPoint(USI);
1342 combineStoreToNewValue(IC, *USI, NewLI);
1343 }
1344 IC.replaceInstUsesWith(*LI, UndefValue::get(LI->getType()));
1345 IC.eraseInstFromFunction(*LI);
Alexey Bataevfa0a76d2017-12-12 19:12:34 +00001346 return true;
Alexey Bataevec95c6c2017-12-08 15:32:10 +00001347}
1348
Chris Lattnera65e2f72010-01-05 05:57:49 +00001349Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
1350 Value *Val = SI.getOperand(0);
1351 Value *Ptr = SI.getOperand(1);
1352
Chandler Carruth816d26f2014-11-25 10:09:51 +00001353 // Try to canonicalize the stored type.
1354 if (combineStoreToValueType(*this, SI))
Sanjay Patel4b198802016-02-01 22:23:39 +00001355 return eraseInstFromFunction(SI);
Chandler Carruth816d26f2014-11-25 10:09:51 +00001356
Chris Lattnera65e2f72010-01-05 05:57:49 +00001357 // Attempt to improve the alignment.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001358 unsigned KnownAlign = getOrEnforceKnownAlignment(
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001359 Ptr, DL.getPrefTypeAlignment(Val->getType()), DL, &SI, &AC, &DT);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001360 unsigned StoreAlign = SI.getAlignment();
1361 unsigned EffectiveStoreAlign =
1362 StoreAlign != 0 ? StoreAlign : DL.getABITypeAlignment(Val->getType());
Dan Gohman36196602010-08-03 18:20:32 +00001363
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001364 if (KnownAlign > EffectiveStoreAlign)
1365 SI.setAlignment(KnownAlign);
1366 else if (StoreAlign == 0)
1367 SI.setAlignment(EffectiveStoreAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001368
Mehdi Aminib344ac92015-03-14 22:19:33 +00001369 // Try to canonicalize the stored type.
1370 if (unpackStoreToAggregate(*this, SI))
Sanjay Patel4b198802016-02-01 22:23:39 +00001371 return eraseInstFromFunction(SI);
Mehdi Aminib344ac92015-03-14 22:19:33 +00001372
Alexey Bataevfa0a76d2017-12-12 19:12:34 +00001373 if (removeBitcastsFromLoadStoreOnMinMax(*this, SI))
1374 return eraseInstFromFunction(SI);
Alexey Bataevec95c6c2017-12-08 15:32:10 +00001375
Hal Finkel847e05f2015-02-20 03:05:53 +00001376 // Replace GEP indices if possible.
1377 if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Ptr, SI)) {
1378 Worklist.Add(NewGEPI);
1379 return &SI;
1380 }
1381
Philip Reamesd7a6cc82015-12-17 22:19:27 +00001382 // Don't hack volatile/ordered stores.
1383 // FIXME: Some bits are legal for ordered atomic stores; needs refactoring.
1384 if (!SI.isUnordered()) return nullptr;
Eli Friedman8bc586e2011-08-15 22:09:40 +00001385
1386 // If the RHS is an alloca with a single use, zapify the store, making the
1387 // alloca dead.
1388 if (Ptr->hasOneUse()) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001389 if (isa<AllocaInst>(Ptr))
Sanjay Patel4b198802016-02-01 22:23:39 +00001390 return eraseInstFromFunction(SI);
Eli Friedman8bc586e2011-08-15 22:09:40 +00001391 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
1392 if (isa<AllocaInst>(GEP->getOperand(0))) {
1393 if (GEP->getOperand(0)->hasOneUse())
Sanjay Patel4b198802016-02-01 22:23:39 +00001394 return eraseInstFromFunction(SI);
Eli Friedman8bc586e2011-08-15 22:09:40 +00001395 }
1396 }
1397 }
1398
Philip Reamesd7486892019-04-22 20:28:19 +00001399 // If we have a store to a location which is known constant, we can conclude
1400 // that the store must be storing the constant value (else the memory
1401 // wouldn't be constant), and this must be a noop.
1402 if (AA->pointsToConstantMemory(Ptr))
1403 return eraseInstFromFunction(SI);
1404
Chris Lattnera65e2f72010-01-05 05:57:49 +00001405 // Do really simple DSE, to catch cases where there are several consecutive
1406 // stores to the same location, separated by a few arithmetic operations. This
1407 // situation often occurs with bitfield accesses.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00001408 BasicBlock::iterator BBI(SI);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001409 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
1410 --ScanInsts) {
1411 --BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +00001412 // Don't count debug info directives, lest they affect codegen,
1413 // and we skip pointer-to-pointer bitcasts, which are NOPs.
1414 if (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +00001415 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +00001416 ScanInsts++;
1417 continue;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001418 }
1419
Chris Lattnera65e2f72010-01-05 05:57:49 +00001420 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
1421 // Prev store isn't volatile, and stores to the same location?
Philip Reamesd7a6cc82015-12-17 22:19:27 +00001422 if (PrevSI->isUnordered() && equivalentAddressValues(PrevSI->getOperand(1),
Eli Friedman8bc586e2011-08-15 22:09:40 +00001423 SI.getOperand(1))) {
Chris Lattnera65e2f72010-01-05 05:57:49 +00001424 ++NumDeadStore;
1425 ++BBI;
Sanjay Patel4b198802016-02-01 22:23:39 +00001426 eraseInstFromFunction(*PrevSI);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001427 continue;
1428 }
1429 break;
1430 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001431
Chris Lattnera65e2f72010-01-05 05:57:49 +00001432 // If this is a load, we have to stop. However, if the loaded value is from
1433 // the pointer we're loading and is producing the pointer we're storing,
1434 // then *this* store is dead (X = load P; store X -> P).
1435 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Philip Reamesd7a6cc82015-12-17 22:19:27 +00001436 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr)) {
1437 assert(SI.isUnordered() && "can't eliminate ordering operation");
Sanjay Patel4b198802016-02-01 22:23:39 +00001438 return eraseInstFromFunction(SI);
Philip Reamesd7a6cc82015-12-17 22:19:27 +00001439 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001440
Chris Lattnera65e2f72010-01-05 05:57:49 +00001441 // Otherwise, this is a load from some other location. Stores before it
1442 // may not be dead.
1443 break;
1444 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001445
Sanjoy Das679bc322017-01-17 05:45:09 +00001446 // Don't skip over loads, throws or things that can modify memory.
1447 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory() || BBI->mayThrow())
Chris Lattnera65e2f72010-01-05 05:57:49 +00001448 break;
1449 }
Chris Lattnera65e2f72010-01-05 05:57:49 +00001450
1451 // store X, null -> turns into 'unreachable' in SimplifyCFG
Anna Thomas2dd98352017-12-12 14:12:33 +00001452 // store X, GEP(null, Y) -> turns into 'unreachable' in SimplifyCFG
1453 if (canSimplifyNullStoreOrGEP(SI)) {
Chris Lattnera65e2f72010-01-05 05:57:49 +00001454 if (!isa<UndefValue>(Val)) {
1455 SI.setOperand(0, UndefValue::get(Val->getType()));
1456 if (Instruction *U = dyn_cast<Instruction>(Val))
1457 Worklist.Add(U); // Dropped a use.
1458 }
Craig Topperf40110f2014-04-25 05:29:35 +00001459 return nullptr; // Do not modify these!
Chris Lattnera65e2f72010-01-05 05:57:49 +00001460 }
1461
1462 // store undef, Ptr -> noop
1463 if (isa<UndefValue>(Val))
Sanjay Patel4b198802016-02-01 22:23:39 +00001464 return eraseInstFromFunction(SI);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001465
Sanjay Patel4a12aa92018-11-10 20:29:25 +00001466 // If this store is the second-to-last instruction in the basic block
1467 // (excluding debug info and bitcasts of pointers) and if the block ends with
1468 // an unconditional branch, try to move the store to the successor block.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00001469 BBI = SI.getIterator();
Chris Lattnera65e2f72010-01-05 05:57:49 +00001470 do {
1471 ++BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +00001472 } while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +00001473 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()));
Sanjay Patel4a12aa92018-11-10 20:29:25 +00001474
Chris Lattnera65e2f72010-01-05 05:57:49 +00001475 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
1476 if (BI->isUnconditional())
Sanjay Patel4a12aa92018-11-10 20:29:25 +00001477 mergeStoreIntoSuccessor(SI);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001478
Craig Topperf40110f2014-04-25 05:29:35 +00001479 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001480}
1481
Sanjay Patel4a12aa92018-11-10 20:29:25 +00001482/// Try to transform:
Chris Lattnera65e2f72010-01-05 05:57:49 +00001483/// if () { *P = v1; } else { *P = v2 }
Sanjay Patel4a12aa92018-11-10 20:29:25 +00001484/// or:
Chris Lattnera65e2f72010-01-05 05:57:49 +00001485/// *P = v1; if () { *P = v2; }
1486/// into a phi node with a store in the successor.
Sanjay Patel4a12aa92018-11-10 20:29:25 +00001487bool InstCombiner::mergeStoreIntoSuccessor(StoreInst &SI) {
Philip Reames5f0e3692016-04-22 20:53:32 +00001488 assert(SI.isUnordered() &&
Sanjay Patel4a12aa92018-11-10 20:29:25 +00001489 "This code has not been audited for volatile or ordered store case.");
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00001490
Sanjay Patel4a12aa92018-11-10 20:29:25 +00001491 // Check if the successor block has exactly 2 incoming edges.
Chris Lattnera65e2f72010-01-05 05:57:49 +00001492 BasicBlock *StoreBB = SI.getParent();
Chris Lattnera65e2f72010-01-05 05:57:49 +00001493 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Vedant Kumar4de31bb2018-11-19 19:54:27 +00001494 if (!DestBB->hasNPredecessors(2))
Chris Lattnera65e2f72010-01-05 05:57:49 +00001495 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001496
Sanjay Patel4a12aa92018-11-10 20:29:25 +00001497 // Capture the other block (the block that doesn't contain our store).
1498 pred_iterator PredIter = pred_begin(DestBB);
1499 if (*PredIter == StoreBB)
1500 ++PredIter;
1501 BasicBlock *OtherBB = *PredIter;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001502
Sanjay Patel4a12aa92018-11-10 20:29:25 +00001503 // Bail out if all of the relevant blocks aren't distinct. This can happen,
1504 // for example, if SI is in an infinite loop.
Chris Lattnera65e2f72010-01-05 05:57:49 +00001505 if (StoreBB == DestBB || OtherBB == DestBB)
1506 return false;
1507
1508 // Verify that the other block ends in a branch and is not otherwise empty.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00001509 BasicBlock::iterator BBI(OtherBB->getTerminator());
Chris Lattnera65e2f72010-01-05 05:57:49 +00001510 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
1511 if (!OtherBr || BBI == OtherBB->begin())
1512 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001513
Chris Lattnera65e2f72010-01-05 05:57:49 +00001514 // If the other block ends in an unconditional branch, check for the 'if then
Sanjay Patel4a12aa92018-11-10 20:29:25 +00001515 // else' case. There is an instruction before the branch.
Craig Topperf40110f2014-04-25 05:29:35 +00001516 StoreInst *OtherStore = nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001517 if (OtherBr->isUnconditional()) {
1518 --BBI;
1519 // Skip over debugging info.
Victor Hernandez5f8c8c02010-01-22 19:05:05 +00001520 while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +00001521 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +00001522 if (BBI==OtherBB->begin())
1523 return false;
1524 --BBI;
1525 }
Eli Friedman8bc586e2011-08-15 22:09:40 +00001526 // If this isn't a store, isn't a store to the same location, or is not the
1527 // right kind of store, bail out.
Chris Lattnera65e2f72010-01-05 05:57:49 +00001528 OtherStore = dyn_cast<StoreInst>(BBI);
1529 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +00001530 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +00001531 return false;
1532 } else {
1533 // Otherwise, the other block ended with a conditional branch. If one of the
1534 // destinations is StoreBB, then we have the if/then case.
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001535 if (OtherBr->getSuccessor(0) != StoreBB &&
Chris Lattnera65e2f72010-01-05 05:57:49 +00001536 OtherBr->getSuccessor(1) != StoreBB)
1537 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001538
Chris Lattnera65e2f72010-01-05 05:57:49 +00001539 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
Sanjay Patel4a12aa92018-11-10 20:29:25 +00001540 // if/then triangle. See if there is a store to the same ptr as SI that
Chris Lattnera65e2f72010-01-05 05:57:49 +00001541 // lives in OtherBB.
1542 for (;; --BBI) {
1543 // Check to see if we find the matching store.
1544 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
1545 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +00001546 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +00001547 return false;
1548 break;
1549 }
1550 // If we find something that may be using or overwriting the stored
Sanjay Patel4a12aa92018-11-10 20:29:25 +00001551 // value, or if we run out of instructions, we can't do the transform.
Sanjoy Das679bc322017-01-17 05:45:09 +00001552 if (BBI->mayReadFromMemory() || BBI->mayThrow() ||
1553 BBI->mayWriteToMemory() || BBI == OtherBB->begin())
Chris Lattnera65e2f72010-01-05 05:57:49 +00001554 return false;
1555 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001556
Sanjay Patel4a12aa92018-11-10 20:29:25 +00001557 // In order to eliminate the store in OtherBr, we have to make sure nothing
1558 // reads or overwrites the stored value in StoreBB.
Chris Lattnera65e2f72010-01-05 05:57:49 +00001559 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
1560 // FIXME: This should really be AA driven.
Sanjoy Das679bc322017-01-17 05:45:09 +00001561 if (I->mayReadFromMemory() || I->mayThrow() || I->mayWriteToMemory())
Chris Lattnera65e2f72010-01-05 05:57:49 +00001562 return false;
1563 }
1564 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001565
Chris Lattnera65e2f72010-01-05 05:57:49 +00001566 // Insert a PHI node now if we need it.
1567 Value *MergedVal = OtherStore->getOperand(0);
Vedant Kumar238533e2018-11-19 19:55:02 +00001568 // The debug locations of the original instructions might differ. Merge them.
1569 DebugLoc MergedLoc = DILocation::getMergedLocation(SI.getDebugLoc(),
1570 OtherStore->getDebugLoc());
Chris Lattnera65e2f72010-01-05 05:57:49 +00001571 if (MergedVal != SI.getOperand(0)) {
Jay Foad52131342011-03-30 11:28:46 +00001572 PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge");
Chris Lattnera65e2f72010-01-05 05:57:49 +00001573 PN->addIncoming(SI.getOperand(0), SI.getParent());
1574 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
1575 MergedVal = InsertNewInstBefore(PN, DestBB->front());
Vedant Kumar238533e2018-11-19 19:55:02 +00001576 PN->setDebugLoc(MergedLoc);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001577 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001578
Sanjay Patel4a12aa92018-11-10 20:29:25 +00001579 // Advance to a place where it is safe to insert the new store and insert it.
Bill Wendling8ddfc092011-08-16 20:45:24 +00001580 BBI = DestBB->getFirstInsertionPt();
Eli Friedman35211c62011-05-27 00:19:40 +00001581 StoreInst *NewSI = new StoreInst(MergedVal, SI.getOperand(1),
Sanjay Patel4a12aa92018-11-10 20:29:25 +00001582 SI.isVolatile(), SI.getAlignment(),
1583 SI.getOrdering(), SI.getSyncScopeID());
Eli Friedman35211c62011-05-27 00:19:40 +00001584 InsertNewInstBefore(NewSI, *BBI);
Vedant Kumar238533e2018-11-19 19:55:02 +00001585 NewSI->setDebugLoc(MergedLoc);
Eli Friedman35211c62011-05-27 00:19:40 +00001586
Hal Finkelcc39b672014-07-24 12:16:19 +00001587 // If the two stores had AA tags, merge them.
1588 AAMDNodes AATags;
1589 SI.getAAMetadata(AATags);
1590 if (AATags) {
1591 OtherStore->getAAMetadata(AATags, /* Merge = */ true);
1592 NewSI->setAAMetadata(AATags);
1593 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001594
Chris Lattnera65e2f72010-01-05 05:57:49 +00001595 // Nuke the old stores.
Sanjay Patel4b198802016-02-01 22:23:39 +00001596 eraseInstFromFunction(SI);
1597 eraseInstFromFunction(*OtherStore);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001598 return true;
1599}