Path: blob/main/contrib/llvm-project/llvm/lib/Transforms/InstCombine/InstCombineLoadStoreAlloca.cpp
35266 views
//===- InstCombineLoadStoreAlloca.cpp -------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This file implements the visit functions for load, store and alloca.9//10//===----------------------------------------------------------------------===//1112#include "InstCombineInternal.h"13#include "llvm/ADT/MapVector.h"14#include "llvm/ADT/SmallString.h"15#include "llvm/ADT/Statistic.h"16#include "llvm/Analysis/AliasAnalysis.h"17#include "llvm/Analysis/Loads.h"18#include "llvm/IR/DataLayout.h"19#include "llvm/IR/DebugInfoMetadata.h"20#include "llvm/IR/IntrinsicInst.h"21#include "llvm/IR/LLVMContext.h"22#include "llvm/IR/PatternMatch.h"23#include "llvm/Transforms/InstCombine/InstCombiner.h"24#include "llvm/Transforms/Utils/Local.h"25using namespace llvm;26using namespace PatternMatch;2728#define DEBUG_TYPE "instcombine"2930STATISTIC(NumDeadStore, "Number of dead stores eliminated");31STATISTIC(NumGlobalCopies, "Number of allocas copied from constant global");3233static cl::opt<unsigned> MaxCopiedFromConstantUsers(34"instcombine-max-copied-from-constant-users", cl::init(300),35cl::desc("Maximum users to visit in copy from constant transform"),36cl::Hidden);3738namespace llvm {39cl::opt<bool> EnableInferAlignmentPass(40"enable-infer-alignment-pass", cl::init(true), cl::Hidden, cl::ZeroOrMore,41cl::desc("Enable the InferAlignment pass, disabling alignment inference in "42"InstCombine"));43}4445/// isOnlyCopiedFromConstantMemory - Recursively walk the uses of a (derived)46/// pointer to an alloca. Ignore any reads of the pointer, return false if we47/// see any stores or other unknown uses. If we see pointer arithmetic, keep48/// track of whether it moves the pointer (with IsOffset) but otherwise traverse49/// the uses. If we see a memcpy/memmove that targets an unoffseted pointer to50/// the alloca, and if the source pointer is a pointer to a constant memory51/// location, we can optimize this.52static bool53isOnlyCopiedFromConstantMemory(AAResults *AA, AllocaInst *V,54MemTransferInst *&TheCopy,55SmallVectorImpl<Instruction *> &ToDelete) {56// We track lifetime intrinsics as we encounter them. If we decide to go57// ahead and replace the value with the memory location, this lets the caller58// quickly eliminate the markers.5960using ValueAndIsOffset = PointerIntPair<Value *, 1, bool>;61SmallVector<ValueAndIsOffset, 32> Worklist;62SmallPtrSet<ValueAndIsOffset, 32> Visited;63Worklist.emplace_back(V, false);64while (!Worklist.empty()) {65ValueAndIsOffset Elem = Worklist.pop_back_val();66if (!Visited.insert(Elem).second)67continue;68if (Visited.size() > MaxCopiedFromConstantUsers)69return false;7071const auto [Value, IsOffset] = Elem;72for (auto &U : Value->uses()) {73auto *I = cast<Instruction>(U.getUser());7475if (auto *LI = dyn_cast<LoadInst>(I)) {76// Ignore non-volatile loads, they are always ok.77if (!LI->isSimple()) return false;78continue;79}8081if (isa<PHINode, SelectInst>(I)) {82// We set IsOffset=true, to forbid the memcpy from occurring after the83// phi: If one of the phi operands is not based on the alloca, we84// would incorrectly omit a write.85Worklist.emplace_back(I, true);86continue;87}88if (isa<BitCastInst, AddrSpaceCastInst>(I)) {89// If uses of the bitcast are ok, we are ok.90Worklist.emplace_back(I, IsOffset);91continue;92}93if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {94// If the GEP has all zero indices, it doesn't offset the pointer. If it95// doesn't, it does.96Worklist.emplace_back(I, IsOffset || !GEP->hasAllZeroIndices());97continue;98}99100if (auto *Call = dyn_cast<CallBase>(I)) {101// If this is the function being called then we treat it like a load and102// ignore it.103if (Call->isCallee(&U))104continue;105106unsigned DataOpNo = Call->getDataOperandNo(&U);107bool IsArgOperand = Call->isArgOperand(&U);108109// Inalloca arguments are clobbered by the call.110if (IsArgOperand && Call->isInAllocaArgument(DataOpNo))111return false;112113// If this call site doesn't modify the memory, then we know it is just114// a load (but one that potentially returns the value itself), so we can115// ignore it if we know that the value isn't captured.116bool NoCapture = Call->doesNotCapture(DataOpNo);117if ((Call->onlyReadsMemory() && (Call->use_empty() || NoCapture)) ||118(Call->onlyReadsMemory(DataOpNo) && NoCapture))119continue;120121// If this is being passed as a byval argument, the caller is making a122// copy, so it is only a read of the alloca.123if (IsArgOperand && Call->isByValArgument(DataOpNo))124continue;125}126127// Lifetime intrinsics can be handled by the caller.128if (I->isLifetimeStartOrEnd()) {129assert(I->use_empty() && "Lifetime markers have no result to use!");130ToDelete.push_back(I);131continue;132}133134// If this is isn't our memcpy/memmove, reject it as something we can't135// handle.136MemTransferInst *MI = dyn_cast<MemTransferInst>(I);137if (!MI)138return false;139140// If the transfer is volatile, reject it.141if (MI->isVolatile())142return false;143144// If the transfer is using the alloca as a source of the transfer, then145// ignore it since it is a load (unless the transfer is volatile).146if (U.getOperandNo() == 1)147continue;148149// If we already have seen a copy, reject the second one.150if (TheCopy) return false;151152// If the pointer has been offset from the start of the alloca, we can't153// safely handle this.154if (IsOffset) return false;155156// If the memintrinsic isn't using the alloca as the dest, reject it.157if (U.getOperandNo() != 0) return false;158159// If the source of the memcpy/move is not constant, reject it.160if (isModSet(AA->getModRefInfoMask(MI->getSource())))161return false;162163// Otherwise, the transform is safe. Remember the copy instruction.164TheCopy = MI;165}166}167return true;168}169170/// isOnlyCopiedFromConstantMemory - Return true if the specified alloca is only171/// modified by a copy from a constant memory location. If we can prove this, we172/// can replace any uses of the alloca with uses of the memory location173/// directly.174static MemTransferInst *175isOnlyCopiedFromConstantMemory(AAResults *AA,176AllocaInst *AI,177SmallVectorImpl<Instruction *> &ToDelete) {178MemTransferInst *TheCopy = nullptr;179if (isOnlyCopiedFromConstantMemory(AA, AI, TheCopy, ToDelete))180return TheCopy;181return nullptr;182}183184/// Returns true if V is dereferenceable for size of alloca.185static bool isDereferenceableForAllocaSize(const Value *V, const AllocaInst *AI,186const DataLayout &DL) {187if (AI->isArrayAllocation())188return false;189uint64_t AllocaSize = DL.getTypeStoreSize(AI->getAllocatedType());190if (!AllocaSize)191return false;192return isDereferenceableAndAlignedPointer(V, AI->getAlign(),193APInt(64, AllocaSize), DL);194}195196static Instruction *simplifyAllocaArraySize(InstCombinerImpl &IC,197AllocaInst &AI, DominatorTree &DT) {198// Check for array size of 1 (scalar allocation).199if (!AI.isArrayAllocation()) {200// i32 1 is the canonical array size for scalar allocations.201if (AI.getArraySize()->getType()->isIntegerTy(32))202return nullptr;203204// Canonicalize it.205return IC.replaceOperand(AI, 0, IC.Builder.getInt32(1));206}207208// Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1209if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {210if (C->getValue().getActiveBits() <= 64) {211Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getZExtValue());212AllocaInst *New = IC.Builder.CreateAlloca(NewTy, AI.getAddressSpace(),213nullptr, AI.getName());214New->setAlignment(AI.getAlign());215New->setUsedWithInAlloca(AI.isUsedWithInAlloca());216217replaceAllDbgUsesWith(AI, *New, *New, DT);218return IC.replaceInstUsesWith(AI, New);219}220}221222if (isa<UndefValue>(AI.getArraySize()))223return IC.replaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));224225// Ensure that the alloca array size argument has type equal to the offset226// size of the alloca() pointer, which, in the tyical case, is intptr_t,227// so that any casting is exposed early.228Type *PtrIdxTy = IC.getDataLayout().getIndexType(AI.getType());229if (AI.getArraySize()->getType() != PtrIdxTy) {230Value *V = IC.Builder.CreateIntCast(AI.getArraySize(), PtrIdxTy, false);231return IC.replaceOperand(AI, 0, V);232}233234return nullptr;235}236237namespace {238// If I and V are pointers in different address space, it is not allowed to239// use replaceAllUsesWith since I and V have different types. A240// non-target-specific transformation should not use addrspacecast on V since241// the two address space may be disjoint depending on target.242//243// This class chases down uses of the old pointer until reaching the load244// instructions, then replaces the old pointer in the load instructions with245// the new pointer. If during the chasing it sees bitcast or GEP, it will246// create new bitcast or GEP with the new pointer and use them in the load247// instruction.248class PointerReplacer {249public:250PointerReplacer(InstCombinerImpl &IC, Instruction &Root, unsigned SrcAS)251: IC(IC), Root(Root), FromAS(SrcAS) {}252253bool collectUsers();254void replacePointer(Value *V);255256private:257bool collectUsersRecursive(Instruction &I);258void replace(Instruction *I);259Value *getReplacement(Value *I);260bool isAvailable(Instruction *I) const {261return I == &Root || Worklist.contains(I);262}263264bool isEqualOrValidAddrSpaceCast(const Instruction *I,265unsigned FromAS) const {266const auto *ASC = dyn_cast<AddrSpaceCastInst>(I);267if (!ASC)268return false;269unsigned ToAS = ASC->getDestAddressSpace();270return (FromAS == ToAS) || IC.isValidAddrSpaceCast(FromAS, ToAS);271}272273SmallPtrSet<Instruction *, 32> ValuesToRevisit;274SmallSetVector<Instruction *, 4> Worklist;275MapVector<Value *, Value *> WorkMap;276InstCombinerImpl &IC;277Instruction &Root;278unsigned FromAS;279};280} // end anonymous namespace281282bool PointerReplacer::collectUsers() {283if (!collectUsersRecursive(Root))284return false;285286// Ensure that all outstanding (indirect) users of I287// are inserted into the Worklist. Return false288// otherwise.289for (auto *Inst : ValuesToRevisit)290if (!Worklist.contains(Inst))291return false;292return true;293}294295bool PointerReplacer::collectUsersRecursive(Instruction &I) {296for (auto *U : I.users()) {297auto *Inst = cast<Instruction>(&*U);298if (auto *Load = dyn_cast<LoadInst>(Inst)) {299if (Load->isVolatile())300return false;301Worklist.insert(Load);302} else if (auto *PHI = dyn_cast<PHINode>(Inst)) {303// All incoming values must be instructions for replacability304if (any_of(PHI->incoming_values(),305[](Value *V) { return !isa<Instruction>(V); }))306return false;307308// If at least one incoming value of the PHI is not in Worklist,309// store the PHI for revisiting and skip this iteration of the310// loop.311if (any_of(PHI->incoming_values(), [this](Value *V) {312return !isAvailable(cast<Instruction>(V));313})) {314ValuesToRevisit.insert(Inst);315continue;316}317318Worklist.insert(PHI);319if (!collectUsersRecursive(*PHI))320return false;321} else if (auto *SI = dyn_cast<SelectInst>(Inst)) {322if (!isa<Instruction>(SI->getTrueValue()) ||323!isa<Instruction>(SI->getFalseValue()))324return false;325326if (!isAvailable(cast<Instruction>(SI->getTrueValue())) ||327!isAvailable(cast<Instruction>(SI->getFalseValue()))) {328ValuesToRevisit.insert(Inst);329continue;330}331Worklist.insert(SI);332if (!collectUsersRecursive(*SI))333return false;334} else if (isa<GetElementPtrInst>(Inst)) {335Worklist.insert(Inst);336if (!collectUsersRecursive(*Inst))337return false;338} else if (auto *MI = dyn_cast<MemTransferInst>(Inst)) {339if (MI->isVolatile())340return false;341Worklist.insert(Inst);342} else if (isEqualOrValidAddrSpaceCast(Inst, FromAS)) {343Worklist.insert(Inst);344if (!collectUsersRecursive(*Inst))345return false;346} else if (Inst->isLifetimeStartOrEnd()) {347continue;348} else {349// TODO: For arbitrary uses with address space mismatches, should we check350// if we can introduce a valid addrspacecast?351LLVM_DEBUG(dbgs() << "Cannot handle pointer user: " << *U << '\n');352return false;353}354}355356return true;357}358359Value *PointerReplacer::getReplacement(Value *V) { return WorkMap.lookup(V); }360361void PointerReplacer::replace(Instruction *I) {362if (getReplacement(I))363return;364365if (auto *LT = dyn_cast<LoadInst>(I)) {366auto *V = getReplacement(LT->getPointerOperand());367assert(V && "Operand not replaced");368auto *NewI = new LoadInst(LT->getType(), V, "", LT->isVolatile(),369LT->getAlign(), LT->getOrdering(),370LT->getSyncScopeID());371NewI->takeName(LT);372copyMetadataForLoad(*NewI, *LT);373374IC.InsertNewInstWith(NewI, LT->getIterator());375IC.replaceInstUsesWith(*LT, NewI);376WorkMap[LT] = NewI;377} else if (auto *PHI = dyn_cast<PHINode>(I)) {378Type *NewTy = getReplacement(PHI->getIncomingValue(0))->getType();379auto *NewPHI = PHINode::Create(NewTy, PHI->getNumIncomingValues(),380PHI->getName(), PHI->getIterator());381for (unsigned int I = 0; I < PHI->getNumIncomingValues(); ++I)382NewPHI->addIncoming(getReplacement(PHI->getIncomingValue(I)),383PHI->getIncomingBlock(I));384WorkMap[PHI] = NewPHI;385} else if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {386auto *V = getReplacement(GEP->getPointerOperand());387assert(V && "Operand not replaced");388SmallVector<Value *, 8> Indices(GEP->indices());389auto *NewI =390GetElementPtrInst::Create(GEP->getSourceElementType(), V, Indices);391IC.InsertNewInstWith(NewI, GEP->getIterator());392NewI->takeName(GEP);393NewI->setNoWrapFlags(GEP->getNoWrapFlags());394WorkMap[GEP] = NewI;395} else if (auto *SI = dyn_cast<SelectInst>(I)) {396Value *TrueValue = SI->getTrueValue();397Value *FalseValue = SI->getFalseValue();398if (Value *Replacement = getReplacement(TrueValue))399TrueValue = Replacement;400if (Value *Replacement = getReplacement(FalseValue))401FalseValue = Replacement;402auto *NewSI = SelectInst::Create(SI->getCondition(), TrueValue, FalseValue,403SI->getName(), nullptr, SI);404IC.InsertNewInstWith(NewSI, SI->getIterator());405NewSI->takeName(SI);406WorkMap[SI] = NewSI;407} else if (auto *MemCpy = dyn_cast<MemTransferInst>(I)) {408auto *DestV = MemCpy->getRawDest();409auto *SrcV = MemCpy->getRawSource();410411if (auto *DestReplace = getReplacement(DestV))412DestV = DestReplace;413if (auto *SrcReplace = getReplacement(SrcV))414SrcV = SrcReplace;415416IC.Builder.SetInsertPoint(MemCpy);417auto *NewI = IC.Builder.CreateMemTransferInst(418MemCpy->getIntrinsicID(), DestV, MemCpy->getDestAlign(), SrcV,419MemCpy->getSourceAlign(), MemCpy->getLength(), MemCpy->isVolatile());420AAMDNodes AAMD = MemCpy->getAAMetadata();421if (AAMD)422NewI->setAAMetadata(AAMD);423424IC.eraseInstFromFunction(*MemCpy);425WorkMap[MemCpy] = NewI;426} else if (auto *ASC = dyn_cast<AddrSpaceCastInst>(I)) {427auto *V = getReplacement(ASC->getPointerOperand());428assert(V && "Operand not replaced");429assert(isEqualOrValidAddrSpaceCast(430ASC, V->getType()->getPointerAddressSpace()) &&431"Invalid address space cast!");432433if (V->getType()->getPointerAddressSpace() !=434ASC->getType()->getPointerAddressSpace()) {435auto *NewI = new AddrSpaceCastInst(V, ASC->getType(), "");436NewI->takeName(ASC);437IC.InsertNewInstWith(NewI, ASC->getIterator());438WorkMap[ASC] = NewI;439} else {440WorkMap[ASC] = V;441}442443} else {444llvm_unreachable("should never reach here");445}446}447448void PointerReplacer::replacePointer(Value *V) {449#ifndef NDEBUG450auto *PT = cast<PointerType>(Root.getType());451auto *NT = cast<PointerType>(V->getType());452assert(PT != NT && "Invalid usage");453#endif454WorkMap[&Root] = V;455456for (Instruction *Workitem : Worklist)457replace(Workitem);458}459460Instruction *InstCombinerImpl::visitAllocaInst(AllocaInst &AI) {461if (auto *I = simplifyAllocaArraySize(*this, AI, DT))462return I;463464if (AI.getAllocatedType()->isSized()) {465// Move all alloca's of zero byte objects to the entry block and merge them466// together. Note that we only do this for alloca's, because malloc should467// allocate and return a unique pointer, even for a zero byte allocation.468if (DL.getTypeAllocSize(AI.getAllocatedType()).getKnownMinValue() == 0) {469// For a zero sized alloca there is no point in doing an array allocation.470// This is helpful if the array size is a complicated expression not used471// elsewhere.472if (AI.isArrayAllocation())473return replaceOperand(AI, 0,474ConstantInt::get(AI.getArraySize()->getType(), 1));475476// Get the first instruction in the entry block.477BasicBlock &EntryBlock = AI.getParent()->getParent()->getEntryBlock();478Instruction *FirstInst = EntryBlock.getFirstNonPHIOrDbg();479if (FirstInst != &AI) {480// If the entry block doesn't start with a zero-size alloca then move481// this one to the start of the entry block. There is no problem with482// dominance as the array size was forced to a constant earlier already.483AllocaInst *EntryAI = dyn_cast<AllocaInst>(FirstInst);484if (!EntryAI || !EntryAI->getAllocatedType()->isSized() ||485DL.getTypeAllocSize(EntryAI->getAllocatedType())486.getKnownMinValue() != 0) {487AI.moveBefore(FirstInst);488return &AI;489}490491// Replace this zero-sized alloca with the one at the start of the entry492// block after ensuring that the address will be aligned enough for both493// types.494const Align MaxAlign = std::max(EntryAI->getAlign(), AI.getAlign());495EntryAI->setAlignment(MaxAlign);496return replaceInstUsesWith(AI, EntryAI);497}498}499}500501// Check to see if this allocation is only modified by a memcpy/memmove from502// a memory location whose alignment is equal to or exceeds that of the503// allocation. If this is the case, we can change all users to use the504// constant memory location instead. This is commonly produced by the CFE by505// constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'506// is only subsequently read.507SmallVector<Instruction *, 4> ToDelete;508if (MemTransferInst *Copy = isOnlyCopiedFromConstantMemory(AA, &AI, ToDelete)) {509Value *TheSrc = Copy->getSource();510Align AllocaAlign = AI.getAlign();511Align SourceAlign = getOrEnforceKnownAlignment(512TheSrc, AllocaAlign, DL, &AI, &AC, &DT);513if (AllocaAlign <= SourceAlign &&514isDereferenceableForAllocaSize(TheSrc, &AI, DL) &&515!isa<Instruction>(TheSrc)) {516// FIXME: Can we sink instructions without violating dominance when TheSrc517// is an instruction instead of a constant or argument?518LLVM_DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n');519LLVM_DEBUG(dbgs() << " memcpy = " << *Copy << '\n');520unsigned SrcAddrSpace = TheSrc->getType()->getPointerAddressSpace();521if (AI.getAddressSpace() == SrcAddrSpace) {522for (Instruction *Delete : ToDelete)523eraseInstFromFunction(*Delete);524525Instruction *NewI = replaceInstUsesWith(AI, TheSrc);526eraseInstFromFunction(*Copy);527++NumGlobalCopies;528return NewI;529}530531PointerReplacer PtrReplacer(*this, AI, SrcAddrSpace);532if (PtrReplacer.collectUsers()) {533for (Instruction *Delete : ToDelete)534eraseInstFromFunction(*Delete);535536PtrReplacer.replacePointer(TheSrc);537++NumGlobalCopies;538}539}540}541542// At last, use the generic allocation site handler to aggressively remove543// unused allocas.544return visitAllocSite(AI);545}546547// Are we allowed to form a atomic load or store of this type?548static bool isSupportedAtomicType(Type *Ty) {549return Ty->isIntOrPtrTy() || Ty->isFloatingPointTy();550}551552/// Helper to combine a load to a new type.553///554/// This just does the work of combining a load to a new type. It handles555/// metadata, etc., and returns the new instruction. The \c NewTy should be the556/// loaded *value* type. This will convert it to a pointer, cast the operand to557/// that pointer type, load it, etc.558///559/// Note that this will create all of the instructions with whatever insert560/// point the \c InstCombinerImpl currently is using.561LoadInst *InstCombinerImpl::combineLoadToNewType(LoadInst &LI, Type *NewTy,562const Twine &Suffix) {563assert((!LI.isAtomic() || isSupportedAtomicType(NewTy)) &&564"can't fold an atomic load to requested type");565566LoadInst *NewLoad =567Builder.CreateAlignedLoad(NewTy, LI.getPointerOperand(), LI.getAlign(),568LI.isVolatile(), LI.getName() + Suffix);569NewLoad->setAtomic(LI.getOrdering(), LI.getSyncScopeID());570copyMetadataForLoad(*NewLoad, LI);571return NewLoad;572}573574/// Combine a store to a new type.575///576/// Returns the newly created store instruction.577static StoreInst *combineStoreToNewValue(InstCombinerImpl &IC, StoreInst &SI,578Value *V) {579assert((!SI.isAtomic() || isSupportedAtomicType(V->getType())) &&580"can't fold an atomic store of requested type");581582Value *Ptr = SI.getPointerOperand();583SmallVector<std::pair<unsigned, MDNode *>, 8> MD;584SI.getAllMetadata(MD);585586StoreInst *NewStore =587IC.Builder.CreateAlignedStore(V, Ptr, SI.getAlign(), SI.isVolatile());588NewStore->setAtomic(SI.getOrdering(), SI.getSyncScopeID());589for (const auto &MDPair : MD) {590unsigned ID = MDPair.first;591MDNode *N = MDPair.second;592// Note, essentially every kind of metadata should be preserved here! This593// routine is supposed to clone a store instruction changing *only its594// type*. The only metadata it makes sense to drop is metadata which is595// invalidated when the pointer type changes. This should essentially596// never be the case in LLVM, but we explicitly switch over only known597// metadata to be conservatively correct. If you are adding metadata to598// LLVM which pertains to stores, you almost certainly want to add it599// here.600switch (ID) {601case LLVMContext::MD_dbg:602case LLVMContext::MD_DIAssignID:603case LLVMContext::MD_tbaa:604case LLVMContext::MD_prof:605case LLVMContext::MD_fpmath:606case LLVMContext::MD_tbaa_struct:607case LLVMContext::MD_alias_scope:608case LLVMContext::MD_noalias:609case LLVMContext::MD_nontemporal:610case LLVMContext::MD_mem_parallel_loop_access:611case LLVMContext::MD_access_group:612// All of these directly apply.613NewStore->setMetadata(ID, N);614break;615case LLVMContext::MD_invariant_load:616case LLVMContext::MD_nonnull:617case LLVMContext::MD_noundef:618case LLVMContext::MD_range:619case LLVMContext::MD_align:620case LLVMContext::MD_dereferenceable:621case LLVMContext::MD_dereferenceable_or_null:622// These don't apply for stores.623break;624}625}626627return NewStore;628}629630/// Combine loads to match the type of their uses' value after looking631/// through intervening bitcasts.632///633/// The core idea here is that if the result of a load is used in an operation,634/// we should load the type most conducive to that operation. For example, when635/// loading an integer and converting that immediately to a pointer, we should636/// instead directly load a pointer.637///638/// However, this routine must never change the width of a load or the number of639/// loads as that would introduce a semantic change. This combine is expected to640/// be a semantic no-op which just allows loads to more closely model the types641/// of their consuming operations.642///643/// Currently, we also refuse to change the precise type used for an atomic load644/// or a volatile load. This is debatable, and might be reasonable to change645/// later. However, it is risky in case some backend or other part of LLVM is646/// relying on the exact type loaded to select appropriate atomic operations.647static Instruction *combineLoadToOperationType(InstCombinerImpl &IC,648LoadInst &Load) {649// FIXME: We could probably with some care handle both volatile and ordered650// atomic loads here but it isn't clear that this is important.651if (!Load.isUnordered())652return nullptr;653654if (Load.use_empty())655return nullptr;656657// swifterror values can't be bitcasted.658if (Load.getPointerOperand()->isSwiftError())659return nullptr;660661// Fold away bit casts of the loaded value by loading the desired type.662// Note that we should not do this for pointer<->integer casts,663// because that would result in type punning.664if (Load.hasOneUse()) {665// Don't transform when the type is x86_amx, it makes the pass that lower666// x86_amx type happy.667Type *LoadTy = Load.getType();668if (auto *BC = dyn_cast<BitCastInst>(Load.user_back())) {669assert(!LoadTy->isX86_AMXTy() && "Load from x86_amx* should not happen!");670if (BC->getType()->isX86_AMXTy())671return nullptr;672}673674if (auto *CastUser = dyn_cast<CastInst>(Load.user_back())) {675Type *DestTy = CastUser->getDestTy();676if (CastUser->isNoopCast(IC.getDataLayout()) &&677LoadTy->isPtrOrPtrVectorTy() == DestTy->isPtrOrPtrVectorTy() &&678(!Load.isAtomic() || isSupportedAtomicType(DestTy))) {679LoadInst *NewLoad = IC.combineLoadToNewType(Load, DestTy);680CastUser->replaceAllUsesWith(NewLoad);681IC.eraseInstFromFunction(*CastUser);682return &Load;683}684}685}686687// FIXME: We should also canonicalize loads of vectors when their elements are688// cast to other types.689return nullptr;690}691692static Instruction *unpackLoadToAggregate(InstCombinerImpl &IC, LoadInst &LI) {693// FIXME: We could probably with some care handle both volatile and atomic694// stores here but it isn't clear that this is important.695if (!LI.isSimple())696return nullptr;697698Type *T = LI.getType();699if (!T->isAggregateType())700return nullptr;701702StringRef Name = LI.getName();703704if (auto *ST = dyn_cast<StructType>(T)) {705// If the struct only have one element, we unpack.706auto NumElements = ST->getNumElements();707if (NumElements == 1) {708LoadInst *NewLoad = IC.combineLoadToNewType(LI, ST->getTypeAtIndex(0U),709".unpack");710NewLoad->setAAMetadata(LI.getAAMetadata());711return IC.replaceInstUsesWith(LI, IC.Builder.CreateInsertValue(712PoisonValue::get(T), NewLoad, 0, Name));713}714715// We don't want to break loads with padding here as we'd loose716// the knowledge that padding exists for the rest of the pipeline.717const DataLayout &DL = IC.getDataLayout();718auto *SL = DL.getStructLayout(ST);719720// Don't unpack for structure with scalable vector.721if (SL->getSizeInBits().isScalable())722return nullptr;723724if (SL->hasPadding())725return nullptr;726727const auto Align = LI.getAlign();728auto *Addr = LI.getPointerOperand();729auto *IdxType = Type::getInt32Ty(T->getContext());730auto *Zero = ConstantInt::get(IdxType, 0);731732Value *V = PoisonValue::get(T);733for (unsigned i = 0; i < NumElements; i++) {734Value *Indices[2] = {735Zero,736ConstantInt::get(IdxType, i),737};738auto *Ptr = IC.Builder.CreateInBoundsGEP(ST, Addr, ArrayRef(Indices),739Name + ".elt");740auto *L = IC.Builder.CreateAlignedLoad(741ST->getElementType(i), Ptr,742commonAlignment(Align, SL->getElementOffset(i)), Name + ".unpack");743// Propagate AA metadata. It'll still be valid on the narrowed load.744L->setAAMetadata(LI.getAAMetadata());745V = IC.Builder.CreateInsertValue(V, L, i);746}747748V->setName(Name);749return IC.replaceInstUsesWith(LI, V);750}751752if (auto *AT = dyn_cast<ArrayType>(T)) {753auto *ET = AT->getElementType();754auto NumElements = AT->getNumElements();755if (NumElements == 1) {756LoadInst *NewLoad = IC.combineLoadToNewType(LI, ET, ".unpack");757NewLoad->setAAMetadata(LI.getAAMetadata());758return IC.replaceInstUsesWith(LI, IC.Builder.CreateInsertValue(759PoisonValue::get(T), NewLoad, 0, Name));760}761762// Bail out if the array is too large. Ideally we would like to optimize763// arrays of arbitrary size but this has a terrible impact on compile time.764// The threshold here is chosen arbitrarily, maybe needs a little bit of765// tuning.766if (NumElements > IC.MaxArraySizeForCombine)767return nullptr;768769const DataLayout &DL = IC.getDataLayout();770TypeSize EltSize = DL.getTypeAllocSize(ET);771const auto Align = LI.getAlign();772773auto *Addr = LI.getPointerOperand();774auto *IdxType = Type::getInt64Ty(T->getContext());775auto *Zero = ConstantInt::get(IdxType, 0);776777Value *V = PoisonValue::get(T);778TypeSize Offset = TypeSize::getZero();779for (uint64_t i = 0; i < NumElements; i++) {780Value *Indices[2] = {781Zero,782ConstantInt::get(IdxType, i),783};784auto *Ptr = IC.Builder.CreateInBoundsGEP(AT, Addr, ArrayRef(Indices),785Name + ".elt");786auto EltAlign = commonAlignment(Align, Offset.getKnownMinValue());787auto *L = IC.Builder.CreateAlignedLoad(AT->getElementType(), Ptr,788EltAlign, Name + ".unpack");789L->setAAMetadata(LI.getAAMetadata());790V = IC.Builder.CreateInsertValue(V, L, i);791Offset += EltSize;792}793794V->setName(Name);795return IC.replaceInstUsesWith(LI, V);796}797798return nullptr;799}800801// If we can determine that all possible objects pointed to by the provided802// pointer value are, not only dereferenceable, but also definitively less than803// or equal to the provided maximum size, then return true. Otherwise, return804// false (constant global values and allocas fall into this category).805//806// FIXME: This should probably live in ValueTracking (or similar).807static bool isObjectSizeLessThanOrEq(Value *V, uint64_t MaxSize,808const DataLayout &DL) {809SmallPtrSet<Value *, 4> Visited;810SmallVector<Value *, 4> Worklist(1, V);811812do {813Value *P = Worklist.pop_back_val();814P = P->stripPointerCasts();815816if (!Visited.insert(P).second)817continue;818819if (SelectInst *SI = dyn_cast<SelectInst>(P)) {820Worklist.push_back(SI->getTrueValue());821Worklist.push_back(SI->getFalseValue());822continue;823}824825if (PHINode *PN = dyn_cast<PHINode>(P)) {826append_range(Worklist, PN->incoming_values());827continue;828}829830if (GlobalAlias *GA = dyn_cast<GlobalAlias>(P)) {831if (GA->isInterposable())832return false;833Worklist.push_back(GA->getAliasee());834continue;835}836837// If we know how big this object is, and it is less than MaxSize, continue838// searching. Otherwise, return false.839if (AllocaInst *AI = dyn_cast<AllocaInst>(P)) {840if (!AI->getAllocatedType()->isSized())841return false;842843ConstantInt *CS = dyn_cast<ConstantInt>(AI->getArraySize());844if (!CS)845return false;846847TypeSize TS = DL.getTypeAllocSize(AI->getAllocatedType());848if (TS.isScalable())849return false;850// Make sure that, even if the multiplication below would wrap as an851// uint64_t, we still do the right thing.852if ((CS->getValue().zext(128) * APInt(128, TS.getFixedValue()))853.ugt(MaxSize))854return false;855continue;856}857858if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {859if (!GV->hasDefinitiveInitializer() || !GV->isConstant())860return false;861862uint64_t InitSize = DL.getTypeAllocSize(GV->getValueType());863if (InitSize > MaxSize)864return false;865continue;866}867868return false;869} while (!Worklist.empty());870871return true;872}873874// If we're indexing into an object of a known size, and the outer index is875// not a constant, but having any value but zero would lead to undefined876// behavior, replace it with zero.877//878// For example, if we have:879// @f.a = private unnamed_addr constant [1 x i32] [i32 12], align 4880// ...881// %arrayidx = getelementptr inbounds [1 x i32]* @f.a, i64 0, i64 %x882// ... = load i32* %arrayidx, align 4883// Then we know that we can replace %x in the GEP with i64 0.884//885// FIXME: We could fold any GEP index to zero that would cause UB if it were886// not zero. Currently, we only handle the first such index. Also, we could887// also search through non-zero constant indices if we kept track of the888// offsets those indices implied.889static bool canReplaceGEPIdxWithZero(InstCombinerImpl &IC,890GetElementPtrInst *GEPI, Instruction *MemI,891unsigned &Idx) {892if (GEPI->getNumOperands() < 2)893return false;894895// Find the first non-zero index of a GEP. If all indices are zero, return896// one past the last index.897auto FirstNZIdx = [](const GetElementPtrInst *GEPI) {898unsigned I = 1;899for (unsigned IE = GEPI->getNumOperands(); I != IE; ++I) {900Value *V = GEPI->getOperand(I);901if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))902if (CI->isZero())903continue;904905break;906}907908return I;909};910911// Skip through initial 'zero' indices, and find the corresponding pointer912// type. See if the next index is not a constant.913Idx = FirstNZIdx(GEPI);914if (Idx == GEPI->getNumOperands())915return false;916if (isa<Constant>(GEPI->getOperand(Idx)))917return false;918919SmallVector<Value *, 4> Ops(GEPI->idx_begin(), GEPI->idx_begin() + Idx);920Type *SourceElementType = GEPI->getSourceElementType();921// Size information about scalable vectors is not available, so we cannot922// deduce whether indexing at n is undefined behaviour or not. Bail out.923if (SourceElementType->isScalableTy())924return false;925926Type *AllocTy = GetElementPtrInst::getIndexedType(SourceElementType, Ops);927if (!AllocTy || !AllocTy->isSized())928return false;929const DataLayout &DL = IC.getDataLayout();930uint64_t TyAllocSize = DL.getTypeAllocSize(AllocTy).getFixedValue();931932// If there are more indices after the one we might replace with a zero, make933// sure they're all non-negative. If any of them are negative, the overall934// address being computed might be before the base address determined by the935// first non-zero index.936auto IsAllNonNegative = [&]() {937for (unsigned i = Idx+1, e = GEPI->getNumOperands(); i != e; ++i) {938KnownBits Known = IC.computeKnownBits(GEPI->getOperand(i), 0, MemI);939if (Known.isNonNegative())940continue;941return false;942}943944return true;945};946947// FIXME: If the GEP is not inbounds, and there are extra indices after the948// one we'll replace, those could cause the address computation to wrap949// (rendering the IsAllNonNegative() check below insufficient). We can do950// better, ignoring zero indices (and other indices we can prove small951// enough not to wrap).952if (Idx+1 != GEPI->getNumOperands() && !GEPI->isInBounds())953return false;954955// Note that isObjectSizeLessThanOrEq will return true only if the pointer is956// also known to be dereferenceable.957return isObjectSizeLessThanOrEq(GEPI->getOperand(0), TyAllocSize, DL) &&958IsAllNonNegative();959}960961// If we're indexing into an object with a variable index for the memory962// access, but the object has only one element, we can assume that the index963// will always be zero. If we replace the GEP, return it.964static Instruction *replaceGEPIdxWithZero(InstCombinerImpl &IC, Value *Ptr,965Instruction &MemI) {966if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr)) {967unsigned Idx;968if (canReplaceGEPIdxWithZero(IC, GEPI, &MemI, Idx)) {969Instruction *NewGEPI = GEPI->clone();970NewGEPI->setOperand(Idx,971ConstantInt::get(GEPI->getOperand(Idx)->getType(), 0));972IC.InsertNewInstBefore(NewGEPI, GEPI->getIterator());973return NewGEPI;974}975}976977return nullptr;978}979980static bool canSimplifyNullStoreOrGEP(StoreInst &SI) {981if (NullPointerIsDefined(SI.getFunction(), SI.getPointerAddressSpace()))982return false;983984auto *Ptr = SI.getPointerOperand();985if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr))986Ptr = GEPI->getOperand(0);987return (isa<ConstantPointerNull>(Ptr) &&988!NullPointerIsDefined(SI.getFunction(), SI.getPointerAddressSpace()));989}990991static bool canSimplifyNullLoadOrGEP(LoadInst &LI, Value *Op) {992if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {993const Value *GEPI0 = GEPI->getOperand(0);994if (isa<ConstantPointerNull>(GEPI0) &&995!NullPointerIsDefined(LI.getFunction(), GEPI->getPointerAddressSpace()))996return true;997}998if (isa<UndefValue>(Op) ||999(isa<ConstantPointerNull>(Op) &&1000!NullPointerIsDefined(LI.getFunction(), LI.getPointerAddressSpace())))1001return true;1002return false;1003}10041005Instruction *InstCombinerImpl::visitLoadInst(LoadInst &LI) {1006Value *Op = LI.getOperand(0);1007if (Value *Res = simplifyLoadInst(&LI, Op, SQ.getWithInstruction(&LI)))1008return replaceInstUsesWith(LI, Res);10091010// Try to canonicalize the loaded type.1011if (Instruction *Res = combineLoadToOperationType(*this, LI))1012return Res;10131014if (!EnableInferAlignmentPass) {1015// Attempt to improve the alignment.1016Align KnownAlign = getOrEnforceKnownAlignment(1017Op, DL.getPrefTypeAlign(LI.getType()), DL, &LI, &AC, &DT);1018if (KnownAlign > LI.getAlign())1019LI.setAlignment(KnownAlign);1020}10211022// Replace GEP indices if possible.1023if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Op, LI))1024return replaceOperand(LI, 0, NewGEPI);10251026if (Instruction *Res = unpackLoadToAggregate(*this, LI))1027return Res;10281029// Do really simple store-to-load forwarding and load CSE, to catch cases1030// where there are several consecutive memory accesses to the same location,1031// separated by a few arithmetic operations.1032bool IsLoadCSE = false;1033BatchAAResults BatchAA(*AA);1034if (Value *AvailableVal = FindAvailableLoadedValue(&LI, BatchAA, &IsLoadCSE)) {1035if (IsLoadCSE)1036combineMetadataForCSE(cast<LoadInst>(AvailableVal), &LI, false);10371038return replaceInstUsesWith(1039LI, Builder.CreateBitOrPointerCast(AvailableVal, LI.getType(),1040LI.getName() + ".cast"));1041}10421043// None of the following transforms are legal for volatile/ordered atomic1044// loads. Most of them do apply for unordered atomics.1045if (!LI.isUnordered()) return nullptr;10461047// load(gep null, ...) -> unreachable1048// load null/undef -> unreachable1049// TODO: Consider a target hook for valid address spaces for this xforms.1050if (canSimplifyNullLoadOrGEP(LI, Op)) {1051CreateNonTerminatorUnreachable(&LI);1052return replaceInstUsesWith(LI, PoisonValue::get(LI.getType()));1053}10541055if (Op->hasOneUse()) {1056// Change select and PHI nodes to select values instead of addresses: this1057// helps alias analysis out a lot, allows many others simplifications, and1058// exposes redundancy in the code.1059//1060// Note that we cannot do the transformation unless we know that the1061// introduced loads cannot trap! Something like this is valid as long as1062// the condition is always false: load (select bool %C, int* null, int* %G),1063// but it would not be valid if we transformed it to load from null1064// unconditionally.1065//1066if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {1067// load (select (Cond, &V1, &V2)) --> select(Cond, load &V1, load &V2).1068Align Alignment = LI.getAlign();1069if (isSafeToLoadUnconditionally(SI->getOperand(1), LI.getType(),1070Alignment, DL, SI) &&1071isSafeToLoadUnconditionally(SI->getOperand(2), LI.getType(),1072Alignment, DL, SI)) {1073LoadInst *V1 =1074Builder.CreateLoad(LI.getType(), SI->getOperand(1),1075SI->getOperand(1)->getName() + ".val");1076LoadInst *V2 =1077Builder.CreateLoad(LI.getType(), SI->getOperand(2),1078SI->getOperand(2)->getName() + ".val");1079assert(LI.isUnordered() && "implied by above");1080V1->setAlignment(Alignment);1081V1->setAtomic(LI.getOrdering(), LI.getSyncScopeID());1082V2->setAlignment(Alignment);1083V2->setAtomic(LI.getOrdering(), LI.getSyncScopeID());1084return SelectInst::Create(SI->getCondition(), V1, V2);1085}10861087// load (select (cond, null, P)) -> load P1088if (isa<ConstantPointerNull>(SI->getOperand(1)) &&1089!NullPointerIsDefined(SI->getFunction(),1090LI.getPointerAddressSpace()))1091return replaceOperand(LI, 0, SI->getOperand(2));10921093// load (select (cond, P, null)) -> load P1094if (isa<ConstantPointerNull>(SI->getOperand(2)) &&1095!NullPointerIsDefined(SI->getFunction(),1096LI.getPointerAddressSpace()))1097return replaceOperand(LI, 0, SI->getOperand(1));1098}1099}1100return nullptr;1101}11021103/// Look for extractelement/insertvalue sequence that acts like a bitcast.1104///1105/// \returns underlying value that was "cast", or nullptr otherwise.1106///1107/// For example, if we have:1108///1109/// %E0 = extractelement <2 x double> %U, i32 01110/// %V0 = insertvalue [2 x double] undef, double %E0, 01111/// %E1 = extractelement <2 x double> %U, i32 11112/// %V1 = insertvalue [2 x double] %V0, double %E1, 11113///1114/// and the layout of a <2 x double> is isomorphic to a [2 x double],1115/// then %V1 can be safely approximated by a conceptual "bitcast" of %U.1116/// Note that %U may contain non-undef values where %V1 has undef.1117static Value *likeBitCastFromVector(InstCombinerImpl &IC, Value *V) {1118Value *U = nullptr;1119while (auto *IV = dyn_cast<InsertValueInst>(V)) {1120auto *E = dyn_cast<ExtractElementInst>(IV->getInsertedValueOperand());1121if (!E)1122return nullptr;1123auto *W = E->getVectorOperand();1124if (!U)1125U = W;1126else if (U != W)1127return nullptr;1128auto *CI = dyn_cast<ConstantInt>(E->getIndexOperand());1129if (!CI || IV->getNumIndices() != 1 || CI->getZExtValue() != *IV->idx_begin())1130return nullptr;1131V = IV->getAggregateOperand();1132}1133if (!match(V, m_Undef()) || !U)1134return nullptr;11351136auto *UT = cast<VectorType>(U->getType());1137auto *VT = V->getType();1138// Check that types UT and VT are bitwise isomorphic.1139const auto &DL = IC.getDataLayout();1140if (DL.getTypeStoreSizeInBits(UT) != DL.getTypeStoreSizeInBits(VT)) {1141return nullptr;1142}1143if (auto *AT = dyn_cast<ArrayType>(VT)) {1144if (AT->getNumElements() != cast<FixedVectorType>(UT)->getNumElements())1145return nullptr;1146} else {1147auto *ST = cast<StructType>(VT);1148if (ST->getNumElements() != cast<FixedVectorType>(UT)->getNumElements())1149return nullptr;1150for (const auto *EltT : ST->elements()) {1151if (EltT != UT->getElementType())1152return nullptr;1153}1154}1155return U;1156}11571158/// Combine stores to match the type of value being stored.1159///1160/// The core idea here is that the memory does not have any intrinsic type and1161/// where we can we should match the type of a store to the type of value being1162/// stored.1163///1164/// However, this routine must never change the width of a store or the number of1165/// stores as that would introduce a semantic change. This combine is expected to1166/// be a semantic no-op which just allows stores to more closely model the types1167/// of their incoming values.1168///1169/// Currently, we also refuse to change the precise type used for an atomic or1170/// volatile store. This is debatable, and might be reasonable to change later.1171/// However, it is risky in case some backend or other part of LLVM is relying1172/// on the exact type stored to select appropriate atomic operations.1173///1174/// \returns true if the store was successfully combined away. This indicates1175/// the caller must erase the store instruction. We have to let the caller erase1176/// the store instruction as otherwise there is no way to signal whether it was1177/// combined or not: IC.EraseInstFromFunction returns a null pointer.1178static bool combineStoreToValueType(InstCombinerImpl &IC, StoreInst &SI) {1179// FIXME: We could probably with some care handle both volatile and ordered1180// atomic stores here but it isn't clear that this is important.1181if (!SI.isUnordered())1182return false;11831184// swifterror values can't be bitcasted.1185if (SI.getPointerOperand()->isSwiftError())1186return false;11871188Value *V = SI.getValueOperand();11891190// Fold away bit casts of the stored value by storing the original type.1191if (auto *BC = dyn_cast<BitCastInst>(V)) {1192assert(!BC->getType()->isX86_AMXTy() &&1193"store to x86_amx* should not happen!");1194V = BC->getOperand(0);1195// Don't transform when the type is x86_amx, it makes the pass that lower1196// x86_amx type happy.1197if (V->getType()->isX86_AMXTy())1198return false;1199if (!SI.isAtomic() || isSupportedAtomicType(V->getType())) {1200combineStoreToNewValue(IC, SI, V);1201return true;1202}1203}12041205if (Value *U = likeBitCastFromVector(IC, V))1206if (!SI.isAtomic() || isSupportedAtomicType(U->getType())) {1207combineStoreToNewValue(IC, SI, U);1208return true;1209}12101211// FIXME: We should also canonicalize stores of vectors when their elements1212// are cast to other types.1213return false;1214}12151216static bool unpackStoreToAggregate(InstCombinerImpl &IC, StoreInst &SI) {1217// FIXME: We could probably with some care handle both volatile and atomic1218// stores here but it isn't clear that this is important.1219if (!SI.isSimple())1220return false;12211222Value *V = SI.getValueOperand();1223Type *T = V->getType();12241225if (!T->isAggregateType())1226return false;12271228if (auto *ST = dyn_cast<StructType>(T)) {1229// If the struct only have one element, we unpack.1230unsigned Count = ST->getNumElements();1231if (Count == 1) {1232V = IC.Builder.CreateExtractValue(V, 0);1233combineStoreToNewValue(IC, SI, V);1234return true;1235}12361237// We don't want to break loads with padding here as we'd loose1238// the knowledge that padding exists for the rest of the pipeline.1239const DataLayout &DL = IC.getDataLayout();1240auto *SL = DL.getStructLayout(ST);12411242// Don't unpack for structure with scalable vector.1243if (SL->getSizeInBits().isScalable())1244return false;12451246if (SL->hasPadding())1247return false;12481249const auto Align = SI.getAlign();12501251SmallString<16> EltName = V->getName();1252EltName += ".elt";1253auto *Addr = SI.getPointerOperand();1254SmallString<16> AddrName = Addr->getName();1255AddrName += ".repack";12561257auto *IdxType = Type::getInt32Ty(ST->getContext());1258auto *Zero = ConstantInt::get(IdxType, 0);1259for (unsigned i = 0; i < Count; i++) {1260Value *Indices[2] = {1261Zero,1262ConstantInt::get(IdxType, i),1263};1264auto *Ptr =1265IC.Builder.CreateInBoundsGEP(ST, Addr, ArrayRef(Indices), AddrName);1266auto *Val = IC.Builder.CreateExtractValue(V, i, EltName);1267auto EltAlign = commonAlignment(Align, SL->getElementOffset(i));1268llvm::Instruction *NS = IC.Builder.CreateAlignedStore(Val, Ptr, EltAlign);1269NS->setAAMetadata(SI.getAAMetadata());1270}12711272return true;1273}12741275if (auto *AT = dyn_cast<ArrayType>(T)) {1276// If the array only have one element, we unpack.1277auto NumElements = AT->getNumElements();1278if (NumElements == 1) {1279V = IC.Builder.CreateExtractValue(V, 0);1280combineStoreToNewValue(IC, SI, V);1281return true;1282}12831284// Bail out if the array is too large. Ideally we would like to optimize1285// arrays of arbitrary size but this has a terrible impact on compile time.1286// The threshold here is chosen arbitrarily, maybe needs a little bit of1287// tuning.1288if (NumElements > IC.MaxArraySizeForCombine)1289return false;12901291const DataLayout &DL = IC.getDataLayout();1292TypeSize EltSize = DL.getTypeAllocSize(AT->getElementType());1293const auto Align = SI.getAlign();12941295SmallString<16> EltName = V->getName();1296EltName += ".elt";1297auto *Addr = SI.getPointerOperand();1298SmallString<16> AddrName = Addr->getName();1299AddrName += ".repack";13001301auto *IdxType = Type::getInt64Ty(T->getContext());1302auto *Zero = ConstantInt::get(IdxType, 0);13031304TypeSize Offset = TypeSize::getZero();1305for (uint64_t i = 0; i < NumElements; i++) {1306Value *Indices[2] = {1307Zero,1308ConstantInt::get(IdxType, i),1309};1310auto *Ptr =1311IC.Builder.CreateInBoundsGEP(AT, Addr, ArrayRef(Indices), AddrName);1312auto *Val = IC.Builder.CreateExtractValue(V, i, EltName);1313auto EltAlign = commonAlignment(Align, Offset.getKnownMinValue());1314Instruction *NS = IC.Builder.CreateAlignedStore(Val, Ptr, EltAlign);1315NS->setAAMetadata(SI.getAAMetadata());1316Offset += EltSize;1317}13181319return true;1320}13211322return false;1323}13241325/// equivalentAddressValues - Test if A and B will obviously have the same1326/// value. This includes recognizing that %t0 and %t1 will have the same1327/// value in code like this:1328/// %t0 = getelementptr \@a, 0, 31329/// store i32 0, i32* %t01330/// %t1 = getelementptr \@a, 0, 31331/// %t2 = load i32* %t11332///1333static bool equivalentAddressValues(Value *A, Value *B) {1334// Test if the values are trivially equivalent.1335if (A == B) return true;13361337// Test if the values come form identical arithmetic instructions.1338// This uses isIdenticalToWhenDefined instead of isIdenticalTo because1339// its only used to compare two uses within the same basic block, which1340// means that they'll always either have the same value or one of them1341// will have an undefined value.1342if (isa<BinaryOperator>(A) ||1343isa<CastInst>(A) ||1344isa<PHINode>(A) ||1345isa<GetElementPtrInst>(A))1346if (Instruction *BI = dyn_cast<Instruction>(B))1347if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))1348return true;13491350// Otherwise they may not be equivalent.1351return false;1352}13531354Instruction *InstCombinerImpl::visitStoreInst(StoreInst &SI) {1355Value *Val = SI.getOperand(0);1356Value *Ptr = SI.getOperand(1);13571358// Try to canonicalize the stored type.1359if (combineStoreToValueType(*this, SI))1360return eraseInstFromFunction(SI);13611362if (!EnableInferAlignmentPass) {1363// Attempt to improve the alignment.1364const Align KnownAlign = getOrEnforceKnownAlignment(1365Ptr, DL.getPrefTypeAlign(Val->getType()), DL, &SI, &AC, &DT);1366if (KnownAlign > SI.getAlign())1367SI.setAlignment(KnownAlign);1368}13691370// Try to canonicalize the stored type.1371if (unpackStoreToAggregate(*this, SI))1372return eraseInstFromFunction(SI);13731374// Replace GEP indices if possible.1375if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Ptr, SI))1376return replaceOperand(SI, 1, NewGEPI);13771378// Don't hack volatile/ordered stores.1379// FIXME: Some bits are legal for ordered atomic stores; needs refactoring.1380if (!SI.isUnordered()) return nullptr;13811382// If the RHS is an alloca with a single use, zapify the store, making the1383// alloca dead.1384if (Ptr->hasOneUse()) {1385if (isa<AllocaInst>(Ptr))1386return eraseInstFromFunction(SI);1387if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {1388if (isa<AllocaInst>(GEP->getOperand(0))) {1389if (GEP->getOperand(0)->hasOneUse())1390return eraseInstFromFunction(SI);1391}1392}1393}13941395// If we have a store to a location which is known constant, we can conclude1396// that the store must be storing the constant value (else the memory1397// wouldn't be constant), and this must be a noop.1398if (!isModSet(AA->getModRefInfoMask(Ptr)))1399return eraseInstFromFunction(SI);14001401// Do really simple DSE, to catch cases where there are several consecutive1402// stores to the same location, separated by a few arithmetic operations. This1403// situation often occurs with bitfield accesses.1404BasicBlock::iterator BBI(SI);1405for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;1406--ScanInsts) {1407--BBI;1408// Don't count debug info directives, lest they affect codegen,1409// and we skip pointer-to-pointer bitcasts, which are NOPs.1410if (BBI->isDebugOrPseudoInst()) {1411ScanInsts++;1412continue;1413}14141415if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {1416// Prev store isn't volatile, and stores to the same location?1417if (PrevSI->isUnordered() &&1418equivalentAddressValues(PrevSI->getOperand(1), SI.getOperand(1)) &&1419PrevSI->getValueOperand()->getType() ==1420SI.getValueOperand()->getType()) {1421++NumDeadStore;1422// Manually add back the original store to the worklist now, so it will1423// be processed after the operands of the removed store, as this may1424// expose additional DSE opportunities.1425Worklist.push(&SI);1426eraseInstFromFunction(*PrevSI);1427return nullptr;1428}1429break;1430}14311432// If this is a load, we have to stop. However, if the loaded value is from1433// the pointer we're loading and is producing the pointer we're storing,1434// then *this* store is dead (X = load P; store X -> P).1435if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {1436if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr)) {1437assert(SI.isUnordered() && "can't eliminate ordering operation");1438return eraseInstFromFunction(SI);1439}14401441// Otherwise, this is a load from some other location. Stores before it1442// may not be dead.1443break;1444}14451446// Don't skip over loads, throws or things that can modify memory.1447if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory() || BBI->mayThrow())1448break;1449}14501451// store X, null -> turns into 'unreachable' in SimplifyCFG1452// store X, GEP(null, Y) -> turns into 'unreachable' in SimplifyCFG1453if (canSimplifyNullStoreOrGEP(SI)) {1454if (!isa<PoisonValue>(Val))1455return replaceOperand(SI, 0, PoisonValue::get(Val->getType()));1456return nullptr; // Do not modify these!1457}14581459// This is a non-terminator unreachable marker. Don't remove it.1460if (isa<UndefValue>(Ptr)) {1461// Remove guaranteed-to-transfer instructions before the marker.1462if (removeInstructionsBeforeUnreachable(SI))1463return &SI;14641465// Remove all instructions after the marker and handle dead blocks this1466// implies.1467SmallVector<BasicBlock *> Worklist;1468handleUnreachableFrom(SI.getNextNode(), Worklist);1469handlePotentiallyDeadBlocks(Worklist);1470return nullptr;1471}14721473// store undef, Ptr -> noop1474// FIXME: This is technically incorrect because it might overwrite a poison1475// value. Change to PoisonValue once #52930 is resolved.1476if (isa<UndefValue>(Val))1477return eraseInstFromFunction(SI);14781479return nullptr;1480}14811482/// Try to transform:1483/// if () { *P = v1; } else { *P = v2 }1484/// or:1485/// *P = v1; if () { *P = v2; }1486/// into a phi node with a store in the successor.1487bool InstCombinerImpl::mergeStoreIntoSuccessor(StoreInst &SI) {1488if (!SI.isUnordered())1489return false; // This code has not been audited for volatile/ordered case.14901491// Check if the successor block has exactly 2 incoming edges.1492BasicBlock *StoreBB = SI.getParent();1493BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);1494if (!DestBB->hasNPredecessors(2))1495return false;14961497// Capture the other block (the block that doesn't contain our store).1498pred_iterator PredIter = pred_begin(DestBB);1499if (*PredIter == StoreBB)1500++PredIter;1501BasicBlock *OtherBB = *PredIter;15021503// Bail out if all of the relevant blocks aren't distinct. This can happen,1504// for example, if SI is in an infinite loop.1505if (StoreBB == DestBB || OtherBB == DestBB)1506return false;15071508// Verify that the other block ends in a branch and is not otherwise empty.1509BasicBlock::iterator BBI(OtherBB->getTerminator());1510BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);1511if (!OtherBr || BBI == OtherBB->begin())1512return false;15131514auto OtherStoreIsMergeable = [&](StoreInst *OtherStore) -> bool {1515if (!OtherStore ||1516OtherStore->getPointerOperand() != SI.getPointerOperand())1517return false;15181519auto *SIVTy = SI.getValueOperand()->getType();1520auto *OSVTy = OtherStore->getValueOperand()->getType();1521return CastInst::isBitOrNoopPointerCastable(OSVTy, SIVTy, DL) &&1522SI.hasSameSpecialState(OtherStore);1523};15241525// If the other block ends in an unconditional branch, check for the 'if then1526// else' case. There is an instruction before the branch.1527StoreInst *OtherStore = nullptr;1528if (OtherBr->isUnconditional()) {1529--BBI;1530// Skip over debugging info and pseudo probes.1531while (BBI->isDebugOrPseudoInst()) {1532if (BBI==OtherBB->begin())1533return false;1534--BBI;1535}1536// If this isn't a store, isn't a store to the same location, or is not the1537// right kind of store, bail out.1538OtherStore = dyn_cast<StoreInst>(BBI);1539if (!OtherStoreIsMergeable(OtherStore))1540return false;1541} else {1542// Otherwise, the other block ended with a conditional branch. If one of the1543// destinations is StoreBB, then we have the if/then case.1544if (OtherBr->getSuccessor(0) != StoreBB &&1545OtherBr->getSuccessor(1) != StoreBB)1546return false;15471548// Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an1549// if/then triangle. See if there is a store to the same ptr as SI that1550// lives in OtherBB.1551for (;; --BBI) {1552// Check to see if we find the matching store.1553OtherStore = dyn_cast<StoreInst>(BBI);1554if (OtherStoreIsMergeable(OtherStore))1555break;15561557// If we find something that may be using or overwriting the stored1558// value, or if we run out of instructions, we can't do the transform.1559if (BBI->mayReadFromMemory() || BBI->mayThrow() ||1560BBI->mayWriteToMemory() || BBI == OtherBB->begin())1561return false;1562}15631564// In order to eliminate the store in OtherBr, we have to make sure nothing1565// reads or overwrites the stored value in StoreBB.1566for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {1567// FIXME: This should really be AA driven.1568if (I->mayReadFromMemory() || I->mayThrow() || I->mayWriteToMemory())1569return false;1570}1571}15721573// Insert a PHI node now if we need it.1574Value *MergedVal = OtherStore->getValueOperand();1575// The debug locations of the original instructions might differ. Merge them.1576DebugLoc MergedLoc = DILocation::getMergedLocation(SI.getDebugLoc(),1577OtherStore->getDebugLoc());1578if (MergedVal != SI.getValueOperand()) {1579PHINode *PN =1580PHINode::Create(SI.getValueOperand()->getType(), 2, "storemerge");1581PN->addIncoming(SI.getValueOperand(), SI.getParent());1582Builder.SetInsertPoint(OtherStore);1583PN->addIncoming(Builder.CreateBitOrPointerCast(MergedVal, PN->getType()),1584OtherBB);1585MergedVal = InsertNewInstBefore(PN, DestBB->begin());1586PN->setDebugLoc(MergedLoc);1587}15881589// Advance to a place where it is safe to insert the new store and insert it.1590BBI = DestBB->getFirstInsertionPt();1591StoreInst *NewSI =1592new StoreInst(MergedVal, SI.getOperand(1), SI.isVolatile(), SI.getAlign(),1593SI.getOrdering(), SI.getSyncScopeID());1594InsertNewInstBefore(NewSI, BBI);1595NewSI->setDebugLoc(MergedLoc);1596NewSI->mergeDIAssignID({&SI, OtherStore});15971598// If the two stores had AA tags, merge them.1599AAMDNodes AATags = SI.getAAMetadata();1600if (AATags)1601NewSI->setAAMetadata(AATags.merge(OtherStore->getAAMetadata()));16021603// Nuke the old stores.1604eraseInstFromFunction(SI);1605eraseInstFromFunction(*OtherStore);1606return true;1607}160816091610