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/MapVector.h"
16 #include "llvm/ADT/SmallString.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/Analysis/Loads.h"
19 #include "llvm/Transforms/Utils/Local.h"
20 #include "llvm/IR/ConstantRange.h"
21 #include "llvm/IR/DataLayout.h"
22 #include "llvm/IR/IntrinsicInst.h"
23 #include "llvm/IR/LLVMContext.h"
24 #include "llvm/IR/MDBuilder.h"
25 #include "llvm/IR/PatternMatch.h"
26 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
28 using namespace PatternMatch;
30 #define DEBUG_TYPE "instcombine"
32 STATISTIC(NumDeadStore, "Number of dead stores eliminated");
33 STATISTIC(NumGlobalCopies, "Number of allocas copied from constant global");
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.
38 static bool pointsToConstantGlobal(Value *V) {
39 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
40 return GV->isConstant();
42 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
43 if (CE->getOpcode() == Instruction::BitCast ||
44 CE->getOpcode() == Instruction::AddrSpaceCast ||
45 CE->getOpcode() == Instruction::GetElementPtr)
46 return pointsToConstantGlobal(CE->getOperand(0));
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.
59 isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
60 SmallVectorImpl<Instruction *> &ToDelete) {
61 // 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.
65 SmallVector<std::pair<Value *, bool>, 35> ValuesToInspect;
66 ValuesToInspect.emplace_back(V, false);
67 while (!ValuesToInspect.empty()) {
68 auto ValuePair = ValuesToInspect.pop_back_val();
69 const bool IsOffset = ValuePair.second;
70 for (auto &U : ValuePair.first->uses()) {
71 auto *I = cast<Instruction>(U.getUser());
73 if (auto *LI = dyn_cast<LoadInst>(I)) {
74 // Ignore non-volatile loads, they are always ok.
75 if (!LI->isSimple()) return false;
79 if (isa<BitCastInst>(I) || isa<AddrSpaceCastInst>(I)) {
80 // If uses of the bitcast are ok, we are ok.
81 ValuesToInspect.emplace_back(I, IsOffset);
84 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
85 // If the GEP has all zero indices, it doesn't offset the pointer. If it
87 ValuesToInspect.emplace_back(I, IsOffset || !GEP->hasAllZeroIndices());
91 if (auto CS = CallSite(I)) {
92 // If this is the function being called then we treat it like a load and
97 unsigned DataOpNo = CS.getDataOperandNo(&U);
98 bool IsArgOperand = CS.isArgOperand(&U);
100 // Inalloca arguments are clobbered by the call.
101 if (IsArgOperand && CS.isInAllocaArgument(DataOpNo))
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() &&
108 (CS.getInstruction()->use_empty() || CS.doesNotCapture(DataOpNo)))
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.
113 if (IsArgOperand && CS.isByValArgument(DataOpNo))
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);
127 // If this is isn't our memcpy/memmove, reject it as something we can't
129 MemTransferInst *MI = dyn_cast<MemTransferInst>(I);
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;
140 // If we already have seen a copy, reject the second one.
141 if (TheCopy) return false;
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;
147 // If the memintrinsic isn't using the alloca as the dest, reject it.
148 if (U.getOperandNo() != 0) return false;
150 // If the source of the memcpy/move is not a constant global, reject it.
151 if (!pointsToConstantGlobal(MI->getSource()))
154 // Otherwise, the transform is safe. Remember the copy instruction.
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.
164 static MemTransferInst *
165 isOnlyCopiedFromConstantGlobal(AllocaInst *AI,
166 SmallVectorImpl<Instruction *> &ToDelete) {
167 MemTransferInst *TheCopy = nullptr;
168 if (isOnlyCopiedFromConstantGlobal(AI, TheCopy, ToDelete))
173 /// Returns true if V is dereferenceable for size of alloca.
174 static bool isDereferenceableForAllocaSize(const Value *V, const AllocaInst *AI,
175 const DataLayout &DL) {
176 if (AI->isArrayAllocation())
178 uint64_t AllocaSize = DL.getTypeStoreSize(AI->getAllocatedType());
181 return isDereferenceableAndAlignedPointer(V, AI->getAlignment(),
182 APInt(64, AllocaSize), DL);
185 static Instruction *simplifyAllocaArraySize(InstCombiner &IC, AllocaInst &AI) {
186 // Check for array size of 1 (scalar allocation).
187 if (!AI.isArrayAllocation()) {
188 // i32 1 is the canonical array size for scalar allocations.
189 if (AI.getArraySize()->getType()->isIntegerTy(32))
193 Value *V = IC.Builder.getInt32(1);
198 // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
199 if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
200 Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
201 AllocaInst *New = IC.Builder.CreateAlloca(NewTy, nullptr, AI.getName());
202 New->setAlignment(AI.getAlignment());
204 // Scan to the end of the allocation instructions, to skip over a block of
205 // allocas if possible...also skip interleaved debug info
207 BasicBlock::iterator It(New);
208 while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It))
211 // Now that I is pointing to the first non-allocation-inst in the block,
212 // insert our getelementptr instruction...
214 Type *IdxTy = IC.getDataLayout().getIntPtrType(AI.getType());
215 Value *NullIdx = Constant::getNullValue(IdxTy);
216 Value *Idx[2] = {NullIdx, NullIdx};
218 GetElementPtrInst::CreateInBounds(New, Idx, New->getName() + ".sub");
219 IC.InsertNewInstBefore(GEP, *It);
221 // Now make everything use the getelementptr instead of the original
223 return IC.replaceInstUsesWith(AI, GEP);
226 if (isa<UndefValue>(AI.getArraySize()))
227 return IC.replaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
229 // 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) {
233 Value *V = IC.Builder.CreateIntCast(AI.getArraySize(), IntPtrTy, false);
242 // 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.
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
252 class PointerReplacer {
254 PointerReplacer(InstCombiner &IC) : IC(IC) {}
255 void replacePointer(Instruction &I, Value *V);
258 void findLoadAndReplace(Instruction &I);
259 void replace(Instruction *I);
260 Value *getReplacement(Value *I);
262 SmallVector<Instruction *, 4> Path;
263 MapVector<Value *, Value *> WorkMap;
266 } // end anonymous namespace
268 void PointerReplacer::findLoadAndReplace(Instruction &I) {
269 for (auto U : I.users()) {
270 auto *Inst = dyn_cast<Instruction>(&*U);
273 LLVM_DEBUG(dbgs() << "Found pointer user: " << *U << '\n');
274 if (isa<LoadInst>(Inst)) {
278 } else if (isa<GetElementPtrInst>(Inst) || isa<BitCastInst>(Inst)) {
279 Path.push_back(Inst);
280 findLoadAndReplace(*Inst);
288 Value *PointerReplacer::getReplacement(Value *V) {
289 auto Loc = WorkMap.find(V);
290 if (Loc != WorkMap.end())
295 void PointerReplacer::replace(Instruction *I) {
296 if (getReplacement(I))
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);
304 IC.InsertNewInstWith(NewI, *LT);
305 IC.replaceInstUsesWith(*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);
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);
327 llvm_unreachable("should never reach here");
331 void PointerReplacer::replacePointer(Instruction &I, Value *V) {
333 auto *PT = cast<PointerType>(I.getType());
334 auto *NT = cast<PointerType>(V->getType());
335 assert(PT != NT && PT->getElementType() == NT->getElementType() &&
339 findLoadAndReplace(I);
342 Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
343 if (auto *I = simplifyAllocaArraySize(*this, AI))
346 if (AI.getAllocatedType()->isSized()) {
347 // If the alignment is 0 (unspecified), assign it the preferred alignment.
348 if (AI.getAlignment() == 0)
349 AI.setAlignment(DL.getPrefTypeAlignment(AI.getAllocatedType()));
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.
354 if (DL.getTypeAllocSize(AI.getAllocatedType()) == 0) {
355 // 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
358 if (AI.isArrayAllocation()) {
359 AI.setOperand(0, ConstantInt::get(AI.getArraySize()->getType(), 1));
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() ||
372 DL.getTypeAllocSize(EntryAI->getAllocatedType()) != 0) {
373 AI.moveBefore(FirstInst);
377 // 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(
381 DL.getPrefTypeAlignment(EntryAI->getAllocatedType()));
382 // 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
385 unsigned MaxAlign = std::max(EntryAI->getAlignment(),
387 EntryAI->setAlignment(MaxAlign);
388 if (AI.getType() != EntryAI->getType())
389 return new BitCastInst(EntryAI, AI.getType());
390 return replaceInstUsesWith(AI, EntryAI);
395 if (AI.getAlignment()) {
396 // 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)) {
404 unsigned SourceAlign = getOrEnforceKnownAlignment(
405 Copy->getSource(), AI.getAlignment(), DL, &AI, &AC, &DT);
406 if (AI.getAlignment() <= SourceAlign &&
407 isDereferenceableForAllocaSize(Copy->getSource(), &AI, DL)) {
408 LLVM_DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n');
409 LLVM_DEBUG(dbgs() << " memcpy = " << *Copy << '\n');
410 for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
411 eraseInstFromFunction(*ToDelete[i]);
412 Constant *TheSrc = cast<Constant>(Copy->getSource());
413 auto *SrcTy = TheSrc->getType();
414 auto *DestTy = PointerType::get(AI.getType()->getPointerElementType(),
415 SrcTy->getPointerAddressSpace());
417 ConstantExpr::getPointerBitCastOrAddrSpaceCast(TheSrc, DestTy);
418 if (AI.getType()->getPointerAddressSpace() ==
419 SrcTy->getPointerAddressSpace()) {
420 Instruction *NewI = replaceInstUsesWith(AI, Cast);
421 eraseInstFromFunction(*Copy);
425 PointerReplacer PtrReplacer(*this);
426 PtrReplacer.replacePointer(AI, Cast);
433 // At last, use the generic allocation site handler to aggressively remove
435 return visitAllocSite(AI);
438 // Are we allowed to form a atomic load or store of this type?
439 static bool isSupportedAtomicType(Type *Ty) {
440 return Ty->isIntOrPtrTy() || Ty->isFloatingPointTy();
443 /// Helper to combine a load to a new type.
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.
450 /// Note that this will create all of the instructions with whatever insert
451 /// point the \c InstCombiner currently is using.
452 static LoadInst *combineLoadToNewType(InstCombiner &IC, LoadInst &LI, Type *NewTy,
453 const Twine &Suffix = "") {
454 assert((!LI.isAtomic() || isSupportedAtomicType(NewTy)) &&
455 "can't fold an atomic load to requested type");
457 Value *Ptr = LI.getPointerOperand();
458 unsigned AS = LI.getPointerAddressSpace();
459 SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
460 LI.getAllMetadata(MD);
462 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));
468 LoadInst *NewLoad = IC.Builder.CreateAlignedLoad(
469 NewPtr, LI.getAlignment(), LI.isVolatile(), LI.getName() + Suffix);
470 NewLoad->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
471 MDBuilder MDB(NewLoad->getContext());
472 for (const auto &MDPair : MD) {
473 unsigned ID = MDPair.first;
474 MDNode *N = MDPair.second;
475 // 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.
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:
491 case LLVMContext::MD_nontemporal:
492 case LLVMContext::MD_mem_parallel_loop_access:
493 // All of these directly apply.
494 NewLoad->setMetadata(ID, N);
497 case LLVMContext::MD_nonnull:
498 copyNonnullMetadata(LI, N, *NewLoad);
500 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);
507 case LLVMContext::MD_range:
508 copyRangeMetadata(IC.getDataLayout(), LI, N, *NewLoad);
515 /// Combine a store to a new type.
517 /// Returns the newly created store instruction.
518 static StoreInst *combineStoreToNewValue(InstCombiner &IC, StoreInst &SI, Value *V) {
519 assert((!SI.isAtomic() || isSupportedAtomicType(V->getType())) &&
520 "can't fold an atomic store of requested type");
522 Value *Ptr = SI.getPointerOperand();
523 unsigned AS = SI.getPointerAddressSpace();
524 SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
525 SI.getAllMetadata(MD);
527 StoreInst *NewStore = IC.Builder.CreateAlignedStore(
528 V, IC.Builder.CreateBitCast(Ptr, V->getType()->getPointerTo(AS)),
529 SI.getAlignment(), SI.isVolatile());
530 NewStore->setAtomic(SI.getOrdering(), SI.getSyncScopeID());
531 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
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:
552 // All of these directly apply.
553 NewStore->setMetadata(ID, N);
556 case LLVMContext::MD_invariant_load:
557 case LLVMContext::MD_nonnull:
558 case LLVMContext::MD_range:
559 case LLVMContext::MD_align:
560 case LLVMContext::MD_dereferenceable:
561 case LLVMContext::MD_dereferenceable_or_null:
562 // These don't apply for stores.
570 /// Returns true if instruction represent minmax pattern like:
571 /// select ((cmp load V1, load V2), V1, V2).
572 static 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
578 CmpInst::Predicate Pred;
583 if (!match(V, m_Select(m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2)),
584 m_Value(LHS), m_Value(RHS))))
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))));
592 /// Combine loads to match the type of their uses' value after looking
593 /// through intervening bitcasts.
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.
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.
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.
609 static Instruction *combineLoadToOperationType(InstCombiner &IC, LoadInst &LI) {
610 // 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())
618 // swifterror values can't be bitcasted.
619 if (LI.getPointerOperand()->isSwiftError())
622 Type *Ty = LI.getType();
623 const DataLayout &DL = IC.getDataLayout();
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.
629 // Do not perform canonicalization if minmax pattern is found (to avoid
631 if (!Ty->isIntegerTy() && Ty->isSized() &&
632 DL.isLegalInteger(DL.getTypeStoreSizeInBits(Ty)) &&
633 DL.getTypeStoreSizeInBits(Ty) == DL.getTypeSizeInBits(Ty) &&
634 !DL.isNonIntegralPointerType(Ty) &&
636 peekThroughBitcast(LI.getPointerOperand(), /*OneUseOnly=*/true))) {
637 if (all_of(LI.users(), [&LI](User *U) {
638 auto *SI = dyn_cast<StoreInst>(U);
639 return SI && SI->getPointerOperand() != &LI &&
640 !SI->getPointerOperand()->isSwiftError();
642 LoadInst *NewLoad = combineLoadToNewType(
644 Type::getIntNTy(LI.getContext(), DL.getTypeStoreSizeInBits(Ty)));
645 // 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++);
648 IC.Builder.SetInsertPoint(SI);
649 combineStoreToNewValue(IC, *SI, NewLoad);
650 IC.eraseInstFromFunction(*SI);
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.
658 // Fold away bit casts of the loaded value by loading the desired type.
659 // 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).
663 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);
672 // FIXME: We should also canonicalize loads of vectors when their elements are
673 // cast to other types.
677 static 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.
683 Type *T = LI.getType();
684 if (!T->isAggregateType())
687 StringRef Name = LI.getName();
688 assert(LI.getAlignment() && "Alignment must be set at this point");
690 if (auto *ST = dyn_cast<StructType>(T)) {
691 // If the struct only have one element, we unpack.
692 auto NumElements = ST->getNumElements();
693 if (NumElements == 1) {
694 LoadInst *NewLoad = combineLoadToNewType(IC, LI, ST->getTypeAtIndex(0U),
697 LI.getAAMetadata(AAMD);
698 NewLoad->setAAMetadata(AAMD);
699 return IC.replaceInstUsesWith(LI, IC.Builder.CreateInsertValue(
700 UndefValue::get(T), NewLoad, 0, Name));
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())
710 auto Align = LI.getAlignment();
712 Align = DL.getABITypeAlignment(ST);
714 auto *Addr = LI.getPointerOperand();
715 auto *IdxType = Type::getInt32Ty(T->getContext());
716 auto *Zero = ConstantInt::get(IdxType, 0);
718 Value *V = UndefValue::get(T);
719 for (unsigned i = 0; i < NumElements; i++) {
720 Value *Indices[2] = {
722 ConstantInt::get(IdxType, i),
724 auto *Ptr = IC.Builder.CreateInBoundsGEP(ST, Addr, makeArrayRef(Indices),
726 auto EltAlign = MinAlign(Align, SL->getElementOffset(i));
727 auto *L = IC.Builder.CreateAlignedLoad(Ptr, EltAlign, Name + ".unpack");
728 // Propagate AA metadata. It'll still be valid on the narrowed load.
730 LI.getAAMetadata(AAMD);
731 L->setAAMetadata(AAMD);
732 V = IC.Builder.CreateInsertValue(V, L, i);
736 return IC.replaceInstUsesWith(LI, V);
739 if (auto *AT = dyn_cast<ArrayType>(T)) {
740 auto *ET = AT->getElementType();
741 auto NumElements = AT->getNumElements();
742 if (NumElements == 1) {
743 LoadInst *NewLoad = combineLoadToNewType(IC, LI, ET, ".unpack");
745 LI.getAAMetadata(AAMD);
746 NewLoad->setAAMetadata(AAMD);
747 return IC.replaceInstUsesWith(LI, IC.Builder.CreateInsertValue(
748 UndefValue::get(T), NewLoad, 0, Name));
751 // 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
755 if (NumElements > IC.MaxArraySizeForCombine)
758 const DataLayout &DL = IC.getDataLayout();
759 auto EltSize = DL.getTypeAllocSize(ET);
760 auto Align = LI.getAlignment();
762 Align = DL.getABITypeAlignment(T);
764 auto *Addr = LI.getPointerOperand();
765 auto *IdxType = Type::getInt64Ty(T->getContext());
766 auto *Zero = ConstantInt::get(IdxType, 0);
768 Value *V = UndefValue::get(T);
770 for (uint64_t i = 0; i < NumElements; i++) {
771 Value *Indices[2] = {
773 ConstantInt::get(IdxType, i),
775 auto *Ptr = IC.Builder.CreateInBoundsGEP(AT, Addr, makeArrayRef(Indices),
777 auto *L = IC.Builder.CreateAlignedLoad(Ptr, MinAlign(Align, Offset),
780 LI.getAAMetadata(AAMD);
781 L->setAAMetadata(AAMD);
782 V = IC.Builder.CreateInsertValue(V, L, i);
787 return IC.replaceInstUsesWith(LI, V);
793 // 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).
798 // FIXME: This should probably live in ValueTracking (or similar).
799 static bool isObjectSizeLessThanOrEq(Value *V, uint64_t MaxSize,
800 const DataLayout &DL) {
801 SmallPtrSet<Value *, 4> Visited;
802 SmallVector<Value *, 4> Worklist(1, V);
805 Value *P = Worklist.pop_back_val();
806 P = P->stripPointerCasts();
808 if (!Visited.insert(P).second)
811 if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
812 Worklist.push_back(SI->getTrueValue());
813 Worklist.push_back(SI->getFalseValue());
817 if (PHINode *PN = dyn_cast<PHINode>(P)) {
818 for (Value *IncValue : PN->incoming_values())
819 Worklist.push_back(IncValue);
823 if (GlobalAlias *GA = dyn_cast<GlobalAlias>(P)) {
824 if (GA->isInterposable())
826 Worklist.push_back(GA->getAliasee());
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())
836 ConstantInt *CS = dyn_cast<ConstantInt>(AI->getArraySize());
840 uint64_t TypeSize = DL.getTypeAllocSize(AI->getAllocatedType());
841 // 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))
848 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
849 if (!GV->hasDefinitiveInitializer() || !GV->isConstant())
852 uint64_t InitSize = DL.getTypeAllocSize(GV->getValueType());
853 if (InitSize > MaxSize)
859 } while (!Worklist.empty());
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.
868 // For example, if we have:
869 // @f.a = private unnamed_addr constant [1 x i32] [i32 12], align 4
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.
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.
879 static bool canReplaceGEPIdxWithZero(InstCombiner &IC, GetElementPtrInst *GEPI,
880 Instruction *MemI, unsigned &Idx) {
881 if (GEPI->getNumOperands() < 2)
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) {
888 for (unsigned IE = GEPI->getNumOperands(); I != IE; ++I) {
889 Value *V = GEPI->getOperand(I);
890 if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
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())
905 if (isa<Constant>(GEPI->getOperand(Idx)))
908 SmallVector<Value *, 4> Ops(GEPI->idx_begin(), GEPI->idx_begin() + Idx);
910 GetElementPtrInst::getIndexedType(GEPI->getSourceElementType(), Ops);
911 if (!AllocTy || !AllocTy->isSized())
913 const DataLayout &DL = IC.getDataLayout();
914 uint64_t TyAllocSize = DL.getTypeAllocSize(AllocTy);
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) {
922 KnownBits Known = IC.computeKnownBits(GEPI->getOperand(i), 0, MemI);
923 if (Known.isNonNegative())
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
934 // better, ignoring zero indices (and other indices we can prove small
935 // enough not to wrap).
936 if (Idx+1 != GEPI->getNumOperands() && !GEPI->isInBounds())
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) &&
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.
948 template <typename T>
949 static Instruction *replaceGEPIdxWithZero(InstCombiner &IC, Value *Ptr,
951 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr)) {
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);
966 static bool canSimplifyNullStoreOrGEP(StoreInst &SI) {
967 if (NullPointerIsDefined(SI.getFunction(), SI.getPointerAddressSpace()))
970 auto *Ptr = SI.getPointerOperand();
971 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr))
972 Ptr = GEPI->getOperand(0);
973 return (isa<ConstantPointerNull>(Ptr) &&
974 !NullPointerIsDefined(SI.getFunction(), SI.getPointerAddressSpace()));
977 static bool canSimplifyNullLoadOrGEP(LoadInst &LI, Value *Op) {
978 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
979 const Value *GEPI0 = GEPI->getOperand(0);
980 if (isa<ConstantPointerNull>(GEPI0) &&
981 !NullPointerIsDefined(LI.getFunction(), GEPI->getPointerAddressSpace()))
984 if (isa<UndefValue>(Op) ||
985 (isa<ConstantPointerNull>(Op) &&
986 !NullPointerIsDefined(LI.getFunction(), LI.getPointerAddressSpace())))
991 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
992 Value *Op = LI.getOperand(0);
994 // Try to canonicalize the loaded type.
995 if (Instruction *Res = combineLoadToOperationType(*this, LI))
998 // Attempt to improve the alignment.
999 unsigned KnownAlign = getOrEnforceKnownAlignment(
1000 Op, DL.getPrefTypeAlignment(LI.getType()), DL, &LI, &AC, &DT);
1001 unsigned LoadAlign = LI.getAlignment();
1002 unsigned EffectiveLoadAlign =
1003 LoadAlign != 0 ? LoadAlign : DL.getABITypeAlignment(LI.getType());
1005 if (KnownAlign > EffectiveLoadAlign)
1006 LI.setAlignment(KnownAlign);
1007 else if (LoadAlign == 0)
1008 LI.setAlignment(EffectiveLoadAlign);
1010 // Replace GEP indices if possible.
1011 if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Op, LI)) {
1012 Worklist.Add(NewGEPI);
1016 if (Instruction *Res = unpackLoadToAggregate(*this, LI))
1019 // Do really simple store-to-load forwarding and load CSE, to catch cases
1020 // where there are several consecutive memory accesses to the same location,
1021 // separated by a few arithmetic operations.
1022 BasicBlock::iterator BBI(LI);
1023 bool IsLoadCSE = false;
1024 if (Value *AvailableVal = FindAvailableLoadedValue(
1025 &LI, LI.getParent(), BBI, DefMaxInstsToScan, AA, &IsLoadCSE)) {
1027 combineMetadataForCSE(cast<LoadInst>(AvailableVal), &LI);
1029 return replaceInstUsesWith(
1030 LI, Builder.CreateBitOrPointerCast(AvailableVal, LI.getType(),
1031 LI.getName() + ".cast"));
1034 // None of the following transforms are legal for volatile/ordered atomic
1035 // loads. Most of them do apply for unordered atomics.
1036 if (!LI.isUnordered()) return nullptr;
1038 // load(gep null, ...) -> unreachable
1039 // load null/undef -> unreachable
1040 // TODO: Consider a target hook for valid address spaces for this xforms.
1041 if (canSimplifyNullLoadOrGEP(LI, Op)) {
1042 // Insert a new store to null instruction before the load to indicate
1043 // that this code is not reachable. We do this instead of inserting
1044 // an unreachable instruction directly because we cannot modify the
1046 StoreInst *SI = new StoreInst(UndefValue::get(LI.getType()),
1047 Constant::getNullValue(Op->getType()), &LI);
1048 SI->setDebugLoc(LI.getDebugLoc());
1049 return replaceInstUsesWith(LI, UndefValue::get(LI.getType()));
1052 if (Op->hasOneUse()) {
1053 // Change select and PHI nodes to select values instead of addresses: this
1054 // helps alias analysis out a lot, allows many others simplifications, and
1055 // exposes redundancy in the code.
1057 // Note that we cannot do the transformation unless we know that the
1058 // introduced loads cannot trap! Something like this is valid as long as
1059 // the condition is always false: load (select bool %C, int* null, int* %G),
1060 // but it would not be valid if we transformed it to load from null
1063 if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
1064 // load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).
1065 unsigned Align = LI.getAlignment();
1066 if (isSafeToLoadUnconditionally(SI->getOperand(1), Align, DL, SI) &&
1067 isSafeToLoadUnconditionally(SI->getOperand(2), Align, DL, SI)) {
1068 LoadInst *V1 = Builder.CreateLoad(SI->getOperand(1),
1069 SI->getOperand(1)->getName()+".val");
1070 LoadInst *V2 = Builder.CreateLoad(SI->getOperand(2),
1071 SI->getOperand(2)->getName()+".val");
1072 assert(LI.isUnordered() && "implied by above");
1073 V1->setAlignment(Align);
1074 V1->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
1075 V2->setAlignment(Align);
1076 V2->setAtomic(LI.getOrdering(), LI.getSyncScopeID());
1077 return SelectInst::Create(SI->getCondition(), V1, V2);
1080 // load (select (cond, null, P)) -> load P
1081 if (isa<ConstantPointerNull>(SI->getOperand(1)) &&
1082 !NullPointerIsDefined(SI->getFunction(),
1083 LI.getPointerAddressSpace())) {
1084 LI.setOperand(0, SI->getOperand(2));
1088 // load (select (cond, P, null)) -> load P
1089 if (isa<ConstantPointerNull>(SI->getOperand(2)) &&
1090 !NullPointerIsDefined(SI->getFunction(),
1091 LI.getPointerAddressSpace())) {
1092 LI.setOperand(0, SI->getOperand(1));
1100 /// Look for extractelement/insertvalue sequence that acts like a bitcast.
1102 /// \returns underlying value that was "cast", or nullptr otherwise.
1104 /// For example, if we have:
1106 /// %E0 = extractelement <2 x double> %U, i32 0
1107 /// %V0 = insertvalue [2 x double] undef, double %E0, 0
1108 /// %E1 = extractelement <2 x double> %U, i32 1
1109 /// %V1 = insertvalue [2 x double] %V0, double %E1, 1
1111 /// and the layout of a <2 x double> is isomorphic to a [2 x double],
1112 /// then %V1 can be safely approximated by a conceptual "bitcast" of %U.
1113 /// Note that %U may contain non-undef values where %V1 has undef.
1114 static Value *likeBitCastFromVector(InstCombiner &IC, Value *V) {
1116 while (auto *IV = dyn_cast<InsertValueInst>(V)) {
1117 auto *E = dyn_cast<ExtractElementInst>(IV->getInsertedValueOperand());
1120 auto *W = E->getVectorOperand();
1125 auto *CI = dyn_cast<ConstantInt>(E->getIndexOperand());
1126 if (!CI || IV->getNumIndices() != 1 || CI->getZExtValue() != *IV->idx_begin())
1128 V = IV->getAggregateOperand();
1130 if (!isa<UndefValue>(V) ||!U)
1133 auto *UT = cast<VectorType>(U->getType());
1134 auto *VT = V->getType();
1135 // Check that types UT and VT are bitwise isomorphic.
1136 const auto &DL = IC.getDataLayout();
1137 if (DL.getTypeStoreSizeInBits(UT) != DL.getTypeStoreSizeInBits(VT)) {
1140 if (auto *AT = dyn_cast<ArrayType>(VT)) {
1141 if (AT->getNumElements() != UT->getNumElements())
1144 auto *ST = cast<StructType>(VT);
1145 if (ST->getNumElements() != UT->getNumElements())
1147 for (const auto *EltT : ST->elements()) {
1148 if (EltT != UT->getElementType())
1155 /// Combine stores to match the type of value being stored.
1157 /// The core idea here is that the memory does not have any intrinsic type and
1158 /// where we can we should match the type of a store to the type of value being
1161 /// However, this routine must never change the width of a store or the number of
1162 /// stores as that would introduce a semantic change. This combine is expected to
1163 /// be a semantic no-op which just allows stores to more closely model the types
1164 /// of their incoming values.
1166 /// Currently, we also refuse to change the precise type used for an atomic or
1167 /// volatile store. This is debatable, and might be reasonable to change later.
1168 /// However, it is risky in case some backend or other part of LLVM is relying
1169 /// on the exact type stored to select appropriate atomic operations.
1171 /// \returns true if the store was successfully combined away. This indicates
1172 /// the caller must erase the store instruction. We have to let the caller erase
1173 /// the store instruction as otherwise there is no way to signal whether it was
1174 /// combined or not: IC.EraseInstFromFunction returns a null pointer.
1175 static bool combineStoreToValueType(InstCombiner &IC, StoreInst &SI) {
1176 // FIXME: We could probably with some care handle both volatile and ordered
1177 // atomic stores here but it isn't clear that this is important.
1178 if (!SI.isUnordered())
1181 // swifterror values can't be bitcasted.
1182 if (SI.getPointerOperand()->isSwiftError())
1185 Value *V = SI.getValueOperand();
1187 // Fold away bit casts of the stored value by storing the original type.
1188 if (auto *BC = dyn_cast<BitCastInst>(V)) {
1189 V = BC->getOperand(0);
1190 if (!SI.isAtomic() || isSupportedAtomicType(V->getType())) {
1191 combineStoreToNewValue(IC, SI, V);
1196 if (Value *U = likeBitCastFromVector(IC, V))
1197 if (!SI.isAtomic() || isSupportedAtomicType(U->getType())) {
1198 combineStoreToNewValue(IC, SI, U);
1202 // FIXME: We should also canonicalize stores of vectors when their elements
1203 // are cast to other types.
1207 static bool unpackStoreToAggregate(InstCombiner &IC, StoreInst &SI) {
1208 // FIXME: We could probably with some care handle both volatile and atomic
1209 // stores here but it isn't clear that this is important.
1213 Value *V = SI.getValueOperand();
1214 Type *T = V->getType();
1216 if (!T->isAggregateType())
1219 if (auto *ST = dyn_cast<StructType>(T)) {
1220 // If the struct only have one element, we unpack.
1221 unsigned Count = ST->getNumElements();
1223 V = IC.Builder.CreateExtractValue(V, 0);
1224 combineStoreToNewValue(IC, SI, V);
1228 // We don't want to break loads with padding here as we'd loose
1229 // the knowledge that padding exists for the rest of the pipeline.
1230 const DataLayout &DL = IC.getDataLayout();
1231 auto *SL = DL.getStructLayout(ST);
1232 if (SL->hasPadding())
1235 auto Align = SI.getAlignment();
1237 Align = DL.getABITypeAlignment(ST);
1239 SmallString<16> EltName = V->getName();
1241 auto *Addr = SI.getPointerOperand();
1242 SmallString<16> AddrName = Addr->getName();
1243 AddrName += ".repack";
1245 auto *IdxType = Type::getInt32Ty(ST->getContext());
1246 auto *Zero = ConstantInt::get(IdxType, 0);
1247 for (unsigned i = 0; i < Count; i++) {
1248 Value *Indices[2] = {
1250 ConstantInt::get(IdxType, i),
1252 auto *Ptr = IC.Builder.CreateInBoundsGEP(ST, Addr, makeArrayRef(Indices),
1254 auto *Val = IC.Builder.CreateExtractValue(V, i, EltName);
1255 auto EltAlign = MinAlign(Align, SL->getElementOffset(i));
1256 llvm::Instruction *NS = IC.Builder.CreateAlignedStore(Val, Ptr, EltAlign);
1258 SI.getAAMetadata(AAMD);
1259 NS->setAAMetadata(AAMD);
1265 if (auto *AT = dyn_cast<ArrayType>(T)) {
1266 // If the array only have one element, we unpack.
1267 auto NumElements = AT->getNumElements();
1268 if (NumElements == 1) {
1269 V = IC.Builder.CreateExtractValue(V, 0);
1270 combineStoreToNewValue(IC, SI, V);
1274 // Bail out if the array is too large. Ideally we would like to optimize
1275 // arrays of arbitrary size but this has a terrible impact on compile time.
1276 // The threshold here is chosen arbitrarily, maybe needs a little bit of
1278 if (NumElements > IC.MaxArraySizeForCombine)
1281 const DataLayout &DL = IC.getDataLayout();
1282 auto EltSize = DL.getTypeAllocSize(AT->getElementType());
1283 auto Align = SI.getAlignment();
1285 Align = DL.getABITypeAlignment(T);
1287 SmallString<16> EltName = V->getName();
1289 auto *Addr = SI.getPointerOperand();
1290 SmallString<16> AddrName = Addr->getName();
1291 AddrName += ".repack";
1293 auto *IdxType = Type::getInt64Ty(T->getContext());
1294 auto *Zero = ConstantInt::get(IdxType, 0);
1296 uint64_t Offset = 0;
1297 for (uint64_t i = 0; i < NumElements; i++) {
1298 Value *Indices[2] = {
1300 ConstantInt::get(IdxType, i),
1302 auto *Ptr = IC.Builder.CreateInBoundsGEP(AT, Addr, makeArrayRef(Indices),
1304 auto *Val = IC.Builder.CreateExtractValue(V, i, EltName);
1305 auto EltAlign = MinAlign(Align, Offset);
1306 Instruction *NS = IC.Builder.CreateAlignedStore(Val, Ptr, EltAlign);
1308 SI.getAAMetadata(AAMD);
1309 NS->setAAMetadata(AAMD);
1319 /// equivalentAddressValues - Test if A and B will obviously have the same
1320 /// value. This includes recognizing that %t0 and %t1 will have the same
1321 /// value in code like this:
1322 /// %t0 = getelementptr \@a, 0, 3
1323 /// store i32 0, i32* %t0
1324 /// %t1 = getelementptr \@a, 0, 3
1325 /// %t2 = load i32* %t1
1327 static bool equivalentAddressValues(Value *A, Value *B) {
1328 // Test if the values are trivially equivalent.
1329 if (A == B) return true;
1331 // Test if the values come form identical arithmetic instructions.
1332 // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
1333 // its only used to compare two uses within the same basic block, which
1334 // means that they'll always either have the same value or one of them
1335 // will have an undefined value.
1336 if (isa<BinaryOperator>(A) ||
1339 isa<GetElementPtrInst>(A))
1340 if (Instruction *BI = dyn_cast<Instruction>(B))
1341 if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
1344 // Otherwise they may not be equivalent.
1348 /// Converts store (bitcast (load (bitcast (select ...)))) to
1349 /// store (load (select ...)), where select is minmax:
1350 /// select ((cmp load V1, load V2), V1, V2).
1351 static bool removeBitcastsFromLoadStoreOnMinMax(InstCombiner &IC,
1354 if (!match(SI.getPointerOperand(), m_BitCast(m_Value())))
1358 if (!match(SI.getValueOperand(), m_Load(m_BitCast(m_Value(LoadAddr)))))
1360 auto *LI = cast<LoadInst>(SI.getValueOperand());
1361 if (!LI->getType()->isIntegerTy())
1363 if (!isMinMaxWithLoads(LoadAddr))
1366 if (!all_of(LI->users(), [LI, LoadAddr](User *U) {
1367 auto *SI = dyn_cast<StoreInst>(U);
1368 return SI && SI->getPointerOperand() != LI &&
1369 peekThroughBitcast(SI->getPointerOperand()) != LoadAddr &&
1370 !SI->getPointerOperand()->isSwiftError();
1374 IC.Builder.SetInsertPoint(LI);
1375 LoadInst *NewLI = combineLoadToNewType(
1376 IC, *LI, LoadAddr->getType()->getPointerElementType());
1377 // Replace all the stores with stores of the newly loaded value.
1378 for (auto *UI : LI->users()) {
1379 auto *USI = cast<StoreInst>(UI);
1380 IC.Builder.SetInsertPoint(USI);
1381 combineStoreToNewValue(IC, *USI, NewLI);
1383 IC.replaceInstUsesWith(*LI, UndefValue::get(LI->getType()));
1384 IC.eraseInstFromFunction(*LI);
1388 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
1389 Value *Val = SI.getOperand(0);
1390 Value *Ptr = SI.getOperand(1);
1392 // Try to canonicalize the stored type.
1393 if (combineStoreToValueType(*this, SI))
1394 return eraseInstFromFunction(SI);
1396 // Attempt to improve the alignment.
1397 unsigned KnownAlign = getOrEnforceKnownAlignment(
1398 Ptr, DL.getPrefTypeAlignment(Val->getType()), DL, &SI, &AC, &DT);
1399 unsigned StoreAlign = SI.getAlignment();
1400 unsigned EffectiveStoreAlign =
1401 StoreAlign != 0 ? StoreAlign : DL.getABITypeAlignment(Val->getType());
1403 if (KnownAlign > EffectiveStoreAlign)
1404 SI.setAlignment(KnownAlign);
1405 else if (StoreAlign == 0)
1406 SI.setAlignment(EffectiveStoreAlign);
1408 // Try to canonicalize the stored type.
1409 if (unpackStoreToAggregate(*this, SI))
1410 return eraseInstFromFunction(SI);
1412 if (removeBitcastsFromLoadStoreOnMinMax(*this, SI))
1413 return eraseInstFromFunction(SI);
1415 // Replace GEP indices if possible.
1416 if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Ptr, SI)) {
1417 Worklist.Add(NewGEPI);
1421 // Don't hack volatile/ordered stores.
1422 // FIXME: Some bits are legal for ordered atomic stores; needs refactoring.
1423 if (!SI.isUnordered()) return nullptr;
1425 // If the RHS is an alloca with a single use, zapify the store, making the
1427 if (Ptr->hasOneUse()) {
1428 if (isa<AllocaInst>(Ptr))
1429 return eraseInstFromFunction(SI);
1430 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
1431 if (isa<AllocaInst>(GEP->getOperand(0))) {
1432 if (GEP->getOperand(0)->hasOneUse())
1433 return eraseInstFromFunction(SI);
1438 // Do really simple DSE, to catch cases where there are several consecutive
1439 // stores to the same location, separated by a few arithmetic operations. This
1440 // situation often occurs with bitfield accesses.
1441 BasicBlock::iterator BBI(SI);
1442 for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
1445 // Don't count debug info directives, lest they affect codegen,
1446 // and we skip pointer-to-pointer bitcasts, which are NOPs.
1447 if (isa<DbgInfoIntrinsic>(BBI) ||
1448 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
1453 if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
1454 // Prev store isn't volatile, and stores to the same location?
1455 if (PrevSI->isUnordered() && equivalentAddressValues(PrevSI->getOperand(1),
1456 SI.getOperand(1))) {
1459 eraseInstFromFunction(*PrevSI);
1465 // If this is a load, we have to stop. However, if the loaded value is from
1466 // the pointer we're loading and is producing the pointer we're storing,
1467 // then *this* store is dead (X = load P; store X -> P).
1468 if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
1469 if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr)) {
1470 assert(SI.isUnordered() && "can't eliminate ordering operation");
1471 return eraseInstFromFunction(SI);
1474 // Otherwise, this is a load from some other location. Stores before it
1479 // Don't skip over loads, throws or things that can modify memory.
1480 if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory() || BBI->mayThrow())
1484 // store X, null -> turns into 'unreachable' in SimplifyCFG
1485 // store X, GEP(null, Y) -> turns into 'unreachable' in SimplifyCFG
1486 if (canSimplifyNullStoreOrGEP(SI)) {
1487 if (!isa<UndefValue>(Val)) {
1488 SI.setOperand(0, UndefValue::get(Val->getType()));
1489 if (Instruction *U = dyn_cast<Instruction>(Val))
1490 Worklist.Add(U); // Dropped a use.
1492 return nullptr; // Do not modify these!
1495 // store undef, Ptr -> noop
1496 if (isa<UndefValue>(Val))
1497 return eraseInstFromFunction(SI);
1499 // If this store is the last instruction in the basic block (possibly
1500 // excepting debug info instructions), and if the block ends with an
1501 // unconditional branch, try to move it to the successor block.
1502 BBI = SI.getIterator();
1505 } while (isa<DbgInfoIntrinsic>(BBI) ||
1506 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()));
1507 if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
1508 if (BI->isUnconditional())
1509 if (SimplifyStoreAtEndOfBlock(SI))
1510 return nullptr; // xform done!
1515 /// SimplifyStoreAtEndOfBlock - Turn things like:
1516 /// if () { *P = v1; } else { *P = v2 }
1517 /// into a phi node with a store in the successor.
1519 /// Simplify things like:
1520 /// *P = v1; if () { *P = v2; }
1521 /// into a phi node with a store in the successor.
1523 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
1524 assert(SI.isUnordered() &&
1525 "this code has not been auditted for volatile or ordered store case");
1527 BasicBlock *StoreBB = SI.getParent();
1529 // Check to see if the successor block has exactly two incoming edges. If
1530 // so, see if the other predecessor contains a store to the same location.
1531 // if so, insert a PHI node (if needed) and move the stores down.
1532 BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
1534 // Determine whether Dest has exactly two predecessors and, if so, compute
1535 // the other predecessor.
1536 pred_iterator PI = pred_begin(DestBB);
1537 BasicBlock *P = *PI;
1538 BasicBlock *OtherBB = nullptr;
1543 if (++PI == pred_end(DestBB))
1552 if (++PI != pred_end(DestBB))
1555 // Bail out if all the relevant blocks aren't distinct (this can happen,
1556 // for example, if SI is in an infinite loop)
1557 if (StoreBB == DestBB || OtherBB == DestBB)
1560 // Verify that the other block ends in a branch and is not otherwise empty.
1561 BasicBlock::iterator BBI(OtherBB->getTerminator());
1562 BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
1563 if (!OtherBr || BBI == OtherBB->begin())
1566 // If the other block ends in an unconditional branch, check for the 'if then
1567 // else' case. there is an instruction before the branch.
1568 StoreInst *OtherStore = nullptr;
1569 if (OtherBr->isUnconditional()) {
1571 // Skip over debugging info.
1572 while (isa<DbgInfoIntrinsic>(BBI) ||
1573 (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
1574 if (BBI==OtherBB->begin())
1578 // If this isn't a store, isn't a store to the same location, or is not the
1579 // right kind of store, bail out.
1580 OtherStore = dyn_cast<StoreInst>(BBI);
1581 if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
1582 !SI.isSameOperationAs(OtherStore))
1585 // Otherwise, the other block ended with a conditional branch. If one of the
1586 // destinations is StoreBB, then we have the if/then case.
1587 if (OtherBr->getSuccessor(0) != StoreBB &&
1588 OtherBr->getSuccessor(1) != StoreBB)
1591 // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
1592 // if/then triangle. See if there is a store to the same ptr as SI that
1593 // lives in OtherBB.
1595 // Check to see if we find the matching store.
1596 if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
1597 if (OtherStore->getOperand(1) != SI.getOperand(1) ||
1598 !SI.isSameOperationAs(OtherStore))
1602 // If we find something that may be using or overwriting the stored
1603 // value, or if we run out of instructions, we can't do the xform.
1604 if (BBI->mayReadFromMemory() || BBI->mayThrow() ||
1605 BBI->mayWriteToMemory() || BBI == OtherBB->begin())
1609 // In order to eliminate the store in OtherBr, we have to
1610 // make sure nothing reads or overwrites the stored value in
1612 for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
1613 // FIXME: This should really be AA driven.
1614 if (I->mayReadFromMemory() || I->mayThrow() || I->mayWriteToMemory())
1619 // Insert a PHI node now if we need it.
1620 Value *MergedVal = OtherStore->getOperand(0);
1621 if (MergedVal != SI.getOperand(0)) {
1622 PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge");
1623 PN->addIncoming(SI.getOperand(0), SI.getParent());
1624 PN->addIncoming(OtherStore->getOperand(0), OtherBB);
1625 MergedVal = InsertNewInstBefore(PN, DestBB->front());
1628 // Advance to a place where it is safe to insert the new store and
1630 BBI = DestBB->getFirstInsertionPt();
1631 StoreInst *NewSI = new StoreInst(MergedVal, SI.getOperand(1),
1635 SI.getSyncScopeID());
1636 InsertNewInstBefore(NewSI, *BBI);
1637 // The debug locations of the original instructions might differ; merge them.
1638 NewSI->applyMergedLocation(SI.getDebugLoc(), OtherStore->getDebugLoc());
1640 // If the two stores had AA tags, merge them.
1642 SI.getAAMetadata(AATags);
1644 OtherStore->getAAMetadata(AATags, /* Merge = */ true);
1645 NewSI->setAAMetadata(AATags);
1648 // Nuke the old stores.
1649 eraseInstFromFunction(SI);
1650 eraseInstFromFunction(*OtherStore);