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 "InstCombineInternal.h"
15 #include "llvm/ADT/Statistic.h"
16 #include "llvm/Analysis/Loads.h"
17 #include "llvm/IR/DataLayout.h"
18 #include "llvm/IR/LLVMContext.h"
19 #include "llvm/IR/IntrinsicInst.h"
20 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
21 #include "llvm/Transforms/Utils/Local.h"
24 #define DEBUG_TYPE "instcombine"
26 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
27 STATISTIC(NumGlobalCopies, "Number of allocas copied from constant global");
29 /// pointsToConstantGlobal - Return true if V (possibly indirectly) points to
30 /// some part of a constant global variable. This intentionally only accepts
31 /// constant expressions because we can't rewrite arbitrary instructions.
32 static bool pointsToConstantGlobal(Value *V) {
33 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
34 return GV->isConstant();
36 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
37 if (CE->getOpcode() == Instruction::BitCast ||
38 CE->getOpcode() == Instruction::AddrSpaceCast ||
39 CE->getOpcode() == Instruction::GetElementPtr)
40 return pointsToConstantGlobal(CE->getOperand(0));
45 /// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
46 /// pointer to an alloca. Ignore any reads of the pointer, return false if we
47 /// see any stores or other unknown uses. If we see pointer arithmetic, keep
48 /// track of whether it moves the pointer (with IsOffset) but otherwise traverse
49 /// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to
50 /// the alloca, and if the source pointer is a pointer to a constant global, we
51 /// can optimize this.
53 isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
54 SmallVectorImpl<Instruction *> &ToDelete) {
55 // We track lifetime intrinsics as we encounter them. If we decide to go
56 // ahead and replace the value with the global, this lets the caller quickly
57 // eliminate the markers.
59 SmallVector<std::pair<Value *, bool>, 35> ValuesToInspect;
60 ValuesToInspect.push_back(std::make_pair(V, false));
61 while (!ValuesToInspect.empty()) {
62 auto ValuePair = ValuesToInspect.pop_back_val();
63 const bool IsOffset = ValuePair.second;
64 for (auto &U : ValuePair.first->uses()) {
65 Instruction *I = cast<Instruction>(U.getUser());
67 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
68 // Ignore non-volatile loads, they are always ok.
69 if (!LI->isSimple()) return false;
73 if (isa<BitCastInst>(I) || isa<AddrSpaceCastInst>(I)) {
74 // If uses of the bitcast are ok, we are ok.
75 ValuesToInspect.push_back(std::make_pair(I, IsOffset));
78 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
79 // If the GEP has all zero indices, it doesn't offset the pointer. If it
81 ValuesToInspect.push_back(
82 std::make_pair(I, IsOffset || !GEP->hasAllZeroIndices()));
86 if (CallSite CS = I) {
87 // If this is the function being called then we treat it like a load and
92 // Inalloca arguments are clobbered by the call.
93 unsigned ArgNo = CS.getArgumentNo(&U);
94 if (CS.isInAllocaArgument(ArgNo))
97 // If this is a readonly/readnone call site, then we know it is just a
98 // load (but one that potentially returns the value itself), so we can
99 // ignore it if we know that the value isn't captured.
100 if (CS.onlyReadsMemory() &&
101 (CS.getInstruction()->use_empty() || CS.doesNotCapture(ArgNo)))
104 // If this is being passed as a byval argument, the caller is making a
105 // copy, so it is only a read of the alloca.
106 if (CS.isByValArgument(ArgNo))
110 // Lifetime intrinsics can be handled by the caller.
111 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
112 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
113 II->getIntrinsicID() == Intrinsic::lifetime_end) {
114 assert(II->use_empty() && "Lifetime markers have no result to use!");
115 ToDelete.push_back(II);
120 // If this is isn't our memcpy/memmove, reject it as something we can't
122 MemTransferInst *MI = dyn_cast<MemTransferInst>(I);
126 // If the transfer is using the alloca as a source of the transfer, then
127 // ignore it since it is a load (unless the transfer is volatile).
128 if (U.getOperandNo() == 1) {
129 if (MI->isVolatile()) return false;
133 // If we already have seen a copy, reject the second one.
134 if (TheCopy) return false;
136 // If the pointer has been offset from the start of the alloca, we can't
137 // safely handle this.
138 if (IsOffset) return false;
140 // If the memintrinsic isn't using the alloca as the dest, reject it.
141 if (U.getOperandNo() != 0) return false;
143 // If the source of the memcpy/move is not a constant global, reject it.
144 if (!pointsToConstantGlobal(MI->getSource()))
147 // Otherwise, the transform is safe. Remember the copy instruction.
154 /// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
155 /// modified by a copy from a constant global. If we can prove this, we can
156 /// replace any uses of the alloca with uses of the global directly.
157 static MemTransferInst *
158 isOnlyCopiedFromConstantGlobal(AllocaInst *AI,
159 SmallVectorImpl<Instruction *> &ToDelete) {
160 MemTransferInst *TheCopy = nullptr;
161 if (isOnlyCopiedFromConstantGlobal(AI, TheCopy, ToDelete))
166 Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
167 // Ensure that the alloca array size argument has type intptr_t, so that
168 // any casting is exposed early.
170 Type *IntPtrTy = DL->getIntPtrType(AI.getType());
171 if (AI.getArraySize()->getType() != IntPtrTy) {
172 Value *V = Builder->CreateIntCast(AI.getArraySize(),
179 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
180 if (AI.isArrayAllocation()) { // Check C != 1
181 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
183 ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
184 AllocaInst *New = Builder->CreateAlloca(NewTy, nullptr, AI.getName());
185 New->setAlignment(AI.getAlignment());
187 // Scan to the end of the allocation instructions, to skip over a block of
188 // allocas if possible...also skip interleaved debug info
190 BasicBlock::iterator It = New;
191 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
193 // Now that I is pointing to the first non-allocation-inst in the block,
194 // insert our getelementptr instruction...
197 ? DL->getIntPtrType(AI.getType())
198 : Type::getInt64Ty(AI.getContext());
199 Value *NullIdx = Constant::getNullValue(IdxTy);
200 Value *Idx[2] = { NullIdx, NullIdx };
202 GetElementPtrInst::CreateInBounds(New, Idx, New->getName() + ".sub");
203 InsertNewInstBefore(GEP, *It);
205 // Now make everything use the getelementptr instead of the original
207 return ReplaceInstUsesWith(AI, GEP);
208 } else if (isa<UndefValue>(AI.getArraySize())) {
209 return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
213 if (DL && AI.getAllocatedType()->isSized()) {
214 // If the alignment is 0 (unspecified), assign it the preferred alignment.
215 if (AI.getAlignment() == 0)
216 AI.setAlignment(DL->getPrefTypeAlignment(AI.getAllocatedType()));
218 // Move all alloca's of zero byte objects to the entry block and merge them
219 // together. Note that we only do this for alloca's, because malloc should
220 // allocate and return a unique pointer, even for a zero byte allocation.
221 if (DL->getTypeAllocSize(AI.getAllocatedType()) == 0) {
222 // For a zero sized alloca there is no point in doing an array allocation.
223 // This is helpful if the array size is a complicated expression not used
225 if (AI.isArrayAllocation()) {
226 AI.setOperand(0, ConstantInt::get(AI.getArraySize()->getType(), 1));
230 // Get the first instruction in the entry block.
231 BasicBlock &EntryBlock = AI.getParent()->getParent()->getEntryBlock();
232 Instruction *FirstInst = EntryBlock.getFirstNonPHIOrDbg();
233 if (FirstInst != &AI) {
234 // If the entry block doesn't start with a zero-size alloca then move
235 // this one to the start of the entry block. There is no problem with
236 // dominance as the array size was forced to a constant earlier already.
237 AllocaInst *EntryAI = dyn_cast<AllocaInst>(FirstInst);
238 if (!EntryAI || !EntryAI->getAllocatedType()->isSized() ||
239 DL->getTypeAllocSize(EntryAI->getAllocatedType()) != 0) {
240 AI.moveBefore(FirstInst);
244 // If the alignment of the entry block alloca is 0 (unspecified),
245 // assign it the preferred alignment.
246 if (EntryAI->getAlignment() == 0)
247 EntryAI->setAlignment(
248 DL->getPrefTypeAlignment(EntryAI->getAllocatedType()));
249 // Replace this zero-sized alloca with the one at the start of the entry
250 // block after ensuring that the address will be aligned enough for both
252 unsigned MaxAlign = std::max(EntryAI->getAlignment(),
254 EntryAI->setAlignment(MaxAlign);
255 if (AI.getType() != EntryAI->getType())
256 return new BitCastInst(EntryAI, AI.getType());
257 return ReplaceInstUsesWith(AI, EntryAI);
262 if (AI.getAlignment()) {
263 // Check to see if this allocation is only modified by a memcpy/memmove from
264 // a constant global whose alignment is equal to or exceeds that of the
265 // allocation. If this is the case, we can change all users to use
266 // the constant global instead. This is commonly produced by the CFE by
267 // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
268 // is only subsequently read.
269 SmallVector<Instruction *, 4> ToDelete;
270 if (MemTransferInst *Copy = isOnlyCopiedFromConstantGlobal(&AI, ToDelete)) {
271 unsigned SourceAlign = getOrEnforceKnownAlignment(
272 Copy->getSource(), AI.getAlignment(), DL, AC, &AI, DT);
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 Helper to combine a load to a new type.
296 /// This just does the work of combining a load to a new type. It handles
297 /// metadata, etc., and returns the new instruction. The \c NewTy should be the
298 /// loaded *value* type. This will convert it to a pointer, cast the operand to
299 /// that pointer type, load it, etc.
301 /// Note that this will create all of the instructions with whatever insert
302 /// point the \c InstCombiner currently is using.
303 static LoadInst *combineLoadToNewType(InstCombiner &IC, LoadInst &LI, Type *NewTy) {
304 Value *Ptr = LI.getPointerOperand();
305 unsigned AS = LI.getPointerAddressSpace();
306 SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
307 LI.getAllMetadata(MD);
309 LoadInst *NewLoad = IC.Builder->CreateAlignedLoad(
310 IC.Builder->CreateBitCast(Ptr, NewTy->getPointerTo(AS)),
311 LI.getAlignment(), LI.getName());
312 for (const auto &MDPair : MD) {
313 unsigned ID = MDPair.first;
314 MDNode *N = MDPair.second;
315 // Note, essentially every kind of metadata should be preserved here! This
316 // routine is supposed to clone a load instruction changing *only its type*.
317 // The only metadata it makes sense to drop is metadata which is invalidated
318 // when the pointer type changes. This should essentially never be the case
319 // in LLVM, but we explicitly switch over only known metadata to be
320 // conservatively correct. If you are adding metadata to LLVM which pertains
321 // to loads, you almost certainly want to add it here.
323 case LLVMContext::MD_dbg:
324 case LLVMContext::MD_tbaa:
325 case LLVMContext::MD_prof:
326 case LLVMContext::MD_fpmath:
327 case LLVMContext::MD_tbaa_struct:
328 case LLVMContext::MD_invariant_load:
329 case LLVMContext::MD_alias_scope:
330 case LLVMContext::MD_noalias:
331 case LLVMContext::MD_nontemporal:
332 case LLVMContext::MD_mem_parallel_loop_access:
333 case LLVMContext::MD_nonnull:
334 // All of these directly apply.
335 NewLoad->setMetadata(ID, N);
338 case LLVMContext::MD_range:
339 // FIXME: It would be nice to propagate this in some way, but the type
340 // conversions make it hard.
347 /// \brief Combine a store to a new type.
349 /// Returns the newly created store instruction.
350 static StoreInst *combineStoreToNewValue(InstCombiner &IC, StoreInst &SI, Value *V) {
351 Value *Ptr = SI.getPointerOperand();
352 unsigned AS = SI.getPointerAddressSpace();
353 SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
354 SI.getAllMetadata(MD);
356 StoreInst *NewStore = IC.Builder->CreateAlignedStore(
357 V, IC.Builder->CreateBitCast(Ptr, V->getType()->getPointerTo(AS)),
359 for (const auto &MDPair : MD) {
360 unsigned ID = MDPair.first;
361 MDNode *N = MDPair.second;
362 // Note, essentially every kind of metadata should be preserved here! This
363 // routine is supposed to clone a store instruction changing *only its
364 // type*. The only metadata it makes sense to drop is metadata which is
365 // invalidated when the pointer type changes. This should essentially
366 // never be the case in LLVM, but we explicitly switch over only known
367 // metadata to be conservatively correct. If you are adding metadata to
368 // LLVM which pertains to stores, you almost certainly want to add it
371 case LLVMContext::MD_dbg:
372 case LLVMContext::MD_tbaa:
373 case LLVMContext::MD_prof:
374 case LLVMContext::MD_fpmath:
375 case LLVMContext::MD_tbaa_struct:
376 case LLVMContext::MD_alias_scope:
377 case LLVMContext::MD_noalias:
378 case LLVMContext::MD_nontemporal:
379 case LLVMContext::MD_mem_parallel_loop_access:
380 case LLVMContext::MD_nonnull:
381 // All of these directly apply.
382 NewStore->setMetadata(ID, N);
385 case LLVMContext::MD_invariant_load:
386 case LLVMContext::MD_range:
394 /// \brief Combine loads to match the type of value their uses after looking
395 /// through intervening bitcasts.
397 /// The core idea here is that if the result of a load is used in an operation,
398 /// we should load the type most conducive to that operation. For example, when
399 /// loading an integer and converting that immediately to a pointer, we should
400 /// instead directly load a pointer.
402 /// However, this routine must never change the width of a load or the number of
403 /// loads as that would introduce a semantic change. This combine is expected to
404 /// be a semantic no-op which just allows loads to more closely model the types
405 /// of their consuming operations.
407 /// Currently, we also refuse to change the precise type used for an atomic load
408 /// or a volatile load. This is debatable, and might be reasonable to change
409 /// later. However, it is risky in case some backend or other part of LLVM is
410 /// relying on the exact type loaded to select appropriate atomic operations.
411 static Instruction *combineLoadToOperationType(InstCombiner &IC, LoadInst &LI) {
412 // FIXME: We could probably with some care handle both volatile and atomic
413 // loads here but it isn't clear that this is important.
420 Type *Ty = LI.getType();
422 // Try to canonicalize loads which are only ever stored to operate over
423 // integers instead of any other type. We only do this when the loaded type
424 // is sized and has a size exactly the same as its store size and the store
425 // size is a legal integer type.
426 const DataLayout *DL = IC.getDataLayout();
427 if (!Ty->isIntegerTy() && Ty->isSized() && DL &&
428 DL->isLegalInteger(DL->getTypeStoreSizeInBits(Ty)) &&
429 DL->getTypeStoreSizeInBits(Ty) == DL->getTypeSizeInBits(Ty)) {
430 if (std::all_of(LI.user_begin(), LI.user_end(), [&LI](User *U) {
431 auto *SI = dyn_cast<StoreInst>(U);
432 return SI && SI->getPointerOperand() != &LI;
434 LoadInst *NewLoad = combineLoadToNewType(
436 Type::getIntNTy(LI.getContext(), DL->getTypeStoreSizeInBits(Ty)));
437 // Replace all the stores with stores of the newly loaded value.
438 for (auto UI = LI.user_begin(), UE = LI.user_end(); UI != UE;) {
439 auto *SI = cast<StoreInst>(*UI++);
440 IC.Builder->SetInsertPoint(SI);
441 combineStoreToNewValue(IC, *SI, NewLoad);
442 IC.EraseInstFromFunction(*SI);
444 assert(LI.use_empty() && "Failed to remove all users of the load!");
445 // Return the old load so the combiner can delete it safely.
450 // Fold away bit casts of the loaded value by loading the desired type.
452 if (auto *BC = dyn_cast<BitCastInst>(LI.user_back())) {
453 LoadInst *NewLoad = combineLoadToNewType(IC, LI, BC->getDestTy());
454 BC->replaceAllUsesWith(NewLoad);
455 IC.EraseInstFromFunction(*BC);
459 // FIXME: We should also canonicalize loads of vectors when their elements are
460 // cast to other types.
464 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
465 Value *Op = LI.getOperand(0);
467 // Try to canonicalize the loaded type.
468 if (Instruction *Res = combineLoadToOperationType(*this, LI))
471 // Attempt to improve the alignment.
473 unsigned KnownAlign = getOrEnforceKnownAlignment(
474 Op, DL->getPrefTypeAlignment(LI.getType()), DL, AC, &LI, DT);
475 unsigned LoadAlign = LI.getAlignment();
476 unsigned EffectiveLoadAlign = LoadAlign != 0 ? LoadAlign :
477 DL->getABITypeAlignment(LI.getType());
479 if (KnownAlign > EffectiveLoadAlign)
480 LI.setAlignment(KnownAlign);
481 else if (LoadAlign == 0)
482 LI.setAlignment(EffectiveLoadAlign);
485 // None of the following transforms are legal for volatile/atomic loads.
486 // FIXME: Some of it is okay for atomic loads; needs refactoring.
487 if (!LI.isSimple()) return nullptr;
489 // Do really simple store-to-load forwarding and load CSE, to catch cases
490 // where there are several consecutive memory accesses to the same location,
491 // separated by a few arithmetic operations.
492 BasicBlock::iterator BBI = &LI;
493 if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
494 return ReplaceInstUsesWith(
495 LI, Builder->CreateBitOrPointerCast(AvailableVal, LI.getType(),
496 LI.getName() + ".cast"));
498 // load(gep null, ...) -> unreachable
499 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
500 const Value *GEPI0 = GEPI->getOperand(0);
501 // TODO: Consider a target hook for valid address spaces for this xform.
502 if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
503 // Insert a new store to null instruction before the load to indicate
504 // that this code is not reachable. We do this instead of inserting
505 // an unreachable instruction directly because we cannot modify the
507 new StoreInst(UndefValue::get(LI.getType()),
508 Constant::getNullValue(Op->getType()), &LI);
509 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
513 // load null/undef -> unreachable
514 // TODO: Consider a target hook for valid address spaces for this xform.
515 if (isa<UndefValue>(Op) ||
516 (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
517 // Insert a new store to null instruction before the load to indicate that
518 // this code is not reachable. We do this instead of inserting an
519 // unreachable instruction directly because we cannot modify the CFG.
520 new StoreInst(UndefValue::get(LI.getType()),
521 Constant::getNullValue(Op->getType()), &LI);
522 return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
525 if (Op->hasOneUse()) {
526 // Change select and PHI nodes to select values instead of addresses: this
527 // helps alias analysis out a lot, allows many others simplifications, and
528 // exposes redundancy in the code.
530 // Note that we cannot do the transformation unless we know that the
531 // introduced loads cannot trap! Something like this is valid as long as
532 // the condition is always false: load (select bool %C, int* null, int* %G),
533 // but it would not be valid if we transformed it to load from null
536 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
537 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
538 unsigned Align = LI.getAlignment();
539 if (isSafeToLoadUnconditionally(SI->getOperand(1), SI, Align, DL) &&
540 isSafeToLoadUnconditionally(SI->getOperand(2), SI, Align, DL)) {
541 LoadInst *V1 = Builder->CreateLoad(SI->getOperand(1),
542 SI->getOperand(1)->getName()+".val");
543 LoadInst *V2 = Builder->CreateLoad(SI->getOperand(2),
544 SI->getOperand(2)->getName()+".val");
545 V1->setAlignment(Align);
546 V2->setAlignment(Align);
547 return SelectInst::Create(SI->getCondition(), V1, V2);
550 // load (select (cond, null, P)) -> load P
551 if (isa<ConstantPointerNull>(SI->getOperand(1)) &&
552 LI.getPointerAddressSpace() == 0) {
553 LI.setOperand(0, SI->getOperand(2));
557 // load (select (cond, P, null)) -> load P
558 if (isa<ConstantPointerNull>(SI->getOperand(2)) &&
559 LI.getPointerAddressSpace() == 0) {
560 LI.setOperand(0, SI->getOperand(1));
568 /// \brief Combine stores to match the type of value being stored.
570 /// The core idea here is that the memory does not have any intrinsic type and
571 /// where we can we should match the type of a store to the type of value being
574 /// However, this routine must never change the width of a store or the number of
575 /// stores as that would introduce a semantic change. This combine is expected to
576 /// be a semantic no-op which just allows stores to more closely model the types
577 /// of their incoming values.
579 /// Currently, we also refuse to change the precise type used for an atomic or
580 /// volatile store. This is debatable, and might be reasonable to change later.
581 /// However, it is risky in case some backend or other part of LLVM is relying
582 /// on the exact type stored to select appropriate atomic operations.
584 /// \returns true if the store was successfully combined away. This indicates
585 /// the caller must erase the store instruction. We have to let the caller erase
586 /// the store instruction sas otherwise there is no way to signal whether it was
587 /// combined or not: IC.EraseInstFromFunction returns a null pointer.
588 static bool combineStoreToValueType(InstCombiner &IC, StoreInst &SI) {
589 // FIXME: We could probably with some care handle both volatile and atomic
590 // stores here but it isn't clear that this is important.
594 Value *V = SI.getValueOperand();
596 // Fold away bit casts of the stored value by storing the original type.
597 if (auto *BC = dyn_cast<BitCastInst>(V)) {
598 V = BC->getOperand(0);
599 combineStoreToNewValue(IC, SI, V);
603 // FIXME: We should also canonicalize loads of vectors when their elements are
604 // cast to other types.
608 /// equivalentAddressValues - Test if A and B will obviously have the same
609 /// value. This includes recognizing that %t0 and %t1 will have the same
610 /// value in code like this:
611 /// %t0 = getelementptr \@a, 0, 3
612 /// store i32 0, i32* %t0
613 /// %t1 = getelementptr \@a, 0, 3
614 /// %t2 = load i32* %t1
616 static bool equivalentAddressValues(Value *A, Value *B) {
617 // Test if the values are trivially equivalent.
618 if (A == B) return true;
620 // Test if the values come form identical arithmetic instructions.
621 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
622 // its only used to compare two uses within the same basic block, which
623 // means that they'll always either have the same value or one of them
624 // will have an undefined value.
625 if (isa<BinaryOperator>(A) ||
628 isa<GetElementPtrInst>(A))
629 if (Instruction *BI = dyn_cast<Instruction>(B))
630 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
633 // Otherwise they may not be equivalent.
637 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
638 Value *Val = SI.getOperand(0);
639 Value *Ptr = SI.getOperand(1);
641 // Try to canonicalize the stored type.
642 if (combineStoreToValueType(*this, SI))
643 return EraseInstFromFunction(SI);
645 // Attempt to improve the alignment.
647 unsigned KnownAlign = getOrEnforceKnownAlignment(
648 Ptr, DL->getPrefTypeAlignment(Val->getType()), DL, AC, &SI, DT);
649 unsigned StoreAlign = SI.getAlignment();
650 unsigned EffectiveStoreAlign = StoreAlign != 0 ? StoreAlign :
651 DL->getABITypeAlignment(Val->getType());
653 if (KnownAlign > EffectiveStoreAlign)
654 SI.setAlignment(KnownAlign);
655 else if (StoreAlign == 0)
656 SI.setAlignment(EffectiveStoreAlign);
659 // Don't hack volatile/atomic stores.
660 // FIXME: Some bits are legal for atomic stores; needs refactoring.
661 if (!SI.isSimple()) return nullptr;
663 // If the RHS is an alloca with a single use, zapify the store, making the
665 if (Ptr->hasOneUse()) {
666 if (isa<AllocaInst>(Ptr))
667 return EraseInstFromFunction(SI);
668 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
669 if (isa<AllocaInst>(GEP->getOperand(0))) {
670 if (GEP->getOperand(0)->hasOneUse())
671 return EraseInstFromFunction(SI);
676 // Do really simple DSE, to catch cases where there are several consecutive
677 // stores to the same location, separated by a few arithmetic operations. This
678 // situation often occurs with bitfield accesses.
679 BasicBlock::iterator BBI = &SI;
680 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
683 // Don't count debug info directives, lest they affect codegen,
684 // and we skip pointer-to-pointer bitcasts, which are NOPs.
685 if (isa<DbgInfoIntrinsic>(BBI) ||
686 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
691 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
692 // Prev store isn't volatile, and stores to the same location?
693 if (PrevSI->isSimple() && equivalentAddressValues(PrevSI->getOperand(1),
697 EraseInstFromFunction(*PrevSI);
703 // If this is a load, we have to stop. However, if the loaded value is from
704 // the pointer we're loading and is producing the pointer we're storing,
705 // then *this* store is dead (X = load P; store X -> P).
706 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
707 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
709 return EraseInstFromFunction(SI);
711 // Otherwise, this is a load from some other location. Stores before it
716 // Don't skip over loads or things that can modify memory.
717 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
721 // store X, null -> turns into 'unreachable' in SimplifyCFG
722 if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
723 if (!isa<UndefValue>(Val)) {
724 SI.setOperand(0, UndefValue::get(Val->getType()));
725 if (Instruction *U = dyn_cast<Instruction>(Val))
726 Worklist.Add(U); // Dropped a use.
728 return nullptr; // Do not modify these!
731 // store undef, Ptr -> noop
732 if (isa<UndefValue>(Val))
733 return EraseInstFromFunction(SI);
735 // If this store is the last instruction in the basic block (possibly
736 // excepting debug info instructions), and if the block ends with an
737 // unconditional branch, try to move it to the successor block.
741 } while (isa<DbgInfoIntrinsic>(BBI) ||
742 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()));
743 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
744 if (BI->isUnconditional())
745 if (SimplifyStoreAtEndOfBlock(SI))
746 return nullptr; // xform done!
751 /// SimplifyStoreAtEndOfBlock - Turn things like:
752 /// if () { *P = v1; } else { *P = v2 }
753 /// into a phi node with a store in the successor.
755 /// Simplify things like:
756 /// *P = v1; if () { *P = v2; }
757 /// into a phi node with a store in the successor.
759 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
760 BasicBlock *StoreBB = SI.getParent();
762 // Check to see if the successor block has exactly two incoming edges. If
763 // so, see if the other predecessor contains a store to the same location.
764 // if so, insert a PHI node (if needed) and move the stores down.
765 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
767 // Determine whether Dest has exactly two predecessors and, if so, compute
768 // the other predecessor.
769 pred_iterator PI = pred_begin(DestBB);
771 BasicBlock *OtherBB = nullptr;
776 if (++PI == pred_end(DestBB))
785 if (++PI != pred_end(DestBB))
788 // Bail out if all the relevant blocks aren't distinct (this can happen,
789 // for example, if SI is in an infinite loop)
790 if (StoreBB == DestBB || OtherBB == DestBB)
793 // Verify that the other block ends in a branch and is not otherwise empty.
794 BasicBlock::iterator BBI = OtherBB->getTerminator();
795 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
796 if (!OtherBr || BBI == OtherBB->begin())
799 // If the other block ends in an unconditional branch, check for the 'if then
800 // else' case. there is an instruction before the branch.
801 StoreInst *OtherStore = nullptr;
802 if (OtherBr->isUnconditional()) {
804 // Skip over debugging info.
805 while (isa<DbgInfoIntrinsic>(BBI) ||
806 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
807 if (BBI==OtherBB->begin())
811 // If this isn't a store, isn't a store to the same location, or is not the
812 // right kind of store, bail out.
813 OtherStore = dyn_cast<StoreInst>(BBI);
814 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
815 !SI.isSameOperationAs(OtherStore))
818 // Otherwise, the other block ended with a conditional branch. If one of the
819 // destinations is StoreBB, then we have the if/then case.
820 if (OtherBr->getSuccessor(0) != StoreBB &&
821 OtherBr->getSuccessor(1) != StoreBB)
824 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
825 // if/then triangle. See if there is a store to the same ptr as SI that
828 // Check to see if we find the matching store.
829 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
830 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
831 !SI.isSameOperationAs(OtherStore))
835 // If we find something that may be using or overwriting the stored
836 // value, or if we run out of instructions, we can't do the xform.
837 if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
838 BBI == OtherBB->begin())
842 // In order to eliminate the store in OtherBr, we have to
843 // make sure nothing reads or overwrites the stored value in
845 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
846 // FIXME: This should really be AA driven.
847 if (I->mayReadFromMemory() || I->mayWriteToMemory())
852 // Insert a PHI node now if we need it.
853 Value *MergedVal = OtherStore->getOperand(0);
854 if (MergedVal != SI.getOperand(0)) {
855 PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge");
856 PN->addIncoming(SI.getOperand(0), SI.getParent());
857 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
858 MergedVal = InsertNewInstBefore(PN, DestBB->front());
861 // Advance to a place where it is safe to insert the new store and
863 BBI = DestBB->getFirstInsertionPt();
864 StoreInst *NewSI = new StoreInst(MergedVal, SI.getOperand(1),
869 InsertNewInstBefore(NewSI, *BBI);
870 NewSI->setDebugLoc(OtherStore->getDebugLoc());
872 // If the two stores had AA tags, merge them.
874 SI.getAAMetadata(AATags);
876 OtherStore->getAAMetadata(AATags, /* Merge = */ true);
877 NewSI->setAAMetadata(AATags);
880 // Nuke the old stores.
881 EraseInstFromFunction(SI);
882 EraseInstFromFunction(*OtherStore);