LLVM  mainline
GlobalOpt.cpp
Go to the documentation of this file.
00001 //===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
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 pass transforms simple global variables that never have their address
00011 // taken.  If obviously true, it marks read/write globals as constant, deletes
00012 // variables only stored to, etc.
00013 //
00014 //===----------------------------------------------------------------------===//
00015 
00016 #include "llvm/Transforms/IPO.h"
00017 #include "llvm/ADT/DenseMap.h"
00018 #include "llvm/ADT/STLExtras.h"
00019 #include "llvm/ADT/SmallPtrSet.h"
00020 #include "llvm/ADT/SmallSet.h"
00021 #include "llvm/ADT/SmallVector.h"
00022 #include "llvm/ADT/Statistic.h"
00023 #include "llvm/Analysis/ConstantFolding.h"
00024 #include "llvm/Analysis/MemoryBuiltins.h"
00025 #include "llvm/Analysis/TargetLibraryInfo.h"
00026 #include "llvm/IR/CallSite.h"
00027 #include "llvm/IR/CallingConv.h"
00028 #include "llvm/IR/Constants.h"
00029 #include "llvm/IR/DataLayout.h"
00030 #include "llvm/IR/DerivedTypes.h"
00031 #include "llvm/IR/Dominators.h"
00032 #include "llvm/IR/GetElementPtrTypeIterator.h"
00033 #include "llvm/IR/Instructions.h"
00034 #include "llvm/IR/IntrinsicInst.h"
00035 #include "llvm/IR/Module.h"
00036 #include "llvm/IR/Operator.h"
00037 #include "llvm/IR/ValueHandle.h"
00038 #include "llvm/Pass.h"
00039 #include "llvm/Support/Debug.h"
00040 #include "llvm/Support/ErrorHandling.h"
00041 #include "llvm/Support/MathExtras.h"
00042 #include "llvm/Support/raw_ostream.h"
00043 #include "llvm/Transforms/Utils/CtorUtils.h"
00044 #include "llvm/Transforms/Utils/GlobalStatus.h"
00045 #include "llvm/Transforms/Utils/ModuleUtils.h"
00046 #include <algorithm>
00047 #include <deque>
00048 using namespace llvm;
00049 
00050 #define DEBUG_TYPE "globalopt"
00051 
00052 STATISTIC(NumMarked    , "Number of globals marked constant");
00053 STATISTIC(NumUnnamed   , "Number of globals marked unnamed_addr");
00054 STATISTIC(NumSRA       , "Number of aggregate globals broken into scalars");
00055 STATISTIC(NumHeapSRA   , "Number of heap objects SRA'd");
00056 STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
00057 STATISTIC(NumDeleted   , "Number of globals deleted");
00058 STATISTIC(NumGlobUses  , "Number of global uses devirtualized");
00059 STATISTIC(NumLocalized , "Number of globals localized");
00060 STATISTIC(NumShrunkToBool  , "Number of global vars shrunk to booleans");
00061 STATISTIC(NumFastCallFns   , "Number of functions converted to fastcc");
00062 STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
00063 STATISTIC(NumNestRemoved   , "Number of nest attributes removed");
00064 STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
00065 STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
00066 STATISTIC(NumCXXDtorsRemoved, "Number of global C++ destructors removed");
00067 
00068 namespace {
00069   struct GlobalOpt : public ModulePass {
00070     void getAnalysisUsage(AnalysisUsage &AU) const override {
00071       AU.addRequired<TargetLibraryInfoWrapperPass>();
00072       AU.addRequired<DominatorTreeWrapperPass>();
00073     }
00074     static char ID; // Pass identification, replacement for typeid
00075     GlobalOpt() : ModulePass(ID) {
00076       initializeGlobalOptPass(*PassRegistry::getPassRegistry());
00077     }
00078 
00079     bool runOnModule(Module &M) override;
00080 
00081   private:
00082     bool OptimizeFunctions(Module &M);
00083     bool OptimizeGlobalVars(Module &M);
00084     bool OptimizeGlobalAliases(Module &M);
00085     bool deleteIfDead(GlobalValue &GV);
00086     bool processGlobal(GlobalValue &GV);
00087     bool processInternalGlobal(GlobalVariable *GV, const GlobalStatus &GS);
00088     bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn);
00089 
00090     bool isPointerValueDeadOnEntryToFunction(const Function *F,
00091                                              GlobalValue *GV);
00092 
00093     TargetLibraryInfo *TLI;
00094     SmallSet<const Comdat *, 8> NotDiscardableComdats;
00095   };
00096 }
00097 
00098 char GlobalOpt::ID = 0;
00099 INITIALIZE_PASS_BEGIN(GlobalOpt, "globalopt",
00100                 "Global Variable Optimizer", false, false)
00101 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
00102 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
00103 INITIALIZE_PASS_END(GlobalOpt, "globalopt",
00104                 "Global Variable Optimizer", false, false)
00105 
00106 ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
00107 
00108 /// Is this global variable possibly used by a leak checker as a root?  If so,
00109 /// we might not really want to eliminate the stores to it.
00110 static bool isLeakCheckerRoot(GlobalVariable *GV) {
00111   // A global variable is a root if it is a pointer, or could plausibly contain
00112   // a pointer.  There are two challenges; one is that we could have a struct
00113   // the has an inner member which is a pointer.  We recurse through the type to
00114   // detect these (up to a point).  The other is that we may actually be a union
00115   // of a pointer and another type, and so our LLVM type is an integer which
00116   // gets converted into a pointer, or our type is an [i8 x #] with a pointer
00117   // potentially contained here.
00118 
00119   if (GV->hasPrivateLinkage())
00120     return false;
00121 
00122   SmallVector<Type *, 4> Types;
00123   Types.push_back(GV->getValueType());
00124 
00125   unsigned Limit = 20;
00126   do {
00127     Type *Ty = Types.pop_back_val();
00128     switch (Ty->getTypeID()) {
00129       default: break;
00130       case Type::PointerTyID: return true;
00131       case Type::ArrayTyID:
00132       case Type::VectorTyID: {
00133         SequentialType *STy = cast<SequentialType>(Ty);
00134         Types.push_back(STy->getElementType());
00135         break;
00136       }
00137       case Type::StructTyID: {
00138         StructType *STy = cast<StructType>(Ty);
00139         if (STy->isOpaque()) return true;
00140         for (StructType::element_iterator I = STy->element_begin(),
00141                  E = STy->element_end(); I != E; ++I) {
00142           Type *InnerTy = *I;
00143           if (isa<PointerType>(InnerTy)) return true;
00144           if (isa<CompositeType>(InnerTy))
00145             Types.push_back(InnerTy);
00146         }
00147         break;
00148       }
00149     }
00150     if (--Limit == 0) return true;
00151   } while (!Types.empty());
00152   return false;
00153 }
00154 
00155 /// Given a value that is stored to a global but never read, determine whether
00156 /// it's safe to remove the store and the chain of computation that feeds the
00157 /// store.
00158 static bool IsSafeComputationToRemove(Value *V, const TargetLibraryInfo *TLI) {
00159   do {
00160     if (isa<Constant>(V))
00161       return true;
00162     if (!V->hasOneUse())
00163       return false;
00164     if (isa<LoadInst>(V) || isa<InvokeInst>(V) || isa<Argument>(V) ||
00165         isa<GlobalValue>(V))
00166       return false;
00167     if (isAllocationFn(V, TLI))
00168       return true;
00169 
00170     Instruction *I = cast<Instruction>(V);
00171     if (I->mayHaveSideEffects())
00172       return false;
00173     if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
00174       if (!GEP->hasAllConstantIndices())
00175         return false;
00176     } else if (I->getNumOperands() != 1) {
00177       return false;
00178     }
00179 
00180     V = I->getOperand(0);
00181   } while (1);
00182 }
00183 
00184 /// This GV is a pointer root.  Loop over all users of the global and clean up
00185 /// any that obviously don't assign the global a value that isn't dynamically
00186 /// allocated.
00187 static bool CleanupPointerRootUsers(GlobalVariable *GV,
00188                                     const TargetLibraryInfo *TLI) {
00189   // A brief explanation of leak checkers.  The goal is to find bugs where
00190   // pointers are forgotten, causing an accumulating growth in memory
00191   // usage over time.  The common strategy for leak checkers is to whitelist the
00192   // memory pointed to by globals at exit.  This is popular because it also
00193   // solves another problem where the main thread of a C++ program may shut down
00194   // before other threads that are still expecting to use those globals.  To
00195   // handle that case, we expect the program may create a singleton and never
00196   // destroy it.
00197 
00198   bool Changed = false;
00199 
00200   // If Dead[n].first is the only use of a malloc result, we can delete its
00201   // chain of computation and the store to the global in Dead[n].second.
00202   SmallVector<std::pair<Instruction *, Instruction *>, 32> Dead;
00203 
00204   // Constants can't be pointers to dynamically allocated memory.
00205   for (Value::user_iterator UI = GV->user_begin(), E = GV->user_end();
00206        UI != E;) {
00207     User *U = *UI++;
00208     if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
00209       Value *V = SI->getValueOperand();
00210       if (isa<Constant>(V)) {
00211         Changed = true;
00212         SI->eraseFromParent();
00213       } else if (Instruction *I = dyn_cast<Instruction>(V)) {
00214         if (I->hasOneUse())
00215           Dead.push_back(std::make_pair(I, SI));
00216       }
00217     } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(U)) {
00218       if (isa<Constant>(MSI->getValue())) {
00219         Changed = true;
00220         MSI->eraseFromParent();
00221       } else if (Instruction *I = dyn_cast<Instruction>(MSI->getValue())) {
00222         if (I->hasOneUse())
00223           Dead.push_back(std::make_pair(I, MSI));
00224       }
00225     } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(U)) {
00226       GlobalVariable *MemSrc = dyn_cast<GlobalVariable>(MTI->getSource());
00227       if (MemSrc && MemSrc->isConstant()) {
00228         Changed = true;
00229         MTI->eraseFromParent();
00230       } else if (Instruction *I = dyn_cast<Instruction>(MemSrc)) {
00231         if (I->hasOneUse())
00232           Dead.push_back(std::make_pair(I, MTI));
00233       }
00234     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
00235       if (CE->use_empty()) {
00236         CE->destroyConstant();
00237         Changed = true;
00238       }
00239     } else if (Constant *C = dyn_cast<Constant>(U)) {
00240       if (isSafeToDestroyConstant(C)) {
00241         C->destroyConstant();
00242         // This could have invalidated UI, start over from scratch.
00243         Dead.clear();
00244         CleanupPointerRootUsers(GV, TLI);
00245         return true;
00246       }
00247     }
00248   }
00249 
00250   for (int i = 0, e = Dead.size(); i != e; ++i) {
00251     if (IsSafeComputationToRemove(Dead[i].first, TLI)) {
00252       Dead[i].second->eraseFromParent();
00253       Instruction *I = Dead[i].first;
00254       do {
00255         if (isAllocationFn(I, TLI))
00256           break;
00257         Instruction *J = dyn_cast<Instruction>(I->getOperand(0));
00258         if (!J)
00259           break;
00260         I->eraseFromParent();
00261         I = J;
00262       } while (1);
00263       I->eraseFromParent();
00264     }
00265   }
00266 
00267   return Changed;
00268 }
00269 
00270 /// We just marked GV constant.  Loop over all users of the global, cleaning up
00271 /// the obvious ones.  This is largely just a quick scan over the use list to
00272 /// clean up the easy and obvious cruft.  This returns true if it made a change.
00273 static bool CleanupConstantGlobalUsers(Value *V, Constant *Init,
00274                                        const DataLayout &DL,
00275                                        TargetLibraryInfo *TLI) {
00276   bool Changed = false;
00277   // Note that we need to use a weak value handle for the worklist items. When
00278   // we delete a constant array, we may also be holding pointer to one of its
00279   // elements (or an element of one of its elements if we're dealing with an
00280   // array of arrays) in the worklist.
00281   SmallVector<WeakVH, 8> WorkList(V->user_begin(), V->user_end());
00282   while (!WorkList.empty()) {
00283     Value *UV = WorkList.pop_back_val();
00284     if (!UV)
00285       continue;
00286 
00287     User *U = cast<User>(UV);
00288 
00289     if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
00290       if (Init) {
00291         // Replace the load with the initializer.
00292         LI->replaceAllUsesWith(Init);
00293         LI->eraseFromParent();
00294         Changed = true;
00295       }
00296     } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
00297       // Store must be unreachable or storing Init into the global.
00298       SI->eraseFromParent();
00299       Changed = true;
00300     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
00301       if (CE->getOpcode() == Instruction::GetElementPtr) {
00302         Constant *SubInit = nullptr;
00303         if (Init)
00304           SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
00305         Changed |= CleanupConstantGlobalUsers(CE, SubInit, DL, TLI);
00306       } else if ((CE->getOpcode() == Instruction::BitCast &&
00307                   CE->getType()->isPointerTy()) ||
00308                  CE->getOpcode() == Instruction::AddrSpaceCast) {
00309         // Pointer cast, delete any stores and memsets to the global.
00310         Changed |= CleanupConstantGlobalUsers(CE, nullptr, DL, TLI);
00311       }
00312 
00313       if (CE->use_empty()) {
00314         CE->destroyConstant();
00315         Changed = true;
00316       }
00317     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
00318       // Do not transform "gepinst (gep constexpr (GV))" here, because forming
00319       // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
00320       // and will invalidate our notion of what Init is.
00321       Constant *SubInit = nullptr;
00322       if (!isa<ConstantExpr>(GEP->getOperand(0))) {
00323         ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(
00324             ConstantFoldInstruction(GEP, DL, TLI));
00325         if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
00326           SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
00327 
00328         // If the initializer is an all-null value and we have an inbounds GEP,
00329         // we already know what the result of any load from that GEP is.
00330         // TODO: Handle splats.
00331         if (Init && isa<ConstantAggregateZero>(Init) && GEP->isInBounds())
00332           SubInit = Constant::getNullValue(GEP->getResultElementType());
00333       }
00334       Changed |= CleanupConstantGlobalUsers(GEP, SubInit, DL, TLI);
00335 
00336       if (GEP->use_empty()) {
00337         GEP->eraseFromParent();
00338         Changed = true;
00339       }
00340     } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
00341       if (MI->getRawDest() == V) {
00342         MI->eraseFromParent();
00343         Changed = true;
00344       }
00345 
00346     } else if (Constant *C = dyn_cast<Constant>(U)) {
00347       // If we have a chain of dead constantexprs or other things dangling from
00348       // us, and if they are all dead, nuke them without remorse.
00349       if (isSafeToDestroyConstant(C)) {
00350         C->destroyConstant();
00351         CleanupConstantGlobalUsers(V, Init, DL, TLI);
00352         return true;
00353       }
00354     }
00355   }
00356   return Changed;
00357 }
00358 
00359 /// Return true if the specified instruction is a safe user of a derived
00360 /// expression from a global that we want to SROA.
00361 static bool isSafeSROAElementUse(Value *V) {
00362   // We might have a dead and dangling constant hanging off of here.
00363   if (Constant *C = dyn_cast<Constant>(V))
00364     return isSafeToDestroyConstant(C);
00365 
00366   Instruction *I = dyn_cast<Instruction>(V);
00367   if (!I) return false;
00368 
00369   // Loads are ok.
00370   if (isa<LoadInst>(I)) return true;
00371 
00372   // Stores *to* the pointer are ok.
00373   if (StoreInst *SI = dyn_cast<StoreInst>(I))
00374     return SI->getOperand(0) != V;
00375 
00376   // Otherwise, it must be a GEP.
00377   GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
00378   if (!GEPI) return false;
00379 
00380   if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
00381       !cast<Constant>(GEPI->getOperand(1))->isNullValue())
00382     return false;
00383 
00384   for (User *U : GEPI->users())
00385     if (!isSafeSROAElementUse(U))
00386       return false;
00387   return true;
00388 }
00389 
00390 
00391 /// U is a direct user of the specified global value.  Look at it and its uses
00392 /// and decide whether it is safe to SROA this global.
00393 static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
00394   // The user of the global must be a GEP Inst or a ConstantExpr GEP.
00395   if (!isa<GetElementPtrInst>(U) &&
00396       (!isa<ConstantExpr>(U) ||
00397        cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
00398     return false;
00399 
00400   // Check to see if this ConstantExpr GEP is SRA'able.  In particular, we
00401   // don't like < 3 operand CE's, and we don't like non-constant integer
00402   // indices.  This enforces that all uses are 'gep GV, 0, C, ...' for some
00403   // value of C.
00404   if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
00405       !cast<Constant>(U->getOperand(1))->isNullValue() ||
00406       !isa<ConstantInt>(U->getOperand(2)))
00407     return false;
00408 
00409   gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
00410   ++GEPI;  // Skip over the pointer index.
00411 
00412   // If this is a use of an array allocation, do a bit more checking for sanity.
00413   if (ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
00414     uint64_t NumElements = AT->getNumElements();
00415     ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
00416 
00417     // Check to make sure that index falls within the array.  If not,
00418     // something funny is going on, so we won't do the optimization.
00419     //
00420     if (Idx->getZExtValue() >= NumElements)
00421       return false;
00422 
00423     // We cannot scalar repl this level of the array unless any array
00424     // sub-indices are in-range constants.  In particular, consider:
00425     // A[0][i].  We cannot know that the user isn't doing invalid things like
00426     // allowing i to index an out-of-range subscript that accesses A[1].
00427     //
00428     // Scalar replacing *just* the outer index of the array is probably not
00429     // going to be a win anyway, so just give up.
00430     for (++GEPI; // Skip array index.
00431          GEPI != E;
00432          ++GEPI) {
00433       uint64_t NumElements;
00434       if (ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
00435         NumElements = SubArrayTy->getNumElements();
00436       else if (VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
00437         NumElements = SubVectorTy->getNumElements();
00438       else {
00439         assert((*GEPI)->isStructTy() &&
00440                "Indexed GEP type is not array, vector, or struct!");
00441         continue;
00442       }
00443 
00444       ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
00445       if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
00446         return false;
00447     }
00448   }
00449 
00450   for (User *UU : U->users())
00451     if (!isSafeSROAElementUse(UU))
00452       return false;
00453 
00454   return true;
00455 }
00456 
00457 /// Look at all uses of the global and decide whether it is safe for us to
00458 /// perform this transformation.
00459 static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
00460   for (User *U : GV->users())
00461     if (!IsUserOfGlobalSafeForSRA(U, GV))
00462       return false;
00463 
00464   return true;
00465 }
00466 
00467 
00468 /// Perform scalar replacement of aggregates on the specified global variable.
00469 /// This opens the door for other optimizations by exposing the behavior of the
00470 /// program in a more fine-grained way.  We have determined that this
00471 /// transformation is safe already.  We return the first global variable we
00472 /// insert so that the caller can reprocess it.
00473 static GlobalVariable *SRAGlobal(GlobalVariable *GV, const DataLayout &DL) {
00474   // Make sure this global only has simple uses that we can SRA.
00475   if (!GlobalUsersSafeToSRA(GV))
00476     return nullptr;
00477 
00478   assert(GV->hasLocalLinkage() && !GV->isConstant());
00479   Constant *Init = GV->getInitializer();
00480   Type *Ty = Init->getType();
00481 
00482   std::vector<GlobalVariable*> NewGlobals;
00483   Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
00484 
00485   // Get the alignment of the global, either explicit or target-specific.
00486   unsigned StartAlignment = GV->getAlignment();
00487   if (StartAlignment == 0)
00488     StartAlignment = DL.getABITypeAlignment(GV->getType());
00489 
00490   if (StructType *STy = dyn_cast<StructType>(Ty)) {
00491     NewGlobals.reserve(STy->getNumElements());
00492     const StructLayout &Layout = *DL.getStructLayout(STy);
00493     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
00494       Constant *In = Init->getAggregateElement(i);
00495       assert(In && "Couldn't get element of initializer?");
00496       GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
00497                                                GlobalVariable::InternalLinkage,
00498                                                In, GV->getName()+"."+Twine(i),
00499                                                GV->getThreadLocalMode(),
00500                                               GV->getType()->getAddressSpace());
00501       NGV->setExternallyInitialized(GV->isExternallyInitialized());
00502       NGV->copyAttributesFrom(GV);
00503       Globals.push_back(NGV);
00504       NewGlobals.push_back(NGV);
00505 
00506       // Calculate the known alignment of the field.  If the original aggregate
00507       // had 256 byte alignment for example, something might depend on that:
00508       // propagate info to each field.
00509       uint64_t FieldOffset = Layout.getElementOffset(i);
00510       unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
00511       if (NewAlign > DL.getABITypeAlignment(STy->getElementType(i)))
00512         NGV->setAlignment(NewAlign);
00513     }
00514   } else if (SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
00515     unsigned NumElements = 0;
00516     if (ArrayType *ATy = dyn_cast<ArrayType>(STy))
00517       NumElements = ATy->getNumElements();
00518     else
00519       NumElements = cast<VectorType>(STy)->getNumElements();
00520 
00521     if (NumElements > 16 && GV->hasNUsesOrMore(16))
00522       return nullptr; // It's not worth it.
00523     NewGlobals.reserve(NumElements);
00524 
00525     uint64_t EltSize = DL.getTypeAllocSize(STy->getElementType());
00526     unsigned EltAlign = DL.getABITypeAlignment(STy->getElementType());
00527     for (unsigned i = 0, e = NumElements; i != e; ++i) {
00528       Constant *In = Init->getAggregateElement(i);
00529       assert(In && "Couldn't get element of initializer?");
00530 
00531       GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
00532                                                GlobalVariable::InternalLinkage,
00533                                                In, GV->getName()+"."+Twine(i),
00534                                                GV->getThreadLocalMode(),
00535                                               GV->getType()->getAddressSpace());
00536       NGV->setExternallyInitialized(GV->isExternallyInitialized());
00537       NGV->copyAttributesFrom(GV);
00538       Globals.push_back(NGV);
00539       NewGlobals.push_back(NGV);
00540 
00541       // Calculate the known alignment of the field.  If the original aggregate
00542       // had 256 byte alignment for example, something might depend on that:
00543       // propagate info to each field.
00544       unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
00545       if (NewAlign > EltAlign)
00546         NGV->setAlignment(NewAlign);
00547     }
00548   }
00549 
00550   if (NewGlobals.empty())
00551     return nullptr;
00552 
00553   DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV << "\n");
00554 
00555   Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
00556 
00557   // Loop over all of the uses of the global, replacing the constantexpr geps,
00558   // with smaller constantexpr geps or direct references.
00559   while (!GV->use_empty()) {
00560     User *GEP = GV->user_back();
00561     assert(((isa<ConstantExpr>(GEP) &&
00562              cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
00563             isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
00564 
00565     // Ignore the 1th operand, which has to be zero or else the program is quite
00566     // broken (undefined).  Get the 2nd operand, which is the structure or array
00567     // index.
00568     unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
00569     if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
00570 
00571     Value *NewPtr = NewGlobals[Val];
00572     Type *NewTy = NewGlobals[Val]->getValueType();
00573 
00574     // Form a shorter GEP if needed.
00575     if (GEP->getNumOperands() > 3) {
00576       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
00577         SmallVector<Constant*, 8> Idxs;
00578         Idxs.push_back(NullInt);
00579         for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
00580           Idxs.push_back(CE->getOperand(i));
00581         NewPtr =
00582             ConstantExpr::getGetElementPtr(NewTy, cast<Constant>(NewPtr), Idxs);
00583       } else {
00584         GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
00585         SmallVector<Value*, 8> Idxs;
00586         Idxs.push_back(NullInt);
00587         for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
00588           Idxs.push_back(GEPI->getOperand(i));
00589         NewPtr = GetElementPtrInst::Create(
00590             NewTy, NewPtr, Idxs, GEPI->getName() + "." + Twine(Val), GEPI);
00591       }
00592     }
00593     GEP->replaceAllUsesWith(NewPtr);
00594 
00595     if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
00596       GEPI->eraseFromParent();
00597     else
00598       cast<ConstantExpr>(GEP)->destroyConstant();
00599   }
00600 
00601   // Delete the old global, now that it is dead.
00602   Globals.erase(GV);
00603   ++NumSRA;
00604 
00605   // Loop over the new globals array deleting any globals that are obviously
00606   // dead.  This can arise due to scalarization of a structure or an array that
00607   // has elements that are dead.
00608   unsigned FirstGlobal = 0;
00609   for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
00610     if (NewGlobals[i]->use_empty()) {
00611       Globals.erase(NewGlobals[i]);
00612       if (FirstGlobal == i) ++FirstGlobal;
00613     }
00614 
00615   return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : nullptr;
00616 }
00617 
00618 /// Return true if all users of the specified value will trap if the value is
00619 /// dynamically null.  PHIs keeps track of any phi nodes we've seen to avoid
00620 /// reprocessing them.
00621 static bool AllUsesOfValueWillTrapIfNull(const Value *V,
00622                                         SmallPtrSetImpl<const PHINode*> &PHIs) {
00623   for (const User *U : V->users())
00624     if (isa<LoadInst>(U)) {
00625       // Will trap.
00626     } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
00627       if (SI->getOperand(0) == V) {
00628         //cerr << "NONTRAPPING USE: " << *U;
00629         return false;  // Storing the value.
00630       }
00631     } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
00632       if (CI->getCalledValue() != V) {
00633         //cerr << "NONTRAPPING USE: " << *U;
00634         return false;  // Not calling the ptr
00635       }
00636     } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
00637       if (II->getCalledValue() != V) {
00638         //cerr << "NONTRAPPING USE: " << *U;
00639         return false;  // Not calling the ptr
00640       }
00641     } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
00642       if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
00643     } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
00644       if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
00645     } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
00646       // If we've already seen this phi node, ignore it, it has already been
00647       // checked.
00648       if (PHIs.insert(PN).second && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
00649         return false;
00650     } else if (isa<ICmpInst>(U) &&
00651                isa<ConstantPointerNull>(U->getOperand(1))) {
00652       // Ignore icmp X, null
00653     } else {
00654       //cerr << "NONTRAPPING USE: " << *U;
00655       return false;
00656     }
00657 
00658   return true;
00659 }
00660 
00661 /// Return true if all uses of any loads from GV will trap if the loaded value
00662 /// is null.  Note that this also permits comparisons of the loaded value
00663 /// against null, as a special case.
00664 static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
00665   for (const User *U : GV->users())
00666     if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
00667       SmallPtrSet<const PHINode*, 8> PHIs;
00668       if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
00669         return false;
00670     } else if (isa<StoreInst>(U)) {
00671       // Ignore stores to the global.
00672     } else {
00673       // We don't know or understand this user, bail out.
00674       //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
00675       return false;
00676     }
00677   return true;
00678 }
00679 
00680 static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
00681   bool Changed = false;
00682   for (auto UI = V->user_begin(), E = V->user_end(); UI != E; ) {
00683     Instruction *I = cast<Instruction>(*UI++);
00684     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
00685       LI->setOperand(0, NewV);
00686       Changed = true;
00687     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
00688       if (SI->getOperand(1) == V) {
00689         SI->setOperand(1, NewV);
00690         Changed = true;
00691       }
00692     } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
00693       CallSite CS(I);
00694       if (CS.getCalledValue() == V) {
00695         // Calling through the pointer!  Turn into a direct call, but be careful
00696         // that the pointer is not also being passed as an argument.
00697         CS.setCalledFunction(NewV);
00698         Changed = true;
00699         bool PassedAsArg = false;
00700         for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
00701           if (CS.getArgument(i) == V) {
00702             PassedAsArg = true;
00703             CS.setArgument(i, NewV);
00704           }
00705 
00706         if (PassedAsArg) {
00707           // Being passed as an argument also.  Be careful to not invalidate UI!
00708           UI = V->user_begin();
00709         }
00710       }
00711     } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
00712       Changed |= OptimizeAwayTrappingUsesOfValue(CI,
00713                                 ConstantExpr::getCast(CI->getOpcode(),
00714                                                       NewV, CI->getType()));
00715       if (CI->use_empty()) {
00716         Changed = true;
00717         CI->eraseFromParent();
00718       }
00719     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
00720       // Should handle GEP here.
00721       SmallVector<Constant*, 8> Idxs;
00722       Idxs.reserve(GEPI->getNumOperands()-1);
00723       for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
00724            i != e; ++i)
00725         if (Constant *C = dyn_cast<Constant>(*i))
00726           Idxs.push_back(C);
00727         else
00728           break;
00729       if (Idxs.size() == GEPI->getNumOperands()-1)
00730         Changed |= OptimizeAwayTrappingUsesOfValue(
00731             GEPI, ConstantExpr::getGetElementPtr(nullptr, NewV, Idxs));
00732       if (GEPI->use_empty()) {
00733         Changed = true;
00734         GEPI->eraseFromParent();
00735       }
00736     }
00737   }
00738 
00739   return Changed;
00740 }
00741 
00742 
00743 /// The specified global has only one non-null value stored into it.  If there
00744 /// are uses of the loaded value that would trap if the loaded value is
00745 /// dynamically null, then we know that they cannot be reachable with a null
00746 /// optimize away the load.
00747 static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
00748                                             const DataLayout &DL,
00749                                             TargetLibraryInfo *TLI) {
00750   bool Changed = false;
00751 
00752   // Keep track of whether we are able to remove all the uses of the global
00753   // other than the store that defines it.
00754   bool AllNonStoreUsesGone = true;
00755 
00756   // Replace all uses of loads with uses of uses of the stored value.
00757   for (Value::user_iterator GUI = GV->user_begin(), E = GV->user_end(); GUI != E;){
00758     User *GlobalUser = *GUI++;
00759     if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
00760       Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
00761       // If we were able to delete all uses of the loads
00762       if (LI->use_empty()) {
00763         LI->eraseFromParent();
00764         Changed = true;
00765       } else {
00766         AllNonStoreUsesGone = false;
00767       }
00768     } else if (isa<StoreInst>(GlobalUser)) {
00769       // Ignore the store that stores "LV" to the global.
00770       assert(GlobalUser->getOperand(1) == GV &&
00771              "Must be storing *to* the global");
00772     } else {
00773       AllNonStoreUsesGone = false;
00774 
00775       // If we get here we could have other crazy uses that are transitively
00776       // loaded.
00777       assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
00778               isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser) ||
00779               isa<BitCastInst>(GlobalUser) ||
00780               isa<GetElementPtrInst>(GlobalUser)) &&
00781              "Only expect load and stores!");
00782     }
00783   }
00784 
00785   if (Changed) {
00786     DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV << "\n");
00787     ++NumGlobUses;
00788   }
00789 
00790   // If we nuked all of the loads, then none of the stores are needed either,
00791   // nor is the global.
00792   if (AllNonStoreUsesGone) {
00793     if (isLeakCheckerRoot(GV)) {
00794       Changed |= CleanupPointerRootUsers(GV, TLI);
00795     } else {
00796       Changed = true;
00797       CleanupConstantGlobalUsers(GV, nullptr, DL, TLI);
00798     }
00799     if (GV->use_empty()) {
00800       DEBUG(dbgs() << "  *** GLOBAL NOW DEAD!\n");
00801       Changed = true;
00802       GV->eraseFromParent();
00803       ++NumDeleted;
00804     }
00805   }
00806   return Changed;
00807 }
00808 
00809 /// Walk the use list of V, constant folding all of the instructions that are
00810 /// foldable.
00811 static void ConstantPropUsersOf(Value *V, const DataLayout &DL,
00812                                 TargetLibraryInfo *TLI) {
00813   for (Value::user_iterator UI = V->user_begin(), E = V->user_end(); UI != E; )
00814     if (Instruction *I = dyn_cast<Instruction>(*UI++))
00815       if (Constant *NewC = ConstantFoldInstruction(I, DL, TLI)) {
00816         I->replaceAllUsesWith(NewC);
00817 
00818         // Advance UI to the next non-I use to avoid invalidating it!
00819         // Instructions could multiply use V.
00820         while (UI != E && *UI == I)
00821           ++UI;
00822         I->eraseFromParent();
00823       }
00824 }
00825 
00826 /// This function takes the specified global variable, and transforms the
00827 /// program as if it always contained the result of the specified malloc.
00828 /// Because it is always the result of the specified malloc, there is no reason
00829 /// to actually DO the malloc.  Instead, turn the malloc into a global, and any
00830 /// loads of GV as uses of the new global.
00831 static GlobalVariable *
00832 OptimizeGlobalAddressOfMalloc(GlobalVariable *GV, CallInst *CI, Type *AllocTy,
00833                               ConstantInt *NElements, const DataLayout &DL,
00834                               TargetLibraryInfo *TLI) {
00835   DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << "  CALL = " << *CI << '\n');
00836 
00837   Type *GlobalType;
00838   if (NElements->getZExtValue() == 1)
00839     GlobalType = AllocTy;
00840   else
00841     // If we have an array allocation, the global variable is of an array.
00842     GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
00843 
00844   // Create the new global variable.  The contents of the malloc'd memory is
00845   // undefined, so initialize with an undef value.
00846   GlobalVariable *NewGV = new GlobalVariable(
00847       *GV->getParent(), GlobalType, false, GlobalValue::InternalLinkage,
00848       UndefValue::get(GlobalType), GV->getName() + ".body", nullptr,
00849       GV->getThreadLocalMode());
00850 
00851   // If there are bitcast users of the malloc (which is typical, usually we have
00852   // a malloc + bitcast) then replace them with uses of the new global.  Update
00853   // other users to use the global as well.
00854   BitCastInst *TheBC = nullptr;
00855   while (!CI->use_empty()) {
00856     Instruction *User = cast<Instruction>(CI->user_back());
00857     if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
00858       if (BCI->getType() == NewGV->getType()) {
00859         BCI->replaceAllUsesWith(NewGV);
00860         BCI->eraseFromParent();
00861       } else {
00862         BCI->setOperand(0, NewGV);
00863       }
00864     } else {
00865       if (!TheBC)
00866         TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
00867       User->replaceUsesOfWith(CI, TheBC);
00868     }
00869   }
00870 
00871   Constant *RepValue = NewGV;
00872   if (NewGV->getType() != GV->getValueType())
00873     RepValue = ConstantExpr::getBitCast(RepValue, GV->getValueType());
00874 
00875   // If there is a comparison against null, we will insert a global bool to
00876   // keep track of whether the global was initialized yet or not.
00877   GlobalVariable *InitBool =
00878     new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
00879                        GlobalValue::InternalLinkage,
00880                        ConstantInt::getFalse(GV->getContext()),
00881                        GV->getName()+".init", GV->getThreadLocalMode());
00882   bool InitBoolUsed = false;
00883 
00884   // Loop over all uses of GV, processing them in turn.
00885   while (!GV->use_empty()) {
00886     if (StoreInst *SI = dyn_cast<StoreInst>(GV->user_back())) {
00887       // The global is initialized when the store to it occurs.
00888       new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, false, 0,
00889                     SI->getOrdering(), SI->getSynchScope(), SI);
00890       SI->eraseFromParent();
00891       continue;
00892     }
00893 
00894     LoadInst *LI = cast<LoadInst>(GV->user_back());
00895     while (!LI->use_empty()) {
00896       Use &LoadUse = *LI->use_begin();
00897       ICmpInst *ICI = dyn_cast<ICmpInst>(LoadUse.getUser());
00898       if (!ICI) {
00899         LoadUse = RepValue;
00900         continue;
00901       }
00902 
00903       // Replace the cmp X, 0 with a use of the bool value.
00904       // Sink the load to where the compare was, if atomic rules allow us to.
00905       Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", false, 0,
00906                                LI->getOrdering(), LI->getSynchScope(),
00907                                LI->isUnordered() ? (Instruction*)ICI : LI);
00908       InitBoolUsed = true;
00909       switch (ICI->getPredicate()) {
00910       default: llvm_unreachable("Unknown ICmp Predicate!");
00911       case ICmpInst::ICMP_ULT:
00912       case ICmpInst::ICMP_SLT:   // X < null -> always false
00913         LV = ConstantInt::getFalse(GV->getContext());
00914         break;
00915       case ICmpInst::ICMP_ULE:
00916       case ICmpInst::ICMP_SLE:
00917       case ICmpInst::ICMP_EQ:
00918         LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
00919         break;
00920       case ICmpInst::ICMP_NE:
00921       case ICmpInst::ICMP_UGE:
00922       case ICmpInst::ICMP_SGE:
00923       case ICmpInst::ICMP_UGT:
00924       case ICmpInst::ICMP_SGT:
00925         break;  // no change.
00926       }
00927       ICI->replaceAllUsesWith(LV);
00928       ICI->eraseFromParent();
00929     }
00930     LI->eraseFromParent();
00931   }
00932 
00933   // If the initialization boolean was used, insert it, otherwise delete it.
00934   if (!InitBoolUsed) {
00935     while (!InitBool->use_empty())  // Delete initializations
00936       cast<StoreInst>(InitBool->user_back())->eraseFromParent();
00937     delete InitBool;
00938   } else
00939     GV->getParent()->getGlobalList().insert(GV->getIterator(), InitBool);
00940 
00941   // Now the GV is dead, nuke it and the malloc..
00942   GV->eraseFromParent();
00943   CI->eraseFromParent();
00944 
00945   // To further other optimizations, loop over all users of NewGV and try to
00946   // constant prop them.  This will promote GEP instructions with constant
00947   // indices into GEP constant-exprs, which will allow global-opt to hack on it.
00948   ConstantPropUsersOf(NewGV, DL, TLI);
00949   if (RepValue != NewGV)
00950     ConstantPropUsersOf(RepValue, DL, TLI);
00951 
00952   return NewGV;
00953 }
00954 
00955 /// Scan the use-list of V checking to make sure that there are no complex uses
00956 /// of V.  We permit simple things like dereferencing the pointer, but not
00957 /// storing through the address, unless it is to the specified global.
00958 static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
00959                                                       const GlobalVariable *GV,
00960                                         SmallPtrSetImpl<const PHINode*> &PHIs) {
00961   for (const User *U : V->users()) {
00962     const Instruction *Inst = cast<Instruction>(U);
00963 
00964     if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
00965       continue; // Fine, ignore.
00966     }
00967 
00968     if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
00969       if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
00970         return false;  // Storing the pointer itself... bad.
00971       continue; // Otherwise, storing through it, or storing into GV... fine.
00972     }
00973 
00974     // Must index into the array and into the struct.
00975     if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
00976       if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
00977         return false;
00978       continue;
00979     }
00980 
00981     if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
00982       // PHIs are ok if all uses are ok.  Don't infinitely recurse through PHI
00983       // cycles.
00984       if (PHIs.insert(PN).second)
00985         if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
00986           return false;
00987       continue;
00988     }
00989 
00990     if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
00991       if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
00992         return false;
00993       continue;
00994     }
00995 
00996     return false;
00997   }
00998   return true;
00999 }
01000 
01001 /// The Alloc pointer is stored into GV somewhere.  Transform all uses of the
01002 /// allocation into loads from the global and uses of the resultant pointer.
01003 /// Further, delete the store into GV.  This assumes that these value pass the
01004 /// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
01005 static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
01006                                           GlobalVariable *GV) {
01007   while (!Alloc->use_empty()) {
01008     Instruction *U = cast<Instruction>(*Alloc->user_begin());
01009     Instruction *InsertPt = U;
01010     if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
01011       // If this is the store of the allocation into the global, remove it.
01012       if (SI->getOperand(1) == GV) {
01013         SI->eraseFromParent();
01014         continue;
01015       }
01016     } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
01017       // Insert the load in the corresponding predecessor, not right before the
01018       // PHI.
01019       InsertPt = PN->getIncomingBlock(*Alloc->use_begin())->getTerminator();
01020     } else if (isa<BitCastInst>(U)) {
01021       // Must be bitcast between the malloc and store to initialize the global.
01022       ReplaceUsesOfMallocWithGlobal(U, GV);
01023       U->eraseFromParent();
01024       continue;
01025     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
01026       // If this is a "GEP bitcast" and the user is a store to the global, then
01027       // just process it as a bitcast.
01028       if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
01029         if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->user_back()))
01030           if (SI->getOperand(1) == GV) {
01031             // Must be bitcast GEP between the malloc and store to initialize
01032             // the global.
01033             ReplaceUsesOfMallocWithGlobal(GEPI, GV);
01034             GEPI->eraseFromParent();
01035             continue;
01036           }
01037     }
01038 
01039     // Insert a load from the global, and use it instead of the malloc.
01040     Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
01041     U->replaceUsesOfWith(Alloc, NL);
01042   }
01043 }
01044 
01045 /// Verify that all uses of V (a load, or a phi of a load) are simple enough to
01046 /// perform heap SRA on.  This permits GEP's that index through the array and
01047 /// struct field, icmps of null, and PHIs.
01048 static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
01049                         SmallPtrSetImpl<const PHINode*> &LoadUsingPHIs,
01050                         SmallPtrSetImpl<const PHINode*> &LoadUsingPHIsPerLoad) {
01051   // We permit two users of the load: setcc comparing against the null
01052   // pointer, and a getelementptr of a specific form.
01053   for (const User *U : V->users()) {
01054     const Instruction *UI = cast<Instruction>(U);
01055 
01056     // Comparison against null is ok.
01057     if (const ICmpInst *ICI = dyn_cast<ICmpInst>(UI)) {
01058       if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
01059         return false;
01060       continue;
01061     }
01062 
01063     // getelementptr is also ok, but only a simple form.
01064     if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(UI)) {
01065       // Must index into the array and into the struct.
01066       if (GEPI->getNumOperands() < 3)
01067         return false;
01068 
01069       // Otherwise the GEP is ok.
01070       continue;
01071     }
01072 
01073     if (const PHINode *PN = dyn_cast<PHINode>(UI)) {
01074       if (!LoadUsingPHIsPerLoad.insert(PN).second)
01075         // This means some phi nodes are dependent on each other.
01076         // Avoid infinite looping!
01077         return false;
01078       if (!LoadUsingPHIs.insert(PN).second)
01079         // If we have already analyzed this PHI, then it is safe.
01080         continue;
01081 
01082       // Make sure all uses of the PHI are simple enough to transform.
01083       if (!LoadUsesSimpleEnoughForHeapSRA(PN,
01084                                           LoadUsingPHIs, LoadUsingPHIsPerLoad))
01085         return false;
01086 
01087       continue;
01088     }
01089 
01090     // Otherwise we don't know what this is, not ok.
01091     return false;
01092   }
01093 
01094   return true;
01095 }
01096 
01097 
01098 /// If all users of values loaded from GV are simple enough to perform HeapSRA,
01099 /// return true.
01100 static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
01101                                                     Instruction *StoredVal) {
01102   SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
01103   SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
01104   for (const User *U : GV->users())
01105     if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
01106       if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
01107                                           LoadUsingPHIsPerLoad))
01108         return false;
01109       LoadUsingPHIsPerLoad.clear();
01110     }
01111 
01112   // If we reach here, we know that all uses of the loads and transitive uses
01113   // (through PHI nodes) are simple enough to transform.  However, we don't know
01114   // that all inputs the to the PHI nodes are in the same equivalence sets.
01115   // Check to verify that all operands of the PHIs are either PHIS that can be
01116   // transformed, loads from GV, or MI itself.
01117   for (const PHINode *PN : LoadUsingPHIs) {
01118     for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
01119       Value *InVal = PN->getIncomingValue(op);
01120 
01121       // PHI of the stored value itself is ok.
01122       if (InVal == StoredVal) continue;
01123 
01124       if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
01125         // One of the PHIs in our set is (optimistically) ok.
01126         if (LoadUsingPHIs.count(InPN))
01127           continue;
01128         return false;
01129       }
01130 
01131       // Load from GV is ok.
01132       if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
01133         if (LI->getOperand(0) == GV)
01134           continue;
01135 
01136       // UNDEF? NULL?
01137 
01138       // Anything else is rejected.
01139       return false;
01140     }
01141   }
01142 
01143   return true;
01144 }
01145 
01146 static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
01147                DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
01148                    std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
01149   std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
01150 
01151   if (FieldNo >= FieldVals.size())
01152     FieldVals.resize(FieldNo+1);
01153 
01154   // If we already have this value, just reuse the previously scalarized
01155   // version.
01156   if (Value *FieldVal = FieldVals[FieldNo])
01157     return FieldVal;
01158 
01159   // Depending on what instruction this is, we have several cases.
01160   Value *Result;
01161   if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
01162     // This is a scalarized version of the load from the global.  Just create
01163     // a new Load of the scalarized global.
01164     Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
01165                                            InsertedScalarizedValues,
01166                                            PHIsToRewrite),
01167                           LI->getName()+".f"+Twine(FieldNo), LI);
01168   } else {
01169     PHINode *PN = cast<PHINode>(V);
01170     // PN's type is pointer to struct.  Make a new PHI of pointer to struct
01171     // field.
01172 
01173     PointerType *PTy = cast<PointerType>(PN->getType());
01174     StructType *ST = cast<StructType>(PTy->getElementType());
01175 
01176     unsigned AS = PTy->getAddressSpace();
01177     PHINode *NewPN =
01178       PHINode::Create(PointerType::get(ST->getElementType(FieldNo), AS),
01179                      PN->getNumIncomingValues(),
01180                      PN->getName()+".f"+Twine(FieldNo), PN);
01181     Result = NewPN;
01182     PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
01183   }
01184 
01185   return FieldVals[FieldNo] = Result;
01186 }
01187 
01188 /// Given a load instruction and a value derived from the load, rewrite the
01189 /// derived value to use the HeapSRoA'd load.
01190 static void RewriteHeapSROALoadUser(Instruction *LoadUser,
01191              DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
01192                    std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
01193   // If this is a comparison against null, handle it.
01194   if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
01195     assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
01196     // If we have a setcc of the loaded pointer, we can use a setcc of any
01197     // field.
01198     Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
01199                                    InsertedScalarizedValues, PHIsToRewrite);
01200 
01201     Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
01202                               Constant::getNullValue(NPtr->getType()),
01203                               SCI->getName());
01204     SCI->replaceAllUsesWith(New);
01205     SCI->eraseFromParent();
01206     return;
01207   }
01208 
01209   // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
01210   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
01211     assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
01212            && "Unexpected GEPI!");
01213 
01214     // Load the pointer for this field.
01215     unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
01216     Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
01217                                      InsertedScalarizedValues, PHIsToRewrite);
01218 
01219     // Create the new GEP idx vector.
01220     SmallVector<Value*, 8> GEPIdx;
01221     GEPIdx.push_back(GEPI->getOperand(1));
01222     GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
01223 
01224     Value *NGEPI = GetElementPtrInst::Create(GEPI->getResultElementType(), NewPtr, GEPIdx,
01225                                              GEPI->getName(), GEPI);
01226     GEPI->replaceAllUsesWith(NGEPI);
01227     GEPI->eraseFromParent();
01228     return;
01229   }
01230 
01231   // Recursively transform the users of PHI nodes.  This will lazily create the
01232   // PHIs that are needed for individual elements.  Keep track of what PHIs we
01233   // see in InsertedScalarizedValues so that we don't get infinite loops (very
01234   // antisocial).  If the PHI is already in InsertedScalarizedValues, it has
01235   // already been seen first by another load, so its uses have already been
01236   // processed.
01237   PHINode *PN = cast<PHINode>(LoadUser);
01238   if (!InsertedScalarizedValues.insert(std::make_pair(PN,
01239                                               std::vector<Value*>())).second)
01240     return;
01241 
01242   // If this is the first time we've seen this PHI, recursively process all
01243   // users.
01244   for (auto UI = PN->user_begin(), E = PN->user_end(); UI != E;) {
01245     Instruction *User = cast<Instruction>(*UI++);
01246     RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
01247   }
01248 }
01249 
01250 /// We are performing Heap SRoA on a global.  Ptr is a value loaded from the
01251 /// global.  Eliminate all uses of Ptr, making them use FieldGlobals instead.
01252 /// All uses of loaded values satisfy AllGlobalLoadUsesSimpleEnoughForHeapSRA.
01253 static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
01254                DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
01255                    std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
01256   for (auto UI = Load->user_begin(), E = Load->user_end(); UI != E;) {
01257     Instruction *User = cast<Instruction>(*UI++);
01258     RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
01259   }
01260 
01261   if (Load->use_empty()) {
01262     Load->eraseFromParent();
01263     InsertedScalarizedValues.erase(Load);
01264   }
01265 }
01266 
01267 /// CI is an allocation of an array of structures.  Break it up into multiple
01268 /// allocations of arrays of the fields.
01269 static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
01270                                             Value *NElems, const DataLayout &DL,
01271                                             const TargetLibraryInfo *TLI) {
01272   DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << "  MALLOC = " << *CI << '\n');
01273   Type *MAT = getMallocAllocatedType(CI, TLI);
01274   StructType *STy = cast<StructType>(MAT);
01275 
01276   // There is guaranteed to be at least one use of the malloc (storing
01277   // it into GV).  If there are other uses, change them to be uses of
01278   // the global to simplify later code.  This also deletes the store
01279   // into GV.
01280   ReplaceUsesOfMallocWithGlobal(CI, GV);
01281 
01282   // Okay, at this point, there are no users of the malloc.  Insert N
01283   // new mallocs at the same place as CI, and N globals.
01284   std::vector<Value*> FieldGlobals;
01285   std::vector<Value*> FieldMallocs;
01286 
01287   unsigned AS = GV->getType()->getPointerAddressSpace();
01288   for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
01289     Type *FieldTy = STy->getElementType(FieldNo);
01290     PointerType *PFieldTy = PointerType::get(FieldTy, AS);
01291 
01292     GlobalVariable *NGV = new GlobalVariable(
01293         *GV->getParent(), PFieldTy, false, GlobalValue::InternalLinkage,
01294         Constant::getNullValue(PFieldTy), GV->getName() + ".f" + Twine(FieldNo),
01295         nullptr, GV->getThreadLocalMode());
01296     NGV->copyAttributesFrom(GV);
01297     FieldGlobals.push_back(NGV);
01298 
01299     unsigned TypeSize = DL.getTypeAllocSize(FieldTy);
01300     if (StructType *ST = dyn_cast<StructType>(FieldTy))
01301       TypeSize = DL.getStructLayout(ST)->getSizeInBytes();
01302     Type *IntPtrTy = DL.getIntPtrType(CI->getType());
01303     Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
01304                                         ConstantInt::get(IntPtrTy, TypeSize),
01305                                         NElems, nullptr,
01306                                         CI->getName() + ".f" + Twine(FieldNo));
01307     FieldMallocs.push_back(NMI);
01308     new StoreInst(NMI, NGV, CI);
01309   }
01310 
01311   // The tricky aspect of this transformation is handling the case when malloc
01312   // fails.  In the original code, malloc failing would set the result pointer
01313   // of malloc to null.  In this case, some mallocs could succeed and others
01314   // could fail.  As such, we emit code that looks like this:
01315   //    F0 = malloc(field0)
01316   //    F1 = malloc(field1)
01317   //    F2 = malloc(field2)
01318   //    if (F0 == 0 || F1 == 0 || F2 == 0) {
01319   //      if (F0) { free(F0); F0 = 0; }
01320   //      if (F1) { free(F1); F1 = 0; }
01321   //      if (F2) { free(F2); F2 = 0; }
01322   //    }
01323   // The malloc can also fail if its argument is too large.
01324   Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
01325   Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
01326                                   ConstantZero, "isneg");
01327   for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
01328     Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
01329                              Constant::getNullValue(FieldMallocs[i]->getType()),
01330                                "isnull");
01331     RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
01332   }
01333 
01334   // Split the basic block at the old malloc.
01335   BasicBlock *OrigBB = CI->getParent();
01336   BasicBlock *ContBB =
01337       OrigBB->splitBasicBlock(CI->getIterator(), "malloc_cont");
01338 
01339   // Create the block to check the first condition.  Put all these blocks at the
01340   // end of the function as they are unlikely to be executed.
01341   BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
01342                                                 "malloc_ret_null",
01343                                                 OrigBB->getParent());
01344 
01345   // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
01346   // branch on RunningOr.
01347   OrigBB->getTerminator()->eraseFromParent();
01348   BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
01349 
01350   // Within the NullPtrBlock, we need to emit a comparison and branch for each
01351   // pointer, because some may be null while others are not.
01352   for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
01353     Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
01354     Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
01355                               Constant::getNullValue(GVVal->getType()));
01356     BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
01357                                                OrigBB->getParent());
01358     BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
01359                                                OrigBB->getParent());
01360     Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
01361                                          Cmp, NullPtrBlock);
01362 
01363     // Fill in FreeBlock.
01364     CallInst::CreateFree(GVVal, BI);
01365     new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
01366                   FreeBlock);
01367     BranchInst::Create(NextBlock, FreeBlock);
01368 
01369     NullPtrBlock = NextBlock;
01370   }
01371 
01372   BranchInst::Create(ContBB, NullPtrBlock);
01373 
01374   // CI is no longer needed, remove it.
01375   CI->eraseFromParent();
01376 
01377   /// As we process loads, if we can't immediately update all uses of the load,
01378   /// keep track of what scalarized loads are inserted for a given load.
01379   DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
01380   InsertedScalarizedValues[GV] = FieldGlobals;
01381 
01382   std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
01383 
01384   // Okay, the malloc site is completely handled.  All of the uses of GV are now
01385   // loads, and all uses of those loads are simple.  Rewrite them to use loads
01386   // of the per-field globals instead.
01387   for (auto UI = GV->user_begin(), E = GV->user_end(); UI != E;) {
01388     Instruction *User = cast<Instruction>(*UI++);
01389 
01390     if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
01391       RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
01392       continue;
01393     }
01394 
01395     // Must be a store of null.
01396     StoreInst *SI = cast<StoreInst>(User);
01397     assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
01398            "Unexpected heap-sra user!");
01399 
01400     // Insert a store of null into each global.
01401     for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
01402       Type *ValTy = cast<GlobalValue>(FieldGlobals[i])->getValueType();
01403       Constant *Null = Constant::getNullValue(ValTy);
01404       new StoreInst(Null, FieldGlobals[i], SI);
01405     }
01406     // Erase the original store.
01407     SI->eraseFromParent();
01408   }
01409 
01410   // While we have PHIs that are interesting to rewrite, do it.
01411   while (!PHIsToRewrite.empty()) {
01412     PHINode *PN = PHIsToRewrite.back().first;
01413     unsigned FieldNo = PHIsToRewrite.back().second;
01414     PHIsToRewrite.pop_back();
01415     PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
01416     assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
01417 
01418     // Add all the incoming values.  This can materialize more phis.
01419     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
01420       Value *InVal = PN->getIncomingValue(i);
01421       InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
01422                                PHIsToRewrite);
01423       FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
01424     }
01425   }
01426 
01427   // Drop all inter-phi links and any loads that made it this far.
01428   for (DenseMap<Value*, std::vector<Value*> >::iterator
01429        I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
01430        I != E; ++I) {
01431     if (PHINode *PN = dyn_cast<PHINode>(I->first))
01432       PN->dropAllReferences();
01433     else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
01434       LI->dropAllReferences();
01435   }
01436 
01437   // Delete all the phis and loads now that inter-references are dead.
01438   for (DenseMap<Value*, std::vector<Value*> >::iterator
01439        I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
01440        I != E; ++I) {
01441     if (PHINode *PN = dyn_cast<PHINode>(I->first))
01442       PN->eraseFromParent();
01443     else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
01444       LI->eraseFromParent();
01445   }
01446 
01447   // The old global is now dead, remove it.
01448   GV->eraseFromParent();
01449 
01450   ++NumHeapSRA;
01451   return cast<GlobalVariable>(FieldGlobals[0]);
01452 }
01453 
01454 /// This function is called when we see a pointer global variable with a single
01455 /// value stored it that is a malloc or cast of malloc.
01456 static bool tryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV, CallInst *CI,
01457                                                Type *AllocTy,
01458                                                AtomicOrdering Ordering,
01459                                                const DataLayout &DL,
01460                                                TargetLibraryInfo *TLI) {
01461   // If this is a malloc of an abstract type, don't touch it.
01462   if (!AllocTy->isSized())
01463     return false;
01464 
01465   // We can't optimize this global unless all uses of it are *known* to be
01466   // of the malloc value, not of the null initializer value (consider a use
01467   // that compares the global's value against zero to see if the malloc has
01468   // been reached).  To do this, we check to see if all uses of the global
01469   // would trap if the global were null: this proves that they must all
01470   // happen after the malloc.
01471   if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
01472     return false;
01473 
01474   // We can't optimize this if the malloc itself is used in a complex way,
01475   // for example, being stored into multiple globals.  This allows the
01476   // malloc to be stored into the specified global, loaded icmp'd, and
01477   // GEP'd.  These are all things we could transform to using the global
01478   // for.
01479   SmallPtrSet<const PHINode*, 8> PHIs;
01480   if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
01481     return false;
01482 
01483   // If we have a global that is only initialized with a fixed size malloc,
01484   // transform the program to use global memory instead of malloc'd memory.
01485   // This eliminates dynamic allocation, avoids an indirection accessing the
01486   // data, and exposes the resultant global to further GlobalOpt.
01487   // We cannot optimize the malloc if we cannot determine malloc array size.
01488   Value *NElems = getMallocArraySize(CI, DL, TLI, true);
01489   if (!NElems)
01490     return false;
01491 
01492   if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
01493     // Restrict this transformation to only working on small allocations
01494     // (2048 bytes currently), as we don't want to introduce a 16M global or
01495     // something.
01496     if (NElements->getZExtValue() * DL.getTypeAllocSize(AllocTy) < 2048) {
01497       OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, DL, TLI);
01498       return true;
01499     }
01500 
01501   // If the allocation is an array of structures, consider transforming this
01502   // into multiple malloc'd arrays, one for each field.  This is basically
01503   // SRoA for malloc'd memory.
01504 
01505   if (Ordering != NotAtomic)
01506     return false;
01507 
01508   // If this is an allocation of a fixed size array of structs, analyze as a
01509   // variable size array.  malloc [100 x struct],1 -> malloc struct, 100
01510   if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
01511     if (ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
01512       AllocTy = AT->getElementType();
01513 
01514   StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
01515   if (!AllocSTy)
01516     return false;
01517 
01518   // This the structure has an unreasonable number of fields, leave it
01519   // alone.
01520   if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
01521       AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
01522 
01523     // If this is a fixed size array, transform the Malloc to be an alloc of
01524     // structs.  malloc [100 x struct],1 -> malloc struct, 100
01525     if (ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI, TLI))) {
01526       Type *IntPtrTy = DL.getIntPtrType(CI->getType());
01527       unsigned TypeSize = DL.getStructLayout(AllocSTy)->getSizeInBytes();
01528       Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
01529       Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
01530       Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
01531                                                    AllocSize, NumElements,
01532                                                    nullptr, CI->getName());
01533       Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
01534       CI->replaceAllUsesWith(Cast);
01535       CI->eraseFromParent();
01536       if (BitCastInst *BCI = dyn_cast<BitCastInst>(Malloc))
01537         CI = cast<CallInst>(BCI->getOperand(0));
01538       else
01539         CI = cast<CallInst>(Malloc);
01540     }
01541 
01542     PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, DL, TLI, true), DL,
01543                          TLI);
01544     return true;
01545   }
01546 
01547   return false;
01548 }
01549 
01550 // Try to optimize globals based on the knowledge that only one value (besides
01551 // its initializer) is ever stored to the global.
01552 static bool optimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
01553                                      AtomicOrdering Ordering,
01554                                      const DataLayout &DL,
01555                                      TargetLibraryInfo *TLI) {
01556   // Ignore no-op GEPs and bitcasts.
01557   StoredOnceVal = StoredOnceVal->stripPointerCasts();
01558 
01559   // If we are dealing with a pointer global that is initialized to null and
01560   // only has one (non-null) value stored into it, then we can optimize any
01561   // users of the loaded value (often calls and loads) that would trap if the
01562   // value was null.
01563   if (GV->getInitializer()->getType()->isPointerTy() &&
01564       GV->getInitializer()->isNullValue()) {
01565     if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
01566       if (GV->getInitializer()->getType() != SOVC->getType())
01567         SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
01568 
01569       // Optimize away any trapping uses of the loaded value.
01570       if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, DL, TLI))
01571         return true;
01572     } else if (CallInst *CI = extractMallocCall(StoredOnceVal, TLI)) {
01573       Type *MallocType = getMallocAllocatedType(CI, TLI);
01574       if (MallocType && tryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType,
01575                                                            Ordering, DL, TLI))
01576         return true;
01577     }
01578   }
01579 
01580   return false;
01581 }
01582 
01583 /// At this point, we have learned that the only two values ever stored into GV
01584 /// are its initializer and OtherVal.  See if we can shrink the global into a
01585 /// boolean and select between the two values whenever it is used.  This exposes
01586 /// the values to other scalar optimizations.
01587 static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
01588   Type *GVElType = GV->getValueType();
01589 
01590   // If GVElType is already i1, it is already shrunk.  If the type of the GV is
01591   // an FP value, pointer or vector, don't do this optimization because a select
01592   // between them is very expensive and unlikely to lead to later
01593   // simplification.  In these cases, we typically end up with "cond ? v1 : v2"
01594   // where v1 and v2 both require constant pool loads, a big loss.
01595   if (GVElType == Type::getInt1Ty(GV->getContext()) ||
01596       GVElType->isFloatingPointTy() ||
01597       GVElType->isPointerTy() || GVElType->isVectorTy())
01598     return false;
01599 
01600   // Walk the use list of the global seeing if all the uses are load or store.
01601   // If there is anything else, bail out.
01602   for (User *U : GV->users())
01603     if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
01604       return false;
01605 
01606   DEBUG(dbgs() << "   *** SHRINKING TO BOOL: " << *GV << "\n");
01607 
01608   // Create the new global, initializing it to false.
01609   GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
01610                                              false,
01611                                              GlobalValue::InternalLinkage,
01612                                         ConstantInt::getFalse(GV->getContext()),
01613                                              GV->getName()+".b",
01614                                              GV->getThreadLocalMode(),
01615                                              GV->getType()->getAddressSpace());
01616   NewGV->copyAttributesFrom(GV);
01617   GV->getParent()->getGlobalList().insert(GV->getIterator(), NewGV);
01618 
01619   Constant *InitVal = GV->getInitializer();
01620   assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
01621          "No reason to shrink to bool!");
01622 
01623   // If initialized to zero and storing one into the global, we can use a cast
01624   // instead of a select to synthesize the desired value.
01625   bool IsOneZero = false;
01626   if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
01627     IsOneZero = InitVal->isNullValue() && CI->isOne();
01628 
01629   while (!GV->use_empty()) {
01630     Instruction *UI = cast<Instruction>(GV->user_back());
01631     if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
01632       // Change the store into a boolean store.
01633       bool StoringOther = SI->getOperand(0) == OtherVal;
01634       // Only do this if we weren't storing a loaded value.
01635       Value *StoreVal;
01636       if (StoringOther || SI->getOperand(0) == InitVal) {
01637         StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
01638                                     StoringOther);
01639       } else {
01640         // Otherwise, we are storing a previously loaded copy.  To do this,
01641         // change the copy from copying the original value to just copying the
01642         // bool.
01643         Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
01644 
01645         // If we've already replaced the input, StoredVal will be a cast or
01646         // select instruction.  If not, it will be a load of the original
01647         // global.
01648         if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
01649           assert(LI->getOperand(0) == GV && "Not a copy!");
01650           // Insert a new load, to preserve the saved value.
01651           StoreVal = new LoadInst(NewGV, LI->getName()+".b", false, 0,
01652                                   LI->getOrdering(), LI->getSynchScope(), LI);
01653         } else {
01654           assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
01655                  "This is not a form that we understand!");
01656           StoreVal = StoredVal->getOperand(0);
01657           assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
01658         }
01659       }
01660       new StoreInst(StoreVal, NewGV, false, 0,
01661                     SI->getOrdering(), SI->getSynchScope(), SI);
01662     } else {
01663       // Change the load into a load of bool then a select.
01664       LoadInst *LI = cast<LoadInst>(UI);
01665       LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", false, 0,
01666                                    LI->getOrdering(), LI->getSynchScope(), LI);
01667       Value *NSI;
01668       if (IsOneZero)
01669         NSI = new ZExtInst(NLI, LI->getType(), "", LI);
01670       else
01671         NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
01672       NSI->takeName(LI);
01673       LI->replaceAllUsesWith(NSI);
01674     }
01675     UI->eraseFromParent();
01676   }
01677 
01678   // Retain the name of the old global variable. People who are debugging their
01679   // programs may expect these variables to be named the same.
01680   NewGV->takeName(GV);
01681   GV->eraseFromParent();
01682   return true;
01683 }
01684 
01685 bool GlobalOpt::deleteIfDead(GlobalValue &GV) {
01686   GV.removeDeadConstantUsers();
01687 
01688   if (!GV.isDiscardableIfUnused())
01689     return false;
01690 
01691   if (const Comdat *C = GV.getComdat())
01692     if (!GV.hasLocalLinkage() && NotDiscardableComdats.count(C))
01693       return false;
01694 
01695   bool Dead;
01696   if (auto *F = dyn_cast<Function>(&GV))
01697     Dead = F->isDefTriviallyDead();
01698   else
01699     Dead = GV.use_empty();
01700   if (!Dead)
01701     return false;
01702 
01703   DEBUG(dbgs() << "GLOBAL DEAD: " << GV << "\n");
01704   GV.eraseFromParent();
01705   ++NumDeleted;
01706   return true;
01707 }
01708 
01709 /// Analyze the specified global variable and optimize it if possible.  If we
01710 /// make a change, return true.
01711 bool GlobalOpt::processGlobal(GlobalValue &GV) {
01712   // Do more involved optimizations if the global is internal.
01713   if (!GV.hasLocalLinkage())
01714     return false;
01715 
01716   GlobalStatus GS;
01717 
01718   if (GlobalStatus::analyzeGlobal(&GV, GS))
01719     return false;
01720 
01721   bool Changed = false;
01722   if (!GS.IsCompared && !GV.hasUnnamedAddr()) {
01723     GV.setUnnamedAddr(true);
01724     NumUnnamed++;
01725     Changed = true;
01726   }
01727 
01728   auto *GVar = dyn_cast<GlobalVariable>(&GV);
01729   if (!GVar)
01730     return Changed;
01731 
01732   if (GVar->isConstant() || !GVar->hasInitializer())
01733     return Changed;
01734 
01735   return processInternalGlobal(GVar, GS) || Changed;
01736 }
01737 
01738 bool GlobalOpt::isPointerValueDeadOnEntryToFunction(const Function *F, GlobalValue *GV) {
01739   // Find all uses of GV. We expect them all to be in F, and if we can't
01740   // identify any of the uses we bail out.
01741   //
01742   // On each of these uses, identify if the memory that GV points to is
01743   // used/required/live at the start of the function. If it is not, for example
01744   // if the first thing the function does is store to the GV, the GV can
01745   // possibly be demoted.
01746   //
01747   // We don't do an exhaustive search for memory operations - simply look
01748   // through bitcasts as they're quite common and benign.
01749   const DataLayout &DL = GV->getParent()->getDataLayout();
01750   SmallVector<LoadInst *, 4> Loads;
01751   SmallVector<StoreInst *, 4> Stores;
01752   for (auto *U : GV->users()) {
01753     if (Operator::getOpcode(U) == Instruction::BitCast) {
01754       for (auto *UU : U->users()) {
01755         if (auto *LI = dyn_cast<LoadInst>(UU))
01756           Loads.push_back(LI);
01757         else if (auto *SI = dyn_cast<StoreInst>(UU))
01758           Stores.push_back(SI);
01759         else
01760           return false;
01761       }
01762       continue;
01763     }
01764 
01765     Instruction *I = dyn_cast<Instruction>(U);
01766     if (!I)
01767       return false;
01768     assert(I->getParent()->getParent() == F);
01769 
01770     if (auto *LI = dyn_cast<LoadInst>(I))
01771       Loads.push_back(LI);
01772     else if (auto *SI = dyn_cast<StoreInst>(I))
01773       Stores.push_back(SI);
01774     else
01775       return false;
01776   }
01777 
01778   // We have identified all uses of GV into loads and stores. Now check if all
01779   // of them are known not to depend on the value of the global at the function
01780   // entry point. We do this by ensuring that every load is dominated by at
01781   // least one store.
01782   auto &DT = getAnalysis<DominatorTreeWrapperPass>(*const_cast<Function *>(F))
01783                  .getDomTree();
01784 
01785   // The below check is quadratic. Check we're not going to do too many tests.
01786   // FIXME: Even though this will always have worst-case quadratic time, we
01787   // could put effort into minimizing the average time by putting stores that
01788   // have been shown to dominate at least one load at the beginning of the
01789   // Stores array, making subsequent dominance checks more likely to succeed
01790   // early.
01791   //
01792   // The threshold here is fairly large because global->local demotion is a
01793   // very powerful optimization should it fire.
01794   const unsigned Threshold = 100;
01795   if (Loads.size() * Stores.size() > Threshold)
01796     return false;
01797 
01798   for (auto *L : Loads) {
01799     auto *LTy = L->getType();
01800     if (!std::any_of(Stores.begin(), Stores.end(), [&](StoreInst *S) {
01801           auto *STy = S->getValueOperand()->getType();
01802           // The load is only dominated by the store if DomTree says so
01803           // and the number of bits loaded in L is less than or equal to
01804           // the number of bits stored in S.
01805           return DT.dominates(S, L) &&
01806                  DL.getTypeStoreSize(LTy) <= DL.getTypeStoreSize(STy);
01807         }))
01808       return false;
01809   }
01810   // All loads have known dependences inside F, so the global can be localized.
01811   return true;
01812 }
01813 
01814 /// C may have non-instruction users. Can all of those users be turned into
01815 /// instructions?
01816 static bool allNonInstructionUsersCanBeMadeInstructions(Constant *C) {
01817   // We don't do this exhaustively. The most common pattern that we really need
01818   // to care about is a constant GEP or constant bitcast - so just looking
01819   // through one single ConstantExpr.
01820   //
01821   // The set of constants that this function returns true for must be able to be
01822   // handled by makeAllConstantUsesInstructions.
01823   for (auto *U : C->users()) {
01824     if (isa<Instruction>(U))
01825       continue;
01826     if (!isa<ConstantExpr>(U))
01827       // Non instruction, non-constantexpr user; cannot convert this.
01828       return false;
01829     for (auto *UU : U->users())
01830       if (!isa<Instruction>(UU))
01831         // A constantexpr used by another constant. We don't try and recurse any
01832         // further but just bail out at this point.
01833         return false;
01834   }
01835 
01836   return true;
01837 }
01838 
01839 /// C may have non-instruction users, and
01840 /// allNonInstructionUsersCanBeMadeInstructions has returned true. Convert the
01841 /// non-instruction users to instructions.
01842 static void makeAllConstantUsesInstructions(Constant *C) {
01843   SmallVector<ConstantExpr*,4> Users;
01844   for (auto *U : C->users()) {
01845     if (isa<ConstantExpr>(U))
01846       Users.push_back(cast<ConstantExpr>(U));
01847     else
01848       // We should never get here; allNonInstructionUsersCanBeMadeInstructions
01849       // should not have returned true for C.
01850       assert(
01851           isa<Instruction>(U) &&
01852           "Can't transform non-constantexpr non-instruction to instruction!");
01853   }
01854 
01855   SmallVector<Value*,4> UUsers;
01856   for (auto *U : Users) {
01857     UUsers.clear();
01858     for (auto *UU : U->users())
01859       UUsers.push_back(UU);
01860     for (auto *UU : UUsers) {
01861       Instruction *UI = cast<Instruction>(UU);
01862       Instruction *NewU = U->getAsInstruction();
01863       NewU->insertBefore(UI);
01864       UI->replaceUsesOfWith(U, NewU);
01865     }
01866     U->dropAllReferences();
01867   }
01868 }
01869 
01870 /// Analyze the specified global variable and optimize
01871 /// it if possible.  If we make a change, return true.
01872 bool GlobalOpt::processInternalGlobal(GlobalVariable *GV,
01873                                       const GlobalStatus &GS) {
01874   auto &DL = GV->getParent()->getDataLayout();
01875   // If this is a first class global and has only one accessing function and
01876   // this function is non-recursive, we replace the global with a local alloca
01877   // in this function.
01878   //
01879   // NOTE: It doesn't make sense to promote non-single-value types since we
01880   // are just replacing static memory to stack memory.
01881   //
01882   // If the global is in different address space, don't bring it to stack.
01883   if (!GS.HasMultipleAccessingFunctions &&
01884       GS.AccessingFunction &&
01885       GV->getValueType()->isSingleValueType() &&
01886       GV->getType()->getAddressSpace() == 0 &&
01887       !GV->isExternallyInitialized() &&
01888       allNonInstructionUsersCanBeMadeInstructions(GV) &&
01889       GS.AccessingFunction->doesNotRecurse() &&
01890       isPointerValueDeadOnEntryToFunction(GS.AccessingFunction, GV) ) {
01891     DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV << "\n");
01892     Instruction &FirstI = const_cast<Instruction&>(*GS.AccessingFunction
01893                                                    ->getEntryBlock().begin());
01894     Type *ElemTy = GV->getValueType();
01895     // FIXME: Pass Global's alignment when globals have alignment
01896     AllocaInst *Alloca = new AllocaInst(ElemTy, nullptr,
01897                                         GV->getName(), &FirstI);
01898     if (!isa<UndefValue>(GV->getInitializer()))
01899       new StoreInst(GV->getInitializer(), Alloca, &FirstI);
01900 
01901     makeAllConstantUsesInstructions(GV);
01902     
01903     GV->replaceAllUsesWith(Alloca);
01904     GV->eraseFromParent();
01905     ++NumLocalized;
01906     return true;
01907   }
01908 
01909   // If the global is never loaded (but may be stored to), it is dead.
01910   // Delete it now.
01911   if (!GS.IsLoaded) {
01912     DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV << "\n");
01913 
01914     bool Changed;
01915     if (isLeakCheckerRoot(GV)) {
01916       // Delete any constant stores to the global.
01917       Changed = CleanupPointerRootUsers(GV, TLI);
01918     } else {
01919       // Delete any stores we can find to the global.  We may not be able to
01920       // make it completely dead though.
01921       Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(), DL, TLI);
01922     }
01923 
01924     // If the global is dead now, delete it.
01925     if (GV->use_empty()) {
01926       GV->eraseFromParent();
01927       ++NumDeleted;
01928       Changed = true;
01929     }
01930     return Changed;
01931 
01932   } else if (GS.StoredType <= GlobalStatus::InitializerStored) {
01933     DEBUG(dbgs() << "MARKING CONSTANT: " << *GV << "\n");
01934     GV->setConstant(true);
01935 
01936     // Clean up any obviously simplifiable users now.
01937     CleanupConstantGlobalUsers(GV, GV->getInitializer(), DL, TLI);
01938 
01939     // If the global is dead now, just nuke it.
01940     if (GV->use_empty()) {
01941       DEBUG(dbgs() << "   *** Marking constant allowed us to simplify "
01942             << "all users and delete global!\n");
01943       GV->eraseFromParent();
01944       ++NumDeleted;
01945     }
01946 
01947     ++NumMarked;
01948     return true;
01949   } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
01950     const DataLayout &DL = GV->getParent()->getDataLayout();
01951     if (SRAGlobal(GV, DL))
01952       return true;
01953   } else if (GS.StoredType == GlobalStatus::StoredOnce && GS.StoredOnceValue) {
01954     // If the initial value for the global was an undef value, and if only
01955     // one other value was stored into it, we can just change the
01956     // initializer to be the stored value, then delete all stores to the
01957     // global.  This allows us to mark it constant.
01958     if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
01959       if (isa<UndefValue>(GV->getInitializer())) {
01960         // Change the initial value here.
01961         GV->setInitializer(SOVConstant);
01962 
01963         // Clean up any obviously simplifiable users now.
01964         CleanupConstantGlobalUsers(GV, GV->getInitializer(), DL, TLI);
01965 
01966         if (GV->use_empty()) {
01967           DEBUG(dbgs() << "   *** Substituting initializer allowed us to "
01968                        << "simplify all users and delete global!\n");
01969           GV->eraseFromParent();
01970           ++NumDeleted;
01971         }
01972         ++NumSubstitute;
01973         return true;
01974       }
01975 
01976     // Try to optimize globals based on the knowledge that only one value
01977     // (besides its initializer) is ever stored to the global.
01978     if (optimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GS.Ordering, DL, TLI))
01979       return true;
01980 
01981     // Otherwise, if the global was not a boolean, we can shrink it to be a
01982     // boolean.
01983     if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue)) {
01984       if (GS.Ordering == NotAtomic) {
01985         if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
01986           ++NumShrunkToBool;
01987           return true;
01988         }
01989       }
01990     }
01991   }
01992 
01993   return false;
01994 }
01995 
01996 /// Walk all of the direct calls of the specified function, changing them to
01997 /// FastCC.
01998 static void ChangeCalleesToFastCall(Function *F) {
01999   for (User *U : F->users()) {
02000     if (isa<BlockAddress>(U))
02001       continue;
02002     CallSite CS(cast<Instruction>(U));
02003     CS.setCallingConv(CallingConv::Fast);
02004   }
02005 }
02006 
02007 static AttributeSet StripNest(LLVMContext &C, const AttributeSet &Attrs) {
02008   for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
02009     unsigned Index = Attrs.getSlotIndex(i);
02010     if (!Attrs.getSlotAttributes(i).hasAttribute(Index, Attribute::Nest))
02011       continue;
02012 
02013     // There can be only one.
02014     return Attrs.removeAttribute(C, Index, Attribute::Nest);
02015   }
02016 
02017   return Attrs;
02018 }
02019 
02020 static void RemoveNestAttribute(Function *F) {
02021   F->setAttributes(StripNest(F->getContext(), F->getAttributes()));
02022   for (User *U : F->users()) {
02023     if (isa<BlockAddress>(U))
02024       continue;
02025     CallSite CS(cast<Instruction>(U));
02026     CS.setAttributes(StripNest(F->getContext(), CS.getAttributes()));
02027   }
02028 }
02029 
02030 /// Return true if this is a calling convention that we'd like to change.  The
02031 /// idea here is that we don't want to mess with the convention if the user
02032 /// explicitly requested something with performance implications like coldcc,
02033 /// GHC, or anyregcc.
02034 static bool isProfitableToMakeFastCC(Function *F) {
02035   CallingConv::ID CC = F->getCallingConv();
02036   // FIXME: Is it worth transforming x86_stdcallcc and x86_fastcallcc?
02037   return CC == CallingConv::C || CC == CallingConv::X86_ThisCall;
02038 }
02039 
02040 bool GlobalOpt::OptimizeFunctions(Module &M) {
02041   bool Changed = false;
02042   // Optimize functions.
02043   for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
02044     Function *F = &*FI++;
02045     // Functions without names cannot be referenced outside this module.
02046     if (!F->hasName() && !F->isDeclaration() && !F->hasLocalLinkage())
02047       F->setLinkage(GlobalValue::InternalLinkage);
02048 
02049     if (deleteIfDead(*F)) {
02050       Changed = true;
02051       continue;
02052     }
02053 
02054     Changed |= processGlobal(*F);
02055 
02056     if (!F->hasLocalLinkage())
02057       continue;
02058     if (isProfitableToMakeFastCC(F) && !F->isVarArg() &&
02059         !F->hasAddressTaken()) {
02060       // If this function has a calling convention worth changing, is not a
02061       // varargs function, and is only called directly, promote it to use the
02062       // Fast calling convention.
02063       F->setCallingConv(CallingConv::Fast);
02064       ChangeCalleesToFastCall(F);
02065       ++NumFastCallFns;
02066       Changed = true;
02067     }
02068 
02069     if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
02070         !F->hasAddressTaken()) {
02071       // The function is not used by a trampoline intrinsic, so it is safe
02072       // to remove the 'nest' attribute.
02073       RemoveNestAttribute(F);
02074       ++NumNestRemoved;
02075       Changed = true;
02076     }
02077   }
02078   return Changed;
02079 }
02080 
02081 bool GlobalOpt::OptimizeGlobalVars(Module &M) {
02082   bool Changed = false;
02083 
02084   for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
02085        GVI != E; ) {
02086     GlobalVariable *GV = &*GVI++;
02087     // Global variables without names cannot be referenced outside this module.
02088     if (!GV->hasName() && !GV->isDeclaration() && !GV->hasLocalLinkage())
02089       GV->setLinkage(GlobalValue::InternalLinkage);
02090     // Simplify the initializer.
02091     if (GV->hasInitializer())
02092       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
02093         auto &DL = M.getDataLayout();
02094         Constant *New = ConstantFoldConstantExpression(CE, DL, TLI);
02095         if (New && New != CE)
02096           GV->setInitializer(New);
02097       }
02098 
02099     if (deleteIfDead(*GV)) {
02100       Changed = true;
02101       continue;
02102     }
02103 
02104     Changed |= processGlobal(*GV);
02105   }
02106   return Changed;
02107 }
02108 
02109 static inline bool
02110 isSimpleEnoughValueToCommit(Constant *C,
02111                             SmallPtrSetImpl<Constant *> &SimpleConstants,
02112                             const DataLayout &DL);
02113 
02114 /// Return true if the specified constant can be handled by the code generator.
02115 /// We don't want to generate something like:
02116 ///   void *X = &X/42;
02117 /// because the code generator doesn't have a relocation that can handle that.
02118 ///
02119 /// This function should be called if C was not found (but just got inserted)
02120 /// in SimpleConstants to avoid having to rescan the same constants all the
02121 /// time.
02122 static bool
02123 isSimpleEnoughValueToCommitHelper(Constant *C,
02124                                   SmallPtrSetImpl<Constant *> &SimpleConstants,
02125                                   const DataLayout &DL) {
02126   // Simple global addresses are supported, do not allow dllimport or
02127   // thread-local globals.
02128   if (auto *GV = dyn_cast<GlobalValue>(C))
02129     return !GV->hasDLLImportStorageClass() && !GV->isThreadLocal();
02130 
02131   // Simple integer, undef, constant aggregate zero, etc are all supported.
02132   if (C->getNumOperands() == 0 || isa<BlockAddress>(C))
02133     return true;
02134 
02135   // Aggregate values are safe if all their elements are.
02136   if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
02137       isa<ConstantVector>(C)) {
02138     for (Value *Op : C->operands())
02139       if (!isSimpleEnoughValueToCommit(cast<Constant>(Op), SimpleConstants, DL))
02140         return false;
02141     return true;
02142   }
02143 
02144   // We don't know exactly what relocations are allowed in constant expressions,
02145   // so we allow &global+constantoffset, which is safe and uniformly supported
02146   // across targets.
02147   ConstantExpr *CE = cast<ConstantExpr>(C);
02148   switch (CE->getOpcode()) {
02149   case Instruction::BitCast:
02150     // Bitcast is fine if the casted value is fine.
02151     return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
02152 
02153   case Instruction::IntToPtr:
02154   case Instruction::PtrToInt:
02155     // int <=> ptr is fine if the int type is the same size as the
02156     // pointer type.
02157     if (DL.getTypeSizeInBits(CE->getType()) !=
02158         DL.getTypeSizeInBits(CE->getOperand(0)->getType()))
02159       return false;
02160     return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
02161 
02162   // GEP is fine if it is simple + constant offset.
02163   case Instruction::GetElementPtr:
02164     for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
02165       if (!isa<ConstantInt>(CE->getOperand(i)))
02166         return false;
02167     return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
02168 
02169   case Instruction::Add:
02170     // We allow simple+cst.
02171     if (!isa<ConstantInt>(CE->getOperand(1)))
02172       return false;
02173     return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, DL);
02174   }
02175   return false;
02176 }
02177 
02178 static inline bool
02179 isSimpleEnoughValueToCommit(Constant *C,
02180                             SmallPtrSetImpl<Constant *> &SimpleConstants,
02181                             const DataLayout &DL) {
02182   // If we already checked this constant, we win.
02183   if (!SimpleConstants.insert(C).second)
02184     return true;
02185   // Check the constant.
02186   return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, DL);
02187 }
02188 
02189 
02190 /// Return true if this constant is simple enough for us to understand.  In
02191 /// particular, if it is a cast to anything other than from one pointer type to
02192 /// another pointer type, we punt.  We basically just support direct accesses to
02193 /// globals and GEP's of globals.  This should be kept up to date with
02194 /// CommitValueTo.
02195 static bool isSimpleEnoughPointerToCommit(Constant *C) {
02196   // Conservatively, avoid aggregate types. This is because we don't
02197   // want to worry about them partially overlapping other stores.
02198   if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
02199     return false;
02200 
02201   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
02202     // Do not allow weak/*_odr/linkonce linkage or external globals.
02203     return GV->hasUniqueInitializer();
02204 
02205   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
02206     // Handle a constantexpr gep.
02207     if (CE->getOpcode() == Instruction::GetElementPtr &&
02208         isa<GlobalVariable>(CE->getOperand(0)) &&
02209         cast<GEPOperator>(CE)->isInBounds()) {
02210       GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
02211       // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
02212       // external globals.
02213       if (!GV->hasUniqueInitializer())
02214         return false;
02215 
02216       // The first index must be zero.
02217       ConstantInt *CI = dyn_cast<ConstantInt>(*std::next(CE->op_begin()));
02218       if (!CI || !CI->isZero()) return false;
02219 
02220       // The remaining indices must be compile-time known integers within the
02221       // notional bounds of the corresponding static array types.
02222       if (!CE->isGEPWithNoNotionalOverIndexing())
02223         return false;
02224 
02225       return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
02226 
02227     // A constantexpr bitcast from a pointer to another pointer is a no-op,
02228     // and we know how to evaluate it by moving the bitcast from the pointer
02229     // operand to the value operand.
02230     } else if (CE->getOpcode() == Instruction::BitCast &&
02231                isa<GlobalVariable>(CE->getOperand(0))) {
02232       // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
02233       // external globals.
02234       return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
02235     }
02236   }
02237 
02238   return false;
02239 }
02240 
02241 /// Evaluate a piece of a constantexpr store into a global initializer.  This
02242 /// returns 'Init' modified to reflect 'Val' stored into it.  At this point, the
02243 /// GEP operands of Addr [0, OpNo) have been stepped into.
02244 static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
02245                                    ConstantExpr *Addr, unsigned OpNo) {
02246   // Base case of the recursion.
02247   if (OpNo == Addr->getNumOperands()) {
02248     assert(Val->getType() == Init->getType() && "Type mismatch!");
02249     return Val;
02250   }
02251 
02252   SmallVector<Constant*, 32> Elts;
02253   if (StructType *STy = dyn_cast<StructType>(Init->getType())) {
02254     // Break up the constant into its elements.
02255     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
02256       Elts.push_back(Init->getAggregateElement(i));
02257 
02258     // Replace the element that we are supposed to.
02259     ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
02260     unsigned Idx = CU->getZExtValue();
02261     assert(Idx < STy->getNumElements() && "Struct index out of range!");
02262     Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
02263 
02264     // Return the modified struct.
02265     return ConstantStruct::get(STy, Elts);
02266   }
02267 
02268   ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
02269   SequentialType *InitTy = cast<SequentialType>(Init->getType());
02270 
02271   uint64_t NumElts;
02272   if (ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
02273     NumElts = ATy->getNumElements();
02274   else
02275     NumElts = InitTy->getVectorNumElements();
02276 
02277   // Break up the array into elements.
02278   for (uint64_t i = 0, e = NumElts; i != e; ++i)
02279     Elts.push_back(Init->getAggregateElement(i));
02280 
02281   assert(CI->getZExtValue() < NumElts);
02282   Elts[CI->getZExtValue()] =
02283     EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
02284 
02285   if (Init->getType()->isArrayTy())
02286     return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
02287   return ConstantVector::get(Elts);
02288 }
02289 
02290 /// We have decided that Addr (which satisfies the predicate
02291 /// isSimpleEnoughPointerToCommit) should get Val as its value.  Make it happen.
02292 static void CommitValueTo(Constant *Val, Constant *Addr) {
02293   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
02294     assert(GV->hasInitializer());
02295     GV->setInitializer(Val);
02296     return;
02297   }
02298 
02299   ConstantExpr *CE = cast<ConstantExpr>(Addr);
02300   GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
02301   GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
02302 }
02303 
02304 namespace {
02305 
02306 /// This class evaluates LLVM IR, producing the Constant representing each SSA
02307 /// instruction.  Changes to global variables are stored in a mapping that can
02308 /// be iterated over after the evaluation is complete.  Once an evaluation call
02309 /// fails, the evaluation object should not be reused.
02310 class Evaluator {
02311 public:
02312   Evaluator(const DataLayout &DL, const TargetLibraryInfo *TLI)
02313       : DL(DL), TLI(TLI) {
02314     ValueStack.emplace_back();
02315   }
02316 
02317   ~Evaluator() {
02318     for (auto &Tmp : AllocaTmps)
02319       // If there are still users of the alloca, the program is doing something
02320       // silly, e.g. storing the address of the alloca somewhere and using it
02321       // later.  Since this is undefined, we'll just make it be null.
02322       if (!Tmp->use_empty())
02323         Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
02324   }
02325 
02326   /// Evaluate a call to function F, returning true if successful, false if we
02327   /// can't evaluate it.  ActualArgs contains the formal arguments for the
02328   /// function.
02329   bool EvaluateFunction(Function *F, Constant *&RetVal,
02330                         const SmallVectorImpl<Constant*> &ActualArgs);
02331 
02332   /// Evaluate all instructions in block BB, returning true if successful, false
02333   /// if we can't evaluate it.  NewBB returns the next BB that control flows
02334   /// into, or null upon return.
02335   bool EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB);
02336 
02337   Constant *getVal(Value *V) {
02338     if (Constant *CV = dyn_cast<Constant>(V)) return CV;
02339     Constant *R = ValueStack.back().lookup(V);
02340     assert(R && "Reference to an uncomputed value!");
02341     return R;
02342   }
02343 
02344   void setVal(Value *V, Constant *C) {
02345     ValueStack.back()[V] = C;
02346   }
02347 
02348   const DenseMap<Constant*, Constant*> &getMutatedMemory() const {
02349     return MutatedMemory;
02350   }
02351 
02352   const SmallPtrSetImpl<GlobalVariable*> &getInvariants() const {
02353     return Invariants;
02354   }
02355 
02356 private:
02357   Constant *ComputeLoadResult(Constant *P);
02358 
02359   /// As we compute SSA register values, we store their contents here. The back
02360   /// of the deque contains the current function and the stack contains the
02361   /// values in the calling frames.
02362   std::deque<DenseMap<Value*, Constant*>> ValueStack;
02363 
02364   /// This is used to detect recursion.  In pathological situations we could hit
02365   /// exponential behavior, but at least there is nothing unbounded.
02366   SmallVector<Function*, 4> CallStack;
02367 
02368   /// For each store we execute, we update this map.  Loads check this to get
02369   /// the most up-to-date value.  If evaluation is successful, this state is
02370   /// committed to the process.
02371   DenseMap<Constant*, Constant*> MutatedMemory;
02372 
02373   /// To 'execute' an alloca, we create a temporary global variable to represent
02374   /// its body.  This vector is needed so we can delete the temporary globals
02375   /// when we are done.
02376   SmallVector<std::unique_ptr<GlobalVariable>, 32> AllocaTmps;
02377 
02378   /// These global variables have been marked invariant by the static
02379   /// constructor.
02380   SmallPtrSet<GlobalVariable*, 8> Invariants;
02381 
02382   /// These are constants we have checked and know to be simple enough to live
02383   /// in a static initializer of a global.
02384   SmallPtrSet<Constant*, 8> SimpleConstants;
02385 
02386   const DataLayout &DL;
02387   const TargetLibraryInfo *TLI;
02388 };
02389 
02390 }  // anonymous namespace
02391 
02392 /// Return the value that would be computed by a load from P after the stores
02393 /// reflected by 'memory' have been performed.  If we can't decide, return null.
02394 Constant *Evaluator::ComputeLoadResult(Constant *P) {
02395   // If this memory location has been recently stored, use the stored value: it
02396   // is the most up-to-date.
02397   DenseMap<Constant*, Constant*>::const_iterator I = MutatedMemory.find(P);
02398   if (I != MutatedMemory.end()) return I->second;
02399 
02400   // Access it.
02401   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
02402     if (GV->hasDefinitiveInitializer())
02403       return GV->getInitializer();
02404     return nullptr;
02405   }
02406 
02407   // Handle a constantexpr getelementptr.
02408   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
02409     if (CE->getOpcode() == Instruction::GetElementPtr &&
02410         isa<GlobalVariable>(CE->getOperand(0))) {
02411       GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
02412       if (GV->hasDefinitiveInitializer())
02413         return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
02414     }
02415 
02416   return nullptr;  // don't know how to evaluate.
02417 }
02418 
02419 /// Evaluate all instructions in block BB, returning true if successful, false
02420 /// if we can't evaluate it.  NewBB returns the next BB that control flows into,
02421 /// or null upon return.
02422 bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
02423                               BasicBlock *&NextBB) {
02424   // This is the main evaluation loop.
02425   while (1) {
02426     Constant *InstResult = nullptr;
02427 
02428     DEBUG(dbgs() << "Evaluating Instruction: " << *CurInst << "\n");
02429 
02430     if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
02431       if (!SI->isSimple()) {
02432         DEBUG(dbgs() << "Store is not simple! Can not evaluate.\n");
02433         return false;  // no volatile/atomic accesses.
02434       }
02435       Constant *Ptr = getVal(SI->getOperand(1));
02436       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
02437         DEBUG(dbgs() << "Folding constant ptr expression: " << *Ptr);
02438         Ptr = ConstantFoldConstantExpression(CE, DL, TLI);
02439         DEBUG(dbgs() << "; To: " << *Ptr << "\n");
02440       }
02441       if (!isSimpleEnoughPointerToCommit(Ptr)) {
02442         // If this is too complex for us to commit, reject it.
02443         DEBUG(dbgs() << "Pointer is too complex for us to evaluate store.");
02444         return false;
02445       }
02446 
02447       Constant *Val = getVal(SI->getOperand(0));
02448 
02449       // If this might be too difficult for the backend to handle (e.g. the addr
02450       // of one global variable divided by another) then we can't commit it.
02451       if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, DL)) {
02452         DEBUG(dbgs() << "Store value is too complex to evaluate store. " << *Val
02453               << "\n");
02454         return false;
02455       }
02456 
02457       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
02458         if (CE->getOpcode() == Instruction::BitCast) {
02459           DEBUG(dbgs() << "Attempting to resolve bitcast on constant ptr.\n");
02460           // If we're evaluating a store through a bitcast, then we need
02461           // to pull the bitcast off the pointer type and push it onto the
02462           // stored value.
02463           Ptr = CE->getOperand(0);
02464 
02465           Type *NewTy = cast<PointerType>(Ptr->getType())->getElementType();
02466 
02467           // In order to push the bitcast onto the stored value, a bitcast
02468           // from NewTy to Val's type must be legal.  If it's not, we can try
02469           // introspecting NewTy to find a legal conversion.
02470           while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) {
02471             // If NewTy is a struct, we can convert the pointer to the struct
02472             // into a pointer to its first member.
02473             // FIXME: This could be extended to support arrays as well.
02474             if (StructType *STy = dyn_cast<StructType>(NewTy)) {
02475               NewTy = STy->getTypeAtIndex(0U);
02476 
02477               IntegerType *IdxTy = IntegerType::get(NewTy->getContext(), 32);
02478               Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
02479               Constant * const IdxList[] = {IdxZero, IdxZero};
02480 
02481               Ptr = ConstantExpr::getGetElementPtr(nullptr, Ptr, IdxList);
02482               if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
02483                 Ptr = ConstantFoldConstantExpression(CE, DL, TLI);
02484 
02485             // If we can't improve the situation by introspecting NewTy,
02486             // we have to give up.
02487             } else {
02488               DEBUG(dbgs() << "Failed to bitcast constant ptr, can not "
02489                     "evaluate.\n");
02490               return false;
02491             }
02492           }
02493 
02494           // If we found compatible types, go ahead and push the bitcast
02495           // onto the stored value.
02496           Val = ConstantExpr::getBitCast(Val, NewTy);
02497 
02498           DEBUG(dbgs() << "Evaluated bitcast: " << *Val << "\n");
02499         }
02500       }
02501 
02502       MutatedMemory[Ptr] = Val;
02503     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
02504       InstResult = ConstantExpr::get(BO->getOpcode(),
02505                                      getVal(BO->getOperand(0)),
02506                                      getVal(BO->getOperand(1)));
02507       DEBUG(dbgs() << "Found a BinaryOperator! Simplifying: " << *InstResult
02508             << "\n");
02509     } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
02510       InstResult = ConstantExpr::getCompare(CI->getPredicate(),
02511                                             getVal(CI->getOperand(0)),
02512                                             getVal(CI->getOperand(1)));
02513       DEBUG(dbgs() << "Found a CmpInst! Simplifying: " << *InstResult
02514             << "\n");
02515     } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
02516       InstResult = ConstantExpr::getCast(CI->getOpcode(),
02517                                          getVal(CI->getOperand(0)),
02518                                          CI->getType());
02519       DEBUG(dbgs() << "Found a Cast! Simplifying: " << *InstResult
02520             << "\n");
02521     } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
02522       InstResult = ConstantExpr::getSelect(getVal(SI->getOperand(0)),
02523                                            getVal(SI->getOperand(1)),
02524                                            getVal(SI->getOperand(2)));
02525       DEBUG(dbgs() << "Found a Select! Simplifying: " << *InstResult
02526             << "\n");
02527     } else if (auto *EVI = dyn_cast<ExtractValueInst>(CurInst)) {
02528       InstResult = ConstantExpr::getExtractValue(
02529           getVal(EVI->getAggregateOperand()), EVI->getIndices());
02530       DEBUG(dbgs() << "Found an ExtractValueInst! Simplifying: " << *InstResult
02531                    << "\n");
02532     } else if (auto *IVI = dyn_cast<InsertValueInst>(CurInst)) {
02533       InstResult = ConstantExpr::getInsertValue(
02534           getVal(IVI->getAggregateOperand()),
02535           getVal(IVI->getInsertedValueOperand()), IVI->getIndices());
02536       DEBUG(dbgs() << "Found an InsertValueInst! Simplifying: " << *InstResult
02537                    << "\n");
02538     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
02539       Constant *P = getVal(GEP->getOperand(0));
02540       SmallVector<Constant*, 8> GEPOps;
02541       for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
02542            i != e; ++i)
02543         GEPOps.push_back(getVal(*i));
02544       InstResult =
02545           ConstantExpr::getGetElementPtr(GEP->getSourceElementType(), P, GEPOps,
02546                                          cast<GEPOperator>(GEP)->isInBounds());
02547       DEBUG(dbgs() << "Found a GEP! Simplifying: " << *InstResult
02548             << "\n");
02549     } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
02550 
02551       if (!LI->isSimple()) {
02552         DEBUG(dbgs() << "Found a Load! Not a simple load, can not evaluate.\n");
02553         return false;  // no volatile/atomic accesses.
02554       }
02555 
02556       Constant *Ptr = getVal(LI->getOperand(0));
02557       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
02558         Ptr = ConstantFoldConstantExpression(CE, DL, TLI);
02559         DEBUG(dbgs() << "Found a constant pointer expression, constant "
02560               "folding: " << *Ptr << "\n");
02561       }
02562       InstResult = ComputeLoadResult(Ptr);
02563       if (!InstResult) {
02564         DEBUG(dbgs() << "Failed to compute load result. Can not evaluate load."
02565               "\n");
02566         return false; // Could not evaluate load.
02567       }
02568 
02569       DEBUG(dbgs() << "Evaluated load: " << *InstResult << "\n");
02570     } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
02571       if (AI->isArrayAllocation()) {
02572         DEBUG(dbgs() << "Found an array alloca. Can not evaluate.\n");
02573         return false;  // Cannot handle array allocs.
02574       }
02575       Type *Ty = AI->getAllocatedType();
02576       AllocaTmps.push_back(
02577           make_unique<GlobalVariable>(Ty, false, GlobalValue::InternalLinkage,
02578                                       UndefValue::get(Ty), AI->getName()));
02579       InstResult = AllocaTmps.back().get();
02580       DEBUG(dbgs() << "Found an alloca. Result: " << *InstResult << "\n");
02581     } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
02582       CallSite CS(&*CurInst);
02583 
02584       // Debug info can safely be ignored here.
02585       if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
02586         DEBUG(dbgs() << "Ignoring debug info.\n");
02587         ++CurInst;
02588         continue;
02589       }
02590 
02591       // Cannot handle inline asm.
02592       if (isa<InlineAsm>(CS.getCalledValue())) {
02593         DEBUG(dbgs() << "Found inline asm, can not evaluate.\n");
02594         return false;
02595       }
02596 
02597       if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
02598         if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
02599           if (MSI->isVolatile()) {
02600             DEBUG(dbgs() << "Can not optimize a volatile memset " <<
02601                   "intrinsic.\n");
02602             return false;
02603           }
02604           Constant *Ptr = getVal(MSI->getDest());
02605           Constant *Val = getVal(MSI->getValue());
02606           Constant *DestVal = ComputeLoadResult(getVal(Ptr));
02607           if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
02608             // This memset is a no-op.
02609             DEBUG(dbgs() << "Ignoring no-op memset.\n");
02610             ++CurInst;
02611             continue;
02612           }
02613         }
02614 
02615         if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
02616             II->getIntrinsicID() == Intrinsic::lifetime_end) {
02617           DEBUG(dbgs() << "Ignoring lifetime intrinsic.\n");
02618           ++CurInst;
02619           continue;
02620         }
02621 
02622         if (II->getIntrinsicID() == Intrinsic::invariant_start) {
02623           // We don't insert an entry into Values, as it doesn't have a
02624           // meaningful return value.
02625           if (!II->use_empty()) {
02626             DEBUG(dbgs() << "Found unused invariant_start. Can't evaluate.\n");
02627             return false;
02628           }
02629           ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
02630           Value *PtrArg = getVal(II->getArgOperand(1));
02631           Value *Ptr = PtrArg->stripPointerCasts();
02632           if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
02633             Type *ElemTy = GV->getValueType();
02634             if (!Size->isAllOnesValue() &&
02635                 Size->getValue().getLimitedValue() >=
02636                     DL.getTypeStoreSize(ElemTy)) {
02637               Invariants.insert(GV);
02638               DEBUG(dbgs() << "Found a global var that is an invariant: " << *GV
02639                     << "\n");
02640             } else {
02641               DEBUG(dbgs() << "Found a global var, but can not treat it as an "
02642                     "invariant.\n");
02643             }
02644           }
02645           // Continue even if we do nothing.
02646           ++CurInst;
02647           continue;
02648         } else if (II->getIntrinsicID() == Intrinsic::assume) {
02649           DEBUG(dbgs() << "Skipping assume intrinsic.\n");
02650           ++CurInst;
02651           continue;
02652         }
02653 
02654         DEBUG(dbgs() << "Unknown intrinsic. Can not evaluate.\n");
02655         return false;
02656       }
02657 
02658       // Resolve function pointers.
02659       Function *Callee = dyn_cast<Function>(getVal(CS.getCalledValue()));
02660       if (!Callee || Callee->mayBeOverridden()) {
02661         DEBUG(dbgs() << "Can not resolve function pointer.\n");
02662         return false;  // Cannot resolve.
02663       }
02664 
02665       SmallVector<Constant*, 8> Formals;
02666       for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end(); i != e; ++i)
02667         Formals.push_back(getVal(*i));
02668 
02669       if (Callee->isDeclaration()) {
02670         // If this is a function we can constant fold, do it.
02671         if (Constant *C = ConstantFoldCall(Callee, Formals, TLI)) {
02672           InstResult = C;
02673           DEBUG(dbgs() << "Constant folded function call. Result: " <<
02674                 *InstResult << "\n");
02675         } else {
02676           DEBUG(dbgs() << "Can not constant fold function call.\n");
02677           return false;
02678         }
02679       } else {
02680         if (Callee->getFunctionType()->isVarArg()) {
02681           DEBUG(dbgs() << "Can not constant fold vararg function call.\n");
02682           return false;
02683         }
02684 
02685         Constant *RetVal = nullptr;
02686         // Execute the call, if successful, use the return value.
02687         ValueStack.emplace_back();
02688         if (!EvaluateFunction(Callee, RetVal, Formals)) {
02689           DEBUG(dbgs() << "Failed to evaluate function.\n");
02690           return false;
02691         }
02692         ValueStack.pop_back();
02693         InstResult = RetVal;
02694 
02695         if (InstResult) {
02696           DEBUG(dbgs() << "Successfully evaluated function. Result: " <<
02697                 InstResult << "\n\n");
02698         } else {
02699           DEBUG(dbgs() << "Successfully evaluated function. Result: 0\n\n");
02700         }
02701       }
02702     } else if (isa<TerminatorInst>(CurInst)) {
02703       DEBUG(dbgs() << "Found a terminator instruction.\n");
02704 
02705       if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
02706         if (BI->isUnconditional()) {
02707           NextBB = BI->getSuccessor(0);
02708         } else {
02709           ConstantInt *Cond =
02710             dyn_cast<ConstantInt>(getVal(BI->getCondition()));
02711           if (!Cond) return false;  // Cannot determine.
02712 
02713           NextBB = BI->getSuccessor(!Cond->getZExtValue());
02714         }
02715       } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
02716         ConstantInt *Val =
02717           dyn_cast<ConstantInt>(getVal(SI->getCondition()));
02718         if (!Val) return false;  // Cannot determine.
02719         NextBB = SI->findCaseValue(Val).getCaseSuccessor();
02720       } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
02721         Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
02722         if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
02723           NextBB = BA->getBasicBlock();
02724         else
02725           return false;  // Cannot determine.
02726       } else if (isa<ReturnInst>(CurInst)) {
02727         NextBB = nullptr;
02728       } else {
02729         // invoke, unwind, resume, unreachable.
02730         DEBUG(dbgs() << "Can not handle terminator.");
02731         return false;  // Cannot handle this terminator.
02732       }
02733 
02734       // We succeeded at evaluating this block!
02735       DEBUG(dbgs() << "Successfully evaluated block.\n");
02736       return true;
02737     } else {
02738       // Did not know how to evaluate this!
02739       DEBUG(dbgs() << "Failed to evaluate block due to unhandled instruction."
02740             "\n");
02741       return false;
02742     }
02743 
02744     if (!CurInst->use_empty()) {
02745       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
02746         InstResult = ConstantFoldConstantExpression(CE, DL, TLI);
02747 
02748       setVal(&*CurInst, InstResult);
02749     }
02750 
02751     // If we just processed an invoke, we finished evaluating the block.
02752     if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
02753       NextBB = II->getNormalDest();
02754       DEBUG(dbgs() << "Found an invoke instruction. Finished Block.\n\n");
02755       return true;
02756     }
02757 
02758     // Advance program counter.
02759     ++CurInst;
02760   }
02761 }
02762 
02763 /// Evaluate a call to function F, returning true if successful, false if we
02764 /// can't evaluate it.  ActualArgs contains the formal arguments for the
02765 /// function.
02766 bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,
02767                                  const SmallVectorImpl<Constant*> &ActualArgs) {
02768   // Check to see if this function is already executing (recursion).  If so,
02769   // bail out.  TODO: we might want to accept limited recursion.
02770   if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
02771     return false;
02772 
02773   CallStack.push_back(F);
02774 
02775   // Initialize arguments to the incoming values specified.
02776   unsigned ArgNo = 0;
02777   for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
02778        ++AI, ++ArgNo)
02779     setVal(&*AI, ActualArgs[ArgNo]);
02780 
02781   // ExecutedBlocks - We only handle non-looping, non-recursive code.  As such,
02782   // we can only evaluate any one basic block at most once.  This set keeps
02783   // track of what we have executed so we can detect recursive cases etc.
02784   SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
02785 
02786   // CurBB - The current basic block we're evaluating.
02787   BasicBlock *CurBB = &F->front();
02788 
02789   BasicBlock::iterator CurInst = CurBB->begin();
02790 
02791   while (1) {
02792     BasicBlock *NextBB = nullptr; // Initialized to avoid compiler warnings.
02793     DEBUG(dbgs() << "Trying to evaluate BB: " << *CurBB << "\n");
02794 
02795     if (!EvaluateBlock(CurInst, NextBB))
02796       return false;
02797 
02798     if (!NextBB) {
02799       // Successfully running until there's no next block means that we found
02800       // the return.  Fill it the return value and pop the call stack.
02801       ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator());
02802       if (RI->getNumOperands())
02803         RetVal = getVal(RI->getOperand(0));
02804       CallStack.pop_back();
02805       return true;
02806     }
02807 
02808     // Okay, we succeeded in evaluating this control flow.  See if we have
02809     // executed the new block before.  If so, we have a looping function,
02810     // which we cannot evaluate in reasonable time.
02811     if (!ExecutedBlocks.insert(NextBB).second)
02812       return false;  // looped!
02813 
02814     // Okay, we have never been in this block before.  Check to see if there
02815     // are any PHI nodes.  If so, evaluate them with information about where
02816     // we came from.
02817     PHINode *PN = nullptr;
02818     for (CurInst = NextBB->begin();
02819          (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
02820       setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));
02821 
02822     // Advance to the next block.
02823     CurBB = NextBB;
02824   }
02825 }
02826 
02827 /// Evaluate static constructors in the function, if we can.  Return true if we
02828 /// can, false otherwise.
02829 static bool EvaluateStaticConstructor(Function *F, const DataLayout &DL,
02830                                       const TargetLibraryInfo *TLI) {
02831   // Call the function.
02832   Evaluator Eval(DL, TLI);
02833   Constant *RetValDummy;
02834   bool EvalSuccess = Eval.EvaluateFunction(F, RetValDummy,
02835                                            SmallVector<Constant*, 0>());
02836 
02837   if (EvalSuccess) {
02838     ++NumCtorsEvaluated;
02839 
02840     // We succeeded at evaluation: commit the result.
02841     DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
02842           << F->getName() << "' to " << Eval.getMutatedMemory().size()
02843           << " stores.\n");
02844     for (DenseMap<Constant*, Constant*>::const_iterator I =
02845            Eval.getMutatedMemory().begin(), E = Eval.getMutatedMemory().end();
02846          I != E; ++I)
02847       CommitValueTo(I->second, I->first);
02848     for (GlobalVariable *GV : Eval.getInvariants())
02849       GV->setConstant(true);
02850   }
02851 
02852   return EvalSuccess;
02853 }
02854 
02855 static int compareNames(Constant *const *A, Constant *const *B) {
02856   return (*A)->stripPointerCasts()->getName().compare(
02857       (*B)->stripPointerCasts()->getName());
02858 }
02859 
02860 static void setUsedInitializer(GlobalVariable &V,
02861                                const SmallPtrSet<GlobalValue *, 8> &Init) {
02862   if (Init.empty()) {
02863     V.eraseFromParent();
02864     return;
02865   }
02866 
02867   // Type of pointer to the array of pointers.
02868   PointerType *Int8PtrTy = Type::getInt8PtrTy(V.getContext(), 0);
02869 
02870   SmallVector<llvm::Constant *, 8> UsedArray;
02871   for (GlobalValue *GV : Init) {
02872     Constant *Cast
02873       = ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, Int8PtrTy);
02874     UsedArray.push_back(Cast);
02875   }
02876   // Sort to get deterministic order.
02877   array_pod_sort(UsedArray.begin(), UsedArray.end(), compareNames);
02878   ArrayType *ATy = ArrayType::get(Int8PtrTy, UsedArray.size());
02879 
02880   Module *M = V.getParent();
02881   V.removeFromParent();
02882   GlobalVariable *NV =
02883       new GlobalVariable(*M, ATy, false, llvm::GlobalValue::AppendingLinkage,
02884                          llvm::ConstantArray::get(ATy, UsedArray), "");
02885   NV->takeName(&V);
02886   NV->setSection("llvm.metadata");
02887   delete &V;
02888 }
02889 
02890 namespace {
02891 /// An easy to access representation of llvm.used and llvm.compiler.used.
02892 class LLVMUsed {
02893   SmallPtrSet<GlobalValue *, 8> Used;
02894   SmallPtrSet<GlobalValue *, 8> CompilerUsed;
02895   GlobalVariable *UsedV;
02896   GlobalVariable *CompilerUsedV;
02897 
02898 public:
02899   LLVMUsed(Module &M) {
02900     UsedV = collectUsedGlobalVariables(M, Used, false);
02901     CompilerUsedV = collectUsedGlobalVariables(M, CompilerUsed, true);
02902   }
02903   typedef SmallPtrSet<GlobalValue *, 8>::iterator iterator;
02904   typedef iterator_range<iterator> used_iterator_range;
02905   iterator usedBegin() { return Used.begin(); }
02906   iterator usedEnd() { return Used.end(); }
02907   used_iterator_range used() {
02908     return used_iterator_range(usedBegin(), usedEnd());
02909   }
02910   iterator compilerUsedBegin() { return CompilerUsed.begin(); }
02911   iterator compilerUsedEnd() { return CompilerUsed.end(); }
02912   used_iterator_range compilerUsed() {
02913     return used_iterator_range(compilerUsedBegin(), compilerUsedEnd());
02914   }
02915   bool usedCount(GlobalValue *GV) const { return Used.count(GV); }
02916   bool compilerUsedCount(GlobalValue *GV) const {
02917     return CompilerUsed.count(GV);
02918   }
02919   bool usedErase(GlobalValue *GV) { return Used.erase(GV); }
02920   bool compilerUsedErase(GlobalValue *GV) { return CompilerUsed.erase(GV); }
02921   bool usedInsert(GlobalValue *GV) { return Used.insert(GV).second; }
02922   bool compilerUsedInsert(GlobalValue *GV) {
02923     return CompilerUsed.insert(GV).second;
02924   }
02925 
02926   void syncVariablesAndSets() {
02927     if (UsedV)
02928       setUsedInitializer(*UsedV, Used);
02929     if (CompilerUsedV)
02930       setUsedInitializer(*CompilerUsedV, CompilerUsed);
02931   }
02932 };
02933 }
02934 
02935 static bool hasUseOtherThanLLVMUsed(GlobalAlias &GA, const LLVMUsed &U) {
02936   if (GA.use_empty()) // No use at all.
02937     return false;
02938 
02939   assert((!U.usedCount(&GA) || !U.compilerUsedCount(&GA)) &&
02940          "We should have removed the duplicated "
02941          "element from llvm.compiler.used");
02942   if (!GA.hasOneUse())
02943     // Strictly more than one use. So at least one is not in llvm.used and
02944     // llvm.compiler.used.
02945     return true;
02946 
02947   // Exactly one use. Check if it is in llvm.used or llvm.compiler.used.
02948   return !U.usedCount(&GA) && !U.compilerUsedCount(&GA);
02949 }
02950 
02951 static bool hasMoreThanOneUseOtherThanLLVMUsed(GlobalValue &V,
02952                                                const LLVMUsed &U) {
02953   unsigned N = 2;
02954   assert((!U.usedCount(&V) || !U.compilerUsedCount(&V)) &&
02955          "We should have removed the duplicated "
02956          "element from llvm.compiler.used");
02957   if (U.usedCount(&V) || U.compilerUsedCount(&V))
02958     ++N;
02959   return V.hasNUsesOrMore(N);
02960 }
02961 
02962 static bool mayHaveOtherReferences(GlobalAlias &GA, const LLVMUsed &U) {
02963   if (!GA.hasLocalLinkage())
02964     return true;
02965 
02966   return U.usedCount(&GA) || U.compilerUsedCount(&GA);
02967 }
02968 
02969 static bool hasUsesToReplace(GlobalAlias &GA, const LLVMUsed &U,
02970                              bool &RenameTarget) {
02971   RenameTarget = false;
02972   bool Ret = false;
02973   if (hasUseOtherThanLLVMUsed(GA, U))
02974     Ret = true;
02975 
02976   // If the alias is externally visible, we may still be able to simplify it.
02977   if (!mayHaveOtherReferences(GA, U))
02978     return Ret;
02979 
02980   // If the aliasee has internal linkage, give it the name and linkage
02981   // of the alias, and delete the alias.  This turns:
02982   //   define internal ... @f(...)
02983   //   @a = alias ... @f
02984   // into:
02985   //   define ... @a(...)
02986   Constant *Aliasee = GA.getAliasee();
02987   GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
02988   if (!Target->hasLocalLinkage())
02989     return Ret;
02990 
02991   // Do not perform the transform if multiple aliases potentially target the
02992   // aliasee. This check also ensures that it is safe to replace the section
02993   // and other attributes of the aliasee with those of the alias.
02994   if (hasMoreThanOneUseOtherThanLLVMUsed(*Target, U))
02995     return Ret;
02996 
02997   RenameTarget = true;
02998   return true;
02999 }
03000 
03001 bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
03002   bool Changed = false;
03003   LLVMUsed Used(M);
03004 
03005   for (GlobalValue *GV : Used.used())
03006     Used.compilerUsedErase(GV);
03007 
03008   for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
03009        I != E;) {
03010     GlobalAlias *J = &*I++;
03011 
03012     // Aliases without names cannot be referenced outside this module.
03013     if (!J->hasName() && !J->isDeclaration() && !J->hasLocalLinkage())
03014       J->setLinkage(GlobalValue::InternalLinkage);
03015 
03016     if (deleteIfDead(*J)) {
03017       Changed = true;
03018       continue;
03019     }
03020 
03021     // If the aliasee may change at link time, nothing can be done - bail out.
03022     if (J->mayBeOverridden())
03023       continue;
03024 
03025     Constant *Aliasee = J->getAliasee();
03026     GlobalValue *Target = dyn_cast<GlobalValue>(Aliasee->stripPointerCasts());
03027     // We can't trivially replace the alias with the aliasee if the aliasee is
03028     // non-trivial in some way.
03029     // TODO: Try to handle non-zero GEPs of local aliasees.
03030     if (!Target)
03031       continue;
03032     Target->removeDeadConstantUsers();
03033 
03034     // Make all users of the alias use the aliasee instead.
03035     bool RenameTarget;
03036     if (!hasUsesToReplace(*J, Used, RenameTarget))
03037       continue;
03038 
03039     J->replaceAllUsesWith(ConstantExpr::getBitCast(Aliasee, J->getType()));
03040     ++NumAliasesResolved;
03041     Changed = true;
03042 
03043     if (RenameTarget) {
03044       // Give the aliasee the name, linkage and other attributes of the alias.
03045       Target->takeName(&*J);
03046       Target->setLinkage(J->getLinkage());
03047       Target->setVisibility(J->getVisibility());
03048       Target->setDLLStorageClass(J->getDLLStorageClass());
03049 
03050       if (Used.usedErase(&*J))
03051         Used.usedInsert(Target);
03052 
03053       if (Used.compilerUsedErase(&*J))
03054         Used.compilerUsedInsert(Target);
03055     } else if (mayHaveOtherReferences(*J, Used))
03056       continue;
03057 
03058     // Delete the alias.
03059     M.getAliasList().erase(J);
03060     ++NumAliasesRemoved;
03061     Changed = true;
03062   }
03063 
03064   Used.syncVariablesAndSets();
03065 
03066   return Changed;
03067 }
03068 
03069 static Function *FindCXAAtExit(Module &M, TargetLibraryInfo *TLI) {
03070   if (!TLI->has(LibFunc::cxa_atexit))
03071     return nullptr;
03072 
03073   Function *Fn = M.getFunction(TLI->getName(LibFunc::cxa_atexit));
03074 
03075   if (!Fn)
03076     return nullptr;
03077 
03078   FunctionType *FTy = Fn->getFunctionType();
03079 
03080   // Checking that the function has the right return type, the right number of
03081   // parameters and that they all have pointer types should be enough.
03082   if (!FTy->getReturnType()->isIntegerTy() ||
03083       FTy->getNumParams() != 3 ||
03084       !FTy->getParamType(0)->isPointerTy() ||
03085       !FTy->getParamType(1)->isPointerTy() ||
03086       !FTy->getParamType(2)->isPointerTy())
03087     return nullptr;
03088 
03089   return Fn;
03090 }
03091 
03092 /// Returns whether the given function is an empty C++ destructor and can
03093 /// therefore be eliminated.
03094 /// Note that we assume that other optimization passes have already simplified
03095 /// the code so we only look for a function with a single basic block, where
03096 /// the only allowed instructions are 'ret', 'call' to an empty C++ dtor and
03097 /// other side-effect free instructions.
03098 static bool cxxDtorIsEmpty(const Function &Fn,
03099                            SmallPtrSet<const Function *, 8> &CalledFunctions) {
03100   // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
03101   // nounwind, but that doesn't seem worth doing.
03102   if (Fn.isDeclaration())
03103     return false;
03104 
03105   if (++Fn.begin() != Fn.end())
03106     return false;
03107 
03108   const BasicBlock &EntryBlock = Fn.getEntryBlock();
03109   for (BasicBlock::const_iterator I = EntryBlock.begin(), E = EntryBlock.end();
03110        I != E; ++I) {
03111     if (const CallInst *CI = dyn_cast<CallInst>(I)) {
03112       // Ignore debug intrinsics.
03113       if (isa<DbgInfoIntrinsic>(CI))
03114         continue;
03115 
03116       const Function *CalledFn = CI->getCalledFunction();
03117 
03118       if (!CalledFn)
03119         return false;
03120 
03121       SmallPtrSet<const Function *, 8> NewCalledFunctions(CalledFunctions);
03122 
03123       // Don't treat recursive functions as empty.
03124       if (!NewCalledFunctions.insert(CalledFn).second)
03125         return false;
03126 
03127       if (!cxxDtorIsEmpty(*CalledFn, NewCalledFunctions))
03128         return false;
03129     } else if (isa<ReturnInst>(*I))
03130       return true; // We're done.
03131     else if (I->mayHaveSideEffects())
03132       return false; // Destructor with side effects, bail.
03133   }
03134 
03135   return false;
03136 }
03137 
03138 bool GlobalOpt::OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) {
03139   /// Itanium C++ ABI p3.3.5:
03140   ///
03141   ///   After constructing a global (or local static) object, that will require
03142   ///   destruction on exit, a termination function is registered as follows:
03143   ///
03144   ///   extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
03145   ///
03146   ///   This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
03147   ///   call f(p) when DSO d is unloaded, before all such termination calls
03148   ///   registered before this one. It returns zero if registration is
03149   ///   successful, nonzero on failure.
03150 
03151   // This pass will look for calls to __cxa_atexit where the function is trivial
03152   // and remove them.
03153   bool Changed = false;
03154 
03155   for (auto I = CXAAtExitFn->user_begin(), E = CXAAtExitFn->user_end();
03156        I != E;) {
03157     // We're only interested in calls. Theoretically, we could handle invoke
03158     // instructions as well, but neither llvm-gcc nor clang generate invokes
03159     // to __cxa_atexit.
03160     CallInst *CI = dyn_cast<CallInst>(*I++);
03161     if (!CI)
03162       continue;
03163 
03164     Function *DtorFn =
03165       dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts());
03166     if (!DtorFn)
03167       continue;
03168 
03169     SmallPtrSet<const Function *, 8> CalledFunctions;
03170     if (!cxxDtorIsEmpty(*DtorFn, CalledFunctions))
03171       continue;
03172 
03173     // Just remove the call.
03174     CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
03175     CI->eraseFromParent();
03176 
03177     ++NumCXXDtorsRemoved;
03178 
03179     Changed |= true;
03180   }
03181 
03182   return Changed;
03183 }
03184 
03185 bool GlobalOpt::runOnModule(Module &M) {
03186   bool Changed = false;
03187 
03188   auto &DL = M.getDataLayout();
03189   TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
03190 
03191   bool LocalChange = true;
03192   while (LocalChange) {
03193     LocalChange = false;
03194 
03195     NotDiscardableComdats.clear();
03196     for (const GlobalVariable &GV : M.globals())
03197       if (const Comdat *C = GV.getComdat())
03198         if (!GV.isDiscardableIfUnused() || !GV.use_empty())
03199           NotDiscardableComdats.insert(C);
03200     for (Function &F : M)
03201       if (const Comdat *C = F.getComdat())
03202         if (!F.isDefTriviallyDead())
03203           NotDiscardableComdats.insert(C);
03204     for (GlobalAlias &GA : M.aliases())
03205       if (const Comdat *C = GA.getComdat())
03206         if (!GA.isDiscardableIfUnused() || !GA.use_empty())
03207           NotDiscardableComdats.insert(C);
03208 
03209     // Delete functions that are trivially dead, ccc -> fastcc
03210     LocalChange |= OptimizeFunctions(M);
03211 
03212     // Optimize global_ctors list.
03213     LocalChange |= optimizeGlobalCtorsList(M, [&](Function *F) {
03214       return EvaluateStaticConstructor(F, DL, TLI);
03215     });
03216 
03217     // Optimize non-address-taken globals.
03218     LocalChange |= OptimizeGlobalVars(M);
03219 
03220     // Resolve aliases, when possible.
03221     LocalChange |= OptimizeGlobalAliases(M);
03222 
03223     // Try to remove trivial global destructors if they are not removed
03224     // already.
03225     Function *CXAAtExitFn = FindCXAAtExit(M, TLI);
03226     if (CXAAtExitFn)
03227       LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn);
03228 
03229     Changed |= LocalChange;
03230   }
03231 
03232   // TODO: Move all global ctors functions to the end of the module for code
03233   // layout.
03234 
03235   return Changed;
03236 }
03237