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 "InstCombineInternal.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(
00272           Copy->getSource(), AI.getAlignment(), DL, AC, &AI, DT);
00273       if (AI.getAlignment() <= SourceAlign) {
00274         DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n');
00275         DEBUG(dbgs() << "  memcpy = " << *Copy << '\n');
00276         for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
00277           EraseInstFromFunction(*ToDelete[i]);
00278         Constant *TheSrc = cast<Constant>(Copy->getSource());
00279         Constant *Cast
00280           = ConstantExpr::getPointerBitCastOrAddrSpaceCast(TheSrc, AI.getType());
00281         Instruction *NewI = ReplaceInstUsesWith(AI, Cast);
00282         EraseInstFromFunction(*Copy);
00283         ++NumGlobalCopies;
00284         return NewI;
00285       }
00286     }
00287   }
00288 
00289   // At last, use the generic allocation site handler to aggressively remove
00290   // unused allocas.
00291   return visitAllocSite(AI);
00292 }
00293 
00294 /// \brief Helper to combine a load to a new type.
00295 ///
00296 /// This just does the work of combining a load to a new type. It handles
00297 /// metadata, etc., and returns the new instruction. The \c NewTy should be the
00298 /// loaded *value* type. This will convert it to a pointer, cast the operand to
00299 /// that pointer type, load it, etc.
00300 ///
00301 /// Note that this will create all of the instructions with whatever insert
00302 /// point the \c InstCombiner currently is using.
00303 static LoadInst *combineLoadToNewType(InstCombiner &IC, LoadInst &LI, Type *NewTy) {
00304   Value *Ptr = LI.getPointerOperand();
00305   unsigned AS = LI.getPointerAddressSpace();
00306   SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
00307   LI.getAllMetadata(MD);
00308 
00309   LoadInst *NewLoad = IC.Builder->CreateAlignedLoad(
00310       IC.Builder->CreateBitCast(Ptr, NewTy->getPointerTo(AS)),
00311       LI.getAlignment(), LI.getName());
00312   for (const auto &MDPair : MD) {
00313     unsigned ID = MDPair.first;
00314     MDNode *N = MDPair.second;
00315     // Note, essentially every kind of metadata should be preserved here! This
00316     // routine is supposed to clone a load instruction changing *only its type*.
00317     // The only metadata it makes sense to drop is metadata which is invalidated
00318     // when the pointer type changes. This should essentially never be the case
00319     // in LLVM, but we explicitly switch over only known metadata to be
00320     // conservatively correct. If you are adding metadata to LLVM which pertains
00321     // to loads, you almost certainly want to add it here.
00322     switch (ID) {
00323     case LLVMContext::MD_dbg:
00324     case LLVMContext::MD_tbaa:
00325     case LLVMContext::MD_prof:
00326     case LLVMContext::MD_fpmath:
00327     case LLVMContext::MD_tbaa_struct:
00328     case LLVMContext::MD_invariant_load:
00329     case LLVMContext::MD_alias_scope:
00330     case LLVMContext::MD_noalias:
00331     case LLVMContext::MD_nontemporal:
00332     case LLVMContext::MD_mem_parallel_loop_access:
00333     case LLVMContext::MD_nonnull:
00334       // All of these directly apply.
00335       NewLoad->setMetadata(ID, N);
00336       break;
00337 
00338     case LLVMContext::MD_range:
00339       // FIXME: It would be nice to propagate this in some way, but the type
00340       // conversions make it hard.
00341       break;
00342     }
00343   }
00344   return NewLoad;
00345 }
00346 
00347 /// \brief Combine a store to a new type.
00348 ///
00349 /// Returns the newly created store instruction.
00350 static StoreInst *combineStoreToNewValue(InstCombiner &IC, StoreInst &SI, Value *V) {
00351   Value *Ptr = SI.getPointerOperand();
00352   unsigned AS = SI.getPointerAddressSpace();
00353   SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
00354   SI.getAllMetadata(MD);
00355 
00356   StoreInst *NewStore = IC.Builder->CreateAlignedStore(
00357       V, IC.Builder->CreateBitCast(Ptr, V->getType()->getPointerTo(AS)),
00358       SI.getAlignment());
00359   for (const auto &MDPair : MD) {
00360     unsigned ID = MDPair.first;
00361     MDNode *N = MDPair.second;
00362     // Note, essentially every kind of metadata should be preserved here! This
00363     // routine is supposed to clone a store instruction changing *only its
00364     // type*. The only metadata it makes sense to drop is metadata which is
00365     // invalidated when the pointer type changes. This should essentially
00366     // never be the case in LLVM, but we explicitly switch over only known
00367     // metadata to be conservatively correct. If you are adding metadata to
00368     // LLVM which pertains to stores, you almost certainly want to add it
00369     // here.
00370     switch (ID) {
00371     case LLVMContext::MD_dbg:
00372     case LLVMContext::MD_tbaa:
00373     case LLVMContext::MD_prof:
00374     case LLVMContext::MD_fpmath:
00375     case LLVMContext::MD_tbaa_struct:
00376     case LLVMContext::MD_alias_scope:
00377     case LLVMContext::MD_noalias:
00378     case LLVMContext::MD_nontemporal:
00379     case LLVMContext::MD_mem_parallel_loop_access:
00380     case LLVMContext::MD_nonnull:
00381       // All of these directly apply.
00382       NewStore->setMetadata(ID, N);
00383       break;
00384 
00385     case LLVMContext::MD_invariant_load:
00386     case LLVMContext::MD_range:
00387       break;
00388     }
00389   }
00390 
00391   return NewStore;
00392 }
00393 
00394 /// \brief Combine loads to match the type of value their uses after looking
00395 /// through intervening bitcasts.
00396 ///
00397 /// The core idea here is that if the result of a load is used in an operation,
00398 /// we should load the type most conducive to that operation. For example, when
00399 /// loading an integer and converting that immediately to a pointer, we should
00400 /// instead directly load a pointer.
00401 ///
00402 /// However, this routine must never change the width of a load or the number of
00403 /// loads as that would introduce a semantic change. This combine is expected to
00404 /// be a semantic no-op which just allows loads to more closely model the types
00405 /// of their consuming operations.
00406 ///
00407 /// Currently, we also refuse to change the precise type used for an atomic load
00408 /// or a volatile load. This is debatable, and might be reasonable to change
00409 /// later. However, it is risky in case some backend or other part of LLVM is
00410 /// relying on the exact type loaded to select appropriate atomic operations.
00411 static Instruction *combineLoadToOperationType(InstCombiner &IC, LoadInst &LI) {
00412   // FIXME: We could probably with some care handle both volatile and atomic
00413   // loads here but it isn't clear that this is important.
00414   if (!LI.isSimple())
00415     return nullptr;
00416 
00417   if (LI.use_empty())
00418     return nullptr;
00419 
00420   Type *Ty = LI.getType();
00421 
00422   // Try to canonicalize loads which are only ever stored to operate over
00423   // integers instead of any other type. We only do this when the loaded type
00424   // is sized and has a size exactly the same as its store size and the store
00425   // size is a legal integer type.
00426   const DataLayout *DL = IC.getDataLayout();
00427   if (!Ty->isIntegerTy() && Ty->isSized() && DL &&
00428       DL->isLegalInteger(DL->getTypeStoreSizeInBits(Ty)) &&
00429       DL->getTypeStoreSizeInBits(Ty) == DL->getTypeSizeInBits(Ty)) {
00430     if (std::all_of(LI.user_begin(), LI.user_end(), [&LI](User *U) {
00431           auto *SI = dyn_cast<StoreInst>(U);
00432           return SI && SI->getPointerOperand() != &LI;
00433         })) {
00434       LoadInst *NewLoad = combineLoadToNewType(
00435           IC, LI,
00436           Type::getIntNTy(LI.getContext(), DL->getTypeStoreSizeInBits(Ty)));
00437       // Replace all the stores with stores of the newly loaded value.
00438       for (auto UI = LI.user_begin(), UE = LI.user_end(); UI != UE;) {
00439         auto *SI = cast<StoreInst>(*UI++);
00440         IC.Builder->SetInsertPoint(SI);
00441         combineStoreToNewValue(IC, *SI, NewLoad);
00442         IC.EraseInstFromFunction(*SI);
00443       }
00444       assert(LI.use_empty() && "Failed to remove all users of the load!");
00445       // Return the old load so the combiner can delete it safely.
00446       return &LI;
00447     }
00448   }
00449 
00450   // Fold away bit casts of the loaded value by loading the desired type.
00451   if (LI.hasOneUse())
00452     if (auto *BC = dyn_cast<BitCastInst>(LI.user_back())) {
00453       LoadInst *NewLoad = combineLoadToNewType(IC, LI, BC->getDestTy());
00454       BC->replaceAllUsesWith(NewLoad);
00455       IC.EraseInstFromFunction(*BC);
00456       return &LI;
00457     }
00458 
00459   // FIXME: We should also canonicalize loads of vectors when their elements are
00460   // cast to other types.
00461   return nullptr;
00462 }
00463 
00464 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
00465   Value *Op = LI.getOperand(0);
00466 
00467   // Try to canonicalize the loaded type.
00468   if (Instruction *Res = combineLoadToOperationType(*this, LI))
00469     return Res;
00470 
00471   // Attempt to improve the alignment.
00472   if (DL) {
00473     unsigned KnownAlign = getOrEnforceKnownAlignment(
00474         Op, DL->getPrefTypeAlignment(LI.getType()), DL, AC, &LI, DT);
00475     unsigned LoadAlign = LI.getAlignment();
00476     unsigned EffectiveLoadAlign = LoadAlign != 0 ? LoadAlign :
00477       DL->getABITypeAlignment(LI.getType());
00478 
00479     if (KnownAlign > EffectiveLoadAlign)
00480       LI.setAlignment(KnownAlign);
00481     else if (LoadAlign == 0)
00482       LI.setAlignment(EffectiveLoadAlign);
00483   }
00484 
00485   // None of the following transforms are legal for volatile/atomic loads.
00486   // FIXME: Some of it is okay for atomic loads; needs refactoring.
00487   if (!LI.isSimple()) return nullptr;
00488 
00489   // Do really simple store-to-load forwarding and load CSE, to catch cases
00490   // where there are several consecutive memory accesses to the same location,
00491   // separated by a few arithmetic operations.
00492   BasicBlock::iterator BBI = &LI;
00493   if (Value *AvailableVal = FindAvailableLoadedValue(Op, LI.getParent(), BBI,6))
00494     return ReplaceInstUsesWith(
00495         LI, Builder->CreateBitOrPointerCast(AvailableVal, LI.getType(),
00496                                             LI.getName() + ".cast"));
00497 
00498   // load(gep null, ...) -> unreachable
00499   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
00500     const Value *GEPI0 = GEPI->getOperand(0);
00501     // TODO: Consider a target hook for valid address spaces for this xform.
00502     if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
00503       // Insert a new store to null instruction before the load to indicate
00504       // that this code is not reachable.  We do this instead of inserting
00505       // an unreachable instruction directly because we cannot modify the
00506       // CFG.
00507       new StoreInst(UndefValue::get(LI.getType()),
00508                     Constant::getNullValue(Op->getType()), &LI);
00509       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
00510     }
00511   }
00512 
00513   // load null/undef -> unreachable
00514   // TODO: Consider a target hook for valid address spaces for this xform.
00515   if (isa<UndefValue>(Op) ||
00516       (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
00517     // Insert a new store to null instruction before the load to indicate that
00518     // this code is not reachable.  We do this instead of inserting an
00519     // unreachable instruction directly because we cannot modify the CFG.
00520     new StoreInst(UndefValue::get(LI.getType()),
00521                   Constant::getNullValue(Op->getType()), &LI);
00522     return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
00523   }
00524 
00525   if (Op->hasOneUse()) {
00526     // Change select and PHI nodes to select values instead of addresses: this
00527     // helps alias analysis out a lot, allows many others simplifications, and
00528     // exposes redundancy in the code.
00529     //
00530     // Note that we cannot do the transformation unless we know that the
00531     // introduced loads cannot trap!  Something like this is valid as long as
00532     // the condition is always false: load (select bool %C, int* null, int* %G),
00533     // but it would not be valid if we transformed it to load from null
00534     // unconditionally.
00535     //
00536     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
00537       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
00538       unsigned Align = LI.getAlignment();
00539       if (isSafeToLoadUnconditionally(SI->getOperand(1), SI, Align, DL) &&
00540           isSafeToLoadUnconditionally(SI->getOperand(2), SI, Align, DL)) {
00541         LoadInst *V1 = Builder->CreateLoad(SI->getOperand(1),
00542                                            SI->getOperand(1)->getName()+".val");
00543         LoadInst *V2 = Builder->CreateLoad(SI->getOperand(2),
00544                                            SI->getOperand(2)->getName()+".val");
00545         V1->setAlignment(Align);
00546         V2->setAlignment(Align);
00547         return SelectInst::Create(SI->getCondition(), V1, V2);
00548       }
00549 
00550       // load (select (cond, null, P)) -> load P
00551       if (isa<ConstantPointerNull>(SI->getOperand(1)) && 
00552           LI.getPointerAddressSpace() == 0) {
00553         LI.setOperand(0, SI->getOperand(2));
00554         return &LI;
00555       }
00556 
00557       // load (select (cond, P, null)) -> load P
00558       if (isa<ConstantPointerNull>(SI->getOperand(2)) &&
00559           LI.getPointerAddressSpace() == 0) {
00560         LI.setOperand(0, SI->getOperand(1));
00561         return &LI;
00562       }
00563     }
00564   }
00565   return nullptr;
00566 }
00567 
00568 /// \brief Combine stores to match the type of value being stored.
00569 ///
00570 /// The core idea here is that the memory does not have any intrinsic type and
00571 /// where we can we should match the type of a store to the type of value being
00572 /// stored.
00573 ///
00574 /// However, this routine must never change the width of a store or the number of
00575 /// stores as that would introduce a semantic change. This combine is expected to
00576 /// be a semantic no-op which just allows stores to more closely model the types
00577 /// of their incoming values.
00578 ///
00579 /// Currently, we also refuse to change the precise type used for an atomic or
00580 /// volatile store. This is debatable, and might be reasonable to change later.
00581 /// However, it is risky in case some backend or other part of LLVM is relying
00582 /// on the exact type stored to select appropriate atomic operations.
00583 ///
00584 /// \returns true if the store was successfully combined away. This indicates
00585 /// the caller must erase the store instruction. We have to let the caller erase
00586 /// the store instruction sas otherwise there is no way to signal whether it was
00587 /// combined or not: IC.EraseInstFromFunction returns a null pointer.
00588 static bool combineStoreToValueType(InstCombiner &IC, StoreInst &SI) {
00589   // FIXME: We could probably with some care handle both volatile and atomic
00590   // stores here but it isn't clear that this is important.
00591   if (!SI.isSimple())
00592     return false;
00593 
00594   Value *V = SI.getValueOperand();
00595 
00596   // Fold away bit casts of the stored value by storing the original type.
00597   if (auto *BC = dyn_cast<BitCastInst>(V)) {
00598     V = BC->getOperand(0);
00599     combineStoreToNewValue(IC, SI, V);
00600     return true;
00601   }
00602 
00603   // FIXME: We should also canonicalize loads of vectors when their elements are
00604   // cast to other types.
00605   return false;
00606 }
00607 
00608 /// equivalentAddressValues - Test if A and B will obviously have the same
00609 /// value. This includes recognizing that %t0 and %t1 will have the same
00610 /// value in code like this:
00611 ///   %t0 = getelementptr \@a, 0, 3
00612 ///   store i32 0, i32* %t0
00613 ///   %t1 = getelementptr \@a, 0, 3
00614 ///   %t2 = load i32* %t1
00615 ///
00616 static bool equivalentAddressValues(Value *A, Value *B) {
00617   // Test if the values are trivially equivalent.
00618   if (A == B) return true;
00619 
00620   // Test if the values come form identical arithmetic instructions.
00621   // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
00622   // its only used to compare two uses within the same basic block, which
00623   // means that they'll always either have the same value or one of them
00624   // will have an undefined value.
00625   if (isa<BinaryOperator>(A) ||
00626       isa<CastInst>(A) ||
00627       isa<PHINode>(A) ||
00628       isa<GetElementPtrInst>(A))
00629     if (Instruction *BI = dyn_cast<Instruction>(B))
00630       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
00631         return true;
00632 
00633   // Otherwise they may not be equivalent.
00634   return false;
00635 }
00636 
00637 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
00638   Value *Val = SI.getOperand(0);
00639   Value *Ptr = SI.getOperand(1);
00640 
00641   // Try to canonicalize the stored type.
00642   if (combineStoreToValueType(*this, SI))
00643     return EraseInstFromFunction(SI);
00644 
00645   // Attempt to improve the alignment.
00646   if (DL) {
00647     unsigned KnownAlign = getOrEnforceKnownAlignment(
00648         Ptr, DL->getPrefTypeAlignment(Val->getType()), DL, AC, &SI, DT);
00649     unsigned StoreAlign = SI.getAlignment();
00650     unsigned EffectiveStoreAlign = StoreAlign != 0 ? StoreAlign :
00651       DL->getABITypeAlignment(Val->getType());
00652 
00653     if (KnownAlign > EffectiveStoreAlign)
00654       SI.setAlignment(KnownAlign);
00655     else if (StoreAlign == 0)
00656       SI.setAlignment(EffectiveStoreAlign);
00657   }
00658 
00659   // Don't hack volatile/atomic stores.
00660   // FIXME: Some bits are legal for atomic stores; needs refactoring.
00661   if (!SI.isSimple()) return nullptr;
00662 
00663   // If the RHS is an alloca with a single use, zapify the store, making the
00664   // alloca dead.
00665   if (Ptr->hasOneUse()) {
00666     if (isa<AllocaInst>(Ptr))
00667       return EraseInstFromFunction(SI);
00668     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
00669       if (isa<AllocaInst>(GEP->getOperand(0))) {
00670         if (GEP->getOperand(0)->hasOneUse())
00671           return EraseInstFromFunction(SI);
00672       }
00673     }
00674   }
00675 
00676   // Do really simple DSE, to catch cases where there are several consecutive
00677   // stores to the same location, separated by a few arithmetic operations. This
00678   // situation often occurs with bitfield accesses.
00679   BasicBlock::iterator BBI = &SI;
00680   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
00681        --ScanInsts) {
00682     --BBI;
00683     // Don't count debug info directives, lest they affect codegen,
00684     // and we skip pointer-to-pointer bitcasts, which are NOPs.
00685     if (isa<DbgInfoIntrinsic>(BBI) ||
00686         (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
00687       ScanInsts++;
00688       continue;
00689     }
00690 
00691     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
00692       // Prev store isn't volatile, and stores to the same location?
00693       if (PrevSI->isSimple() && equivalentAddressValues(PrevSI->getOperand(1),
00694                                                         SI.getOperand(1))) {
00695         ++NumDeadStore;
00696         ++BBI;
00697         EraseInstFromFunction(*PrevSI);
00698         continue;
00699       }
00700       break;
00701     }
00702 
00703     // If this is a load, we have to stop.  However, if the loaded value is from
00704     // the pointer we're loading and is producing the pointer we're storing,
00705     // then *this* store is dead (X = load P; store X -> P).
00706     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
00707       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr) &&
00708           LI->isSimple())
00709         return EraseInstFromFunction(SI);
00710 
00711       // Otherwise, this is a load from some other location.  Stores before it
00712       // may not be dead.
00713       break;
00714     }
00715 
00716     // Don't skip over loads or things that can modify memory.
00717     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
00718       break;
00719   }
00720 
00721   // store X, null    -> turns into 'unreachable' in SimplifyCFG
00722   if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
00723     if (!isa<UndefValue>(Val)) {
00724       SI.setOperand(0, UndefValue::get(Val->getType()));
00725       if (Instruction *U = dyn_cast<Instruction>(Val))
00726         Worklist.Add(U);  // Dropped a use.
00727     }
00728     return nullptr;  // Do not modify these!
00729   }
00730 
00731   // store undef, Ptr -> noop
00732   if (isa<UndefValue>(Val))
00733     return EraseInstFromFunction(SI);
00734 
00735   // If this store is the last instruction in the basic block (possibly
00736   // excepting debug info instructions), and if the block ends with an
00737   // unconditional branch, try to move it to the successor block.
00738   BBI = &SI;
00739   do {
00740     ++BBI;
00741   } while (isa<DbgInfoIntrinsic>(BBI) ||
00742            (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()));
00743   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
00744     if (BI->isUnconditional())
00745       if (SimplifyStoreAtEndOfBlock(SI))
00746         return nullptr;  // xform done!
00747 
00748   return nullptr;
00749 }
00750 
00751 /// SimplifyStoreAtEndOfBlock - Turn things like:
00752 ///   if () { *P = v1; } else { *P = v2 }
00753 /// into a phi node with a store in the successor.
00754 ///
00755 /// Simplify things like:
00756 ///   *P = v1; if () { *P = v2; }
00757 /// into a phi node with a store in the successor.
00758 ///
00759 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
00760   BasicBlock *StoreBB = SI.getParent();
00761 
00762   // Check to see if the successor block has exactly two incoming edges.  If
00763   // so, see if the other predecessor contains a store to the same location.
00764   // if so, insert a PHI node (if needed) and move the stores down.
00765   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
00766 
00767   // Determine whether Dest has exactly two predecessors and, if so, compute
00768   // the other predecessor.
00769   pred_iterator PI = pred_begin(DestBB);
00770   BasicBlock *P = *PI;
00771   BasicBlock *OtherBB = nullptr;
00772 
00773   if (P != StoreBB)
00774     OtherBB = P;
00775 
00776   if (++PI == pred_end(DestBB))
00777     return false;
00778 
00779   P = *PI;
00780   if (P != StoreBB) {
00781     if (OtherBB)
00782       return false;
00783     OtherBB = P;
00784   }
00785   if (++PI != pred_end(DestBB))
00786     return false;
00787 
00788   // Bail out if all the relevant blocks aren't distinct (this can happen,
00789   // for example, if SI is in an infinite loop)
00790   if (StoreBB == DestBB || OtherBB == DestBB)
00791     return false;
00792 
00793   // Verify that the other block ends in a branch and is not otherwise empty.
00794   BasicBlock::iterator BBI = OtherBB->getTerminator();
00795   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
00796   if (!OtherBr || BBI == OtherBB->begin())
00797     return false;
00798 
00799   // If the other block ends in an unconditional branch, check for the 'if then
00800   // else' case.  there is an instruction before the branch.
00801   StoreInst *OtherStore = nullptr;
00802   if (OtherBr->isUnconditional()) {
00803     --BBI;
00804     // Skip over debugging info.
00805     while (isa<DbgInfoIntrinsic>(BBI) ||
00806            (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
00807       if (BBI==OtherBB->begin())
00808         return false;
00809       --BBI;
00810     }
00811     // If this isn't a store, isn't a store to the same location, or is not the
00812     // right kind of store, bail out.
00813     OtherStore = dyn_cast<StoreInst>(BBI);
00814     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
00815         !SI.isSameOperationAs(OtherStore))
00816       return false;
00817   } else {
00818     // Otherwise, the other block ended with a conditional branch. If one of the
00819     // destinations is StoreBB, then we have the if/then case.
00820     if (OtherBr->getSuccessor(0) != StoreBB &&
00821         OtherBr->getSuccessor(1) != StoreBB)
00822       return false;
00823 
00824     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
00825     // if/then triangle.  See if there is a store to the same ptr as SI that
00826     // lives in OtherBB.
00827     for (;; --BBI) {
00828       // Check to see if we find the matching store.
00829       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
00830         if (OtherStore->getOperand(1) != SI.getOperand(1) ||
00831             !SI.isSameOperationAs(OtherStore))
00832           return false;
00833         break;
00834       }
00835       // If we find something that may be using or overwriting the stored
00836       // value, or if we run out of instructions, we can't do the xform.
00837       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
00838           BBI == OtherBB->begin())
00839         return false;
00840     }
00841 
00842     // In order to eliminate the store in OtherBr, we have to
00843     // make sure nothing reads or overwrites the stored value in
00844     // StoreBB.
00845     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
00846       // FIXME: This should really be AA driven.
00847       if (I->mayReadFromMemory() || I->mayWriteToMemory())
00848         return false;
00849     }
00850   }
00851 
00852   // Insert a PHI node now if we need it.
00853   Value *MergedVal = OtherStore->getOperand(0);
00854   if (MergedVal != SI.getOperand(0)) {
00855     PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge");
00856     PN->addIncoming(SI.getOperand(0), SI.getParent());
00857     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
00858     MergedVal = InsertNewInstBefore(PN, DestBB->front());
00859   }
00860 
00861   // Advance to a place where it is safe to insert the new store and
00862   // insert it.
00863   BBI = DestBB->getFirstInsertionPt();
00864   StoreInst *NewSI = new StoreInst(MergedVal, SI.getOperand(1),
00865                                    SI.isVolatile(),
00866                                    SI.getAlignment(),
00867                                    SI.getOrdering(),
00868                                    SI.getSynchScope());
00869   InsertNewInstBefore(NewSI, *BBI);
00870   NewSI->setDebugLoc(OtherStore->getDebugLoc());
00871 
00872   // If the two stores had AA tags, merge them.
00873   AAMDNodes AATags;
00874   SI.getAAMetadata(AATags);
00875   if (AATags) {
00876     OtherStore->getAAMetadata(AATags, /* Merge = */ true);
00877     NewSI->setAAMetadata(AATags);
00878   }
00879 
00880   // Nuke the old stores.
00881   EraseInstFromFunction(SI);
00882   EraseInstFromFunction(*OtherStore);
00883   return true;
00884 }