1 //===- InstCombineLoadStoreAlloca.cpp -------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the visit functions for load, store and alloca.
12 //===----------------------------------------------------------------------===//
14 #include "InstCombine.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/Analysis/Loads.h"
17 #include "llvm/IR/DataLayout.h"
18 #include "llvm/IR/IntrinsicInst.h"
19 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
20 #include "llvm/Transforms/Utils/Local.h"
23 #define DEBUG_TYPE "instcombine"
25 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
26 STATISTIC(NumGlobalCopies, "Number of allocas copied from constant global");
28 /// pointsToConstantGlobal - Return true if V (possibly indirectly) points to
29 /// some part of a constant global variable. This intentionally only accepts
30 /// constant expressions because we can't rewrite arbitrary instructions.
31 static bool pointsToConstantGlobal(Value *V) {
32 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
33 return GV->isConstant();
35 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
36 if (CE->getOpcode() == Instruction::BitCast ||
37 CE->getOpcode() == Instruction::AddrSpaceCast ||
38 CE->getOpcode() == Instruction::GetElementPtr)
39 return pointsToConstantGlobal(CE->getOperand(0));
44 /// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
45 /// pointer to an alloca. Ignore any reads of the pointer, return false if we
46 /// see any stores or other unknown uses. If we see pointer arithmetic, keep
47 /// track of whether it moves the pointer (with IsOffset) but otherwise traverse
48 /// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
49 /// the alloca, and if the source pointer is a pointer to a constant global, we
50 /// can optimize this.
52 isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
53 SmallVectorImpl<Instruction *> &ToDelete) {
54 // We track lifetime intrinsics as we encounter them. If we decide to go
55 // ahead and replace the value with the global, this lets the caller quickly
56 // eliminate the markers.
58 SmallVector<std::pair<Value *, bool>, 35> ValuesToInspect;
59 ValuesToInspect.push_back(std::make_pair(V, false));
60 while (!ValuesToInspect.empty()) {
61 auto ValuePair = ValuesToInspect.pop_back_val();
62 const bool IsOffset = ValuePair.second;
63 for (auto &U : ValuePair.first->uses()) {
64 Instruction *I = cast<Instruction>(U.getUser());
66 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
67 // Ignore non-volatile loads, they are always ok.
68 if (!LI->isSimple()) return false;
72 if (isa<BitCastInst>(I) || isa<AddrSpaceCastInst>(I)) {
73 // If uses of the bitcast are ok, we are ok.
74 ValuesToInspect.push_back(std::make_pair(I, IsOffset));
77 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
78 // If the GEP has all zero indices, it doesn't offset the pointer. If it
80 ValuesToInspect.push_back(
81 std::make_pair(I, IsOffset || !GEP->hasAllZeroIndices()));
85 if (CallSite CS = I) {
86 // If this is the function being called then we treat it like a load and
91 // Inalloca arguments are clobbered by the call.
92 unsigned ArgNo = CS.getArgumentNo(&U);
93 if (CS.isInAllocaArgument(ArgNo))
96 // If this is a readonly/readnone call site, then we know it is just a
97 // load (but one that potentially returns the value itself), so we can
98 // ignore it if we know that the value isn't captured.
99 if (CS.onlyReadsMemory() &&
100 (CS.getInstruction()->use_empty() || CS.doesNotCapture(ArgNo)))
103 // If this is being passed as a byval argument, the caller is making a
104 // copy, so it is only a read of the alloca.
105 if (CS.isByValArgument(ArgNo))
109 // Lifetime intrinsics can be handled by the caller.
110 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
111 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
112 II->getIntrinsicID() == Intrinsic::lifetime_end) {
113 assert(II->use_empty() && "Lifetime markers have no result to use!");
114 ToDelete.push_back(II);
119 // If this is isn't our memcpy/memmove, reject it as something we can't
121 MemTransferInst *MI = dyn_cast<MemTransferInst>(I);
125 // If the transfer is using the alloca as a source of the transfer, then
126 // ignore it since it is a load (unless the transfer is volatile).
127 if (U.getOperandNo() == 1) {
128 if (MI->isVolatile()) return false;
132 // If we already have seen a copy, reject the second one.
133 if (TheCopy) return false;
135 // If the pointer has been offset from the start of the alloca, we can't
136 // safely handle this.
137 if (IsOffset) return false;
139 // If the memintrinsic isn't using the alloca as the dest, reject it.
140 if (U.getOperandNo() != 0) return false;
142 // If the source of the memcpy/move is not a constant global, reject it.
143 if (!pointsToConstantGlobal(MI->getSource()))
146 // Otherwise, the transform is safe. Remember the copy instruction.
153 /// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
154 /// modified by a copy from a constant global. If we can prove this, we can
155 /// replace any uses of the alloca with uses of the global directly.
156 static MemTransferInst *
157 isOnlyCopiedFromConstantGlobal(AllocaInst *AI,
158 SmallVectorImpl<Instruction *> &ToDelete) {
159 MemTransferInst *TheCopy = nullptr;
160 if (isOnlyCopiedFromConstantGlobal(AI, TheCopy, ToDelete))
165 Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
166 // Ensure that the alloca array size argument has type intptr_t, so that
167 // any casting is exposed early.
169 Type *IntPtrTy = DL->getIntPtrType(AI.getType());
170 if (AI.getArraySize()->getType() != IntPtrTy) {
171 Value *V = Builder->CreateIntCast(AI.getArraySize(),
178 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
179 if (AI.isArrayAllocation()) { // Check C != 1
180 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
182 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
183 AllocaInst *New = Builder->CreateAlloca(NewTy, nullptr, AI.getName());
184 New->setAlignment(AI.getAlignment());
186 // Scan to the end of the allocation instructions, to skip over a block of
187 // allocas if possible...also skip interleaved debug info
189 BasicBlock::iterator It = New;
190 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
192 // Now that I is pointing to the first non-allocation-inst in the block,
193 // insert our getelementptr instruction...
196 ? DL->getIntPtrType(AI.getType())
197 : Type::getInt64Ty(AI.getContext());
198 Value *NullIdx = Constant::getNullValue(IdxTy);
199 Value *Idx[2] = { NullIdx, NullIdx };
201 GetElementPtrInst::CreateInBounds(New, Idx, New->getName() + ".sub");
202 InsertNewInstBefore(GEP, *It);
204 // Now make everything use the getelementptr instead of the original
206 return ReplaceInstUsesWith(AI, GEP);
207 } else if (isa<UndefValue>(AI.getArraySize())) {
208 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
212 if (DL && AI.getAllocatedType()->isSized()) {
213 // If the alignment is 0 (unspecified), assign it the preferred alignment.
214 if (AI.getAlignment() == 0)
215 AI.setAlignment(DL->getPrefTypeAlignment(AI.getAllocatedType()));
217 // Move all alloca's of zero byte objects to the entry block and merge them
218 // together. Note that we only do this for alloca's, because malloc should
219 // allocate and return a unique pointer, even for a zero byte allocation.
220 if (DL->getTypeAllocSize(AI.getAllocatedType()) == 0) {
221 // For a zero sized alloca there is no point in doing an array allocation.
222 // This is helpful if the array size is a complicated expression not used
224 if (AI.isArrayAllocation()) {
225 AI.setOperand(0, ConstantInt::get(AI.getArraySize()->getType(), 1));
229 // Get the first instruction in the entry block.
230 BasicBlock &EntryBlock = AI.getParent()->getParent()->getEntryBlock();
231 Instruction *FirstInst = EntryBlock.getFirstNonPHIOrDbg();
232 if (FirstInst != &AI) {
233 // If the entry block doesn't start with a zero-size alloca then move
234 // this one to the start of the entry block. There is no problem with
235 // dominance as the array size was forced to a constant earlier already.
236 AllocaInst *EntryAI = dyn_cast<AllocaInst>(FirstInst);
237 if (!EntryAI || !EntryAI->getAllocatedType()->isSized() ||
238 DL->getTypeAllocSize(EntryAI->getAllocatedType()) != 0) {
239 AI.moveBefore(FirstInst);
243 // If the alignment of the entry block alloca is 0 (unspecified),
244 // assign it the preferred alignment.
245 if (EntryAI->getAlignment() == 0)
246 EntryAI->setAlignment(
247 DL->getPrefTypeAlignment(EntryAI->getAllocatedType()));
248 // Replace this zero-sized alloca with the one at the start of the entry
249 // block after ensuring that the address will be aligned enough for both
251 unsigned MaxAlign = std::max(EntryAI->getAlignment(),
253 EntryAI->setAlignment(MaxAlign);
254 if (AI.getType() != EntryAI->getType())
255 return new BitCastInst(EntryAI, AI.getType());
256 return ReplaceInstUsesWith(AI, EntryAI);
261 if (AI.getAlignment()) {
262 // Check to see if this allocation is only modified by a memcpy/memmove from
263 // a constant global whose alignment is equal to or exceeds that of the
264 // allocation. If this is the case, we can change all users to use
265 // the constant global instead. This is commonly produced by the CFE by
266 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
267 // is only subsequently read.
268 SmallVector<Instruction *, 4> ToDelete;
269 if (MemTransferInst *Copy = isOnlyCopiedFromConstantGlobal(&AI, ToDelete)) {
270 unsigned SourceAlign = getOrEnforceKnownAlignment(Copy->getSource(),
273 if (AI.getAlignment() <= SourceAlign) {
274 DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n');
275 DEBUG(dbgs() << " memcpy = " << *Copy << '\n');
276 for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
277 EraseInstFromFunction(*ToDelete[i]);
278 Constant *TheSrc = cast<Constant>(Copy->getSource());
280 = ConstantExpr::getPointerBitCastOrAddrSpaceCast(TheSrc, AI.getType());
281 Instruction *NewI = ReplaceInstUsesWith(AI, Cast);
282 EraseInstFromFunction(*Copy);
289 // At last, use the generic allocation site handler to aggressively remove
291 return visitAllocSite(AI);
294 /// \brief Combine loads to match the type of value their uses after looking
295 /// through intervening bitcasts.
297 /// The core idea here is that if the result of a load is used in an operation,
298 /// we should load the type most conducive to that operation. For example, when
299 /// loading an integer and converting that immediately to a pointer, we should
300 /// instead directly load a pointer.
302 /// However, this routine must never change the width of a load or the number of
303 /// loads as that would introduce a semantic change. This combine is expected to
304 /// be a semantic no-op which just allows loads to more closely model the types
305 /// of their consuming operations.
307 /// Currently, we also refuse to change the precise type used for an atomic load
308 /// or a volatile load. This is debatable, and might be reasonable to change
309 /// later. However, it is risky in case some backend or other part of LLVM is
310 /// relying on the exact type loaded to select appropriate atomic operations.
311 static Instruction *combineLoadToOperationType(InstCombiner &IC, LoadInst &LI) {
312 // FIXME: We could probably with some care handle both volatile and atomic
313 // loads here but it isn't clear that this is important.
320 Value *Ptr = LI.getPointerOperand();
321 unsigned AS = LI.getPointerAddressSpace();
323 // Fold away bit casts of the loaded value by loading the desired type.
325 if (auto *BC = dyn_cast<BitCastInst>(LI.user_back())) {
326 LoadInst *NewLoad = IC.Builder->CreateAlignedLoad(
327 IC.Builder->CreateBitCast(Ptr, BC->getDestTy()->getPointerTo(AS)),
328 LI.getAlignment(), LI.getName());
329 BC->replaceAllUsesWith(NewLoad);
330 IC.EraseInstFromFunction(*BC);
334 // FIXME: We should also canonicalize loads of vectors when their elements are
335 // cast to other types.
339 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
340 Value *Op = LI.getOperand(0);
342 // Try to canonicalize the loaded type.
343 if (Instruction *Res = combineLoadToOperationType(*this, LI))
346 // Attempt to improve the alignment.
348 unsigned KnownAlign =
349 getOrEnforceKnownAlignment(Op, DL->getPrefTypeAlignment(LI.getType()),
351 unsigned LoadAlign = LI.getAlignment();
352 unsigned EffectiveLoadAlign = LoadAlign != 0 ? LoadAlign :
353 DL->getABITypeAlignment(LI.getType());
355 if (KnownAlign > EffectiveLoadAlign)
356 LI.setAlignment(KnownAlign);
357 else if (LoadAlign == 0)
358 LI.setAlignment(EffectiveLoadAlign);
361 // None of the following transforms are legal for volatile/atomic loads.
362 // FIXME: Some of it is okay for atomic loads; needs refactoring.
363 if (!LI.isSimple()) return nullptr;
365 // Do really simple store-to-load forwarding and load CSE, to catch cases
366 // where there are several consecutive memory accesses to the same location,
367 // separated by a few arithmetic operations.
368 BasicBlock::iterator BBI = &LI;
369 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
370 return ReplaceInstUsesWith(LI, AvailableVal);
372 // load(gep null, ...) -> unreachable
373 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
374 const Value *GEPI0 = GEPI->getOperand(0);
375 // TODO: Consider a target hook for valid address spaces for this xform.
376 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
377 // Insert a new store to null instruction before the load to indicate
378 // that this code is not reachable. We do this instead of inserting
379 // an unreachable instruction directly because we cannot modify the
381 new StoreInst(UndefValue::get(LI.getType()),
382 Constant::getNullValue(Op->getType()), &LI);
383 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
387 // load null/undef -> unreachable
388 // TODO: Consider a target hook for valid address spaces for this xform.
389 if (isa<UndefValue>(Op) ||
390 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
391 // Insert a new store to null instruction before the load to indicate that
392 // this code is not reachable. We do this instead of inserting an
393 // unreachable instruction directly because we cannot modify the CFG.
394 new StoreInst(UndefValue::get(LI.getType()),
395 Constant::getNullValue(Op->getType()), &LI);
396 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
399 if (Op->hasOneUse()) {
400 // Change select and PHI nodes to select values instead of addresses: this
401 // helps alias analysis out a lot, allows many others simplifications, and
402 // exposes redundancy in the code.
404 // Note that we cannot do the transformation unless we know that the
405 // introduced loads cannot trap! Something like this is valid as long as
406 // the condition is always false: load (select bool %C, int* null, int* %G),
407 // but it would not be valid if we transformed it to load from null
410 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
411 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
412 unsigned Align = LI.getAlignment();
413 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI, Align, DL) &&
414 isSafeToLoadUnconditionally(SI->getOperand(2), SI, Align, DL)) {
415 LoadInst *V1 = Builder->CreateLoad(SI->getOperand(1),
416 SI->getOperand(1)->getName()+".val");
417 LoadInst *V2 = Builder->CreateLoad(SI->getOperand(2),
418 SI->getOperand(2)->getName()+".val");
419 V1->setAlignment(Align);
420 V2->setAlignment(Align);
421 return SelectInst::Create(SI->getCondition(), V1, V2);
424 // load (select (cond, null, P)) -> load P
425 if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
426 if (C->isNullValue()) {
427 LI.setOperand(0, SI->getOperand(2));
431 // load (select (cond, P, null)) -> load P
432 if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
433 if (C->isNullValue()) {
434 LI.setOperand(0, SI->getOperand(1));
442 /// InstCombineStoreToCast - Fold store V, (cast P) -> store (cast V), P
443 /// when possible. This makes it generally easy to do alias analysis and/or
444 /// SROA/mem2reg of the memory object.
445 static Instruction *InstCombineStoreToCast(InstCombiner &IC, StoreInst &SI) {
446 User *CI = cast<User>(SI.getOperand(1));
447 Value *CastOp = CI->getOperand(0);
449 Type *DestPTy = CI->getType()->getPointerElementType();
450 PointerType *SrcTy = dyn_cast<PointerType>(CastOp->getType());
451 if (!SrcTy) return nullptr;
453 Type *SrcPTy = SrcTy->getElementType();
455 if (!DestPTy->isIntegerTy() && !DestPTy->isPointerTy())
458 /// NewGEPIndices - If SrcPTy is an aggregate type, we can emit a "noop gep"
459 /// to its first element. This allows us to handle things like:
460 /// store i32 xxx, (bitcast {foo*, float}* %P to i32*)
462 SmallVector<Value*, 4> NewGEPIndices;
464 // If the source is an array, the code below will not succeed. Check to
465 // see if a trivial 'gep P, 0, 0' will help matters. Only do this for
467 if (SrcPTy->isArrayTy() || SrcPTy->isStructTy()) {
468 // Index through pointer.
469 Constant *Zero = Constant::getNullValue(Type::getInt32Ty(SI.getContext()));
470 NewGEPIndices.push_back(Zero);
473 if (StructType *STy = dyn_cast<StructType>(SrcPTy)) {
474 if (!STy->getNumElements()) /* Struct can be empty {} */
476 NewGEPIndices.push_back(Zero);
477 SrcPTy = STy->getElementType(0);
478 } else if (ArrayType *ATy = dyn_cast<ArrayType>(SrcPTy)) {
479 NewGEPIndices.push_back(Zero);
480 SrcPTy = ATy->getElementType();
486 SrcTy = PointerType::get(SrcPTy, SrcTy->getAddressSpace());
489 if (!SrcPTy->isIntegerTy() && !SrcPTy->isPointerTy())
492 // If the pointers point into different address spaces don't do the
494 if (SrcTy->getAddressSpace() != CI->getType()->getPointerAddressSpace())
497 // If the pointers point to values of different sizes don't do the
499 if (!IC.getDataLayout() ||
500 IC.getDataLayout()->getTypeSizeInBits(SrcPTy) !=
501 IC.getDataLayout()->getTypeSizeInBits(DestPTy))
504 // If the pointers point to pointers to different address spaces don't do the
505 // transformation. It is not safe to introduce an addrspacecast instruction in
506 // this case since, depending on the target, addrspacecast may not be a no-op
508 if (SrcPTy->isPointerTy() && DestPTy->isPointerTy() &&
509 SrcPTy->getPointerAddressSpace() != DestPTy->getPointerAddressSpace())
512 // Okay, we are casting from one integer or pointer type to another of
513 // the same size. Instead of casting the pointer before
514 // the store, cast the value to be stored.
516 Instruction::CastOps opcode = Instruction::BitCast;
517 Type* CastSrcTy = DestPTy;
518 Type* CastDstTy = SrcPTy;
519 if (CastDstTy->isPointerTy()) {
520 if (CastSrcTy->isIntegerTy())
521 opcode = Instruction::IntToPtr;
522 } else if (CastDstTy->isIntegerTy()) {
523 if (CastSrcTy->isPointerTy())
524 opcode = Instruction::PtrToInt;
527 // SIOp0 is a pointer to aggregate and this is a store to the first field,
528 // emit a GEP to index into its first field.
529 if (!NewGEPIndices.empty())
530 CastOp = IC.Builder->CreateInBoundsGEP(CastOp, NewGEPIndices);
532 Value *SIOp0 = SI.getOperand(0);
533 NewCast = IC.Builder->CreateCast(opcode, SIOp0, CastDstTy,
534 SIOp0->getName()+".c");
535 SI.setOperand(0, NewCast);
536 SI.setOperand(1, CastOp);
540 /// equivalentAddressValues - Test if A and B will obviously have the same
541 /// value. This includes recognizing that %t0 and %t1 will have the same
542 /// value in code like this:
543 /// %t0 = getelementptr \@a, 0, 3
544 /// store i32 0, i32* %t0
545 /// %t1 = getelementptr \@a, 0, 3
546 /// %t2 = load i32* %t1
548 static bool equivalentAddressValues(Value *A, Value *B) {
549 // Test if the values are trivially equivalent.
550 if (A == B) return true;
552 // Test if the values come form identical arithmetic instructions.
553 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
554 // its only used to compare two uses within the same basic block, which
555 // means that they'll always either have the same value or one of them
556 // will have an undefined value.
557 if (isa<BinaryOperator>(A) ||
560 isa<GetElementPtrInst>(A))
561 if (Instruction *BI = dyn_cast<Instruction>(B))
562 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
565 // Otherwise they may not be equivalent.
569 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
570 Value *Val = SI.getOperand(0);
571 Value *Ptr = SI.getOperand(1);
573 // Attempt to improve the alignment.
575 unsigned KnownAlign =
576 getOrEnforceKnownAlignment(Ptr, DL->getPrefTypeAlignment(Val->getType()),
578 unsigned StoreAlign = SI.getAlignment();
579 unsigned EffectiveStoreAlign = StoreAlign != 0 ? StoreAlign :
580 DL->getABITypeAlignment(Val->getType());
582 if (KnownAlign > EffectiveStoreAlign)
583 SI.setAlignment(KnownAlign);
584 else if (StoreAlign == 0)
585 SI.setAlignment(EffectiveStoreAlign);
588 // Don't hack volatile/atomic stores.
589 // FIXME: Some bits are legal for atomic stores; needs refactoring.
590 if (!SI.isSimple()) return nullptr;
592 // If the RHS is an alloca with a single use, zapify the store, making the
594 if (Ptr->hasOneUse()) {
595 if (isa<AllocaInst>(Ptr))
596 return EraseInstFromFunction(SI);
597 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
598 if (isa<AllocaInst>(GEP->getOperand(0))) {
599 if (GEP->getOperand(0)->hasOneUse())
600 return EraseInstFromFunction(SI);
605 // Do really simple DSE, to catch cases where there are several consecutive
606 // stores to the same location, separated by a few arithmetic operations. This
607 // situation often occurs with bitfield accesses.
608 BasicBlock::iterator BBI = &SI;
609 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
612 // Don't count debug info directives, lest they affect codegen,
613 // and we skip pointer-to-pointer bitcasts, which are NOPs.
614 if (isa<DbgInfoIntrinsic>(BBI) ||
615 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
620 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
621 // Prev store isn't volatile, and stores to the same location?
622 if (PrevSI->isSimple() && equivalentAddressValues(PrevSI->getOperand(1),
626 EraseInstFromFunction(*PrevSI);
632 // If this is a load, we have to stop. However, if the loaded value is from
633 // the pointer we're loading and is producing the pointer we're storing,
634 // then *this* store is dead (X = load P; store X -> P).
635 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
636 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
638 return EraseInstFromFunction(SI);
640 // Otherwise, this is a load from some other location. Stores before it
645 // Don't skip over loads or things that can modify memory.
646 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
650 // store X, null -> turns into 'unreachable' in SimplifyCFG
651 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
652 if (!isa<UndefValue>(Val)) {
653 SI.setOperand(0, UndefValue::get(Val->getType()));
654 if (Instruction *U = dyn_cast<Instruction>(Val))
655 Worklist.Add(U); // Dropped a use.
657 return nullptr; // Do not modify these!
660 // store undef, Ptr -> noop
661 if (isa<UndefValue>(Val))
662 return EraseInstFromFunction(SI);
664 // If the pointer destination is a cast, see if we can fold the cast into the
666 if (isa<CastInst>(Ptr))
667 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
669 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
671 if (Instruction *Res = InstCombineStoreToCast(*this, SI))
675 // If this store is the last instruction in the basic block (possibly
676 // excepting debug info instructions), and if the block ends with an
677 // unconditional branch, try to move it to the successor block.
681 } while (isa<DbgInfoIntrinsic>(BBI) ||
682 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()));
683 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
684 if (BI->isUnconditional())
685 if (SimplifyStoreAtEndOfBlock(SI))
686 return nullptr; // xform done!
691 /// SimplifyStoreAtEndOfBlock - Turn things like:
692 /// if () { *P = v1; } else { *P = v2 }
693 /// into a phi node with a store in the successor.
695 /// Simplify things like:
696 /// *P = v1; if () { *P = v2; }
697 /// into a phi node with a store in the successor.
699 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
700 BasicBlock *StoreBB = SI.getParent();
702 // Check to see if the successor block has exactly two incoming edges. If
703 // so, see if the other predecessor contains a store to the same location.
704 // if so, insert a PHI node (if needed) and move the stores down.
705 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
707 // Determine whether Dest has exactly two predecessors and, if so, compute
708 // the other predecessor.
709 pred_iterator PI = pred_begin(DestBB);
711 BasicBlock *OtherBB = nullptr;
716 if (++PI == pred_end(DestBB))
725 if (++PI != pred_end(DestBB))
728 // Bail out if all the relevant blocks aren't distinct (this can happen,
729 // for example, if SI is in an infinite loop)
730 if (StoreBB == DestBB || OtherBB == DestBB)
733 // Verify that the other block ends in a branch and is not otherwise empty.
734 BasicBlock::iterator BBI = OtherBB->getTerminator();
735 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
736 if (!OtherBr || BBI == OtherBB->begin())
739 // If the other block ends in an unconditional branch, check for the 'if then
740 // else' case. there is an instruction before the branch.
741 StoreInst *OtherStore = nullptr;
742 if (OtherBr->isUnconditional()) {
744 // Skip over debugging info.
745 while (isa<DbgInfoIntrinsic>(BBI) ||
746 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
747 if (BBI==OtherBB->begin())
751 // If this isn't a store, isn't a store to the same location, or is not the
752 // right kind of store, bail out.
753 OtherStore = dyn_cast<StoreInst>(BBI);
754 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
755 !SI.isSameOperationAs(OtherStore))
758 // Otherwise, the other block ended with a conditional branch. If one of the
759 // destinations is StoreBB, then we have the if/then case.
760 if (OtherBr->getSuccessor(0) != StoreBB &&
761 OtherBr->getSuccessor(1) != StoreBB)
764 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
765 // if/then triangle. See if there is a store to the same ptr as SI that
768 // Check to see if we find the matching store.
769 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
770 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
771 !SI.isSameOperationAs(OtherStore))
775 // If we find something that may be using or overwriting the stored
776 // value, or if we run out of instructions, we can't do the xform.
777 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
778 BBI == OtherBB->begin())
782 // In order to eliminate the store in OtherBr, we have to
783 // make sure nothing reads or overwrites the stored value in
785 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
786 // FIXME: This should really be AA driven.
787 if (I->mayReadFromMemory() || I->mayWriteToMemory())
792 // Insert a PHI node now if we need it.
793 Value *MergedVal = OtherStore->getOperand(0);
794 if (MergedVal != SI.getOperand(0)) {
795 PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge");
796 PN->addIncoming(SI.getOperand(0), SI.getParent());
797 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
798 MergedVal = InsertNewInstBefore(PN, DestBB->front());
801 // Advance to a place where it is safe to insert the new store and
803 BBI = DestBB->getFirstInsertionPt();
804 StoreInst *NewSI = new StoreInst(MergedVal, SI.getOperand(1),
809 InsertNewInstBefore(NewSI, *BBI);
810 NewSI->setDebugLoc(OtherStore->getDebugLoc());
812 // If the two stores had AA tags, merge them.
814 SI.getAAMetadata(AATags);
816 OtherStore->getAAMetadata(AATags, /* Merge = */ true);
817 NewSI->setAAMetadata(AATags);
820 // Nuke the old stores.
821 EraseInstFromFunction(SI);
822 EraseInstFromFunction(*OtherStore);