LLVM  mainline
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/SmallString.h"
00016 #include "llvm/ADT/Statistic.h"
00017 #include "llvm/Analysis/Loads.h"
00018 #include "llvm/IR/DataLayout.h"
00019 #include "llvm/IR/LLVMContext.h"
00020 #include "llvm/IR/IntrinsicInst.h"
00021 #include "llvm/IR/MDBuilder.h"
00022 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
00023 #include "llvm/Transforms/Utils/Local.h"
00024 using namespace llvm;
00025 
00026 #define DEBUG_TYPE "instcombine"
00027 
00028 STATISTIC(NumDeadStore,    "Number of dead stores eliminated");
00029 STATISTIC(NumGlobalCopies, "Number of allocas copied from constant global");
00030 
00031 /// pointsToConstantGlobal - Return true if V (possibly indirectly) points to
00032 /// some part of a constant global variable.  This intentionally only accepts
00033 /// constant expressions because we can't rewrite arbitrary instructions.
00034 static bool pointsToConstantGlobal(Value *V) {
00035   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V))
00036     return GV->isConstant();
00037 
00038   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V)) {
00039     if (CE->getOpcode() == Instruction::BitCast ||
00040         CE->getOpcode() == Instruction::AddrSpaceCast ||
00041         CE->getOpcode() == Instruction::GetElementPtr)
00042       return pointsToConstantGlobal(CE->getOperand(0));
00043   }
00044   return false;
00045 }
00046 
00047 /// isOnlyCopiedFromConstantGlobal - Recursively walk the uses of a (derived)
00048 /// pointer to an alloca.  Ignore any reads of the pointer, return false if we
00049 /// see any stores or other unknown uses.  If we see pointer arithmetic, keep
00050 /// track of whether it moves the pointer (with IsOffset) but otherwise traverse
00051 /// the uses.  If we see a memcpy/memmove that targets an unoffseted pointer to
00052 /// the alloca, and if the source pointer is a pointer to a constant global, we
00053 /// can optimize this.
00054 static bool
00055 isOnlyCopiedFromConstantGlobal(Value *V, MemTransferInst *&TheCopy,
00056                                SmallVectorImpl<Instruction *> &ToDelete) {
00057   // We track lifetime intrinsics as we encounter them.  If we decide to go
00058   // ahead and replace the value with the global, this lets the caller quickly
00059   // eliminate the markers.
00060 
00061   SmallVector<std::pair<Value *, bool>, 35> ValuesToInspect;
00062   ValuesToInspect.push_back(std::make_pair(V, false));
00063   while (!ValuesToInspect.empty()) {
00064     auto ValuePair = ValuesToInspect.pop_back_val();
00065     const bool IsOffset = ValuePair.second;
00066     for (auto &U : ValuePair.first->uses()) {
00067       Instruction *I = cast<Instruction>(U.getUser());
00068 
00069       if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
00070         // Ignore non-volatile loads, they are always ok.
00071         if (!LI->isSimple()) return false;
00072         continue;
00073       }
00074 
00075       if (isa<BitCastInst>(I) || isa<AddrSpaceCastInst>(I)) {
00076         // If uses of the bitcast are ok, we are ok.
00077         ValuesToInspect.push_back(std::make_pair(I, IsOffset));
00078         continue;
00079       }
00080       if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
00081         // If the GEP has all zero indices, it doesn't offset the pointer. If it
00082         // doesn't, it does.
00083         ValuesToInspect.push_back(
00084             std::make_pair(I, IsOffset || !GEP->hasAllZeroIndices()));
00085         continue;
00086       }
00087 
00088       if (auto CS = CallSite(I)) {
00089         // If this is the function being called then we treat it like a load and
00090         // ignore it.
00091         if (CS.isCallee(&U))
00092           continue;
00093 
00094         unsigned DataOpNo = CS.getDataOperandNo(&U);
00095         bool IsArgOperand = CS.isArgOperand(&U);
00096 
00097         // Inalloca arguments are clobbered by the call.
00098         if (IsArgOperand && CS.isInAllocaArgument(DataOpNo))
00099           return false;
00100 
00101         // If this is a readonly/readnone call site, then we know it is just a
00102         // load (but one that potentially returns the value itself), so we can
00103         // ignore it if we know that the value isn't captured.
00104         if (CS.onlyReadsMemory() &&
00105             (CS.getInstruction()->use_empty() || CS.doesNotCapture(DataOpNo)))
00106           continue;
00107 
00108         // If this is being passed as a byval argument, the caller is making a
00109         // copy, so it is only a read of the alloca.
00110         if (IsArgOperand && CS.isByValArgument(DataOpNo))
00111           continue;
00112       }
00113 
00114       // Lifetime intrinsics can be handled by the caller.
00115       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
00116         if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
00117             II->getIntrinsicID() == Intrinsic::lifetime_end) {
00118           assert(II->use_empty() && "Lifetime markers have no result to use!");
00119           ToDelete.push_back(II);
00120           continue;
00121         }
00122       }
00123 
00124       // If this is isn't our memcpy/memmove, reject it as something we can't
00125       // handle.
00126       MemTransferInst *MI = dyn_cast<MemTransferInst>(I);
00127       if (!MI)
00128         return false;
00129 
00130       // If the transfer is using the alloca as a source of the transfer, then
00131       // ignore it since it is a load (unless the transfer is volatile).
00132       if (U.getOperandNo() == 1) {
00133         if (MI->isVolatile()) return false;
00134         continue;
00135       }
00136 
00137       // If we already have seen a copy, reject the second one.
00138       if (TheCopy) return false;
00139 
00140       // If the pointer has been offset from the start of the alloca, we can't
00141       // safely handle this.
00142       if (IsOffset) return false;
00143 
00144       // If the memintrinsic isn't using the alloca as the dest, reject it.
00145       if (U.getOperandNo() != 0) return false;
00146 
00147       // If the source of the memcpy/move is not a constant global, reject it.
00148       if (!pointsToConstantGlobal(MI->getSource()))
00149         return false;
00150 
00151       // Otherwise, the transform is safe.  Remember the copy instruction.
00152       TheCopy = MI;
00153     }
00154   }
00155   return true;
00156 }
00157 
00158 /// isOnlyCopiedFromConstantGlobal - Return true if the specified alloca is only
00159 /// modified by a copy from a constant global.  If we can prove this, we can
00160 /// replace any uses of the alloca with uses of the global directly.
00161 static MemTransferInst *
00162 isOnlyCopiedFromConstantGlobal(AllocaInst *AI,
00163                                SmallVectorImpl<Instruction *> &ToDelete) {
00164   MemTransferInst *TheCopy = nullptr;
00165   if (isOnlyCopiedFromConstantGlobal(AI, TheCopy, ToDelete))
00166     return TheCopy;
00167   return nullptr;
00168 }
00169 
00170 static Instruction *simplifyAllocaArraySize(InstCombiner &IC, AllocaInst &AI) {
00171   // Check for array size of 1 (scalar allocation).
00172   if (!AI.isArrayAllocation()) {
00173     // i32 1 is the canonical array size for scalar allocations.
00174     if (AI.getArraySize()->getType()->isIntegerTy(32))
00175       return nullptr;
00176 
00177     // Canonicalize it.
00178     Value *V = IC.Builder->getInt32(1);
00179     AI.setOperand(0, V);
00180     return &AI;
00181   }
00182 
00183   // Convert: alloca Ty, C - where C is a constant != 1 into: alloca [C x Ty], 1
00184   if (const ConstantInt *C = dyn_cast<ConstantInt>(AI.getArraySize())) {
00185     Type *NewTy = ArrayType::get(AI.getAllocatedType(), C->getZExtValue());
00186     AllocaInst *New = IC.Builder->CreateAlloca(NewTy, nullptr, AI.getName());
00187     New->setAlignment(AI.getAlignment());
00188 
00189     // Scan to the end of the allocation instructions, to skip over a block of
00190     // allocas if possible...also skip interleaved debug info
00191     //
00192     BasicBlock::iterator It(New);
00193     while (isa<AllocaInst>(*It) || isa<DbgInfoIntrinsic>(*It))
00194       ++It;
00195 
00196     // Now that I is pointing to the first non-allocation-inst in the block,
00197     // insert our getelementptr instruction...
00198     //
00199     Type *IdxTy = IC.getDataLayout().getIntPtrType(AI.getType());
00200     Value *NullIdx = Constant::getNullValue(IdxTy);
00201     Value *Idx[2] = {NullIdx, NullIdx};
00202     Instruction *GEP =
00203         GetElementPtrInst::CreateInBounds(New, Idx, New->getName() + ".sub");
00204     IC.InsertNewInstBefore(GEP, *It);
00205 
00206     // Now make everything use the getelementptr instead of the original
00207     // allocation.
00208     return IC.ReplaceInstUsesWith(AI, GEP);
00209   }
00210 
00211   if (isa<UndefValue>(AI.getArraySize()))
00212     return IC.ReplaceInstUsesWith(AI, Constant::getNullValue(AI.getType()));
00213 
00214   // Ensure that the alloca array size argument has type intptr_t, so that
00215   // any casting is exposed early.
00216   Type *IntPtrTy = IC.getDataLayout().getIntPtrType(AI.getType());
00217   if (AI.getArraySize()->getType() != IntPtrTy) {
00218     Value *V = IC.Builder->CreateIntCast(AI.getArraySize(), IntPtrTy, false);
00219     AI.setOperand(0, V);
00220     return &AI;
00221   }
00222 
00223   return nullptr;
00224 }
00225 
00226 Instruction *InstCombiner::visitAllocaInst(AllocaInst &AI) {
00227   if (auto *I = simplifyAllocaArraySize(*this, AI))
00228     return I;
00229 
00230   if (AI.getAllocatedType()->isSized()) {
00231     // If the alignment is 0 (unspecified), assign it the preferred alignment.
00232     if (AI.getAlignment() == 0)
00233       AI.setAlignment(DL.getPrefTypeAlignment(AI.getAllocatedType()));
00234 
00235     // Move all alloca's of zero byte objects to the entry block and merge them
00236     // together.  Note that we only do this for alloca's, because malloc should
00237     // allocate and return a unique pointer, even for a zero byte allocation.
00238     if (DL.getTypeAllocSize(AI.getAllocatedType()) == 0) {
00239       // For a zero sized alloca there is no point in doing an array allocation.
00240       // This is helpful if the array size is a complicated expression not used
00241       // elsewhere.
00242       if (AI.isArrayAllocation()) {
00243         AI.setOperand(0, ConstantInt::get(AI.getArraySize()->getType(), 1));
00244         return &AI;
00245       }
00246 
00247       // Get the first instruction in the entry block.
00248       BasicBlock &EntryBlock = AI.getParent()->getParent()->getEntryBlock();
00249       Instruction *FirstInst = EntryBlock.getFirstNonPHIOrDbg();
00250       if (FirstInst != &AI) {
00251         // If the entry block doesn't start with a zero-size alloca then move
00252         // this one to the start of the entry block.  There is no problem with
00253         // dominance as the array size was forced to a constant earlier already.
00254         AllocaInst *EntryAI = dyn_cast<AllocaInst>(FirstInst);
00255         if (!EntryAI || !EntryAI->getAllocatedType()->isSized() ||
00256             DL.getTypeAllocSize(EntryAI->getAllocatedType()) != 0) {
00257           AI.moveBefore(FirstInst);
00258           return &AI;
00259         }
00260 
00261         // If the alignment of the entry block alloca is 0 (unspecified),
00262         // assign it the preferred alignment.
00263         if (EntryAI->getAlignment() == 0)
00264           EntryAI->setAlignment(
00265               DL.getPrefTypeAlignment(EntryAI->getAllocatedType()));
00266         // Replace this zero-sized alloca with the one at the start of the entry
00267         // block after ensuring that the address will be aligned enough for both
00268         // types.
00269         unsigned MaxAlign = std::max(EntryAI->getAlignment(),
00270                                      AI.getAlignment());
00271         EntryAI->setAlignment(MaxAlign);
00272         if (AI.getType() != EntryAI->getType())
00273           return new BitCastInst(EntryAI, AI.getType());
00274         return ReplaceInstUsesWith(AI, EntryAI);
00275       }
00276     }
00277   }
00278 
00279   if (AI.getAlignment()) {
00280     // Check to see if this allocation is only modified by a memcpy/memmove from
00281     // a constant global whose alignment is equal to or exceeds that of the
00282     // allocation.  If this is the case, we can change all users to use
00283     // the constant global instead.  This is commonly produced by the CFE by
00284     // constructs like "void foo() { int A[] = {1,2,3,4,5,6,7,8,9...}; }" if 'A'
00285     // is only subsequently read.
00286     SmallVector<Instruction *, 4> ToDelete;
00287     if (MemTransferInst *Copy = isOnlyCopiedFromConstantGlobal(&AI, ToDelete)) {
00288       unsigned SourceAlign = getOrEnforceKnownAlignment(
00289           Copy->getSource(), AI.getAlignment(), DL, &AI, AC, DT);
00290       if (AI.getAlignment() <= SourceAlign) {
00291         DEBUG(dbgs() << "Found alloca equal to global: " << AI << '\n');
00292         DEBUG(dbgs() << "  memcpy = " << *Copy << '\n');
00293         for (unsigned i = 0, e = ToDelete.size(); i != e; ++i)
00294           EraseInstFromFunction(*ToDelete[i]);
00295         Constant *TheSrc = cast<Constant>(Copy->getSource());
00296         Constant *Cast
00297           = ConstantExpr::getPointerBitCastOrAddrSpaceCast(TheSrc, AI.getType());
00298         Instruction *NewI = ReplaceInstUsesWith(AI, Cast);
00299         EraseInstFromFunction(*Copy);
00300         ++NumGlobalCopies;
00301         return NewI;
00302       }
00303     }
00304   }
00305 
00306   // At last, use the generic allocation site handler to aggressively remove
00307   // unused allocas.
00308   return visitAllocSite(AI);
00309 }
00310 
00311 /// \brief Helper to combine a load to a new type.
00312 ///
00313 /// This just does the work of combining a load to a new type. It handles
00314 /// metadata, etc., and returns the new instruction. The \c NewTy should be the
00315 /// loaded *value* type. This will convert it to a pointer, cast the operand to
00316 /// that pointer type, load it, etc.
00317 ///
00318 /// Note that this will create all of the instructions with whatever insert
00319 /// point the \c InstCombiner currently is using.
00320 static LoadInst *combineLoadToNewType(InstCombiner &IC, LoadInst &LI, Type *NewTy,
00321                                       const Twine &Suffix = "") {
00322   Value *Ptr = LI.getPointerOperand();
00323   unsigned AS = LI.getPointerAddressSpace();
00324   SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
00325   LI.getAllMetadata(MD);
00326 
00327   LoadInst *NewLoad = IC.Builder->CreateAlignedLoad(
00328       IC.Builder->CreateBitCast(Ptr, NewTy->getPointerTo(AS)),
00329       LI.getAlignment(), LI.getName() + Suffix);
00330   MDBuilder MDB(NewLoad->getContext());
00331   for (const auto &MDPair : MD) {
00332     unsigned ID = MDPair.first;
00333     MDNode *N = MDPair.second;
00334     // Note, essentially every kind of metadata should be preserved here! This
00335     // routine is supposed to clone a load instruction changing *only its type*.
00336     // The only metadata it makes sense to drop is metadata which is invalidated
00337     // when the pointer type changes. This should essentially never be the case
00338     // in LLVM, but we explicitly switch over only known metadata to be
00339     // conservatively correct. If you are adding metadata to LLVM which pertains
00340     // to loads, you almost certainly want to add it here.
00341     switch (ID) {
00342     case LLVMContext::MD_dbg:
00343     case LLVMContext::MD_tbaa:
00344     case LLVMContext::MD_prof:
00345     case LLVMContext::MD_fpmath:
00346     case LLVMContext::MD_tbaa_struct:
00347     case LLVMContext::MD_invariant_load:
00348     case LLVMContext::MD_alias_scope:
00349     case LLVMContext::MD_noalias:
00350     case LLVMContext::MD_nontemporal:
00351     case LLVMContext::MD_mem_parallel_loop_access:
00352       // All of these directly apply.
00353       NewLoad->setMetadata(ID, N);
00354       break;
00355 
00356     case LLVMContext::MD_nonnull:
00357       // This only directly applies if the new type is also a pointer.
00358       if (NewTy->isPointerTy()) {
00359         NewLoad->setMetadata(ID, N);
00360         break;
00361       }
00362       // If it's integral now, translate it to !range metadata.
00363       if (NewTy->isIntegerTy()) {
00364         auto *ITy = cast<IntegerType>(NewTy);
00365         auto *NullInt = ConstantExpr::getPtrToInt(
00366             ConstantPointerNull::get(cast<PointerType>(Ptr->getType())), ITy);
00367         auto *NonNullInt =
00368             ConstantExpr::getAdd(NullInt, ConstantInt::get(ITy, 1));
00369         NewLoad->setMetadata(LLVMContext::MD_range,
00370                              MDB.createRange(NonNullInt, NullInt));
00371       }
00372       break;
00373     case LLVMContext::MD_align:
00374     case LLVMContext::MD_dereferenceable:
00375     case LLVMContext::MD_dereferenceable_or_null:
00376       // These only directly apply if the new type is also a pointer.
00377       if (NewTy->isPointerTy())
00378         NewLoad->setMetadata(ID, N);
00379       break;
00380     case LLVMContext::MD_range:
00381       // FIXME: It would be nice to propagate this in some way, but the type
00382       // conversions make it hard. If the new type is a pointer, we could
00383       // translate it to !nonnull metadata.
00384       break;
00385     }
00386   }
00387   return NewLoad;
00388 }
00389 
00390 /// \brief Combine a store to a new type.
00391 ///
00392 /// Returns the newly created store instruction.
00393 static StoreInst *combineStoreToNewValue(InstCombiner &IC, StoreInst &SI, Value *V) {
00394   Value *Ptr = SI.getPointerOperand();
00395   unsigned AS = SI.getPointerAddressSpace();
00396   SmallVector<std::pair<unsigned, MDNode *>, 8> MD;
00397   SI.getAllMetadata(MD);
00398 
00399   StoreInst *NewStore = IC.Builder->CreateAlignedStore(
00400       V, IC.Builder->CreateBitCast(Ptr, V->getType()->getPointerTo(AS)),
00401       SI.getAlignment());
00402   for (const auto &MDPair : MD) {
00403     unsigned ID = MDPair.first;
00404     MDNode *N = MDPair.second;
00405     // Note, essentially every kind of metadata should be preserved here! This
00406     // routine is supposed to clone a store instruction changing *only its
00407     // type*. The only metadata it makes sense to drop is metadata which is
00408     // invalidated when the pointer type changes. This should essentially
00409     // never be the case in LLVM, but we explicitly switch over only known
00410     // metadata to be conservatively correct. If you are adding metadata to
00411     // LLVM which pertains to stores, you almost certainly want to add it
00412     // here.
00413     switch (ID) {
00414     case LLVMContext::MD_dbg:
00415     case LLVMContext::MD_tbaa:
00416     case LLVMContext::MD_prof:
00417     case LLVMContext::MD_fpmath:
00418     case LLVMContext::MD_tbaa_struct:
00419     case LLVMContext::MD_alias_scope:
00420     case LLVMContext::MD_noalias:
00421     case LLVMContext::MD_nontemporal:
00422     case LLVMContext::MD_mem_parallel_loop_access:
00423       // All of these directly apply.
00424       NewStore->setMetadata(ID, N);
00425       break;
00426 
00427     case LLVMContext::MD_invariant_load:
00428     case LLVMContext::MD_nonnull:
00429     case LLVMContext::MD_range:
00430     case LLVMContext::MD_align:
00431     case LLVMContext::MD_dereferenceable:
00432     case LLVMContext::MD_dereferenceable_or_null:
00433       // These don't apply for stores.
00434       break;
00435     }
00436   }
00437 
00438   return NewStore;
00439 }
00440 
00441 /// \brief Combine loads to match the type of value their uses after looking
00442 /// through intervening bitcasts.
00443 ///
00444 /// The core idea here is that if the result of a load is used in an operation,
00445 /// we should load the type most conducive to that operation. For example, when
00446 /// loading an integer and converting that immediately to a pointer, we should
00447 /// instead directly load a pointer.
00448 ///
00449 /// However, this routine must never change the width of a load or the number of
00450 /// loads as that would introduce a semantic change. This combine is expected to
00451 /// be a semantic no-op which just allows loads to more closely model the types
00452 /// of their consuming operations.
00453 ///
00454 /// Currently, we also refuse to change the precise type used for an atomic load
00455 /// or a volatile load. This is debatable, and might be reasonable to change
00456 /// later. However, it is risky in case some backend or other part of LLVM is
00457 /// relying on the exact type loaded to select appropriate atomic operations.
00458 static Instruction *combineLoadToOperationType(InstCombiner &IC, LoadInst &LI) {
00459   // FIXME: We could probably with some care handle both volatile and atomic
00460   // loads here but it isn't clear that this is important.
00461   if (!LI.isSimple())
00462     return nullptr;
00463 
00464   if (LI.use_empty())
00465     return nullptr;
00466 
00467   Type *Ty = LI.getType();
00468   const DataLayout &DL = IC.getDataLayout();
00469 
00470   // Try to canonicalize loads which are only ever stored to operate over
00471   // integers instead of any other type. We only do this when the loaded type
00472   // is sized and has a size exactly the same as its store size and the store
00473   // size is a legal integer type.
00474   if (!Ty->isIntegerTy() && Ty->isSized() &&
00475       DL.isLegalInteger(DL.getTypeStoreSizeInBits(Ty)) &&
00476       DL.getTypeStoreSizeInBits(Ty) == DL.getTypeSizeInBits(Ty)) {
00477     if (std::all_of(LI.user_begin(), LI.user_end(), [&LI](User *U) {
00478           auto *SI = dyn_cast<StoreInst>(U);
00479           return SI && SI->getPointerOperand() != &LI;
00480         })) {
00481       LoadInst *NewLoad = combineLoadToNewType(
00482           IC, LI,
00483           Type::getIntNTy(LI.getContext(), DL.getTypeStoreSizeInBits(Ty)));
00484       // Replace all the stores with stores of the newly loaded value.
00485       for (auto UI = LI.user_begin(), UE = LI.user_end(); UI != UE;) {
00486         auto *SI = cast<StoreInst>(*UI++);
00487         IC.Builder->SetInsertPoint(SI);
00488         combineStoreToNewValue(IC, *SI, NewLoad);
00489         IC.EraseInstFromFunction(*SI);
00490       }
00491       assert(LI.use_empty() && "Failed to remove all users of the load!");
00492       // Return the old load so the combiner can delete it safely.
00493       return &LI;
00494     }
00495   }
00496 
00497   // Fold away bit casts of the loaded value by loading the desired type.
00498   // We can do this for BitCastInsts as well as casts from and to pointer types,
00499   // as long as those are noops (i.e., the source or dest type have the same
00500   // bitwidth as the target's pointers).
00501   if (LI.hasOneUse())
00502     if (auto* CI = dyn_cast<CastInst>(LI.user_back())) {
00503       if (CI->isNoopCast(DL)) {
00504         LoadInst *NewLoad = combineLoadToNewType(IC, LI, CI->getDestTy());
00505         CI->replaceAllUsesWith(NewLoad);
00506         IC.EraseInstFromFunction(*CI);
00507         return &LI;
00508       }
00509     }
00510 
00511   // FIXME: We should also canonicalize loads of vectors when their elements are
00512   // cast to other types.
00513   return nullptr;
00514 }
00515 
00516 static Instruction *unpackLoadToAggregate(InstCombiner &IC, LoadInst &LI) {
00517   // FIXME: We could probably with some care handle both volatile and atomic
00518   // stores here but it isn't clear that this is important.
00519   if (!LI.isSimple())
00520     return nullptr;
00521 
00522   Type *T = LI.getType();
00523   if (!T->isAggregateType())
00524     return nullptr;
00525 
00526   assert(LI.getAlignment() && "Alignment must be set at this point");
00527 
00528   if (auto *ST = dyn_cast<StructType>(T)) {
00529     // If the struct only have one element, we unpack.
00530     unsigned Count = ST->getNumElements();
00531     if (Count == 1) {
00532       LoadInst *NewLoad = combineLoadToNewType(IC, LI, ST->getTypeAtIndex(0U),
00533                                                ".unpack");
00534       return IC.ReplaceInstUsesWith(LI, IC.Builder->CreateInsertValue(
00535         UndefValue::get(T), NewLoad, 0, LI.getName()));
00536     }
00537 
00538     // We don't want to break loads with padding here as we'd loose
00539     // the knowledge that padding exists for the rest of the pipeline.
00540     const DataLayout &DL = IC.getDataLayout();
00541     auto *SL = DL.getStructLayout(ST);
00542     if (SL->hasPadding())
00543       return nullptr;
00544 
00545     auto Name = LI.getName();
00546     SmallString<16> LoadName = Name;
00547     LoadName += ".unpack";
00548     SmallString<16> EltName = Name;
00549     EltName += ".elt";
00550     auto *Addr = LI.getPointerOperand();
00551     Value *V = UndefValue::get(T);
00552     auto *IdxType = Type::getInt32Ty(ST->getContext());
00553     auto *Zero = ConstantInt::get(IdxType, 0);
00554     for (unsigned i = 0; i < Count; i++) {
00555       Value *Indices[2] = {
00556         Zero,
00557         ConstantInt::get(IdxType, i),
00558       };
00559       auto *Ptr = IC.Builder->CreateInBoundsGEP(ST, Addr, makeArrayRef(Indices), EltName);
00560       auto *L = IC.Builder->CreateLoad(ST->getTypeAtIndex(i), Ptr, LoadName);
00561       V = IC.Builder->CreateInsertValue(V, L, i);
00562     }
00563 
00564     V->setName(Name);
00565     return IC.ReplaceInstUsesWith(LI, V);
00566   }
00567 
00568   if (auto *AT = dyn_cast<ArrayType>(T)) {
00569     // If the array only have one element, we unpack.
00570     if (AT->getNumElements() == 1) {
00571       LoadInst *NewLoad = combineLoadToNewType(IC, LI, AT->getElementType(),
00572                                                ".unpack");
00573       return IC.ReplaceInstUsesWith(LI, IC.Builder->CreateInsertValue(
00574         UndefValue::get(T), NewLoad, 0, LI.getName()));
00575     }
00576   }
00577 
00578   return nullptr;
00579 }
00580 
00581 // If we can determine that all possible objects pointed to by the provided
00582 // pointer value are, not only dereferenceable, but also definitively less than
00583 // or equal to the provided maximum size, then return true. Otherwise, return
00584 // false (constant global values and allocas fall into this category).
00585 //
00586 // FIXME: This should probably live in ValueTracking (or similar).
00587 static bool isObjectSizeLessThanOrEq(Value *V, uint64_t MaxSize,
00588                                      const DataLayout &DL) {
00589   SmallPtrSet<Value *, 4> Visited;
00590   SmallVector<Value *, 4> Worklist(1, V);
00591 
00592   do {
00593     Value *P = Worklist.pop_back_val();
00594     P = P->stripPointerCasts();
00595 
00596     if (!Visited.insert(P).second)
00597       continue;
00598 
00599     if (SelectInst *SI = dyn_cast<SelectInst>(P)) {
00600       Worklist.push_back(SI->getTrueValue());
00601       Worklist.push_back(SI->getFalseValue());
00602       continue;
00603     }
00604 
00605     if (PHINode *PN = dyn_cast<PHINode>(P)) {
00606       for (Value *IncValue : PN->incoming_values())
00607         Worklist.push_back(IncValue);
00608       continue;
00609     }
00610 
00611     if (GlobalAlias *GA = dyn_cast<GlobalAlias>(P)) {
00612       if (GA->mayBeOverridden())
00613         return false;
00614       Worklist.push_back(GA->getAliasee());
00615       continue;
00616     }
00617 
00618     // If we know how big this object is, and it is less than MaxSize, continue
00619     // searching. Otherwise, return false.
00620     if (AllocaInst *AI = dyn_cast<AllocaInst>(P)) {
00621       if (!AI->getAllocatedType()->isSized())
00622         return false;
00623 
00624       ConstantInt *CS = dyn_cast<ConstantInt>(AI->getArraySize());
00625       if (!CS)
00626         return false;
00627 
00628       uint64_t TypeSize = DL.getTypeAllocSize(AI->getAllocatedType());
00629       // Make sure that, even if the multiplication below would wrap as an
00630       // uint64_t, we still do the right thing.
00631       if ((CS->getValue().zextOrSelf(128)*APInt(128, TypeSize)).ugt(MaxSize))
00632         return false;
00633       continue;
00634     }
00635 
00636     if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
00637       if (!GV->hasDefinitiveInitializer() || !GV->isConstant())
00638         return false;
00639 
00640       uint64_t InitSize = DL.getTypeAllocSize(GV->getValueType());
00641       if (InitSize > MaxSize)
00642         return false;
00643       continue;
00644     }
00645 
00646     return false;
00647   } while (!Worklist.empty());
00648 
00649   return true;
00650 }
00651 
00652 // If we're indexing into an object of a known size, and the outer index is
00653 // not a constant, but having any value but zero would lead to undefined
00654 // behavior, replace it with zero.
00655 //
00656 // For example, if we have:
00657 // @f.a = private unnamed_addr constant [1 x i32] [i32 12], align 4
00658 // ...
00659 // %arrayidx = getelementptr inbounds [1 x i32]* @f.a, i64 0, i64 %x
00660 // ... = load i32* %arrayidx, align 4
00661 // Then we know that we can replace %x in the GEP with i64 0.
00662 //
00663 // FIXME: We could fold any GEP index to zero that would cause UB if it were
00664 // not zero. Currently, we only handle the first such index. Also, we could
00665 // also search through non-zero constant indices if we kept track of the
00666 // offsets those indices implied.
00667 static bool canReplaceGEPIdxWithZero(InstCombiner &IC, GetElementPtrInst *GEPI,
00668                                      Instruction *MemI, unsigned &Idx) {
00669   if (GEPI->getNumOperands() < 2)
00670     return false;
00671 
00672   // Find the first non-zero index of a GEP. If all indices are zero, return
00673   // one past the last index.
00674   auto FirstNZIdx = [](const GetElementPtrInst *GEPI) {
00675     unsigned I = 1;
00676     for (unsigned IE = GEPI->getNumOperands(); I != IE; ++I) {
00677       Value *V = GEPI->getOperand(I);
00678       if (const ConstantInt *CI = dyn_cast<ConstantInt>(V))
00679         if (CI->isZero())
00680           continue;
00681 
00682       break;
00683     }
00684 
00685     return I;
00686   };
00687 
00688   // Skip through initial 'zero' indices, and find the corresponding pointer
00689   // type. See if the next index is not a constant.
00690   Idx = FirstNZIdx(GEPI);
00691   if (Idx == GEPI->getNumOperands())
00692     return false;
00693   if (isa<Constant>(GEPI->getOperand(Idx)))
00694     return false;
00695 
00696   SmallVector<Value *, 4> Ops(GEPI->idx_begin(), GEPI->idx_begin() + Idx);
00697   Type *AllocTy =
00698     GetElementPtrInst::getIndexedType(GEPI->getSourceElementType(), Ops);
00699   if (!AllocTy || !AllocTy->isSized())
00700     return false;
00701   const DataLayout &DL = IC.getDataLayout();
00702   uint64_t TyAllocSize = DL.getTypeAllocSize(AllocTy);
00703 
00704   // If there are more indices after the one we might replace with a zero, make
00705   // sure they're all non-negative. If any of them are negative, the overall
00706   // address being computed might be before the base address determined by the
00707   // first non-zero index.
00708   auto IsAllNonNegative = [&]() {
00709     for (unsigned i = Idx+1, e = GEPI->getNumOperands(); i != e; ++i) {
00710       bool KnownNonNegative, KnownNegative;
00711       IC.ComputeSignBit(GEPI->getOperand(i), KnownNonNegative,
00712                         KnownNegative, 0, MemI);
00713       if (KnownNonNegative)
00714         continue;
00715       return false;
00716     }
00717 
00718     return true;
00719   };
00720 
00721   // FIXME: If the GEP is not inbounds, and there are extra indices after the
00722   // one we'll replace, those could cause the address computation to wrap
00723   // (rendering the IsAllNonNegative() check below insufficient). We can do
00724   // better, ignoring zero indices (and other indices we can prove small
00725   // enough not to wrap).
00726   if (Idx+1 != GEPI->getNumOperands() && !GEPI->isInBounds())
00727     return false;
00728 
00729   // Note that isObjectSizeLessThanOrEq will return true only if the pointer is
00730   // also known to be dereferenceable.
00731   return isObjectSizeLessThanOrEq(GEPI->getOperand(0), TyAllocSize, DL) &&
00732          IsAllNonNegative();
00733 }
00734 
00735 // If we're indexing into an object with a variable index for the memory
00736 // access, but the object has only one element, we can assume that the index
00737 // will always be zero. If we replace the GEP, return it.
00738 template <typename T>
00739 static Instruction *replaceGEPIdxWithZero(InstCombiner &IC, Value *Ptr,
00740                                           T &MemI) {
00741   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Ptr)) {
00742     unsigned Idx;
00743     if (canReplaceGEPIdxWithZero(IC, GEPI, &MemI, Idx)) {
00744       Instruction *NewGEPI = GEPI->clone();
00745       NewGEPI->setOperand(Idx,
00746         ConstantInt::get(GEPI->getOperand(Idx)->getType(), 0));
00747       NewGEPI->insertBefore(GEPI);
00748       MemI.setOperand(MemI.getPointerOperandIndex(), NewGEPI);
00749       return NewGEPI;
00750     }
00751   }
00752 
00753   return nullptr;
00754 }
00755 
00756 Instruction *InstCombiner::visitLoadInst(LoadInst &LI) {
00757   Value *Op = LI.getOperand(0);
00758 
00759   // Try to canonicalize the loaded type.
00760   if (Instruction *Res = combineLoadToOperationType(*this, LI))
00761     return Res;
00762 
00763   // Attempt to improve the alignment.
00764   unsigned KnownAlign = getOrEnforceKnownAlignment(
00765       Op, DL.getPrefTypeAlignment(LI.getType()), DL, &LI, AC, DT);
00766   unsigned LoadAlign = LI.getAlignment();
00767   unsigned EffectiveLoadAlign =
00768       LoadAlign != 0 ? LoadAlign : DL.getABITypeAlignment(LI.getType());
00769 
00770   if (KnownAlign > EffectiveLoadAlign)
00771     LI.setAlignment(KnownAlign);
00772   else if (LoadAlign == 0)
00773     LI.setAlignment(EffectiveLoadAlign);
00774 
00775   // Replace GEP indices if possible.
00776   if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Op, LI)) {
00777       Worklist.Add(NewGEPI);
00778       return &LI;
00779   }
00780 
00781   // None of the following transforms are legal for volatile/atomic loads.
00782   // FIXME: Some of it is okay for atomic loads; needs refactoring.
00783   if (!LI.isSimple()) return nullptr;
00784 
00785   if (Instruction *Res = unpackLoadToAggregate(*this, LI))
00786     return Res;
00787 
00788   // Do really simple store-to-load forwarding and load CSE, to catch cases
00789   // where there are several consecutive memory accesses to the same location,
00790   // separated by a few arithmetic operations.
00791   BasicBlock::iterator BBI(LI);
00792   AAMDNodes AATags;
00793   if (Value *AvailableVal =
00794       FindAvailableLoadedValue(&LI, LI.getParent(), BBI,
00795                                DefMaxInstsToScan, AA, &AATags)) {
00796     if (LoadInst *NLI = dyn_cast<LoadInst>(AvailableVal)) {
00797       unsigned KnownIDs[] = {
00798           LLVMContext::MD_tbaa,            LLVMContext::MD_alias_scope,
00799           LLVMContext::MD_noalias,         LLVMContext::MD_range,
00800           LLVMContext::MD_invariant_load,  LLVMContext::MD_nonnull,
00801           LLVMContext::MD_invariant_group, LLVMContext::MD_align,
00802           LLVMContext::MD_dereferenceable,
00803           LLVMContext::MD_dereferenceable_or_null};
00804       combineMetadata(NLI, &LI, KnownIDs);
00805     };
00806 
00807     return ReplaceInstUsesWith(
00808         LI, Builder->CreateBitOrPointerCast(AvailableVal, LI.getType(),
00809                                             LI.getName() + ".cast"));
00810   }
00811 
00812   // load(gep null, ...) -> unreachable
00813   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(Op)) {
00814     const Value *GEPI0 = GEPI->getOperand(0);
00815     // TODO: Consider a target hook for valid address spaces for this xform.
00816     if (isa<ConstantPointerNull>(GEPI0) && GEPI->getPointerAddressSpace() == 0){
00817       // Insert a new store to null instruction before the load to indicate
00818       // that this code is not reachable.  We do this instead of inserting
00819       // an unreachable instruction directly because we cannot modify the
00820       // CFG.
00821       new StoreInst(UndefValue::get(LI.getType()),
00822                     Constant::getNullValue(Op->getType()), &LI);
00823       return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
00824     }
00825   }
00826 
00827   // load null/undef -> unreachable
00828   // TODO: Consider a target hook for valid address spaces for this xform.
00829   if (isa<UndefValue>(Op) ||
00830       (isa<ConstantPointerNull>(Op) && LI.getPointerAddressSpace() == 0)) {
00831     // Insert a new store to null instruction before the load to indicate that
00832     // this code is not reachable.  We do this instead of inserting an
00833     // unreachable instruction directly because we cannot modify the CFG.
00834     new StoreInst(UndefValue::get(LI.getType()),
00835                   Constant::getNullValue(Op->getType()), &LI);
00836     return ReplaceInstUsesWith(LI, UndefValue::get(LI.getType()));
00837   }
00838 
00839   if (Op->hasOneUse()) {
00840     // Change select and PHI nodes to select values instead of addresses: this
00841     // helps alias analysis out a lot, allows many others simplifications, and
00842     // exposes redundancy in the code.
00843     //
00844     // Note that we cannot do the transformation unless we know that the
00845     // introduced loads cannot trap!  Something like this is valid as long as
00846     // the condition is always false: load (select bool %C, int* null, int* %G),
00847     // but it would not be valid if we transformed it to load from null
00848     // unconditionally.
00849     //
00850     if (SelectInst *SI = dyn_cast<SelectInst>(Op)) {
00851       // load (select (Cond, &V1, &V2))  --> select(Cond, load &V1, load &V2).
00852       unsigned Align = LI.getAlignment();
00853       if (isSafeToLoadUnconditionally(SI->getOperand(1), Align, SI) &&
00854           isSafeToLoadUnconditionally(SI->getOperand(2), Align, SI)) {
00855         LoadInst *V1 = Builder->CreateLoad(SI->getOperand(1),
00856                                            SI->getOperand(1)->getName()+".val");
00857         LoadInst *V2 = Builder->CreateLoad(SI->getOperand(2),
00858                                            SI->getOperand(2)->getName()+".val");
00859         V1->setAlignment(Align);
00860         V2->setAlignment(Align);
00861         return SelectInst::Create(SI->getCondition(), V1, V2);
00862       }
00863 
00864       // load (select (cond, null, P)) -> load P
00865       if (isa<ConstantPointerNull>(SI->getOperand(1)) &&
00866           LI.getPointerAddressSpace() == 0) {
00867         LI.setOperand(0, SI->getOperand(2));
00868         return &LI;
00869       }
00870 
00871       // load (select (cond, P, null)) -> load P
00872       if (isa<ConstantPointerNull>(SI->getOperand(2)) &&
00873           LI.getPointerAddressSpace() == 0) {
00874         LI.setOperand(0, SI->getOperand(1));
00875         return &LI;
00876       }
00877     }
00878   }
00879   return nullptr;
00880 }
00881 
00882 /// \brief Combine stores to match the type of value being stored.
00883 ///
00884 /// The core idea here is that the memory does not have any intrinsic type and
00885 /// where we can we should match the type of a store to the type of value being
00886 /// stored.
00887 ///
00888 /// However, this routine must never change the width of a store or the number of
00889 /// stores as that would introduce a semantic change. This combine is expected to
00890 /// be a semantic no-op which just allows stores to more closely model the types
00891 /// of their incoming values.
00892 ///
00893 /// Currently, we also refuse to change the precise type used for an atomic or
00894 /// volatile store. This is debatable, and might be reasonable to change later.
00895 /// However, it is risky in case some backend or other part of LLVM is relying
00896 /// on the exact type stored to select appropriate atomic operations.
00897 ///
00898 /// \returns true if the store was successfully combined away. This indicates
00899 /// the caller must erase the store instruction. We have to let the caller erase
00900 /// the store instruction as otherwise there is no way to signal whether it was
00901 /// combined or not: IC.EraseInstFromFunction returns a null pointer.
00902 static bool combineStoreToValueType(InstCombiner &IC, StoreInst &SI) {
00903   // FIXME: We could probably with some care handle both volatile and atomic
00904   // stores here but it isn't clear that this is important.
00905   if (!SI.isSimple())
00906     return false;
00907 
00908   Value *V = SI.getValueOperand();
00909 
00910   // Fold away bit casts of the stored value by storing the original type.
00911   if (auto *BC = dyn_cast<BitCastInst>(V)) {
00912     V = BC->getOperand(0);
00913     combineStoreToNewValue(IC, SI, V);
00914     return true;
00915   }
00916 
00917   // FIXME: We should also canonicalize loads of vectors when their elements are
00918   // cast to other types.
00919   return false;
00920 }
00921 
00922 static bool unpackStoreToAggregate(InstCombiner &IC, StoreInst &SI) {
00923   // FIXME: We could probably with some care handle both volatile and atomic
00924   // stores here but it isn't clear that this is important.
00925   if (!SI.isSimple())
00926     return false;
00927 
00928   Value *V = SI.getValueOperand();
00929   Type *T = V->getType();
00930 
00931   if (!T->isAggregateType())
00932     return false;
00933 
00934   if (auto *ST = dyn_cast<StructType>(T)) {
00935     // If the struct only have one element, we unpack.
00936     unsigned Count = ST->getNumElements();
00937     if (Count == 1) {
00938       V = IC.Builder->CreateExtractValue(V, 0);
00939       combineStoreToNewValue(IC, SI, V);
00940       return true;
00941     }
00942 
00943     // We don't want to break loads with padding here as we'd loose
00944     // the knowledge that padding exists for the rest of the pipeline.
00945     const DataLayout &DL = IC.getDataLayout();
00946     auto *SL = DL.getStructLayout(ST);
00947     if (SL->hasPadding())
00948       return false;
00949 
00950     SmallString<16> EltName = V->getName();
00951     EltName += ".elt";
00952     auto *Addr = SI.getPointerOperand();
00953     SmallString<16> AddrName = Addr->getName();
00954     AddrName += ".repack";
00955     auto *IdxType = Type::getInt32Ty(ST->getContext());
00956     auto *Zero = ConstantInt::get(IdxType, 0);
00957     for (unsigned i = 0; i < Count; i++) {
00958       Value *Indices[2] = {
00959         Zero,
00960         ConstantInt::get(IdxType, i),
00961       };
00962       auto *Ptr = IC.Builder->CreateInBoundsGEP(ST, Addr, makeArrayRef(Indices), AddrName);
00963       auto *Val = IC.Builder->CreateExtractValue(V, i, EltName);
00964       IC.Builder->CreateStore(Val, Ptr);
00965     }
00966 
00967     return true;
00968   }
00969 
00970   if (auto *AT = dyn_cast<ArrayType>(T)) {
00971     // If the array only have one element, we unpack.
00972     if (AT->getNumElements() == 1) {
00973       V = IC.Builder->CreateExtractValue(V, 0);
00974       combineStoreToNewValue(IC, SI, V);
00975       return true;
00976     }
00977   }
00978 
00979   return false;
00980 }
00981 
00982 /// equivalentAddressValues - Test if A and B will obviously have the same
00983 /// value. This includes recognizing that %t0 and %t1 will have the same
00984 /// value in code like this:
00985 ///   %t0 = getelementptr \@a, 0, 3
00986 ///   store i32 0, i32* %t0
00987 ///   %t1 = getelementptr \@a, 0, 3
00988 ///   %t2 = load i32* %t1
00989 ///
00990 static bool equivalentAddressValues(Value *A, Value *B) {
00991   // Test if the values are trivially equivalent.
00992   if (A == B) return true;
00993 
00994   // Test if the values come form identical arithmetic instructions.
00995   // This uses isIdenticalToWhenDefined instead of isIdenticalTo because
00996   // its only used to compare two uses within the same basic block, which
00997   // means that they'll always either have the same value or one of them
00998   // will have an undefined value.
00999   if (isa<BinaryOperator>(A) ||
01000       isa<CastInst>(A) ||
01001       isa<PHINode>(A) ||
01002       isa<GetElementPtrInst>(A))
01003     if (Instruction *BI = dyn_cast<Instruction>(B))
01004       if (cast<Instruction>(A)->isIdenticalToWhenDefined(BI))
01005         return true;
01006 
01007   // Otherwise they may not be equivalent.
01008   return false;
01009 }
01010 
01011 Instruction *InstCombiner::visitStoreInst(StoreInst &SI) {
01012   Value *Val = SI.getOperand(0);
01013   Value *Ptr = SI.getOperand(1);
01014 
01015   // Try to canonicalize the stored type.
01016   if (combineStoreToValueType(*this, SI))
01017     return EraseInstFromFunction(SI);
01018 
01019   // Attempt to improve the alignment.
01020   unsigned KnownAlign = getOrEnforceKnownAlignment(
01021       Ptr, DL.getPrefTypeAlignment(Val->getType()), DL, &SI, AC, DT);
01022   unsigned StoreAlign = SI.getAlignment();
01023   unsigned EffectiveStoreAlign =
01024       StoreAlign != 0 ? StoreAlign : DL.getABITypeAlignment(Val->getType());
01025 
01026   if (KnownAlign > EffectiveStoreAlign)
01027     SI.setAlignment(KnownAlign);
01028   else if (StoreAlign == 0)
01029     SI.setAlignment(EffectiveStoreAlign);
01030 
01031   // Try to canonicalize the stored type.
01032   if (unpackStoreToAggregate(*this, SI))
01033     return EraseInstFromFunction(SI);
01034 
01035   // Replace GEP indices if possible.
01036   if (Instruction *NewGEPI = replaceGEPIdxWithZero(*this, Ptr, SI)) {
01037       Worklist.Add(NewGEPI);
01038       return &SI;
01039   }
01040 
01041   // Don't hack volatile/ordered stores.
01042   // FIXME: Some bits are legal for ordered atomic stores; needs refactoring.
01043   if (!SI.isUnordered()) return nullptr;
01044 
01045   // If the RHS is an alloca with a single use, zapify the store, making the
01046   // alloca dead.
01047   if (Ptr->hasOneUse()) {
01048     if (isa<AllocaInst>(Ptr))
01049       return EraseInstFromFunction(SI);
01050     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
01051       if (isa<AllocaInst>(GEP->getOperand(0))) {
01052         if (GEP->getOperand(0)->hasOneUse())
01053           return EraseInstFromFunction(SI);
01054       }
01055     }
01056   }
01057 
01058   // Do really simple DSE, to catch cases where there are several consecutive
01059   // stores to the same location, separated by a few arithmetic operations. This
01060   // situation often occurs with bitfield accesses.
01061   BasicBlock::iterator BBI(SI);
01062   for (unsigned ScanInsts = 6; BBI != SI.getParent()->begin() && ScanInsts;
01063        --ScanInsts) {
01064     --BBI;
01065     // Don't count debug info directives, lest they affect codegen,
01066     // and we skip pointer-to-pointer bitcasts, which are NOPs.
01067     if (isa<DbgInfoIntrinsic>(BBI) ||
01068         (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
01069       ScanInsts++;
01070       continue;
01071     }
01072 
01073     if (StoreInst *PrevSI = dyn_cast<StoreInst>(BBI)) {
01074       // Prev store isn't volatile, and stores to the same location?
01075       if (PrevSI->isUnordered() && equivalentAddressValues(PrevSI->getOperand(1),
01076                                                         SI.getOperand(1))) {
01077         ++NumDeadStore;
01078         ++BBI;
01079         EraseInstFromFunction(*PrevSI);
01080         continue;
01081       }
01082       break;
01083     }
01084 
01085     // If this is a load, we have to stop.  However, if the loaded value is from
01086     // the pointer we're loading and is producing the pointer we're storing,
01087     // then *this* store is dead (X = load P; store X -> P).
01088     if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
01089       if (LI == Val && equivalentAddressValues(LI->getOperand(0), Ptr)) {
01090         assert(SI.isUnordered() && "can't eliminate ordering operation");
01091         return EraseInstFromFunction(SI);
01092       }
01093 
01094       // Otherwise, this is a load from some other location.  Stores before it
01095       // may not be dead.
01096       break;
01097     }
01098 
01099     // Don't skip over loads or things that can modify memory.
01100     if (BBI->mayWriteToMemory() || BBI->mayReadFromMemory())
01101       break;
01102   }
01103 
01104   // store X, null    -> turns into 'unreachable' in SimplifyCFG
01105   if (isa<ConstantPointerNull>(Ptr) && SI.getPointerAddressSpace() == 0) {
01106     if (!isa<UndefValue>(Val)) {
01107       SI.setOperand(0, UndefValue::get(Val->getType()));
01108       if (Instruction *U = dyn_cast<Instruction>(Val))
01109         Worklist.Add(U);  // Dropped a use.
01110     }
01111     return nullptr;  // Do not modify these!
01112   }
01113 
01114   // store undef, Ptr -> noop
01115   if (isa<UndefValue>(Val))
01116     return EraseInstFromFunction(SI);
01117 
01118   // The code below needs to be audited and adjusted for unordered atomics
01119   if (!SI.isSimple())
01120     return nullptr;
01121 
01122   // If this store is the last instruction in the basic block (possibly
01123   // excepting debug info instructions), and if the block ends with an
01124   // unconditional branch, try to move it to the successor block.
01125   BBI = SI.getIterator();
01126   do {
01127     ++BBI;
01128   } while (isa<DbgInfoIntrinsic>(BBI) ||
01129            (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy()));
01130   if (BranchInst *BI = dyn_cast<BranchInst>(BBI))
01131     if (BI->isUnconditional())
01132       if (SimplifyStoreAtEndOfBlock(SI))
01133         return nullptr;  // xform done!
01134 
01135   return nullptr;
01136 }
01137 
01138 /// SimplifyStoreAtEndOfBlock - Turn things like:
01139 ///   if () { *P = v1; } else { *P = v2 }
01140 /// into a phi node with a store in the successor.
01141 ///
01142 /// Simplify things like:
01143 ///   *P = v1; if () { *P = v2; }
01144 /// into a phi node with a store in the successor.
01145 ///
01146 bool InstCombiner::SimplifyStoreAtEndOfBlock(StoreInst &SI) {
01147   BasicBlock *StoreBB = SI.getParent();
01148 
01149   // Check to see if the successor block has exactly two incoming edges.  If
01150   // so, see if the other predecessor contains a store to the same location.
01151   // if so, insert a PHI node (if needed) and move the stores down.
01152   BasicBlock *DestBB = StoreBB->getTerminator()->getSuccessor(0);
01153 
01154   // Determine whether Dest has exactly two predecessors and, if so, compute
01155   // the other predecessor.
01156   pred_iterator PI = pred_begin(DestBB);
01157   BasicBlock *P = *PI;
01158   BasicBlock *OtherBB = nullptr;
01159 
01160   if (P != StoreBB)
01161     OtherBB = P;
01162 
01163   if (++PI == pred_end(DestBB))
01164     return false;
01165 
01166   P = *PI;
01167   if (P != StoreBB) {
01168     if (OtherBB)
01169       return false;
01170     OtherBB = P;
01171   }
01172   if (++PI != pred_end(DestBB))
01173     return false;
01174 
01175   // Bail out if all the relevant blocks aren't distinct (this can happen,
01176   // for example, if SI is in an infinite loop)
01177   if (StoreBB == DestBB || OtherBB == DestBB)
01178     return false;
01179 
01180   // Verify that the other block ends in a branch and is not otherwise empty.
01181   BasicBlock::iterator BBI(OtherBB->getTerminator());
01182   BranchInst *OtherBr = dyn_cast<BranchInst>(BBI);
01183   if (!OtherBr || BBI == OtherBB->begin())
01184     return false;
01185 
01186   // If the other block ends in an unconditional branch, check for the 'if then
01187   // else' case.  there is an instruction before the branch.
01188   StoreInst *OtherStore = nullptr;
01189   if (OtherBr->isUnconditional()) {
01190     --BBI;
01191     // Skip over debugging info.
01192     while (isa<DbgInfoIntrinsic>(BBI) ||
01193            (isa<BitCastInst>(BBI) && BBI->getType()->isPointerTy())) {
01194       if (BBI==OtherBB->begin())
01195         return false;
01196       --BBI;
01197     }
01198     // If this isn't a store, isn't a store to the same location, or is not the
01199     // right kind of store, bail out.
01200     OtherStore = dyn_cast<StoreInst>(BBI);
01201     if (!OtherStore || OtherStore->getOperand(1) != SI.getOperand(1) ||
01202         !SI.isSameOperationAs(OtherStore))
01203       return false;
01204   } else {
01205     // Otherwise, the other block ended with a conditional branch. If one of the
01206     // destinations is StoreBB, then we have the if/then case.
01207     if (OtherBr->getSuccessor(0) != StoreBB &&
01208         OtherBr->getSuccessor(1) != StoreBB)
01209       return false;
01210 
01211     // Okay, we know that OtherBr now goes to Dest and StoreBB, so this is an
01212     // if/then triangle.  See if there is a store to the same ptr as SI that
01213     // lives in OtherBB.
01214     for (;; --BBI) {
01215       // Check to see if we find the matching store.
01216       if ((OtherStore = dyn_cast<StoreInst>(BBI))) {
01217         if (OtherStore->getOperand(1) != SI.getOperand(1) ||
01218             !SI.isSameOperationAs(OtherStore))
01219           return false;
01220         break;
01221       }
01222       // If we find something that may be using or overwriting the stored
01223       // value, or if we run out of instructions, we can't do the xform.
01224       if (BBI->mayReadFromMemory() || BBI->mayWriteToMemory() ||
01225           BBI == OtherBB->begin())
01226         return false;
01227     }
01228 
01229     // In order to eliminate the store in OtherBr, we have to
01230     // make sure nothing reads or overwrites the stored value in
01231     // StoreBB.
01232     for (BasicBlock::iterator I = StoreBB->begin(); &*I != &SI; ++I) {
01233       // FIXME: This should really be AA driven.
01234       if (I->mayReadFromMemory() || I->mayWriteToMemory())
01235         return false;
01236     }
01237   }
01238 
01239   // Insert a PHI node now if we need it.
01240   Value *MergedVal = OtherStore->getOperand(0);
01241   if (MergedVal != SI.getOperand(0)) {
01242     PHINode *PN = PHINode::Create(MergedVal->getType(), 2, "storemerge");
01243     PN->addIncoming(SI.getOperand(0), SI.getParent());
01244     PN->addIncoming(OtherStore->getOperand(0), OtherBB);
01245     MergedVal = InsertNewInstBefore(PN, DestBB->front());
01246   }
01247 
01248   // Advance to a place where it is safe to insert the new store and
01249   // insert it.
01250   BBI = DestBB->getFirstInsertionPt();
01251   StoreInst *NewSI = new StoreInst(MergedVal, SI.getOperand(1),
01252                                    SI.isVolatile(),
01253                                    SI.getAlignment(),
01254                                    SI.getOrdering(),
01255                                    SI.getSynchScope());
01256   InsertNewInstBefore(NewSI, *BBI);
01257   NewSI->setDebugLoc(OtherStore->getDebugLoc());
01258 
01259   // If the two stores had AA tags, merge them.
01260   AAMDNodes AATags;
01261   SI.getAAMetadata(AATags);
01262   if (AATags) {
01263     OtherStore->getAAMetadata(AATags, /* Merge = */ true);
01264     NewSI->setAAMetadata(AATags);
01265   }
01266 
01267   // Nuke the old stores.
01268   EraseInstFromFunction(SI);
01269   EraseInstFromFunction(*OtherStore);
01270   return true;
01271 }