LLVM API Documentation

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