LLVM API Documentation

InstCombineLoadStoreAlloca.cpp
Go to the documentation of this file.
00001 //===- InstCombineLoadStoreAlloca.cpp -------------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the visit functions for load, store and alloca.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "InstCombine.h"
00015 #include "llvm/ADT/Statistic.h"
00016 #include "llvm/Analysis/Loads.h"
00017 #include "llvm/IR/DataLayout.h"
00018 #include "llvm/IR/LLVMContext.h"
00019 #include "llvm/IR/IntrinsicInst.h"
00020 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00021 #include "llvm/Transforms/Utils/Local.h"
00022 using namespace llvm;
00023 
00024 #define DEBUG_TYPE "instcombine"
00025 
00026 STATISTIC(NumDeadStore,    "Number of dead stores eliminated");
00027 STATISTIC(NumGlobalCopies, "Number of allocas copied from constant global");
00028 
00029 /// pointsToConstantGlobal - Return true if V (possibly indirectly) points to
00030 /// some part of a constant global variable.  This intentionally only accepts
00031 /// constant expressions because we can't rewrite arbitrary instructions.
00032 static bool pointsToConstantGlobal(Value *V) {
00033   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
00034     return GV->isConstant();
00035 
00036   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
00037     if (CE->getOpcode() == Instruction::BitCast ||
00038         CE->getOpcode() == Instruction::AddrSpaceCast ||
00039         CE->getOpcode() == Instruction::GetElementPtr)
00040       return pointsToConstantGlobal(CE->getOperand(0));
00041   }
00042   return false;
00043 }
00044 
00045 /// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
00046 /// pointer to an alloca.  Ignore any reads of the pointer, return false if we
00047 /// see any stores or other unknown uses.  If we see pointer arithmetic, keep
00048 /// track of whether it moves the pointer (with IsOffset) but otherwise traverse
00049 /// the uses.  If we see a memcpy/memmove that targets an unoffseted pointer to
00050 /// the alloca, and if the source pointer is a pointer to a constant global, we
00051 /// can optimize this.
00052 static bool
00053 isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
00054                                SmallVectorImpl<Instruction *> &ToDelete) {
00055   // We track lifetime intrinsics as we encounter them.  If we decide to go
00056   // ahead and replace the value with the global, this lets the caller quickly
00057   // eliminate the markers.
00058 
00059   SmallVector<std::pair<Value *, bool>, 35> ValuesToInspect;
00060   ValuesToInspect.push_back(std::make_pair(V, false));
00061   while (!ValuesToInspect.empty()) {
00062     auto ValuePair = ValuesToInspect.pop_back_val();
00063     const bool IsOffset = ValuePair.second;
00064     for (auto &U : ValuePair.first->uses()) {
00065       Instruction *I = cast<Instruction>(U.getUser());
00066 
00067       if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
00068         // Ignore non-volatile loads, they are always ok.
00069         if (!LI->isSimple()) return false;
00070         continue;
00071       }
00072 
00073       if (isa<BitCastInst>(I) || isa<AddrSpaceCastInst>(I)) {
00074         // If uses of the bitcast are ok, we are ok.
00075         ValuesToInspect.push_back(std::make_pair(I, IsOffset));
00076         continue;
00077       }
00078       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
00079         // If the GEP has all zero indices, it doesn't offset the pointer. If it
00080         // doesn't, it does.
00081         ValuesToInspect.push_back(
00082             std::make_pair(I, IsOffset || !GEP->hasAllZeroIndices()));
00083         continue;
00084       }
00085 
00086       if (CallSite CS = I) {
00087         // If this is the function being called then we treat it like a load and
00088         // ignore it.
00089         if (CS.isCallee(&U))
00090           continue;
00091 
00092         // Inalloca arguments are clobbered by the call.
00093         unsigned ArgNo = CS.getArgumentNo(&U);
00094         if (CS.isInAllocaArgument(ArgNo))
00095           return false;
00096 
00097         // If this is a readonly/readnone call site, then we know it is just a
00098         // load (but one that potentially returns the value itself), so we can
00099         // ignore it if we know that the value isn't captured.
00100         if (CS.onlyReadsMemory() &&
00101             (CS.getInstruction()->use_empty() || CS.doesNotCapture(ArgNo)))
00102           continue;
00103 
00104         // If this is being passed as a byval argument, the caller is making a
00105         // copy, so it is only a read of the alloca.
00106         if (CS.isByValArgument(ArgNo))
00107           continue;
00108       }
00109 
00110       // Lifetime intrinsics can be handled by the caller.
00111       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
00112         if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
00113             II->getIntrinsicID() == Intrinsic::lifetime_end) {
00114           assert(II->use_empty() && "Lifetime markers have no result to use!");
00115           ToDelete.push_back(II);
00116           continue;
00117         }
00118       }
00119 
00120       // If this is isn't our memcpy/memmove, reject it as something we can't
00121       // handle.
00122       MemTransferInst *MI = dyn_cast<MemTransferInst>(I);
00123       if (!MI)
00124         return false;
00125 
00126       // If the transfer is using the alloca as a source of the transfer, then
00127       // ignore it since it is a load (unless the transfer is volatile).
00128       if (U.getOperandNo() == 1) {
00129         if (MI->isVolatile()) return false;
00130         continue;
00131       }
00132 
00133       // If we already have seen a copy, reject the second one.
00134       if (TheCopy) return false;
00135 
00136       // If the pointer has been offset from the start of the alloca, we can't
00137       // safely handle this.
00138       if (IsOffset) return false;
00139 
00140       // If the memintrinsic isn't using the alloca as the dest, reject it.
00141       if (U.getOperandNo() != 0) return false;
00142 
00143       // If the source of the memcpy/move is not a constant global, reject it.
00144       if (!pointsToConstantGlobal(MI->getSource()))
00145         return false;
00146 
00147       // Otherwise, the transform is safe.  Remember the copy instruction.
00148       TheCopy = MI;
00149     }
00150   }
00151   return true;
00152 }
00153 
00154 /// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
00155 /// modified by a copy from a constant global.  If we can prove this, we can
00156 /// replace any uses of the alloca with uses of the global directly.
00157 static MemTransferInst *
00158 isOnlyCopiedFromConstantGlobal(AllocaInst *AI,
00159                                SmallVectorImpl<Instruction *> &ToDelete) {
00160   MemTransferInst *TheCopy = nullptr;
00161   if (isOnlyCopiedFromConstantGlobal(AI, TheCopy, ToDelete))
00162     return TheCopy;
00163   return nullptr;
00164 }
00165 
00166 Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
00167   // Ensure that the alloca array size argument has type intptr_t, so that
00168   // any casting is exposed early.
00169   if (DL) {
00170     Type *IntPtrTy = DL->getIntPtrType(AI.getType());
00171     if (AI.getArraySize()->getType() != IntPtrTy) {
00172       Value *V = Builder->CreateIntCast(AI.getArraySize(),
00173                                         IntPtrTy, false);
00174       AI.setOperand(0, V);
00175       return &AI;
00176     }
00177   }
00178 
00179   // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
00180   if (AI.isArrayAllocation()) {  // Check C != 1
00181     if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
00182       Type *NewTy =
00183         ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
00184       AllocaInst *New = Builder->CreateAlloca(NewTy, nullptr, AI.getName());
00185       New->setAlignment(AI.getAlignment());
00186 
00187       // Scan to the end of the allocation instructions, to skip over a block of
00188       // allocas if possible...also skip interleaved debug info
00189       //
00190       BasicBlock::iterator It = New;
00191       while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It)) ++It;
00192 
00193       // Now that I is pointing to the first non-allocation-inst in the block,
00194       // insert our getelementptr instruction...
00195       //
00196       Type *IdxTy = DL
00197                   ? DL->getIntPtrType(AI.getType())
00198                   : Type::getInt64Ty(AI.getContext());
00199       Value *NullIdx = Constant::getNullValue(IdxTy);
00200       Value *Idx[2] = { NullIdx, NullIdx };
00201       Instruction *GEP =
00202         GetElementPtrInst::CreateInBounds(New, Idx, New->getName() + ".sub");
00203       InsertNewInstBefore(GEP, *It);
00204 
00205       // Now make everything use the getelementptr instead of the original
00206       // allocation.
00207       return ReplaceInstUsesWith(AI, GEP);
00208     } else if (isa<UndefValue>(AI.getArraySize())) {
00209       return ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
00210     }
00211   }
00212 
00213   if (DL && AI.getAllocatedType()->isSized()) {
00214     // If the alignment is 0 (unspecified), assign it the preferred alignment.
00215     if (AI.getAlignment() == 0)
00216       AI.setAlignment(DL->getPrefTypeAlignment(AI.getAllocatedType()));
00217 
00218     // Move all alloca's of zero byte objects to the entry block and merge them
00219     // together.  Note that we only do this for alloca's, because malloc should
00220     // allocate and return a unique pointer, even for a zero byte allocation.
00221     if (DL->getTypeAllocSize(AI.getAllocatedType()) == 0) {
00222       // For a zero sized alloca there is no point in doing an array allocation.
00223       // This is helpful if the array size is a complicated expression not used
00224       // elsewhere.
00225       if (AI.isArrayAllocation()) {
00226         AI.setOperand(0, ConstantInt::get(AI.getArraySize()->getType(), 1));
00227         return &AI;
00228       }
00229 
00230       // Get the first instruction in the entry block.
00231       BasicBlock &EntryBlock = AI.getParent()->getParent()->getEntryBlock();
00232       Instruction *FirstInst = EntryBlock.getFirstNonPHIOrDbg();
00233       if (FirstInst != &AI) {
00234         // If the entry block doesn't start with a zero-size alloca then move
00235         // this one to the start of the entry block.  There is no problem with
00236         // dominance as the array size was forced to a constant earlier already.
00237         AllocaInst *EntryAI = dyn_cast<AllocaInst>(FirstInst);
00238         if (!EntryAI || !EntryAI->getAllocatedType()->isSized() ||
00239             DL->getTypeAllocSize(EntryAI->getAllocatedType()) != 0) {
00240           AI.moveBefore(FirstInst);
00241           return &AI;
00242         }
00243 
00244         // If the alignment of the entry block alloca is 0 (unspecified),
00245         // assign it the preferred alignment.
00246         if (EntryAI->getAlignment() == 0)
00247           EntryAI->setAlignment(
00248             DL->getPrefTypeAlignment(EntryAI->getAllocatedType()));
00249         // Replace this zero-sized alloca with the one at the start of the entry
00250         // block after ensuring that the address will be aligned enough for both
00251         // types.
00252         unsigned MaxAlign = std::max(EntryAI->getAlignment(),
00253                                      AI.getAlignment());
00254         EntryAI->setAlignment(MaxAlign);
00255         if (AI.getType() != EntryAI->getType())
00256           return new BitCastInst(EntryAI, AI.getType());
00257         return ReplaceInstUsesWith(AI, EntryAI);
00258       }
00259     }
00260   }
00261 
00262   if (AI.getAlignment()) {
00263     // Check to see if this allocation is only modified by a memcpy/memmove from
00264     // a constant global whose alignment is equal to or exceeds that of the
00265     // allocation.  If this is the case, we can change all users to use
00266     // the constant global instead.  This is commonly produced by the CFE by
00267     // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
00268     // is only subsequently read.
00269     SmallVector<Instruction *, 4> ToDelete;
00270     if (MemTransferInst *Copy = isOnlyCopiedFromConstantGlobal(&AI, ToDelete)) {
00271       unsigned SourceAlign = getOrEnforceKnownAlignment(Copy->getSource(),
00272                                                         AI.getAlignment(),
00273                                                         DL, AT, &AI, DT);
00274       if (AI.getAlignment() <= SourceAlign) {
00275         DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n');
00276         DEBUG(dbgs() << "  memcpy = " << *Copy << '\n');
00277         for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
00278           EraseInstFromFunction(*ToDelete[i]);
00279         Constant *TheSrc = cast<Constant>(Copy->getSource());
00280         Constant *Cast
00281           = ConstantExpr::getPointerBitCastOrAddrSpaceCast(TheSrc, AI.getType());
00282         Instruction *NewI = ReplaceInstUsesWith(AI, Cast);
00283         EraseInstFromFunction(*Copy);
00284         ++NumGlobalCopies;
00285         return NewI;
00286       }
00287     }
00288   }
00289 
00290   // At last, use the generic allocation site handler to aggressively remove
00291   // unused allocas.
00292   return visitAllocSite(AI);
00293 }
00294 
00295 /// \brief Helper to combine a load to a new type.
00296 ///
00297 /// This just does the work of combining a load to a new type. It handles
00298 /// metadata, etc., and returns the new instruction. The \c NewTy should be the
00299 /// loaded *value* type. This will convert it to a pointer, cast the operand to
00300 /// that pointer type, load it, etc.
00301 ///
00302 /// Note that this will create all of the instructions with whatever insert
00303 /// point the \c InstCombiner currently is using.
00304 static LoadInst *combineLoadToNewType(InstCombiner &IC, LoadInst &LI, Type *NewTy) {
00305   Value *Ptr = LI.getPointerOperand();
00306   unsigned AS = LI.getPointerAddressSpace();
00307   SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
00308   LI.getAllMetadata(MD);
00309 
00310   LoadInst *NewLoad = IC.Builder->CreateAlignedLoad(
00311       IC.Builder->CreateBitCast(Ptr, NewTy->getPointerTo(AS)),
00312       LI.getAlignment(), LI.getName());
00313   for (const auto &MDPair : MD) {
00314     unsigned ID = MDPair.first;
00315     MDNode *N = MDPair.second;
00316     // Note, essentially every kind of metadata should be preserved here! This
00317     // routine is supposed to clone a load instruction changing *only its type*.
00318     // The only metadata it makes sense to drop is metadata which is invalidated
00319     // when the pointer type changes. This should essentially never be the case
00320     // in LLVM, but we explicitly switch over only known metadata to be
00321     // conservatively correct. If you are adding metadata to LLVM which pertains
00322     // to loads, you almost certainly want to add it here.
00323     switch (ID) {
00324     case LLVMContext::MD_dbg:
00325     case LLVMContext::MD_tbaa:
00326     case LLVMContext::MD_prof:
00327     case LLVMContext::MD_fpmath:
00328     case LLVMContext::MD_tbaa_struct:
00329     case LLVMContext::MD_invariant_load:
00330     case LLVMContext::MD_alias_scope:
00331     case LLVMContext::MD_noalias:
00332     case LLVMContext::MD_nontemporal:
00333     case LLVMContext::MD_mem_parallel_loop_access:
00334     case LLVMContext::MD_nonnull:
00335       // All of these directly apply.
00336       NewLoad->setMetadata(ID, N);
00337       break;
00338 
00339     case LLVMContext::MD_range:
00340       // FIXME: It would be nice to propagate this in some way, but the type
00341       // conversions make it hard.
00342       break;
00343     }
00344   }
00345   return NewLoad;
00346 }
00347 
00348 /// \brief Combine loads to match the type of value their uses after looking
00349 /// through intervening bitcasts.
00350 ///
00351 /// The core idea here is that if the result of a load is used in an operation,
00352 /// we should load the type most conducive to that operation. For example, when
00353 /// loading an integer and converting that immediately to a pointer, we should
00354 /// instead directly load a pointer.
00355 ///
00356 /// However, this routine must never change the width of a load or the number of
00357 /// loads as that would introduce a semantic change. This combine is expected to
00358 /// be a semantic no-op which just allows loads to more closely model the types
00359 /// of their consuming operations.
00360 ///
00361 /// Currently, we also refuse to change the precise type used for an atomic load
00362 /// or a volatile load. This is debatable, and might be reasonable to change
00363 /// later. However, it is risky in case some backend or other part of LLVM is
00364 /// relying on the exact type loaded to select appropriate atomic operations.
00365 static Instruction *combineLoadToOperationType(InstCombiner &IC, LoadInst &LI) {
00366   // FIXME: We could probably with some care handle both volatile and atomic
00367   // loads here but it isn't clear that this is important.
00368   if (!LI.isSimple())
00369     return nullptr;
00370 
00371   if (LI.use_empty())
00372     return nullptr;
00373 
00374 
00375   // Fold away bit casts of the loaded value by loading the desired type.
00376   if (LI.hasOneUse())
00377     if (auto *BC = dyn_cast<BitCastInst>(LI.user_back())) {
00378       LoadInst *NewLoad = combineLoadToNewType(IC, LI, BC->getDestTy());
00379       BC->replaceAllUsesWith(NewLoad);
00380       IC.EraseInstFromFunction(*BC);
00381       return &LI;
00382     }
00383 
00384   // FIXME: We should also canonicalize loads of vectors when their elements are
00385   // cast to other types.
00386   return nullptr;
00387 }
00388 
00389 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
00390   Value *Op = LI.getOperand(0);
00391 
00392   // Try to canonicalize the loaded type.
00393   if (Instruction *Res = combineLoadToOperationType(*this, LI))
00394     return Res;
00395 
00396   // Attempt to improve the alignment.
00397   if (DL) {
00398     unsigned KnownAlign =
00399       getOrEnforceKnownAlignment(Op, DL->getPrefTypeAlignment(LI.getType()),
00400                                  DL, AT, &LI, DT);
00401     unsigned LoadAlign = LI.getAlignment();
00402     unsigned EffectiveLoadAlign = LoadAlign != 0 ? LoadAlign :
00403       DL->getABITypeAlignment(LI.getType());
00404 
00405     if (KnownAlign > EffectiveLoadAlign)
00406       LI.setAlignment(KnownAlign);
00407     else if (LoadAlign == 0)
00408       LI.setAlignment(EffectiveLoadAlign);
00409   }
00410 
00411   // None of the following transforms are legal for volatile/atomic loads.
00412   // FIXME: Some of it is okay for atomic loads; needs refactoring.
00413   if (!LI.isSimple()) return nullptr;
00414 
00415   // Do really simple store-to-load forwarding and load CSE, to catch cases
00416   // where there are several consecutive memory accesses to the same location,
00417   // separated by a few arithmetic operations.
00418   BasicBlock::iterator BBI = &LI;
00419   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
00420     return ReplaceInstUsesWith(
00421         LI, Builder->CreateBitOrPointerCast(AvailableVal, LI.getType(),
00422                                             LI.getName() + ".cast"));
00423 
00424   // load(gep null, ...) -> unreachable
00425   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
00426     const Value *GEPI0 = GEPI->getOperand(0);
00427     // TODO: Consider a target hook for valid address spaces for this xform.
00428     if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
00429       // Insert a new store to null instruction before the load to indicate
00430       // that this code is not reachable.  We do this instead of inserting
00431       // an unreachable instruction directly because we cannot modify the
00432       // CFG.
00433       new StoreInst(UndefValue::get(LI.getType()),
00434                     Constant::getNullValue(Op->getType()), &LI);
00435       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
00436     }
00437   }
00438 
00439   // load null/undef -> unreachable
00440   // TODO: Consider a target hook for valid address spaces for this xform.
00441   if (isa<UndefValue>(Op) ||
00442       (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
00443     // Insert a new store to null instruction before the load to indicate that
00444     // this code is not reachable.  We do this instead of inserting an
00445     // unreachable instruction directly because we cannot modify the CFG.
00446     new StoreInst(UndefValue::get(LI.getType()),
00447                   Constant::getNullValue(Op->getType()), &LI);
00448     return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
00449   }
00450 
00451   if (Op->hasOneUse()) {
00452     // Change select and PHI nodes to select values instead of addresses: this
00453     // helps alias analysis out a lot, allows many others simplifications, and
00454     // exposes redundancy in the code.
00455     //
00456     // Note that we cannot do the transformation unless we know that the
00457     // introduced loads cannot trap!  Something like this is valid as long as
00458     // the condition is always false: load (select bool %C, int* null, int* %G),
00459     // but it would not be valid if we transformed it to load from null
00460     // unconditionally.
00461     //
00462     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
00463       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
00464       unsigned Align = LI.getAlignment();
00465       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI, Align, DL) &&
00466           isSafeToLoadUnconditionally(SI->getOperand(2), SI, Align, DL)) {
00467         LoadInst *V1 = Builder->CreateLoad(SI->getOperand(1),
00468                                            SI->getOperand(1)->getName()+".val");
00469         LoadInst *V2 = Builder->CreateLoad(SI->getOperand(2),
00470                                            SI->getOperand(2)->getName()+".val");
00471         V1->setAlignment(Align);
00472         V2->setAlignment(Align);
00473         return SelectInst::Create(SI->getCondition(), V1, V2);
00474       }
00475 
00476       // load (select (cond, null, P)) -> load P
00477       if (Constant *C = dyn_cast<Constant>(SI->getOperand(1)))
00478         if (C->isNullValue()) {
00479           LI.setOperand(0, SI->getOperand(2));
00480           return &LI;
00481         }
00482 
00483       // load (select (cond, P, null)) -> load P
00484       if (Constant *C = dyn_cast<Constant>(SI->getOperand(2)))
00485         if (C->isNullValue()) {
00486           LI.setOperand(0, SI->getOperand(1));
00487           return &LI;
00488         }
00489     }
00490   }
00491   return nullptr;
00492 }
00493 
00494 /// \brief Combine stores to match the type of value being stored.
00495 ///
00496 /// The core idea here is that the memory does not have any intrinsic type and
00497 /// where we can we should match the type of a store to the type of value being
00498 /// stored.
00499 ///
00500 /// However, this routine must never change the width of a store or the number of
00501 /// stores as that would introduce a semantic change. This combine is expected to
00502 /// be a semantic no-op which just allows stores to more closely model the types
00503 /// of their incoming values.
00504 ///
00505 /// Currently, we also refuse to change the precise type used for an atomic or
00506 /// volatile store. This is debatable, and might be reasonable to change later.
00507 /// However, it is risky in case some backend or other part of LLVM is relying
00508 /// on the exact type stored to select appropriate atomic operations.
00509 ///
00510 /// \returns true if the store was successfully combined away. This indicates
00511 /// the caller must erase the store instruction. We have to let the caller erase
00512 /// the store instruction sas otherwise there is no way to signal whether it was
00513 /// combined or not: IC.EraseInstFromFunction returns a null pointer.
00514 static bool combineStoreToValueType(InstCombiner &IC, StoreInst &SI) {
00515   // FIXME: We could probably with some care handle both volatile and atomic
00516   // stores here but it isn't clear that this is important.
00517   if (!SI.isSimple())
00518     return false;
00519 
00520   Value *Ptr = SI.getPointerOperand();
00521   Value *V = SI.getValueOperand();
00522   unsigned AS = SI.getPointerAddressSpace();
00523   SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
00524   SI.getAllMetadata(MD);
00525 
00526   // Fold away bit casts of the stored value by storing the original type.
00527   if (auto *BC = dyn_cast<BitCastInst>(V)) {
00528     V = BC->getOperand(0);
00529     StoreInst *NewStore = IC.Builder->CreateAlignedStore(
00530         V, IC.Builder->CreateBitCast(Ptr, V->getType()->getPointerTo(AS)),
00531         SI.getAlignment());
00532     for (const auto &MDPair : MD) {
00533       unsigned ID = MDPair.first;
00534       MDNode *N = MDPair.second;
00535       // Note, essentially every kind of metadata should be preserved here! This
00536       // routine is supposed to clone a store instruction changing *only its
00537       // type*. The only metadata it makes sense to drop is metadata which is
00538       // invalidated when the pointer type changes. This should essentially
00539       // never be the case in LLVM, but we explicitly switch over only known
00540       // metadata to be conservatively correct. If you are adding metadata to
00541       // LLVM which pertains to stores, you almost certainly want to add it
00542       // here.
00543       switch (ID) {
00544       case LLVMContext::MD_dbg:
00545       case LLVMContext::MD_tbaa:
00546       case LLVMContext::MD_prof:
00547       case LLVMContext::MD_fpmath:
00548       case LLVMContext::MD_tbaa_struct:
00549       case LLVMContext::MD_alias_scope:
00550       case LLVMContext::MD_noalias:
00551       case LLVMContext::MD_nontemporal:
00552       case LLVMContext::MD_mem_parallel_loop_access:
00553       case LLVMContext::MD_nonnull:
00554         // All of these directly apply.
00555         NewStore->setMetadata(ID, N);
00556         break;
00557 
00558       case LLVMContext::MD_invariant_load:
00559       case LLVMContext::MD_range:
00560         break;
00561       }
00562     }
00563     return true;
00564   }
00565 
00566   // FIXME: We should also canonicalize loads of vectors when their elements are
00567   // cast to other types.
00568   return false;
00569 }
00570 
00571 /// equivalentAddressValues - Test if A and B will obviously have the same
00572 /// value. This includes recognizing that %t0 and %t1 will have the same
00573 /// value in code like this:
00574 ///   %t0 = getelementptr \@a, 0, 3
00575 ///   store i32 0, i32* %t0
00576 ///   %t1 = getelementptr \@a, 0, 3
00577 ///   %t2 = load i32* %t1
00578 ///
00579 static bool equivalentAddressValues(Value *A, Value *B) {
00580   // Test if the values are trivially equivalent.
00581   if (A == B) return true;
00582 
00583   // Test if the values come form identical arithmetic instructions.
00584   // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
00585   // its only used to compare two uses within the same basic block, which
00586   // means that they'll always either have the same value or one of them
00587   // will have an undefined value.
00588   if (isa<BinaryOperator>(A) ||
00589       isa<CastInst>(A) ||
00590       isa<PHINode>(A) ||
00591       isa<GetElementPtrInst>(A))
00592     if (Instruction *BI = dyn_cast<Instruction>(B))
00593       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
00594         return true;
00595 
00596   // Otherwise they may not be equivalent.
00597   return false;
00598 }
00599 
00600 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
00601   Value *Val = SI.getOperand(0);
00602   Value *Ptr = SI.getOperand(1);
00603 
00604   // Try to canonicalize the stored type.
00605   if (combineStoreToValueType(*this, SI))
00606     return EraseInstFromFunction(SI);
00607 
00608   // Attempt to improve the alignment.
00609   if (DL) {
00610     unsigned KnownAlign =
00611       getOrEnforceKnownAlignment(Ptr, DL->getPrefTypeAlignment(Val->getType()),
00612                                  DL, AT, &SI, DT);
00613     unsigned StoreAlign = SI.getAlignment();
00614     unsigned EffectiveStoreAlign = StoreAlign != 0 ? StoreAlign :
00615       DL->getABITypeAlignment(Val->getType());
00616 
00617     if (KnownAlign > EffectiveStoreAlign)
00618       SI.setAlignment(KnownAlign);
00619     else if (StoreAlign == 0)
00620       SI.setAlignment(EffectiveStoreAlign);
00621   }
00622 
00623   // Don't hack volatile/atomic stores.
00624   // FIXME: Some bits are legal for atomic stores; needs refactoring.
00625   if (!SI.isSimple()) return nullptr;
00626 
00627   // If the RHS is an alloca with a single use, zapify the store, making the
00628   // alloca dead.
00629   if (Ptr->hasOneUse()) {
00630     if (isa<AllocaInst>(Ptr))
00631       return EraseInstFromFunction(SI);
00632     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
00633       if (isa<AllocaInst>(GEP->getOperand(0))) {
00634         if (GEP->getOperand(0)->hasOneUse())
00635           return EraseInstFromFunction(SI);
00636       }
00637     }
00638   }
00639 
00640   // Do really simple DSE, to catch cases where there are several consecutive
00641   // stores to the same location, separated by a few arithmetic operations. This
00642   // situation often occurs with bitfield accesses.
00643   BasicBlock::iterator BBI = &SI;
00644   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
00645        --ScanInsts) {
00646     --BBI;
00647     // Don't count debug info directives, lest they affect codegen,
00648     // and we skip pointer-to-pointer bitcasts, which are NOPs.
00649     if (isa<DbgInfoIntrinsic>(BBI) ||
00650         (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
00651       ScanInsts++;
00652       continue;
00653     }
00654 
00655     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
00656       // Prev store isn't volatile, and stores to the same location?
00657       if (PrevSI->isSimple() && equivalentAddressValues(PrevSI->getOperand(1),
00658                                                         SI.getOperand(1))) {
00659         ++NumDeadStore;
00660         ++BBI;
00661         EraseInstFromFunction(*PrevSI);
00662         continue;
00663       }
00664       break;
00665     }
00666 
00667     // If this is a load, we have to stop.  However, if the loaded value is from
00668     // the pointer we're loading and is producing the pointer we're storing,
00669     // then *this* store is dead (X = load P; store X -> P).
00670     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
00671       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
00672           LI->isSimple())
00673         return EraseInstFromFunction(SI);
00674 
00675       // Otherwise, this is a load from some other location.  Stores before it
00676       // may not be dead.
00677       break;
00678     }
00679 
00680     // Don't skip over loads or things that can modify memory.
00681     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
00682       break;
00683   }
00684 
00685   // store X, null    -> turns into 'unreachable' in SimplifyCFG
00686   if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
00687     if (!isa<UndefValue>(Val)) {
00688       SI.setOperand(0, UndefValue::get(Val->getType()));
00689       if (Instruction *U = dyn_cast<Instruction>(Val))
00690         Worklist.Add(U);  // Dropped a use.
00691     }
00692     return nullptr;  // Do not modify these!
00693   }
00694 
00695   // store undef, Ptr -> noop
00696   if (isa<UndefValue>(Val))
00697     return EraseInstFromFunction(SI);
00698 
00699   // If this store is the last instruction in the basic block (possibly
00700   // excepting debug info instructions), and if the block ends with an
00701   // unconditional branch, try to move it to the successor block.
00702   BBI = &SI;
00703   do {
00704     ++BBI;
00705   } while (isa<DbgInfoIntrinsic>(BBI) ||
00706            (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()));
00707   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
00708     if (BI->isUnconditional())
00709       if (SimplifyStoreAtEndOfBlock(SI))
00710         return nullptr;  // xform done!
00711 
00712   return nullptr;
00713 }
00714 
00715 /// SimplifyStoreAtEndOfBlock - Turn things like:
00716 ///   if () { *P = v1; } else { *P = v2 }
00717 /// into a phi node with a store in the successor.
00718 ///
00719 /// Simplify things like:
00720 ///   *P = v1; if () { *P = v2; }
00721 /// into a phi node with a store in the successor.
00722 ///
00723 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
00724   BasicBlock *StoreBB = SI.getParent();
00725 
00726   // Check to see if the successor block has exactly two incoming edges.  If
00727   // so, see if the other predecessor contains a store to the same location.
00728   // if so, insert a PHI node (if needed) and move the stores down.
00729   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
00730 
00731   // Determine whether Dest has exactly two predecessors and, if so, compute
00732   // the other predecessor.
00733   pred_iterator PI = pred_begin(DestBB);
00734   BasicBlock *P = *PI;
00735   BasicBlock *OtherBB = nullptr;
00736 
00737   if (P != StoreBB)
00738     OtherBB = P;
00739 
00740   if (++PI == pred_end(DestBB))
00741     return false;
00742 
00743   P = *PI;
00744   if (P != StoreBB) {
00745     if (OtherBB)
00746       return false;
00747     OtherBB = P;
00748   }
00749   if (++PI != pred_end(DestBB))
00750     return false;
00751 
00752   // Bail out if all the relevant blocks aren't distinct (this can happen,
00753   // for example, if SI is in an infinite loop)
00754   if (StoreBB == DestBB || OtherBB == DestBB)
00755     return false;
00756 
00757   // Verify that the other block ends in a branch and is not otherwise empty.
00758   BasicBlock::iterator BBI = OtherBB->getTerminator();
00759   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
00760   if (!OtherBr || BBI == OtherBB->begin())
00761     return false;
00762 
00763   // If the other block ends in an unconditional branch, check for the 'if then
00764   // else' case.  there is an instruction before the branch.
00765   StoreInst *OtherStore = nullptr;
00766   if (OtherBr->isUnconditional()) {
00767     --BBI;
00768     // Skip over debugging info.
00769     while (isa<DbgInfoIntrinsic>(BBI) ||
00770            (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
00771       if (BBI==OtherBB->begin())
00772         return false;
00773       --BBI;
00774     }
00775     // If this isn't a store, isn't a store to the same location, or is not the
00776     // right kind of store, bail out.
00777     OtherStore = dyn_cast<StoreInst>(BBI);
00778     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
00779         !SI.isSameOperationAs(OtherStore))
00780       return false;
00781   } else {
00782     // Otherwise, the other block ended with a conditional branch. If one of the
00783     // destinations is StoreBB, then we have the if/then case.
00784     if (OtherBr->getSuccessor(0) != StoreBB &&
00785         OtherBr->getSuccessor(1) != StoreBB)
00786       return false;
00787 
00788     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
00789     // if/then triangle.  See if there is a store to the same ptr as SI that
00790     // lives in OtherBB.
00791     for (;; --BBI) {
00792       // Check to see if we find the matching store.
00793       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
00794         if (OtherStore->getOperand(1) != SI.getOperand(1) ||
00795             !SI.isSameOperationAs(OtherStore))
00796           return false;
00797         break;
00798       }
00799       // If we find something that may be using or overwriting the stored
00800       // value, or if we run out of instructions, we can't do the xform.
00801       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
00802           BBI == OtherBB->begin())
00803         return false;
00804     }
00805 
00806     // In order to eliminate the store in OtherBr, we have to
00807     // make sure nothing reads or overwrites the stored value in
00808     // StoreBB.
00809     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
00810       // FIXME: This should really be AA driven.
00811       if (I->mayReadFromMemory() || I->mayWriteToMemory())
00812         return false;
00813     }
00814   }
00815 
00816   // Insert a PHI node now if we need it.
00817   Value *MergedVal = OtherStore->getOperand(0);
00818   if (MergedVal != SI.getOperand(0)) {
00819     PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge");
00820     PN->addIncoming(SI.getOperand(0), SI.getParent());
00821     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
00822     MergedVal = InsertNewInstBefore(PN, DestBB->front());
00823   }
00824 
00825   // Advance to a place where it is safe to insert the new store and
00826   // insert it.
00827   BBI = DestBB->getFirstInsertionPt();
00828   StoreInst *NewSI = new StoreInst(MergedVal, SI.getOperand(1),
00829                                    SI.isVolatile(),
00830                                    SI.getAlignment(),
00831                                    SI.getOrdering(),
00832                                    SI.getSynchScope());
00833   InsertNewInstBefore(NewSI, *BBI);
00834   NewSI->setDebugLoc(OtherStore->getDebugLoc());
00835 
00836   // If the two stores had AA tags, merge them.
00837   AAMDNodes AATags;
00838   SI.getAAMetadata(AATags);
00839   if (AATags) {
00840     OtherStore->getAAMetadata(AATags, /* Merge = */ true);
00841     NewSI->setAAMetadata(AATags);
00842   }
00843 
00844   // Nuke the old stores.
00845   EraseInstFromFunction(SI);
00846   EraseInstFromFunction(*OtherStore);
00847   return true;
00848 }