blob: 9bcfbef61386c74f20eab75f9b8be26cc473cee1 [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"
22#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
Benjamin Kramer3a09ef62015-04-10 14:50:08 +000091 if (auto CS = CallSite(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.
94 if (CS.isCallee(&U))
95 continue;
96
David Majnemer02f47872015-12-23 09:58:41 +000097 unsigned DataOpNo = CS.getDataOperandNo(&U);
98 bool IsArgOperand = CS.isArgOperand(&U);
99
Reid Kleckner813dab22014-07-01 21:36:20 +0000100 // Inalloca arguments are clobbered by the call.
David Majnemer02f47872015-12-23 09:58:41 +0000101 if (IsArgOperand && CS.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.
107 if (CS.onlyReadsMemory() &&
David Majnemer02f47872015-12-23 09:58:41 +0000108 (CS.getInstruction()->use_empty() || CS.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.
David Majnemer02f47872015-12-23 09:58:41 +0000113 if (IsArgOperand && CS.isByValArgument(DataOpNo))
Reid Kleckner813dab22014-07-01 21:36:20 +0000114 continue;
115 }
116
117 // Lifetime intrinsics can be handled by the caller.
118 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
119 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
120 II->getIntrinsicID() == Intrinsic::lifetime_end) {
121 assert(II->use_empty() && "Lifetime markers have no result to use!");
122 ToDelete.push_back(II);
123 continue;
124 }
125 }
126
127 // If this is isn't our memcpy/memmove, reject it as something we can't
128 // handle.
129 MemTransferInst *MI = dyn_cast<MemTransferInst>(I);
130 if (!MI)
131 return false;
132
133 // If the transfer is using the alloca as a source of the transfer, then
134 // ignore it since it is a load (unless the transfer is volatile).
135 if (U.getOperandNo() == 1) {
136 if (MI->isVolatile()) return false;
137 continue;
138 }
139
140 // If we already have seen a copy, reject the second one.
141 if (TheCopy) return false;
142
143 // If the pointer has been offset from the start of the alloca, we can't
144 // safely handle this.
145 if (IsOffset) return false;
146
147 // If the memintrinsic isn't using the alloca as the dest, reject it.
148 if (U.getOperandNo() != 0) return false;
149
150 // If the source of the memcpy/move is not a constant global, reject it.
151 if (!pointsToConstantGlobal(MI->getSource()))
152 return false;
153
154 // Otherwise, the transform is safe. Remember the copy instruction.
155 TheCopy = MI;
Chandler Carruthc908ca12012-08-21 08:39:44 +0000156 }
Chandler Carruthc908ca12012-08-21 08:39:44 +0000157 }
158 return true;
159}
160
161/// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
162/// modified by a copy from a constant global. If we can prove this, we can
163/// replace any uses of the alloca with uses of the global directly.
164static MemTransferInst *
165isOnlyCopiedFromConstantGlobal(AllocaInst *AI,
166 SmallVectorImpl<Instruction *> &ToDelete) {
Craig Topperf40110f2014-04-25 05:29:35 +0000167 MemTransferInst *TheCopy = nullptr;
Chandler Carruthc908ca12012-08-21 08:39:44 +0000168 if (isOnlyCopiedFromConstantGlobal(AI, TheCopy, ToDelete))
169 return TheCopy;
Craig Topperf40110f2014-04-25 05:29:35 +0000170 return nullptr;
Chandler Carruthc908ca12012-08-21 08:39:44 +0000171}
172
Vitaly Bukadf19ad42017-06-24 01:35:19 +0000173/// Returns true if V is dereferenceable for size of alloca.
174static bool isDereferenceableForAllocaSize(const Value *V, const AllocaInst *AI,
175 const DataLayout &DL) {
176 if (AI->isArrayAllocation())
177 return false;
178 uint64_t AllocaSize = DL.getTypeStoreSize(AI->getAllocatedType());
179 if (!AllocaSize)
180 return false;
181 return isDereferenceableAndAlignedPointer(V, AI->getAlignment(),
182 APInt(64, AllocaSize), DL);
183}
184
Duncan P. N. Exon Smithc6820ec2015-03-13 19:22:03 +0000185static Instruction *simplifyAllocaArraySize(InstCombiner &IC, AllocaInst &AI) {
Duncan P. N. Exon Smith720762e2015-03-13 19:30:44 +0000186 // Check for array size of 1 (scalar allocation).
Duncan P. N. Exon Smithbe95b4a2015-03-13 19:42:09 +0000187 if (!AI.isArrayAllocation()) {
188 // i32 1 is the canonical array size for scalar allocations.
189 if (AI.getArraySize()->getType()->isIntegerTy(32))
190 return nullptr;
191
192 // Canonicalize it.
Craig Topperbb4069e2017-07-07 23:16:26 +0000193 Value *V = IC.Builder.getInt32(1);
Duncan P. N. Exon Smithbe95b4a2015-03-13 19:42:09 +0000194 AI.setOperand(0, V);
195 return &AI;
196 }
Duncan P. N. Exon Smith720762e2015-03-13 19:30:44 +0000197
Chris Lattnera65e2f72010-01-05 05:57:49 +0000198 // 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 +0000199 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
200 Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
Craig Topperbb4069e2017-07-07 23:16:26 +0000201 AllocaInst *New = IC.Builder.CreateAlloca(NewTy, nullptr, AI.getName());
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000202 New->setAlignment(AI.getAlignment());
Chris Lattnera65e2f72010-01-05 05:57:49 +0000203
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000204 // Scan to the end of the allocation instructions, to skip over a block of
205 // allocas if possible...also skip interleaved debug info
206 //
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +0000207 BasicBlock::iterator It(New);
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000208 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It))
209 ++It;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000210
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000211 // Now that I is pointing to the first non-allocation-inst in the block,
212 // insert our getelementptr instruction...
213 //
214 Type *IdxTy = IC.getDataLayout().getIntPtrType(AI.getType());
215 Value *NullIdx = Constant::getNullValue(IdxTy);
216 Value *Idx[2] = {NullIdx, NullIdx};
217 Instruction *GEP =
Matt Arsenault640ff9d2013-08-14 00:24:05 +0000218 GetElementPtrInst::CreateInBounds(New, Idx, New->getName() + ".sub");
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000219 IC.InsertNewInstBefore(GEP, *It);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000220
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000221 // Now make everything use the getelementptr instead of the original
222 // allocation.
Sanjay Patel4b198802016-02-01 22:23:39 +0000223 return IC.replaceInstUsesWith(AI, GEP);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000224 }
225
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000226 if (isa<UndefValue>(AI.getArraySize()))
Sanjay Patel4b198802016-02-01 22:23:39 +0000227 return IC.replaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
Duncan P. N. Exon Smithbb730132015-03-13 19:26:33 +0000228
Duncan P. N. Exon Smith07ff9b02015-03-13 19:34:55 +0000229 // Ensure that the alloca array size argument has type intptr_t, so that
230 // any casting is exposed early.
231 Type *IntPtrTy = IC.getDataLayout().getIntPtrType(AI.getType());
232 if (AI.getArraySize()->getType() != IntPtrTy) {
Craig Topperbb4069e2017-07-07 23:16:26 +0000233 Value *V = IC.Builder.CreateIntCast(AI.getArraySize(), IntPtrTy, false);
Duncan P. N. Exon Smith07ff9b02015-03-13 19:34:55 +0000234 AI.setOperand(0, V);
235 return &AI;
236 }
237
Duncan P. N. Exon Smithc6820ec2015-03-13 19:22:03 +0000238 return nullptr;
239}
240
Benjamin Kramer03ab8a32017-02-10 22:26:35 +0000241namespace {
Yaxun Liuba01ed02017-02-10 21:46:07 +0000242// If I and V are pointers in different address space, it is not allowed to
243// use replaceAllUsesWith since I and V have different types. A
244// non-target-specific transformation should not use addrspacecast on V since
245// the two address space may be disjoint depending on target.
246//
247// This class chases down uses of the old pointer until reaching the load
248// instructions, then replaces the old pointer in the load instructions with
249// the new pointer. If during the chasing it sees bitcast or GEP, it will
250// create new bitcast or GEP with the new pointer and use them in the load
251// instruction.
252class PointerReplacer {
253public:
254 PointerReplacer(InstCombiner &IC) : IC(IC) {}
255 void replacePointer(Instruction &I, Value *V);
256
257private:
258 void findLoadAndReplace(Instruction &I);
259 void replace(Instruction *I);
260 Value *getReplacement(Value *I);
261
262 SmallVector<Instruction *, 4> Path;
263 MapVector<Value *, Value *> WorkMap;
264 InstCombiner &IC;
265};
Benjamin Kramer03ab8a32017-02-10 22:26:35 +0000266} // end anonymous namespace
Yaxun Liuba01ed02017-02-10 21:46:07 +0000267
268void PointerReplacer::findLoadAndReplace(Instruction &I) {
269 for (auto U : I.users()) {
270 auto *Inst = dyn_cast<Instruction>(&*U);
271 if (!Inst)
272 return;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000273 LLVM_DEBUG(dbgs() << "Found pointer user: " << *U << '\n');
Yaxun Liuba01ed02017-02-10 21:46:07 +0000274 if (isa<LoadInst>(Inst)) {
275 for (auto P : Path)
276 replace(P);
277 replace(Inst);
278 } else if (isa<GetElementPtrInst>(Inst) || isa<BitCastInst>(Inst)) {
279 Path.push_back(Inst);
280 findLoadAndReplace(*Inst);
281 Path.pop_back();
282 } else {
283 return;
284 }
285 }
286}
287
288Value *PointerReplacer::getReplacement(Value *V) {
289 auto Loc = WorkMap.find(V);
290 if (Loc != WorkMap.end())
291 return Loc->second;
292 return nullptr;
293}
294
295void PointerReplacer::replace(Instruction *I) {
296 if (getReplacement(I))
297 return;
298
299 if (auto *LT = dyn_cast<LoadInst>(I)) {
300 auto *V = getReplacement(LT->getPointerOperand());
301 assert(V && "Operand not replaced");
302 auto *NewI = new LoadInst(V);
303 NewI->takeName(LT);
304 IC.InsertNewInstWith(NewI, *LT);
305 IC.replaceInstUsesWith(*LT, NewI);
306 WorkMap[LT] = NewI;
307 } else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
308 auto *V = getReplacement(GEP->getPointerOperand());
309 assert(V && "Operand not replaced");
310 SmallVector<Value *, 8> Indices;
311 Indices.append(GEP->idx_begin(), GEP->idx_end());
312 auto *NewI = GetElementPtrInst::Create(
313 V->getType()->getPointerElementType(), V, Indices);
314 IC.InsertNewInstWith(NewI, *GEP);
315 NewI->takeName(GEP);
316 WorkMap[GEP] = NewI;
317 } else if (auto *BC = dyn_cast<BitCastInst>(I)) {
318 auto *V = getReplacement(BC->getOperand(0));
319 assert(V && "Operand not replaced");
320 auto *NewT = PointerType::get(BC->getType()->getPointerElementType(),
321 V->getType()->getPointerAddressSpace());
322 auto *NewI = new BitCastInst(V, NewT);
323 IC.InsertNewInstWith(NewI, *BC);
324 NewI->takeName(BC);
Yaxun Liue6d1ce52017-02-24 20:27:25 +0000325 WorkMap[BC] = NewI;
Yaxun Liuba01ed02017-02-10 21:46:07 +0000326 } else {
327 llvm_unreachable("should never reach here");
328 }
329}
330
331void PointerReplacer::replacePointer(Instruction &I, Value *V) {
Benjamin Kramer684c87b2017-02-10 22:04:17 +0000332#ifndef NDEBUG
Yaxun Liuba01ed02017-02-10 21:46:07 +0000333 auto *PT = cast<PointerType>(I.getType());
334 auto *NT = cast<PointerType>(V->getType());
335 assert(PT != NT && PT->getElementType() == NT->getElementType() &&
336 "Invalid usage");
Benjamin Kramer684c87b2017-02-10 22:04:17 +0000337#endif
Yaxun Liuba01ed02017-02-10 21:46:07 +0000338 WorkMap[&I] = V;
339 findLoadAndReplace(I);
340}
341
Duncan P. N. Exon Smithc6820ec2015-03-13 19:22:03 +0000342Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
343 if (auto *I = simplifyAllocaArraySize(*this, AI))
344 return I;
345
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000346 if (AI.getAllocatedType()->isSized()) {
Chris Lattnera65e2f72010-01-05 05:57:49 +0000347 // If the alignment is 0 (unspecified), assign it the preferred alignment.
348 if (AI.getAlignment() == 0)
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000349 AI.setAlignment(DL.getPrefTypeAlignment(AI.getAllocatedType()));
Duncan Sands8bc764a2012-06-26 13:39:21 +0000350
351 // Move all alloca's of zero byte objects to the entry block and merge them
352 // together. Note that we only do this for alloca's, because malloc should
353 // allocate and return a unique pointer, even for a zero byte allocation.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000354 if (DL.getTypeAllocSize(AI.getAllocatedType()) == 0) {
Duncan Sands8bc764a2012-06-26 13:39:21 +0000355 // For a zero sized alloca there is no point in doing an array allocation.
356 // This is helpful if the array size is a complicated expression not used
357 // elsewhere.
358 if (AI.isArrayAllocation()) {
359 AI.setOperand(0, ConstantInt::get(AI.getArraySize()->getType(), 1));
360 return &AI;
361 }
362
363 // Get the first instruction in the entry block.
364 BasicBlock &EntryBlock = AI.getParent()->getParent()->getEntryBlock();
365 Instruction *FirstInst = EntryBlock.getFirstNonPHIOrDbg();
366 if (FirstInst != &AI) {
367 // If the entry block doesn't start with a zero-size alloca then move
368 // this one to the start of the entry block. There is no problem with
369 // dominance as the array size was forced to a constant earlier already.
370 AllocaInst *EntryAI = dyn_cast<AllocaInst>(FirstInst);
371 if (!EntryAI || !EntryAI->getAllocatedType()->isSized() ||
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000372 DL.getTypeAllocSize(EntryAI->getAllocatedType()) != 0) {
Duncan Sands8bc764a2012-06-26 13:39:21 +0000373 AI.moveBefore(FirstInst);
374 return &AI;
375 }
376
Richard Osborneb68053e2012-09-18 09:31:44 +0000377 // If the alignment of the entry block alloca is 0 (unspecified),
378 // assign it the preferred alignment.
379 if (EntryAI->getAlignment() == 0)
380 EntryAI->setAlignment(
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000381 DL.getPrefTypeAlignment(EntryAI->getAllocatedType()));
Duncan Sands8bc764a2012-06-26 13:39:21 +0000382 // Replace this zero-sized alloca with the one at the start of the entry
383 // block after ensuring that the address will be aligned enough for both
384 // types.
Richard Osborneb68053e2012-09-18 09:31:44 +0000385 unsigned MaxAlign = std::max(EntryAI->getAlignment(),
386 AI.getAlignment());
Duncan Sands8bc764a2012-06-26 13:39:21 +0000387 EntryAI->setAlignment(MaxAlign);
388 if (AI.getType() != EntryAI->getType())
389 return new BitCastInst(EntryAI, AI.getType());
Sanjay Patel4b198802016-02-01 22:23:39 +0000390 return replaceInstUsesWith(AI, EntryAI);
Duncan Sands8bc764a2012-06-26 13:39:21 +0000391 }
392 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000393 }
394
Eli Friedmanb14873c2012-11-26 23:04:53 +0000395 if (AI.getAlignment()) {
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000396 // Check to see if this allocation is only modified by a memcpy/memmove from
397 // a constant global whose alignment is equal to or exceeds that of the
398 // allocation. If this is the case, we can change all users to use
399 // the constant global instead. This is commonly produced by the CFE by
400 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
401 // is only subsequently read.
402 SmallVector<Instruction *, 4> ToDelete;
403 if (MemTransferInst *Copy = isOnlyCopiedFromConstantGlobal(&AI, ToDelete)) {
Chandler Carruth66b31302015-01-04 12:03:27 +0000404 unsigned SourceAlign = getOrEnforceKnownAlignment(
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000405 Copy->getSource(), AI.getAlignment(), DL, &AI, &AC, &DT);
Vitaly Bukadf19ad42017-06-24 01:35:19 +0000406 if (AI.getAlignment() <= SourceAlign &&
407 isDereferenceableForAllocaSize(Copy->getSource(), &AI, DL)) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000408 LLVM_DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n');
409 LLVM_DEBUG(dbgs() << " memcpy = " << *Copy << '\n');
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000410 for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
Sanjay Patel4b198802016-02-01 22:23:39 +0000411 eraseInstFromFunction(*ToDelete[i]);
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000412 Constant *TheSrc = cast<Constant>(Copy->getSource());
Yaxun Liuba01ed02017-02-10 21:46:07 +0000413 auto *SrcTy = TheSrc->getType();
414 auto *DestTy = PointerType::get(AI.getType()->getPointerElementType(),
415 SrcTy->getPointerAddressSpace());
416 Constant *Cast =
417 ConstantExpr::getPointerBitCastOrAddrSpaceCast(TheSrc, DestTy);
418 if (AI.getType()->getPointerAddressSpace() ==
419 SrcTy->getPointerAddressSpace()) {
420 Instruction *NewI = replaceInstUsesWith(AI, Cast);
421 eraseInstFromFunction(*Copy);
422 ++NumGlobalCopies;
423 return NewI;
424 } else {
425 PointerReplacer PtrReplacer(*this);
426 PtrReplacer.replacePointer(AI, Cast);
427 ++NumGlobalCopies;
428 }
Richard Osborne2fd29bf2012-09-24 17:10:03 +0000429 }
Chandler Carruthc908ca12012-08-21 08:39:44 +0000430 }
431 }
432
Nuno Lopes95cc4f32012-07-09 18:38:20 +0000433 // At last, use the generic allocation site handler to aggressively remove
434 // unused allocas.
435 return visitAllocSite(AI);
Chris Lattnera65e2f72010-01-05 05:57:49 +0000436}
437
Philip Reames89e92d22016-12-01 20:17:06 +0000438// Are we allowed to form a atomic load or store of this type?
439static bool isSupportedAtomicType(Type *Ty) {
440 return Ty->isIntegerTy() || Ty->isPointerTy() || Ty->isFloatingPointTy();
441}
442
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000443/// Helper to combine a load to a new type.
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000444///
445/// This just does the work of combining a load to a new type. It handles
446/// metadata, etc., and returns the new instruction. The \c NewTy should be the
447/// loaded *value* type. This will convert it to a pointer, cast the operand to
448/// that pointer type, load it, etc.
449///
450/// Note that this will create all of the instructions with whatever insert
451/// point the \c InstCombiner currently is using.
Mehdi Amini2668a482015-05-07 05:52:40 +0000452static LoadInst *combineLoadToNewType(InstCombiner &IC, LoadInst &LI, Type *NewTy,
453 const Twine &Suffix = "") {
Philip Reames89e92d22016-12-01 20:17:06 +0000454 assert((!LI.isAtomic() || isSupportedAtomicType(NewTy)) &&
455 "can't fold an atomic load to requested type");
Alexey Bataev7c9ad0d2018-05-21 17:46:34 +0000456
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000457 Value *Ptr = LI.getPointerOperand();
458 unsigned AS = LI.getPointerAddressSpace();
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000459 SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000460 LI.getAllMetadata(MD);
461
Alexey Bataev7c9ad0d2018-05-21 17:46:34 +0000462 Value *NewPtr = nullptr;
463 if (!(match(Ptr, m_BitCast(m_Value(NewPtr))) &&
464 NewPtr->getType()->getPointerElementType() == NewTy &&
465 NewPtr->getType()->getPointerAddressSpace() == AS))
466 NewPtr = IC.Builder.CreateBitCast(Ptr, NewTy->getPointerTo(AS));
467
Craig Topperbb4069e2017-07-07 23:16:26 +0000468 LoadInst *NewLoad = IC.Builder.CreateAlignedLoad(
Alexey Bataev7c9ad0d2018-05-21 17:46:34 +0000469 NewPtr, LI.getAlignment(), LI.isVolatile(), LI.getName() + Suffix);
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +0000470 NewLoad->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
Charles Davis33d1dc02015-02-25 05:10:25 +0000471 MDBuilder MDB(NewLoad->getContext());
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000472 for (const auto &MDPair : MD) {
473 unsigned ID = MDPair.first;
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000474 MDNode *N = MDPair.second;
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000475 // Note, essentially every kind of metadata should be preserved here! This
476 // routine is supposed to clone a load instruction changing *only its type*.
477 // The only metadata it makes sense to drop is metadata which is invalidated
478 // when the pointer type changes. This should essentially never be the case
479 // in LLVM, but we explicitly switch over only known metadata to be
480 // conservatively correct. If you are adding metadata to LLVM which pertains
481 // to loads, you almost certainly want to add it here.
482 switch (ID) {
483 case LLVMContext::MD_dbg:
484 case LLVMContext::MD_tbaa:
485 case LLVMContext::MD_prof:
486 case LLVMContext::MD_fpmath:
487 case LLVMContext::MD_tbaa_struct:
488 case LLVMContext::MD_invariant_load:
489 case LLVMContext::MD_alias_scope:
490 case LLVMContext::MD_noalias:
Philip Reames5a3f5f72014-10-21 00:13:20 +0000491 case LLVMContext::MD_nontemporal:
492 case LLVMContext::MD_mem_parallel_loop_access:
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000493 // All of these directly apply.
494 NewLoad->setMetadata(ID, N);
495 break;
496
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000497 case LLVMContext::MD_nonnull:
Chandler Carruth2abb65a2017-06-26 03:31:31 +0000498 copyNonnullMetadata(LI, N, *NewLoad);
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000499 break;
Artur Pilipenko5c5011d2015-11-02 17:53:51 +0000500 case LLVMContext::MD_align:
501 case LLVMContext::MD_dereferenceable:
502 case LLVMContext::MD_dereferenceable_or_null:
503 // These only directly apply if the new type is also a pointer.
504 if (NewTy->isPointerTy())
505 NewLoad->setMetadata(ID, N);
506 break;
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000507 case LLVMContext::MD_range:
Chandler Carruth2abb65a2017-06-26 03:31:31 +0000508 copyRangeMetadata(IC.getDataLayout(), LI, N, *NewLoad);
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000509 break;
510 }
511 }
Chandler Carruthbc6378d2014-10-19 10:46:46 +0000512 return NewLoad;
513}
514
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000515/// Combine a store to a new type.
Chandler Carruthfa11d832015-01-22 03:34:54 +0000516///
517/// Returns the newly created store instruction.
518static StoreInst *combineStoreToNewValue(InstCombiner &IC, StoreInst &SI, Value *V) {
Philip Reames89e92d22016-12-01 20:17:06 +0000519 assert((!SI.isAtomic() || isSupportedAtomicType(V->getType())) &&
520 "can't fold an atomic store of requested type");
521
Chandler Carruthfa11d832015-01-22 03:34:54 +0000522 Value *Ptr = SI.getPointerOperand();
523 unsigned AS = SI.getPointerAddressSpace();
524 SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
525 SI.getAllMetadata(MD);
526
Craig Topperbb4069e2017-07-07 23:16:26 +0000527 StoreInst *NewStore = IC.Builder.CreateAlignedStore(
528 V, IC.Builder.CreateBitCast(Ptr, V->getType()->getPointerTo(AS)),
Philip Reames6f4d0082016-05-06 22:17:01 +0000529 SI.getAlignment(), SI.isVolatile());
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +0000530 NewStore->setAtomic(SI.getOrdering(), SI.getSyncScopeID());
Chandler Carruthfa11d832015-01-22 03:34:54 +0000531 for (const auto &MDPair : MD) {
532 unsigned ID = MDPair.first;
533 MDNode *N = MDPair.second;
534 // Note, essentially every kind of metadata should be preserved here! This
535 // routine is supposed to clone a store instruction changing *only its
536 // type*. The only metadata it makes sense to drop is metadata which is
537 // invalidated when the pointer type changes. This should essentially
538 // never be the case in LLVM, but we explicitly switch over only known
539 // metadata to be conservatively correct. If you are adding metadata to
540 // LLVM which pertains to stores, you almost certainly want to add it
541 // here.
542 switch (ID) {
543 case LLVMContext::MD_dbg:
544 case LLVMContext::MD_tbaa:
545 case LLVMContext::MD_prof:
546 case LLVMContext::MD_fpmath:
547 case LLVMContext::MD_tbaa_struct:
548 case LLVMContext::MD_alias_scope:
549 case LLVMContext::MD_noalias:
550 case LLVMContext::MD_nontemporal:
551 case LLVMContext::MD_mem_parallel_loop_access:
Chandler Carruthfa11d832015-01-22 03:34:54 +0000552 // All of these directly apply.
553 NewStore->setMetadata(ID, N);
554 break;
555
556 case LLVMContext::MD_invariant_load:
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000557 case LLVMContext::MD_nonnull:
Chandler Carruthfa11d832015-01-22 03:34:54 +0000558 case LLVMContext::MD_range:
Artur Pilipenko5c5011d2015-11-02 17:53:51 +0000559 case LLVMContext::MD_align:
560 case LLVMContext::MD_dereferenceable:
561 case LLVMContext::MD_dereferenceable_or_null:
Chandler Carruth87fdafc2015-02-13 02:30:01 +0000562 // These don't apply for stores.
Chandler Carruthfa11d832015-01-22 03:34:54 +0000563 break;
564 }
565 }
566
567 return NewStore;
568}
569
Alexey Bataevec95c6c2017-12-08 15:32:10 +0000570/// Returns true if instruction represent minmax pattern like:
571/// select ((cmp load V1, load V2), V1, V2).
572static bool isMinMaxWithLoads(Value *V) {
573 assert(V->getType()->isPointerTy() && "Expected pointer type.");
574 // Ignore possible ty* to ixx* bitcast.
575 V = peekThroughBitcast(V);
576 // Check that select is select ((cmp load V1, load V2), V1, V2) - minmax
577 // pattern.
578 CmpInst::Predicate Pred;
579 Instruction *L1;
580 Instruction *L2;
581 Value *LHS;
582 Value *RHS;
583 if (!match(V, m_Select(m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2)),
584 m_Value(LHS), m_Value(RHS))))
585 return false;
586 return (match(L1, m_Load(m_Specific(LHS))) &&
587 match(L2, m_Load(m_Specific(RHS)))) ||
588 (match(L1, m_Load(m_Specific(RHS))) &&
589 match(L2, m_Load(m_Specific(LHS))));
590}
591
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000592/// Combine loads to match the type of their uses' value after looking
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000593/// through intervening bitcasts.
594///
595/// The core idea here is that if the result of a load is used in an operation,
596/// we should load the type most conducive to that operation. For example, when
597/// loading an integer and converting that immediately to a pointer, we should
598/// instead directly load a pointer.
599///
600/// However, this routine must never change the width of a load or the number of
601/// loads as that would introduce a semantic change. This combine is expected to
602/// be a semantic no-op which just allows loads to more closely model the types
603/// of their consuming operations.
604///
605/// Currently, we also refuse to change the precise type used for an atomic load
606/// or a volatile load. This is debatable, and might be reasonable to change
607/// later. However, it is risky in case some backend or other part of LLVM is
608/// relying on the exact type loaded to select appropriate atomic operations.
609static Instruction *combineLoadToOperationType(InstCombiner &IC, LoadInst &LI) {
Philip Reames6f4d0082016-05-06 22:17:01 +0000610 // FIXME: We could probably with some care handle both volatile and ordered
611 // atomic loads here but it isn't clear that this is important.
612 if (!LI.isUnordered())
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000613 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000614
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000615 if (LI.use_empty())
616 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000617
Arnold Schwaighofer5d335552016-09-10 18:14:57 +0000618 // swifterror values can't be bitcasted.
619 if (LI.getPointerOperand()->isSwiftError())
620 return nullptr;
621
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000622 Type *Ty = LI.getType();
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000623 const DataLayout &DL = IC.getDataLayout();
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000624
625 // Try to canonicalize loads which are only ever stored to operate over
626 // integers instead of any other type. We only do this when the loaded type
627 // is sized and has a size exactly the same as its store size and the store
628 // size is a legal integer type.
Alexey Bataevec95c6c2017-12-08 15:32:10 +0000629 // Do not perform canonicalization if minmax pattern is found (to avoid
630 // infinite loop).
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000631 if (!Ty->isIntegerTy() && Ty->isSized() &&
632 DL.isLegalInteger(DL.getTypeStoreSizeInBits(Ty)) &&
Sanjoy Dasba04d3a2016-08-06 02:58:48 +0000633 DL.getTypeStoreSizeInBits(Ty) == DL.getTypeSizeInBits(Ty) &&
Alexey Bataevec95c6c2017-12-08 15:32:10 +0000634 !DL.isNonIntegralPointerType(Ty) &&
635 !isMinMaxWithLoads(
636 peekThroughBitcast(LI.getPointerOperand(), /*OneUseOnly=*/true))) {
David Majnemer0a16c222016-08-11 21:15:00 +0000637 if (all_of(LI.users(), [&LI](User *U) {
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000638 auto *SI = dyn_cast<StoreInst>(U);
Arnold Schwaighoferc3685632017-01-31 17:53:49 +0000639 return SI && SI->getPointerOperand() != &LI &&
640 !SI->getPointerOperand()->isSwiftError();
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000641 })) {
642 LoadInst *NewLoad = combineLoadToNewType(
643 IC, LI,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000644 Type::getIntNTy(LI.getContext(), DL.getTypeStoreSizeInBits(Ty)));
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000645 // Replace all the stores with stores of the newly loaded value.
646 for (auto UI = LI.user_begin(), UE = LI.user_end(); UI != UE;) {
647 auto *SI = cast<StoreInst>(*UI++);
Craig Topperbb4069e2017-07-07 23:16:26 +0000648 IC.Builder.SetInsertPoint(SI);
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000649 combineStoreToNewValue(IC, *SI, NewLoad);
Sanjay Patel4b198802016-02-01 22:23:39 +0000650 IC.eraseInstFromFunction(*SI);
Chandler Carruthcd8522e2015-01-22 05:08:12 +0000651 }
652 assert(LI.use_empty() && "Failed to remove all users of the load!");
653 // Return the old load so the combiner can delete it safely.
654 return &LI;
655 }
656 }
Chris Lattnera65e2f72010-01-05 05:57:49 +0000657
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000658 // Fold away bit casts of the loaded value by loading the desired type.
Quentin Colombet490cfbe2016-02-11 22:30:41 +0000659 // We can do this for BitCastInsts as well as casts from and to pointer types,
660 // as long as those are noops (i.e., the source or dest type have the same
661 // bitwidth as the target's pointers).
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000662 if (LI.hasOneUse())
Philip Reames89e92d22016-12-01 20:17:06 +0000663 if (auto* CI = dyn_cast<CastInst>(LI.user_back()))
664 if (CI->isNoopCast(DL))
665 if (!LI.isAtomic() || isSupportedAtomicType(CI->getDestTy())) {
666 LoadInst *NewLoad = combineLoadToNewType(IC, LI, CI->getDestTy());
667 CI->replaceAllUsesWith(NewLoad);
668 IC.eraseInstFromFunction(*CI);
669 return &LI;
670 }
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000671
Chandler Carrutha7f247e2014-12-09 19:21:16 +0000672 // FIXME: We should also canonicalize loads of vectors when their elements are
673 // cast to other types.
Craig Topperf40110f2014-04-25 05:29:35 +0000674 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +0000675}
676
Mehdi Amini2668a482015-05-07 05:52:40 +0000677static Instruction *unpackLoadToAggregate(InstCombiner &IC, LoadInst &LI) {
678 // FIXME: We could probably with some care handle both volatile and atomic
679 // stores here but it isn't clear that this is important.
680 if (!LI.isSimple())
681 return nullptr;
682
683 Type *T = LI.getType();
684 if (!T->isAggregateType())
685 return nullptr;
686
Benjamin Kramerc1263532016-03-11 10:20:56 +0000687 StringRef Name = LI.getName();
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000688 assert(LI.getAlignment() && "Alignment must be set at this point");
Mehdi Amini2668a482015-05-07 05:52:40 +0000689
690 if (auto *ST = dyn_cast<StructType>(T)) {
691 // If the struct only have one element, we unpack.
Amaury Sechet61a7d622016-02-17 19:21:28 +0000692 auto NumElements = ST->getNumElements();
693 if (NumElements == 1) {
Mehdi Amini2668a482015-05-07 05:52:40 +0000694 LoadInst *NewLoad = combineLoadToNewType(IC, LI, ST->getTypeAtIndex(0U),
695 ".unpack");
Keno Fischera236dae2017-06-28 23:36:40 +0000696 AAMDNodes AAMD;
697 LI.getAAMetadata(AAMD);
698 NewLoad->setAAMetadata(AAMD);
Craig Topperbb4069e2017-07-07 23:16:26 +0000699 return IC.replaceInstUsesWith(LI, IC.Builder.CreateInsertValue(
Amaury Sechet61a7d622016-02-17 19:21:28 +0000700 UndefValue::get(T), NewLoad, 0, Name));
Mehdi Amini2668a482015-05-07 05:52:40 +0000701 }
Mehdi Amini1c131b32015-12-15 01:44:07 +0000702
703 // We don't want to break loads with padding here as we'd loose
704 // the knowledge that padding exists for the rest of the pipeline.
705 const DataLayout &DL = IC.getDataLayout();
706 auto *SL = DL.getStructLayout(ST);
707 if (SL->hasPadding())
708 return nullptr;
709
Amaury Sechet61a7d622016-02-17 19:21:28 +0000710 auto Align = LI.getAlignment();
711 if (!Align)
712 Align = DL.getABITypeAlignment(ST);
713
Mehdi Amini1c131b32015-12-15 01:44:07 +0000714 auto *Addr = LI.getPointerOperand();
Amaury Sechet61a7d622016-02-17 19:21:28 +0000715 auto *IdxType = Type::getInt32Ty(T->getContext());
Mehdi Amini1c131b32015-12-15 01:44:07 +0000716 auto *Zero = ConstantInt::get(IdxType, 0);
Amaury Sechet61a7d622016-02-17 19:21:28 +0000717
718 Value *V = UndefValue::get(T);
719 for (unsigned i = 0; i < NumElements; i++) {
Mehdi Amini1c131b32015-12-15 01:44:07 +0000720 Value *Indices[2] = {
721 Zero,
722 ConstantInt::get(IdxType, i),
723 };
Craig Topperbb4069e2017-07-07 23:16:26 +0000724 auto *Ptr = IC.Builder.CreateInBoundsGEP(ST, Addr, makeArrayRef(Indices),
725 Name + ".elt");
Amaury Sechet61a7d622016-02-17 19:21:28 +0000726 auto EltAlign = MinAlign(Align, SL->getElementOffset(i));
Craig Topperbb4069e2017-07-07 23:16:26 +0000727 auto *L = IC.Builder.CreateAlignedLoad(Ptr, EltAlign, Name + ".unpack");
Keno Fischera236dae2017-06-28 23:36:40 +0000728 // Propagate AA metadata. It'll still be valid on the narrowed load.
729 AAMDNodes AAMD;
730 LI.getAAMetadata(AAMD);
731 L->setAAMetadata(AAMD);
Craig Topperbb4069e2017-07-07 23:16:26 +0000732 V = IC.Builder.CreateInsertValue(V, L, i);
Mehdi Amini1c131b32015-12-15 01:44:07 +0000733 }
734
735 V->setName(Name);
Sanjay Patel4b198802016-02-01 22:23:39 +0000736 return IC.replaceInstUsesWith(LI, V);
Mehdi Amini2668a482015-05-07 05:52:40 +0000737 }
738
David Majnemer58fb0382015-05-11 05:04:22 +0000739 if (auto *AT = dyn_cast<ArrayType>(T)) {
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000740 auto *ET = AT->getElementType();
741 auto NumElements = AT->getNumElements();
742 if (NumElements == 1) {
743 LoadInst *NewLoad = combineLoadToNewType(IC, LI, ET, ".unpack");
Keno Fischera236dae2017-06-28 23:36:40 +0000744 AAMDNodes AAMD;
745 LI.getAAMetadata(AAMD);
746 NewLoad->setAAMetadata(AAMD);
Craig Topperbb4069e2017-07-07 23:16:26 +0000747 return IC.replaceInstUsesWith(LI, IC.Builder.CreateInsertValue(
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000748 UndefValue::get(T), NewLoad, 0, Name));
David Majnemer58fb0382015-05-11 05:04:22 +0000749 }
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000750
Davide Italianoda114122016-10-07 20:57:42 +0000751 // Bail out if the array is too large. Ideally we would like to optimize
752 // arrays of arbitrary size but this has a terrible impact on compile time.
753 // The threshold here is chosen arbitrarily, maybe needs a little bit of
754 // tuning.
Davide Italiano2133bf52017-02-07 17:56:50 +0000755 if (NumElements > IC.MaxArraySizeForCombine)
Davide Italianoda114122016-10-07 20:57:42 +0000756 return nullptr;
757
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000758 const DataLayout &DL = IC.getDataLayout();
759 auto EltSize = DL.getTypeAllocSize(ET);
760 auto Align = LI.getAlignment();
761 if (!Align)
762 Align = DL.getABITypeAlignment(T);
763
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000764 auto *Addr = LI.getPointerOperand();
765 auto *IdxType = Type::getInt64Ty(T->getContext());
766 auto *Zero = ConstantInt::get(IdxType, 0);
767
768 Value *V = UndefValue::get(T);
769 uint64_t Offset = 0;
770 for (uint64_t i = 0; i < NumElements; i++) {
771 Value *Indices[2] = {
772 Zero,
773 ConstantInt::get(IdxType, i),
774 };
Craig Topperbb4069e2017-07-07 23:16:26 +0000775 auto *Ptr = IC.Builder.CreateInBoundsGEP(AT, Addr, makeArrayRef(Indices),
776 Name + ".elt");
777 auto *L = IC.Builder.CreateAlignedLoad(Ptr, MinAlign(Align, Offset),
778 Name + ".unpack");
Keno Fischera236dae2017-06-28 23:36:40 +0000779 AAMDNodes AAMD;
780 LI.getAAMetadata(AAMD);
781 L->setAAMetadata(AAMD);
Craig Topperbb4069e2017-07-07 23:16:26 +0000782 V = IC.Builder.CreateInsertValue(V, L, i);
Amaury Sechet7cd3fe72016-03-02 21:28:30 +0000783 Offset += EltSize;
784 }
785
786 V->setName(Name);
787 return IC.replaceInstUsesWith(LI, V);
David Majnemer58fb0382015-05-11 05:04:22 +0000788 }
789
Mehdi Amini2668a482015-05-07 05:52:40 +0000790 return nullptr;
791}
792
Hal Finkel847e05f2015-02-20 03:05:53 +0000793// If we can determine that all possible objects pointed to by the provided
794// pointer value are, not only dereferenceable, but also definitively less than
795// or equal to the provided maximum size, then return true. Otherwise, return
796// false (constant global values and allocas fall into this category).
797//
798// FIXME: This should probably live in ValueTracking (or similar).
799static bool isObjectSizeLessThanOrEq(Value *V, uint64_t MaxSize,
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000800 const DataLayout &DL) {
Hal Finkel847e05f2015-02-20 03:05:53 +0000801 SmallPtrSet<Value *, 4> Visited;
802 SmallVector<Value *, 4> Worklist(1, V);
803
804 do {
805 Value *P = Worklist.pop_back_val();
806 P = P->stripPointerCasts();
807
808 if (!Visited.insert(P).second)
809 continue;
810
811 if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
812 Worklist.push_back(SI->getTrueValue());
813 Worklist.push_back(SI->getFalseValue());
814 continue;
815 }
816
817 if (PHINode *PN = dyn_cast<PHINode>(P)) {
Pete Cooper833f34d2015-05-12 20:05:31 +0000818 for (Value *IncValue : PN->incoming_values())
819 Worklist.push_back(IncValue);
Hal Finkel847e05f2015-02-20 03:05:53 +0000820 continue;
821 }
822
823 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(P)) {
Sanjoy Das99042472016-04-17 04:30:43 +0000824 if (GA->isInterposable())
Hal Finkel847e05f2015-02-20 03:05:53 +0000825 return false;
826 Worklist.push_back(GA->getAliasee());
827 continue;
828 }
829
830 // If we know how big this object is, and it is less than MaxSize, continue
831 // searching. Otherwise, return false.
832 if (AllocaInst *AI = dyn_cast<AllocaInst>(P)) {
833 if (!AI->getAllocatedType()->isSized())
834 return false;
835
836 ConstantInt *CS = dyn_cast<ConstantInt>(AI->getArraySize());
837 if (!CS)
838 return false;
839
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000840 uint64_t TypeSize = DL.getTypeAllocSize(AI->getAllocatedType());
Hal Finkel847e05f2015-02-20 03:05:53 +0000841 // Make sure that, even if the multiplication below would wrap as an
842 // uint64_t, we still do the right thing.
843 if ((CS->getValue().zextOrSelf(128)*APInt(128, TypeSize)).ugt(MaxSize))
844 return false;
845 continue;
846 }
847
848 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
849 if (!GV->hasDefinitiveInitializer() || !GV->isConstant())
850 return false;
851
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000852 uint64_t InitSize = DL.getTypeAllocSize(GV->getValueType());
Hal Finkel847e05f2015-02-20 03:05:53 +0000853 if (InitSize > MaxSize)
854 return false;
855 continue;
856 }
857
858 return false;
859 } while (!Worklist.empty());
860
861 return true;
862}
863
864// If we're indexing into an object of a known size, and the outer index is
865// not a constant, but having any value but zero would lead to undefined
866// behavior, replace it with zero.
867//
868// For example, if we have:
869// @f.a = private unnamed_addr constant [1 x i32] [i32 12], align 4
870// ...
871// %arrayidx = getelementptr inbounds [1 x i32]* @f.a, i64 0, i64 %x
872// ... = load i32* %arrayidx, align 4
873// Then we know that we can replace %x in the GEP with i64 0.
874//
875// FIXME: We could fold any GEP index to zero that would cause UB if it were
876// not zero. Currently, we only handle the first such index. Also, we could
877// also search through non-zero constant indices if we kept track of the
878// offsets those indices implied.
879static bool canReplaceGEPIdxWithZero(InstCombiner &IC, GetElementPtrInst *GEPI,
880 Instruction *MemI, unsigned &Idx) {
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000881 if (GEPI->getNumOperands() < 2)
Hal Finkel847e05f2015-02-20 03:05:53 +0000882 return false;
883
884 // Find the first non-zero index of a GEP. If all indices are zero, return
885 // one past the last index.
886 auto FirstNZIdx = [](const GetElementPtrInst *GEPI) {
887 unsigned I = 1;
888 for (unsigned IE = GEPI->getNumOperands(); I != IE; ++I) {
889 Value *V = GEPI->getOperand(I);
890 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
891 if (CI->isZero())
892 continue;
893
894 break;
895 }
896
897 return I;
898 };
899
900 // Skip through initial 'zero' indices, and find the corresponding pointer
901 // type. See if the next index is not a constant.
902 Idx = FirstNZIdx(GEPI);
903 if (Idx == GEPI->getNumOperands())
904 return false;
905 if (isa<Constant>(GEPI->getOperand(Idx)))
906 return false;
907
908 SmallVector<Value *, 4> Ops(GEPI->idx_begin(), GEPI->idx_begin() + Idx);
Eduard Burtescu19eb0312016-01-19 17:28:00 +0000909 Type *AllocTy =
910 GetElementPtrInst::getIndexedType(GEPI->getSourceElementType(), Ops);
Hal Finkel847e05f2015-02-20 03:05:53 +0000911 if (!AllocTy || !AllocTy->isSized())
912 return false;
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000913 const DataLayout &DL = IC.getDataLayout();
914 uint64_t TyAllocSize = DL.getTypeAllocSize(AllocTy);
Hal Finkel847e05f2015-02-20 03:05:53 +0000915
916 // If there are more indices after the one we might replace with a zero, make
917 // sure they're all non-negative. If any of them are negative, the overall
918 // address being computed might be before the base address determined by the
919 // first non-zero index.
920 auto IsAllNonNegative = [&]() {
921 for (unsigned i = Idx+1, e = GEPI->getNumOperands(); i != e; ++i) {
Craig Topper1a36b7d2017-05-15 06:39:41 +0000922 KnownBits Known = IC.computeKnownBits(GEPI->getOperand(i), 0, MemI);
923 if (Known.isNonNegative())
Hal Finkel847e05f2015-02-20 03:05:53 +0000924 continue;
925 return false;
926 }
927
928 return true;
929 };
930
931 // FIXME: If the GEP is not inbounds, and there are extra indices after the
932 // one we'll replace, those could cause the address computation to wrap
933 // (rendering the IsAllNonNegative() check below insufficient). We can do
Bruce Mitchenere9ffb452015-09-12 01:17:08 +0000934 // better, ignoring zero indices (and other indices we can prove small
Hal Finkel847e05f2015-02-20 03:05:53 +0000935 // enough not to wrap).
936 if (Idx+1 != GEPI->getNumOperands() && !GEPI->isInBounds())
937 return false;
938
939 // Note that isObjectSizeLessThanOrEq will return true only if the pointer is
940 // also known to be dereferenceable.
941 return isObjectSizeLessThanOrEq(GEPI->getOperand(0), TyAllocSize, DL) &&
942 IsAllNonNegative();
943}
944
945// If we're indexing into an object with a variable index for the memory
946// access, but the object has only one element, we can assume that the index
947// will always be zero. If we replace the GEP, return it.
948template <typename T>
949static Instruction *replaceGEPIdxWithZero(InstCombiner &IC, Value *Ptr,
950 T &MemI) {
951 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr)) {
952 unsigned Idx;
953 if (canReplaceGEPIdxWithZero(IC, GEPI, &MemI, Idx)) {
954 Instruction *NewGEPI = GEPI->clone();
955 NewGEPI->setOperand(Idx,
956 ConstantInt::get(GEPI->getOperand(Idx)->getType(), 0));
957 NewGEPI->insertBefore(GEPI);
958 MemI.setOperand(MemI.getPointerOperandIndex(), NewGEPI);
959 return NewGEPI;
960 }
961 }
962
963 return nullptr;
964}
965
Anna Thomas2dd98352017-12-12 14:12:33 +0000966static bool canSimplifyNullStoreOrGEP(StoreInst &SI) {
967 if (SI.getPointerAddressSpace() != 0)
968 return false;
969
970 auto *Ptr = SI.getPointerOperand();
971 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr))
972 Ptr = GEPI->getOperand(0);
973 return isa<ConstantPointerNull>(Ptr);
974}
975
Davide Italianoffcb4df2017-04-19 17:26:57 +0000976static bool canSimplifyNullLoadOrGEP(LoadInst &LI, Value *Op) {
977 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
978 const Value *GEPI0 = GEPI->getOperand(0);
979 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0)
980 return true;
981 }
982 if (isa<UndefValue>(Op) ||
983 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0))
984 return true;
985 return false;
986}
987
Chris Lattnera65e2f72010-01-05 05:57:49 +0000988Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
989 Value *Op = LI.getOperand(0);
990
Chandler Carruth2f75fcf2014-10-18 06:36:22 +0000991 // Try to canonicalize the loaded type.
992 if (Instruction *Res = combineLoadToOperationType(*this, LI))
993 return Res;
994
Chris Lattnera65e2f72010-01-05 05:57:49 +0000995 // Attempt to improve the alignment.
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000996 unsigned KnownAlign = getOrEnforceKnownAlignment(
Daniel Jasperaec2fa32016-12-19 08:22:17 +0000997 Op, DL.getPrefTypeAlignment(LI.getType()), DL, &LI, &AC, &DT);
Mehdi Aminia28d91d2015-03-10 02:37:25 +0000998 unsigned LoadAlign = LI.getAlignment();
999 unsigned EffectiveLoadAlign =
1000 LoadAlign != 0 ? LoadAlign : DL.getABITypeAlignment(LI.getType());
Dan Gohman36196602010-08-03 18:20:32 +00001001
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001002 if (KnownAlign > EffectiveLoadAlign)
1003 LI.setAlignment(KnownAlign);
1004 else if (LoadAlign == 0)
1005 LI.setAlignment(EffectiveLoadAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001006
Hal Finkel847e05f2015-02-20 03:05:53 +00001007 // Replace GEP indices if possible.
1008 if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Op, LI)) {
1009 Worklist.Add(NewGEPI);
1010 return &LI;
1011 }
1012
Mehdi Amini2668a482015-05-07 05:52:40 +00001013 if (Instruction *Res = unpackLoadToAggregate(*this, LI))
1014 return Res;
1015
Chris Lattnera65e2f72010-01-05 05:57:49 +00001016 // Do really simple store-to-load forwarding and load CSE, to catch cases
Duncan Sands75b5d272011-02-15 09:23:02 +00001017 // where there are several consecutive memory accesses to the same location,
Chris Lattnera65e2f72010-01-05 05:57:49 +00001018 // separated by a few arithmetic operations.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00001019 BasicBlock::iterator BBI(LI);
Eli Friedmanbd254a62016-06-16 02:33:42 +00001020 bool IsLoadCSE = false;
Sanjay Patelb38ad88e2017-01-02 23:25:28 +00001021 if (Value *AvailableVal = FindAvailableLoadedValue(
1022 &LI, LI.getParent(), BBI, DefMaxInstsToScan, AA, &IsLoadCSE)) {
1023 if (IsLoadCSE)
1024 combineMetadataForCSE(cast<LoadInst>(AvailableVal), &LI);
Bjorn Steinbrinka91fd092015-07-10 06:55:44 +00001025
Sanjay Patel4b198802016-02-01 22:23:39 +00001026 return replaceInstUsesWith(
Craig Topperbb4069e2017-07-07 23:16:26 +00001027 LI, Builder.CreateBitOrPointerCast(AvailableVal, LI.getType(),
1028 LI.getName() + ".cast"));
Bjorn Steinbrinka91fd092015-07-10 06:55:44 +00001029 }
Chris Lattnera65e2f72010-01-05 05:57:49 +00001030
Philip Reames3ac07182016-04-21 17:45:05 +00001031 // None of the following transforms are legal for volatile/ordered atomic
1032 // loads. Most of them do apply for unordered atomics.
1033 if (!LI.isUnordered()) return nullptr;
Philip Reamesac550902016-04-21 17:03:33 +00001034
Chris Lattnera65e2f72010-01-05 05:57:49 +00001035 // load(gep null, ...) -> unreachable
Chris Lattnera65e2f72010-01-05 05:57:49 +00001036 // load null/undef -> unreachable
Davide Italianoffcb4df2017-04-19 17:26:57 +00001037 // TODO: Consider a target hook for valid address spaces for this xforms.
1038 if (canSimplifyNullLoadOrGEP(LI, Op)) {
1039 // Insert a new store to null instruction before the load to indicate
1040 // that this code is not reachable. We do this instead of inserting
1041 // an unreachable instruction directly because we cannot modify the
1042 // CFG.
Weiming Zhao984f1dc2017-07-19 01:27:24 +00001043 StoreInst *SI = new StoreInst(UndefValue::get(LI.getType()),
1044 Constant::getNullValue(Op->getType()), &LI);
1045 SI->setDebugLoc(LI.getDebugLoc());
Sanjay Patel4b198802016-02-01 22:23:39 +00001046 return replaceInstUsesWith(LI, UndefValue::get(LI.getType()));
Chris Lattnera65e2f72010-01-05 05:57:49 +00001047 }
1048
Chris Lattnera65e2f72010-01-05 05:57:49 +00001049 if (Op->hasOneUse()) {
1050 // Change select and PHI nodes to select values instead of addresses: this
1051 // helps alias analysis out a lot, allows many others simplifications, and
1052 // exposes redundancy in the code.
1053 //
1054 // Note that we cannot do the transformation unless we know that the
1055 // introduced loads cannot trap! Something like this is valid as long as
1056 // the condition is always false: load (select bool %C, int* null, int* %G),
1057 // but it would not be valid if we transformed it to load from null
1058 // unconditionally.
1059 //
1060 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
1061 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
Bob Wilson56600a12010-01-30 04:42:39 +00001062 unsigned Align = LI.getAlignment();
Artur Pilipenko9bb6bea2016-04-27 11:00:48 +00001063 if (isSafeToLoadUnconditionally(SI->getOperand(1), Align, DL, SI) &&
1064 isSafeToLoadUnconditionally(SI->getOperand(2), Align, DL, SI)) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001065 LoadInst *V1 = Builder.CreateLoad(SI->getOperand(1),
1066 SI->getOperand(1)->getName()+".val");
1067 LoadInst *V2 = Builder.CreateLoad(SI->getOperand(2),
1068 SI->getOperand(2)->getName()+".val");
Philip Reamesa98c7ea2016-04-21 17:59:40 +00001069 assert(LI.isUnordered() && "implied by above");
Bob Wilson56600a12010-01-30 04:42:39 +00001070 V1->setAlignment(Align);
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00001071 V1->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
Bob Wilson56600a12010-01-30 04:42:39 +00001072 V2->setAlignment(Align);
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00001073 V2->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
Chris Lattnera65e2f72010-01-05 05:57:49 +00001074 return SelectInst::Create(SI->getCondition(), V1, V2);
1075 }
1076
1077 // load (select (cond, null, P)) -> load P
Larisse Voufo532bf712015-09-18 19:14:35 +00001078 if (isa<ConstantPointerNull>(SI->getOperand(1)) &&
Philip Reames5ad26c32014-12-29 22:46:21 +00001079 LI.getPointerAddressSpace() == 0) {
1080 LI.setOperand(0, SI->getOperand(2));
1081 return &LI;
1082 }
Chris Lattnera65e2f72010-01-05 05:57:49 +00001083
1084 // load (select (cond, P, null)) -> load P
Philip Reames5ad26c32014-12-29 22:46:21 +00001085 if (isa<ConstantPointerNull>(SI->getOperand(2)) &&
1086 LI.getPointerAddressSpace() == 0) {
1087 LI.setOperand(0, SI->getOperand(1));
1088 return &LI;
1089 }
Chris Lattnera65e2f72010-01-05 05:57:49 +00001090 }
1091 }
Craig Topperf40110f2014-04-25 05:29:35 +00001092 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001093}
1094
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001095/// Look for extractelement/insertvalue sequence that acts like a bitcast.
Arch D. Robisonbe0490a2016-04-25 22:22:39 +00001096///
1097/// \returns underlying value that was "cast", or nullptr otherwise.
1098///
1099/// For example, if we have:
1100///
1101/// %E0 = extractelement <2 x double> %U, i32 0
1102/// %V0 = insertvalue [2 x double] undef, double %E0, 0
1103/// %E1 = extractelement <2 x double> %U, i32 1
1104/// %V1 = insertvalue [2 x double] %V0, double %E1, 1
1105///
1106/// and the layout of a <2 x double> is isomorphic to a [2 x double],
1107/// then %V1 can be safely approximated by a conceptual "bitcast" of %U.
1108/// Note that %U may contain non-undef values where %V1 has undef.
1109static Value *likeBitCastFromVector(InstCombiner &IC, Value *V) {
1110 Value *U = nullptr;
1111 while (auto *IV = dyn_cast<InsertValueInst>(V)) {
1112 auto *E = dyn_cast<ExtractElementInst>(IV->getInsertedValueOperand());
1113 if (!E)
1114 return nullptr;
1115 auto *W = E->getVectorOperand();
1116 if (!U)
1117 U = W;
1118 else if (U != W)
1119 return nullptr;
1120 auto *CI = dyn_cast<ConstantInt>(E->getIndexOperand());
1121 if (!CI || IV->getNumIndices() != 1 || CI->getZExtValue() != *IV->idx_begin())
1122 return nullptr;
1123 V = IV->getAggregateOperand();
1124 }
1125 if (!isa<UndefValue>(V) ||!U)
1126 return nullptr;
1127
1128 auto *UT = cast<VectorType>(U->getType());
1129 auto *VT = V->getType();
1130 // Check that types UT and VT are bitwise isomorphic.
1131 const auto &DL = IC.getDataLayout();
1132 if (DL.getTypeStoreSizeInBits(UT) != DL.getTypeStoreSizeInBits(VT)) {
1133 return nullptr;
1134 }
1135 if (auto *AT = dyn_cast<ArrayType>(VT)) {
1136 if (AT->getNumElements() != UT->getNumElements())
1137 return nullptr;
1138 } else {
1139 auto *ST = cast<StructType>(VT);
1140 if (ST->getNumElements() != UT->getNumElements())
1141 return nullptr;
1142 for (const auto *EltT : ST->elements()) {
1143 if (EltT != UT->getElementType())
1144 return nullptr;
1145 }
1146 }
1147 return U;
1148}
1149
Adrian Prantl5f8f34e42018-05-01 15:54:18 +00001150/// Combine stores to match the type of value being stored.
Chandler Carruth816d26f2014-11-25 10:09:51 +00001151///
1152/// The core idea here is that the memory does not have any intrinsic type and
1153/// where we can we should match the type of a store to the type of value being
1154/// stored.
1155///
1156/// However, this routine must never change the width of a store or the number of
1157/// stores as that would introduce a semantic change. This combine is expected to
1158/// be a semantic no-op which just allows stores to more closely model the types
1159/// of their incoming values.
1160///
1161/// Currently, we also refuse to change the precise type used for an atomic or
1162/// volatile store. This is debatable, and might be reasonable to change later.
1163/// However, it is risky in case some backend or other part of LLVM is relying
1164/// on the exact type stored to select appropriate atomic operations.
1165///
1166/// \returns true if the store was successfully combined away. This indicates
1167/// the caller must erase the store instruction. We have to let the caller erase
Bruce Mitchenere9ffb452015-09-12 01:17:08 +00001168/// the store instruction as otherwise there is no way to signal whether it was
Chandler Carruth816d26f2014-11-25 10:09:51 +00001169/// combined or not: IC.EraseInstFromFunction returns a null pointer.
1170static bool combineStoreToValueType(InstCombiner &IC, StoreInst &SI) {
Philip Reames6f4d0082016-05-06 22:17:01 +00001171 // FIXME: We could probably with some care handle both volatile and ordered
1172 // atomic stores here but it isn't clear that this is important.
1173 if (!SI.isUnordered())
Chandler Carruth816d26f2014-11-25 10:09:51 +00001174 return false;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001175
Arnold Schwaighofer5d335552016-09-10 18:14:57 +00001176 // swifterror values can't be bitcasted.
1177 if (SI.getPointerOperand()->isSwiftError())
1178 return false;
1179
Chandler Carruth816d26f2014-11-25 10:09:51 +00001180 Value *V = SI.getValueOperand();
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001181
Chandler Carruth816d26f2014-11-25 10:09:51 +00001182 // Fold away bit casts of the stored value by storing the original type.
1183 if (auto *BC = dyn_cast<BitCastInst>(V)) {
Chandler Carrutha7f247e2014-12-09 19:21:16 +00001184 V = BC->getOperand(0);
Philip Reames89e92d22016-12-01 20:17:06 +00001185 if (!SI.isAtomic() || isSupportedAtomicType(V->getType())) {
1186 combineStoreToNewValue(IC, SI, V);
1187 return true;
1188 }
Chris Lattnera65e2f72010-01-05 05:57:49 +00001189 }
1190
Philip Reames89e92d22016-12-01 20:17:06 +00001191 if (Value *U = likeBitCastFromVector(IC, V))
1192 if (!SI.isAtomic() || isSupportedAtomicType(U->getType())) {
1193 combineStoreToNewValue(IC, SI, U);
1194 return true;
1195 }
Arch D. Robisonbe0490a2016-04-25 22:22:39 +00001196
JF Bastienc22d2992016-04-21 19:53:39 +00001197 // FIXME: We should also canonicalize stores of vectors when their elements
1198 // are cast to other types.
Chandler Carruth816d26f2014-11-25 10:09:51 +00001199 return false;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001200}
1201
Mehdi Aminib344ac92015-03-14 22:19:33 +00001202static bool unpackStoreToAggregate(InstCombiner &IC, StoreInst &SI) {
1203 // FIXME: We could probably with some care handle both volatile and atomic
1204 // stores here but it isn't clear that this is important.
1205 if (!SI.isSimple())
1206 return false;
1207
1208 Value *V = SI.getValueOperand();
1209 Type *T = V->getType();
1210
1211 if (!T->isAggregateType())
1212 return false;
1213
Mehdi Amini2668a482015-05-07 05:52:40 +00001214 if (auto *ST = dyn_cast<StructType>(T)) {
Mehdi Aminib344ac92015-03-14 22:19:33 +00001215 // If the struct only have one element, we unpack.
Mehdi Amini1c131b32015-12-15 01:44:07 +00001216 unsigned Count = ST->getNumElements();
1217 if (Count == 1) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001218 V = IC.Builder.CreateExtractValue(V, 0);
Mehdi Aminib344ac92015-03-14 22:19:33 +00001219 combineStoreToNewValue(IC, SI, V);
1220 return true;
1221 }
Mehdi Amini1c131b32015-12-15 01:44:07 +00001222
1223 // We don't want to break loads with padding here as we'd loose
1224 // the knowledge that padding exists for the rest of the pipeline.
1225 const DataLayout &DL = IC.getDataLayout();
1226 auto *SL = DL.getStructLayout(ST);
1227 if (SL->hasPadding())
1228 return false;
1229
Amaury Sechet61a7d622016-02-17 19:21:28 +00001230 auto Align = SI.getAlignment();
1231 if (!Align)
1232 Align = DL.getABITypeAlignment(ST);
1233
NAKAMURA Takumiec6b1fc2015-12-15 09:37:31 +00001234 SmallString<16> EltName = V->getName();
1235 EltName += ".elt";
Mehdi Amini1c131b32015-12-15 01:44:07 +00001236 auto *Addr = SI.getPointerOperand();
NAKAMURA Takumiec6b1fc2015-12-15 09:37:31 +00001237 SmallString<16> AddrName = Addr->getName();
1238 AddrName += ".repack";
Amaury Sechet61a7d622016-02-17 19:21:28 +00001239
Mehdi Amini1c131b32015-12-15 01:44:07 +00001240 auto *IdxType = Type::getInt32Ty(ST->getContext());
1241 auto *Zero = ConstantInt::get(IdxType, 0);
1242 for (unsigned i = 0; i < Count; i++) {
1243 Value *Indices[2] = {
1244 Zero,
1245 ConstantInt::get(IdxType, i),
1246 };
Craig Topperbb4069e2017-07-07 23:16:26 +00001247 auto *Ptr = IC.Builder.CreateInBoundsGEP(ST, Addr, makeArrayRef(Indices),
1248 AddrName);
1249 auto *Val = IC.Builder.CreateExtractValue(V, i, EltName);
Amaury Sechet61a7d622016-02-17 19:21:28 +00001250 auto EltAlign = MinAlign(Align, SL->getElementOffset(i));
Craig Topperbb4069e2017-07-07 23:16:26 +00001251 llvm::Instruction *NS = IC.Builder.CreateAlignedStore(Val, Ptr, EltAlign);
Keno Fischera236dae2017-06-28 23:36:40 +00001252 AAMDNodes AAMD;
1253 SI.getAAMetadata(AAMD);
1254 NS->setAAMetadata(AAMD);
Mehdi Amini1c131b32015-12-15 01:44:07 +00001255 }
1256
1257 return true;
Mehdi Aminib344ac92015-03-14 22:19:33 +00001258 }
1259
David Majnemer75364602015-05-11 05:04:27 +00001260 if (auto *AT = dyn_cast<ArrayType>(T)) {
1261 // If the array only have one element, we unpack.
Amaury Sechet3b8b2ea2016-03-02 22:36:45 +00001262 auto NumElements = AT->getNumElements();
1263 if (NumElements == 1) {
Craig Topperbb4069e2017-07-07 23:16:26 +00001264 V = IC.Builder.CreateExtractValue(V, 0);
David Majnemer75364602015-05-11 05:04:27 +00001265 combineStoreToNewValue(IC, SI, V);
1266 return true;
1267 }
Amaury Sechet3b8b2ea2016-03-02 22:36:45 +00001268
Davide Italianof6988d22016-10-07 21:53:09 +00001269 // Bail out if the array is too large. Ideally we would like to optimize
1270 // arrays of arbitrary size but this has a terrible impact on compile time.
1271 // The threshold here is chosen arbitrarily, maybe needs a little bit of
1272 // tuning.
Davide Italiano2133bf52017-02-07 17:56:50 +00001273 if (NumElements > IC.MaxArraySizeForCombine)
Davide Italianof6988d22016-10-07 21:53:09 +00001274 return false;
1275
Amaury Sechet3b8b2ea2016-03-02 22:36:45 +00001276 const DataLayout &DL = IC.getDataLayout();
1277 auto EltSize = DL.getTypeAllocSize(AT->getElementType());
1278 auto Align = SI.getAlignment();
1279 if (!Align)
1280 Align = DL.getABITypeAlignment(T);
1281
1282 SmallString<16> EltName = V->getName();
1283 EltName += ".elt";
1284 auto *Addr = SI.getPointerOperand();
1285 SmallString<16> AddrName = Addr->getName();
1286 AddrName += ".repack";
1287
1288 auto *IdxType = Type::getInt64Ty(T->getContext());
1289 auto *Zero = ConstantInt::get(IdxType, 0);
1290
1291 uint64_t Offset = 0;
1292 for (uint64_t i = 0; i < NumElements; i++) {
1293 Value *Indices[2] = {
1294 Zero,
1295 ConstantInt::get(IdxType, i),
1296 };
Craig Topperbb4069e2017-07-07 23:16:26 +00001297 auto *Ptr = IC.Builder.CreateInBoundsGEP(AT, Addr, makeArrayRef(Indices),
1298 AddrName);
1299 auto *Val = IC.Builder.CreateExtractValue(V, i, EltName);
Amaury Sechet3b8b2ea2016-03-02 22:36:45 +00001300 auto EltAlign = MinAlign(Align, Offset);
Craig Topperbb4069e2017-07-07 23:16:26 +00001301 Instruction *NS = IC.Builder.CreateAlignedStore(Val, Ptr, EltAlign);
Keno Fischera236dae2017-06-28 23:36:40 +00001302 AAMDNodes AAMD;
1303 SI.getAAMetadata(AAMD);
1304 NS->setAAMetadata(AAMD);
Amaury Sechet3b8b2ea2016-03-02 22:36:45 +00001305 Offset += EltSize;
1306 }
1307
1308 return true;
David Majnemer75364602015-05-11 05:04:27 +00001309 }
1310
Mehdi Aminib344ac92015-03-14 22:19:33 +00001311 return false;
1312}
1313
Chris Lattnera65e2f72010-01-05 05:57:49 +00001314/// equivalentAddressValues - Test if A and B will obviously have the same
1315/// value. This includes recognizing that %t0 and %t1 will have the same
1316/// value in code like this:
1317/// %t0 = getelementptr \@a, 0, 3
1318/// store i32 0, i32* %t0
1319/// %t1 = getelementptr \@a, 0, 3
1320/// %t2 = load i32* %t1
1321///
1322static bool equivalentAddressValues(Value *A, Value *B) {
1323 // Test if the values are trivially equivalent.
1324 if (A == B) return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001325
Chris Lattnera65e2f72010-01-05 05:57:49 +00001326 // Test if the values come form identical arithmetic instructions.
1327 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
1328 // its only used to compare two uses within the same basic block, which
1329 // means that they'll always either have the same value or one of them
1330 // will have an undefined value.
1331 if (isa<BinaryOperator>(A) ||
1332 isa<CastInst>(A) ||
1333 isa<PHINode>(A) ||
1334 isa<GetElementPtrInst>(A))
1335 if (Instruction *BI = dyn_cast<Instruction>(B))
1336 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
1337 return true;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001338
Chris Lattnera65e2f72010-01-05 05:57:49 +00001339 // Otherwise they may not be equivalent.
1340 return false;
1341}
1342
Alexey Bataevec95c6c2017-12-08 15:32:10 +00001343/// Converts store (bitcast (load (bitcast (select ...)))) to
1344/// store (load (select ...)), where select is minmax:
1345/// select ((cmp load V1, load V2), V1, V2).
Alexey Bataev83c15b12017-12-12 20:28:46 +00001346static bool removeBitcastsFromLoadStoreOnMinMax(InstCombiner &IC,
1347 StoreInst &SI) {
Alexey Bataevec95c6c2017-12-08 15:32:10 +00001348 // bitcast?
Alexey Bataev83c15b12017-12-12 20:28:46 +00001349 if (!match(SI.getPointerOperand(), m_BitCast(m_Value())))
Alexey Bataevfa0a76d2017-12-12 19:12:34 +00001350 return false;
Alexey Bataevec95c6c2017-12-08 15:32:10 +00001351 // load? integer?
1352 Value *LoadAddr;
1353 if (!match(SI.getValueOperand(), m_Load(m_BitCast(m_Value(LoadAddr)))))
Alexey Bataevfa0a76d2017-12-12 19:12:34 +00001354 return false;
Alexey Bataevec95c6c2017-12-08 15:32:10 +00001355 auto *LI = cast<LoadInst>(SI.getValueOperand());
1356 if (!LI->getType()->isIntegerTy())
Alexey Bataevfa0a76d2017-12-12 19:12:34 +00001357 return false;
Alexey Bataevec95c6c2017-12-08 15:32:10 +00001358 if (!isMinMaxWithLoads(LoadAddr))
Alexey Bataevfa0a76d2017-12-12 19:12:34 +00001359 return false;
Alexey Bataevec95c6c2017-12-08 15:32:10 +00001360
Alexey Bataev83c15b12017-12-12 20:28:46 +00001361 if (!all_of(LI->users(), [LI, LoadAddr](User *U) {
1362 auto *SI = dyn_cast<StoreInst>(U);
1363 return SI && SI->getPointerOperand() != LI &&
1364 peekThroughBitcast(SI->getPointerOperand()) != LoadAddr &&
1365 !SI->getPointerOperand()->isSwiftError();
1366 }))
1367 return false;
1368
1369 IC.Builder.SetInsertPoint(LI);
Alexey Bataevec95c6c2017-12-08 15:32:10 +00001370 LoadInst *NewLI = combineLoadToNewType(
1371 IC, *LI, LoadAddr->getType()->getPointerElementType());
Alexey Bataev83c15b12017-12-12 20:28:46 +00001372 // Replace all the stores with stores of the newly loaded value.
1373 for (auto *UI : LI->users()) {
1374 auto *USI = cast<StoreInst>(UI);
1375 IC.Builder.SetInsertPoint(USI);
1376 combineStoreToNewValue(IC, *USI, NewLI);
1377 }
1378 IC.replaceInstUsesWith(*LI, UndefValue::get(LI->getType()));
1379 IC.eraseInstFromFunction(*LI);
Alexey Bataevfa0a76d2017-12-12 19:12:34 +00001380 return true;
Alexey Bataevec95c6c2017-12-08 15:32:10 +00001381}
1382
Chris Lattnera65e2f72010-01-05 05:57:49 +00001383Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
1384 Value *Val = SI.getOperand(0);
1385 Value *Ptr = SI.getOperand(1);
1386
Chandler Carruth816d26f2014-11-25 10:09:51 +00001387 // Try to canonicalize the stored type.
1388 if (combineStoreToValueType(*this, SI))
Sanjay Patel4b198802016-02-01 22:23:39 +00001389 return eraseInstFromFunction(SI);
Chandler Carruth816d26f2014-11-25 10:09:51 +00001390
Chris Lattnera65e2f72010-01-05 05:57:49 +00001391 // Attempt to improve the alignment.
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001392 unsigned KnownAlign = getOrEnforceKnownAlignment(
Daniel Jasperaec2fa32016-12-19 08:22:17 +00001393 Ptr, DL.getPrefTypeAlignment(Val->getType()), DL, &SI, &AC, &DT);
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001394 unsigned StoreAlign = SI.getAlignment();
1395 unsigned EffectiveStoreAlign =
1396 StoreAlign != 0 ? StoreAlign : DL.getABITypeAlignment(Val->getType());
Dan Gohman36196602010-08-03 18:20:32 +00001397
Mehdi Aminia28d91d2015-03-10 02:37:25 +00001398 if (KnownAlign > EffectiveStoreAlign)
1399 SI.setAlignment(KnownAlign);
1400 else if (StoreAlign == 0)
1401 SI.setAlignment(EffectiveStoreAlign);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001402
Mehdi Aminib344ac92015-03-14 22:19:33 +00001403 // Try to canonicalize the stored type.
1404 if (unpackStoreToAggregate(*this, SI))
Sanjay Patel4b198802016-02-01 22:23:39 +00001405 return eraseInstFromFunction(SI);
Mehdi Aminib344ac92015-03-14 22:19:33 +00001406
Alexey Bataevfa0a76d2017-12-12 19:12:34 +00001407 if (removeBitcastsFromLoadStoreOnMinMax(*this, SI))
1408 return eraseInstFromFunction(SI);
Alexey Bataevec95c6c2017-12-08 15:32:10 +00001409
Hal Finkel847e05f2015-02-20 03:05:53 +00001410 // Replace GEP indices if possible.
1411 if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Ptr, SI)) {
1412 Worklist.Add(NewGEPI);
1413 return &SI;
1414 }
1415
Philip Reamesd7a6cc82015-12-17 22:19:27 +00001416 // Don't hack volatile/ordered stores.
1417 // FIXME: Some bits are legal for ordered atomic stores; needs refactoring.
1418 if (!SI.isUnordered()) return nullptr;
Eli Friedman8bc586e2011-08-15 22:09:40 +00001419
1420 // If the RHS is an alloca with a single use, zapify the store, making the
1421 // alloca dead.
1422 if (Ptr->hasOneUse()) {
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001423 if (isa<AllocaInst>(Ptr))
Sanjay Patel4b198802016-02-01 22:23:39 +00001424 return eraseInstFromFunction(SI);
Eli Friedman8bc586e2011-08-15 22:09:40 +00001425 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
1426 if (isa<AllocaInst>(GEP->getOperand(0))) {
1427 if (GEP->getOperand(0)->hasOneUse())
Sanjay Patel4b198802016-02-01 22:23:39 +00001428 return eraseInstFromFunction(SI);
Eli Friedman8bc586e2011-08-15 22:09:40 +00001429 }
1430 }
1431 }
1432
Chris Lattnera65e2f72010-01-05 05:57:49 +00001433 // Do really simple DSE, to catch cases where there are several consecutive
1434 // stores to the same location, separated by a few arithmetic operations. This
1435 // situation often occurs with bitfield accesses.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00001436 BasicBlock::iterator BBI(SI);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001437 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
1438 --ScanInsts) {
1439 --BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +00001440 // Don't count debug info directives, lest they affect codegen,
1441 // and we skip pointer-to-pointer bitcasts, which are NOPs.
1442 if (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +00001443 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +00001444 ScanInsts++;
1445 continue;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001446 }
1447
Chris Lattnera65e2f72010-01-05 05:57:49 +00001448 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
1449 // Prev store isn't volatile, and stores to the same location?
Philip Reamesd7a6cc82015-12-17 22:19:27 +00001450 if (PrevSI->isUnordered() && equivalentAddressValues(PrevSI->getOperand(1),
Eli Friedman8bc586e2011-08-15 22:09:40 +00001451 SI.getOperand(1))) {
Chris Lattnera65e2f72010-01-05 05:57:49 +00001452 ++NumDeadStore;
1453 ++BBI;
Sanjay Patel4b198802016-02-01 22:23:39 +00001454 eraseInstFromFunction(*PrevSI);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001455 continue;
1456 }
1457 break;
1458 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001459
Chris Lattnera65e2f72010-01-05 05:57:49 +00001460 // If this is a load, we have to stop. However, if the loaded value is from
1461 // the pointer we're loading and is producing the pointer we're storing,
1462 // then *this* store is dead (X = load P; store X -> P).
1463 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
Philip Reamesd7a6cc82015-12-17 22:19:27 +00001464 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr)) {
1465 assert(SI.isUnordered() && "can't eliminate ordering operation");
Sanjay Patel4b198802016-02-01 22:23:39 +00001466 return eraseInstFromFunction(SI);
Philip Reamesd7a6cc82015-12-17 22:19:27 +00001467 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001468
Chris Lattnera65e2f72010-01-05 05:57:49 +00001469 // Otherwise, this is a load from some other location. Stores before it
1470 // may not be dead.
1471 break;
1472 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001473
Sanjoy Das679bc322017-01-17 05:45:09 +00001474 // Don't skip over loads, throws or things that can modify memory.
1475 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory() || BBI->mayThrow())
Chris Lattnera65e2f72010-01-05 05:57:49 +00001476 break;
1477 }
Chris Lattnera65e2f72010-01-05 05:57:49 +00001478
1479 // store X, null -> turns into 'unreachable' in SimplifyCFG
Anna Thomas2dd98352017-12-12 14:12:33 +00001480 // store X, GEP(null, Y) -> turns into 'unreachable' in SimplifyCFG
1481 if (canSimplifyNullStoreOrGEP(SI)) {
Chris Lattnera65e2f72010-01-05 05:57:49 +00001482 if (!isa<UndefValue>(Val)) {
1483 SI.setOperand(0, UndefValue::get(Val->getType()));
1484 if (Instruction *U = dyn_cast<Instruction>(Val))
1485 Worklist.Add(U); // Dropped a use.
1486 }
Craig Topperf40110f2014-04-25 05:29:35 +00001487 return nullptr; // Do not modify these!
Chris Lattnera65e2f72010-01-05 05:57:49 +00001488 }
1489
1490 // store undef, Ptr -> noop
1491 if (isa<UndefValue>(Val))
Sanjay Patel4b198802016-02-01 22:23:39 +00001492 return eraseInstFromFunction(SI);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001493
Chris Lattnera65e2f72010-01-05 05:57:49 +00001494 // If this store is the last instruction in the basic block (possibly
Victor Hernandez5f5abd52010-01-21 23:07:15 +00001495 // excepting debug info instructions), and if the block ends with an
1496 // unconditional branch, try to move it to the successor block.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00001497 BBI = SI.getIterator();
Chris Lattnera65e2f72010-01-05 05:57:49 +00001498 do {
1499 ++BBI;
Victor Hernandez5f8c8c02010-01-22 19:05:05 +00001500 } while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +00001501 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()));
Chris Lattnera65e2f72010-01-05 05:57:49 +00001502 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
1503 if (BI->isUnconditional())
1504 if (SimplifyStoreAtEndOfBlock(SI))
Craig Topperf40110f2014-04-25 05:29:35 +00001505 return nullptr; // xform done!
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001506
Craig Topperf40110f2014-04-25 05:29:35 +00001507 return nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001508}
1509
1510/// SimplifyStoreAtEndOfBlock - Turn things like:
1511/// if () { *P = v1; } else { *P = v2 }
1512/// into a phi node with a store in the successor.
1513///
1514/// Simplify things like:
1515/// *P = v1; if () { *P = v2; }
1516/// into a phi node with a store in the successor.
1517///
1518bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
Philip Reames5f0e3692016-04-22 20:53:32 +00001519 assert(SI.isUnordered() &&
1520 "this code has not been auditted for volatile or ordered store case");
Justin Bognerc7e4fbe2016-08-05 01:09:48 +00001521
Chris Lattnera65e2f72010-01-05 05:57:49 +00001522 BasicBlock *StoreBB = SI.getParent();
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001523
Chris Lattnera65e2f72010-01-05 05:57:49 +00001524 // Check to see if the successor block has exactly two incoming edges. If
1525 // so, see if the other predecessor contains a store to the same location.
1526 // if so, insert a PHI node (if needed) and move the stores down.
1527 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001528
Chris Lattnera65e2f72010-01-05 05:57:49 +00001529 // Determine whether Dest has exactly two predecessors and, if so, compute
1530 // the other predecessor.
1531 pred_iterator PI = pred_begin(DestBB);
Gabor Greif1b787df2010-07-12 15:48:26 +00001532 BasicBlock *P = *PI;
Craig Topperf40110f2014-04-25 05:29:35 +00001533 BasicBlock *OtherBB = nullptr;
Gabor Greif1b787df2010-07-12 15:48:26 +00001534
1535 if (P != StoreBB)
1536 OtherBB = P;
1537
1538 if (++PI == pred_end(DestBB))
Chris Lattnera65e2f72010-01-05 05:57:49 +00001539 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001540
Gabor Greif1b787df2010-07-12 15:48:26 +00001541 P = *PI;
1542 if (P != StoreBB) {
Chris Lattnera65e2f72010-01-05 05:57:49 +00001543 if (OtherBB)
1544 return false;
Gabor Greif1b787df2010-07-12 15:48:26 +00001545 OtherBB = P;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001546 }
1547 if (++PI != pred_end(DestBB))
1548 return false;
1549
1550 // Bail out if all the relevant blocks aren't distinct (this can happen,
1551 // for example, if SI is in an infinite loop)
1552 if (StoreBB == DestBB || OtherBB == DestBB)
1553 return false;
1554
1555 // Verify that the other block ends in a branch and is not otherwise empty.
Duncan P. N. Exon Smith9f8aaf22015-10-13 16:59:33 +00001556 BasicBlock::iterator BBI(OtherBB->getTerminator());
Chris Lattnera65e2f72010-01-05 05:57:49 +00001557 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
1558 if (!OtherBr || BBI == OtherBB->begin())
1559 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001560
Chris Lattnera65e2f72010-01-05 05:57:49 +00001561 // If the other block ends in an unconditional branch, check for the 'if then
1562 // else' case. there is an instruction before the branch.
Craig Topperf40110f2014-04-25 05:29:35 +00001563 StoreInst *OtherStore = nullptr;
Chris Lattnera65e2f72010-01-05 05:57:49 +00001564 if (OtherBr->isUnconditional()) {
1565 --BBI;
1566 // Skip over debugging info.
Victor Hernandez5f8c8c02010-01-22 19:05:05 +00001567 while (isa<DbgInfoIntrinsic>(BBI) ||
Duncan Sands19d0b472010-02-16 11:11:14 +00001568 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
Chris Lattnera65e2f72010-01-05 05:57:49 +00001569 if (BBI==OtherBB->begin())
1570 return false;
1571 --BBI;
1572 }
Eli Friedman8bc586e2011-08-15 22:09:40 +00001573 // If this isn't a store, isn't a store to the same location, or is not the
1574 // right kind of store, bail out.
Chris Lattnera65e2f72010-01-05 05:57:49 +00001575 OtherStore = dyn_cast<StoreInst>(BBI);
1576 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +00001577 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +00001578 return false;
1579 } else {
1580 // Otherwise, the other block ended with a conditional branch. If one of the
1581 // destinations is StoreBB, then we have the if/then case.
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001582 if (OtherBr->getSuccessor(0) != StoreBB &&
Chris Lattnera65e2f72010-01-05 05:57:49 +00001583 OtherBr->getSuccessor(1) != StoreBB)
1584 return false;
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001585
Chris Lattnera65e2f72010-01-05 05:57:49 +00001586 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
1587 // if/then triangle. See if there is a store to the same ptr as SI that
1588 // lives in OtherBB.
1589 for (;; --BBI) {
1590 // Check to see if we find the matching store.
1591 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
1592 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
Eli Friedman8bc586e2011-08-15 22:09:40 +00001593 !SI.isSameOperationAs(OtherStore))
Chris Lattnera65e2f72010-01-05 05:57:49 +00001594 return false;
1595 break;
1596 }
1597 // If we find something that may be using or overwriting the stored
1598 // value, or if we run out of instructions, we can't do the xform.
Sanjoy Das679bc322017-01-17 05:45:09 +00001599 if (BBI->mayReadFromMemory() || BBI->mayThrow() ||
1600 BBI->mayWriteToMemory() || BBI == OtherBB->begin())
Chris Lattnera65e2f72010-01-05 05:57:49 +00001601 return false;
1602 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001603
Chris Lattnera65e2f72010-01-05 05:57:49 +00001604 // In order to eliminate the store in OtherBr, we have to
1605 // make sure nothing reads or overwrites the stored value in
1606 // StoreBB.
1607 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
1608 // FIXME: This should really be AA driven.
Sanjoy Das679bc322017-01-17 05:45:09 +00001609 if (I->mayReadFromMemory() || I->mayThrow() || I->mayWriteToMemory())
Chris Lattnera65e2f72010-01-05 05:57:49 +00001610 return false;
1611 }
1612 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001613
Chris Lattnera65e2f72010-01-05 05:57:49 +00001614 // Insert a PHI node now if we need it.
1615 Value *MergedVal = OtherStore->getOperand(0);
1616 if (MergedVal != SI.getOperand(0)) {
Jay Foad52131342011-03-30 11:28:46 +00001617 PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge");
Chris Lattnera65e2f72010-01-05 05:57:49 +00001618 PN->addIncoming(SI.getOperand(0), SI.getParent());
1619 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
1620 MergedVal = InsertNewInstBefore(PN, DestBB->front());
1621 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001622
Chris Lattnera65e2f72010-01-05 05:57:49 +00001623 // Advance to a place where it is safe to insert the new store and
1624 // insert it.
Bill Wendling8ddfc092011-08-16 20:45:24 +00001625 BBI = DestBB->getFirstInsertionPt();
Eli Friedman35211c62011-05-27 00:19:40 +00001626 StoreInst *NewSI = new StoreInst(MergedVal, SI.getOperand(1),
Eli Friedman8bc586e2011-08-15 22:09:40 +00001627 SI.isVolatile(),
1628 SI.getAlignment(),
1629 SI.getOrdering(),
Konstantin Zhuravlyovbb80d3e2017-07-11 22:23:00 +00001630 SI.getSyncScopeID());
Eli Friedman35211c62011-05-27 00:19:40 +00001631 InsertNewInstBefore(NewSI, *BBI);
Paul Robinson383c5c22017-02-06 22:19:04 +00001632 // The debug locations of the original instructions might differ; merge them.
Dehao Chenf4646272017-10-02 18:13:14 +00001633 NewSI->applyMergedLocation(SI.getDebugLoc(), OtherStore->getDebugLoc());
Eli Friedman35211c62011-05-27 00:19:40 +00001634
Hal Finkelcc39b672014-07-24 12:16:19 +00001635 // If the two stores had AA tags, merge them.
1636 AAMDNodes AATags;
1637 SI.getAAMetadata(AATags);
1638 if (AATags) {
1639 OtherStore->getAAMetadata(AATags, /* Merge = */ true);
1640 NewSI->setAAMetadata(AATags);
1641 }
Jim Grosbachbdbd7342013-04-05 21:20:12 +00001642
Chris Lattnera65e2f72010-01-05 05:57:49 +00001643 // Nuke the old stores.
Sanjay Patel4b198802016-02-01 22:23:39 +00001644 eraseInstFromFunction(SI);
1645 eraseInstFromFunction(*OtherStore);
Chris Lattnera65e2f72010-01-05 05:57:49 +00001646 return true;
1647}