LLVM API Documentation

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 #define DEBUG_TYPE "globalopt"
00017 #include "llvm/Transforms/IPO.h"
00018 #include "llvm/CallingConv.h"
00019 #include "llvm/Constants.h"
00020 #include "llvm/DerivedTypes.h"
00021 #include "llvm/Instructions.h"
00022 #include "llvm/IntrinsicInst.h"
00023 #include "llvm/Module.h"
00024 #include "llvm/Pass.h"
00025 #include "llvm/Analysis/ConstantFolding.h"
00026 #include "llvm/Target/TargetData.h"
00027 #include "llvm/Support/CallSite.h"
00028 #include "llvm/Support/Compiler.h"
00029 #include "llvm/Support/Debug.h"
00030 #include "llvm/Support/GetElementPtrTypeIterator.h"
00031 #include "llvm/Support/MathExtras.h"
00032 #include "llvm/ADT/DenseMap.h"
00033 #include "llvm/ADT/SmallPtrSet.h"
00034 #include "llvm/ADT/SmallVector.h"
00035 #include "llvm/ADT/Statistic.h"
00036 #include "llvm/ADT/StringExtras.h"
00037 #include "llvm/ADT/STLExtras.h"
00038 #include <algorithm>
00039 using namespace llvm;
00040 
00041 STATISTIC(NumMarked    , "Number of globals marked constant");
00042 STATISTIC(NumSRA       , "Number of aggregate globals broken into scalars");
00043 STATISTIC(NumHeapSRA   , "Number of heap objects SRA'd");
00044 STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
00045 STATISTIC(NumDeleted   , "Number of globals deleted");
00046 STATISTIC(NumFnDeleted , "Number of functions deleted");
00047 STATISTIC(NumGlobUses  , "Number of global uses devirtualized");
00048 STATISTIC(NumLocalized , "Number of globals localized");
00049 STATISTIC(NumShrunkToBool  , "Number of global vars shrunk to booleans");
00050 STATISTIC(NumFastCallFns   , "Number of functions converted to fastcc");
00051 STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
00052 STATISTIC(NumNestRemoved   , "Number of nest attributes removed");
00053 
00054 namespace {
00055   struct VISIBILITY_HIDDEN GlobalOpt : public ModulePass {
00056     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
00057       AU.addRequired<TargetData>();
00058     }
00059     static char ID; // Pass identification, replacement for typeid
00060     GlobalOpt() : ModulePass(&ID) {}
00061 
00062     bool runOnModule(Module &M);
00063 
00064   private:
00065     GlobalVariable *FindGlobalCtors(Module &M);
00066     bool OptimizeFunctions(Module &M);
00067     bool OptimizeGlobalVars(Module &M);
00068     bool ResolveAliases(Module &M);
00069     bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
00070     bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
00071   };
00072 }
00073 
00074 char GlobalOpt::ID = 0;
00075 static RegisterPass<GlobalOpt> X("globalopt", "Global Variable Optimizer");
00076 
00077 ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
00078 
00079 namespace {
00080 
00081 /// GlobalStatus - As we analyze each global, keep track of some information
00082 /// about it.  If we find out that the address of the global is taken, none of
00083 /// this info will be accurate.
00084 struct VISIBILITY_HIDDEN GlobalStatus {
00085   /// isLoaded - True if the global is ever loaded.  If the global isn't ever
00086   /// loaded it can be deleted.
00087   bool isLoaded;
00088 
00089   /// StoredType - Keep track of what stores to the global look like.
00090   ///
00091   enum StoredType {
00092     /// NotStored - There is no store to this global.  It can thus be marked
00093     /// constant.
00094     NotStored,
00095 
00096     /// isInitializerStored - This global is stored to, but the only thing
00097     /// stored is the constant it was initialized with.  This is only tracked
00098     /// for scalar globals.
00099     isInitializerStored,
00100 
00101     /// isStoredOnce - This global is stored to, but only its initializer and
00102     /// one other value is ever stored to it.  If this global isStoredOnce, we
00103     /// track the value stored to it in StoredOnceValue below.  This is only
00104     /// tracked for scalar globals.
00105     isStoredOnce,
00106 
00107     /// isStored - This global is stored to by multiple values or something else
00108     /// that we cannot track.
00109     isStored
00110   } StoredType;
00111 
00112   /// StoredOnceValue - If only one value (besides the initializer constant) is
00113   /// ever stored to this global, keep track of what value it is.
00114   Value *StoredOnceValue;
00115 
00116   /// AccessingFunction/HasMultipleAccessingFunctions - These start out
00117   /// null/false.  When the first accessing function is noticed, it is recorded.
00118   /// When a second different accessing function is noticed,
00119   /// HasMultipleAccessingFunctions is set to true.
00120   Function *AccessingFunction;
00121   bool HasMultipleAccessingFunctions;
00122 
00123   /// HasNonInstructionUser - Set to true if this global has a user that is not
00124   /// an instruction (e.g. a constant expr or GV initializer).
00125   bool HasNonInstructionUser;
00126 
00127   /// HasPHIUser - Set to true if this global has a user that is a PHI node.
00128   bool HasPHIUser;
00129   
00130   GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
00131                    AccessingFunction(0), HasMultipleAccessingFunctions(false),
00132                    HasNonInstructionUser(false), HasPHIUser(false) {}
00133 };
00134 
00135 }
00136 
00137 /// ConstantIsDead - Return true if the specified constant is (transitively)
00138 /// dead.  The constant may be used by other constants (e.g. constant arrays and
00139 /// constant exprs) as long as they are dead, but it cannot be used by anything
00140 /// else.
00141 static bool ConstantIsDead(Constant *C) {
00142   if (isa<GlobalValue>(C)) return false;
00143 
00144   for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
00145     if (Constant *CU = dyn_cast<Constant>(*UI)) {
00146       if (!ConstantIsDead(CU)) return false;
00147     } else
00148       return false;
00149   return true;
00150 }
00151 
00152 
00153 /// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
00154 /// structure.  If the global has its address taken, return true to indicate we
00155 /// can't do anything with it.
00156 ///
00157 static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
00158                           SmallPtrSet<PHINode*, 16> &PHIUsers) {
00159   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
00160     if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
00161       GS.HasNonInstructionUser = true;
00162 
00163       if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
00164 
00165     } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
00166       if (!GS.HasMultipleAccessingFunctions) {
00167         Function *F = I->getParent()->getParent();
00168         if (GS.AccessingFunction == 0)
00169           GS.AccessingFunction = F;
00170         else if (GS.AccessingFunction != F)
00171           GS.HasMultipleAccessingFunctions = true;
00172       }
00173       if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
00174         GS.isLoaded = true;
00175         if (LI->isVolatile()) return true;  // Don't hack on volatile loads.
00176       } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
00177         // Don't allow a store OF the address, only stores TO the address.
00178         if (SI->getOperand(0) == V) return true;
00179 
00180         if (SI->isVolatile()) return true;  // Don't hack on volatile stores.
00181 
00182         // If this is a direct store to the global (i.e., the global is a scalar
00183         // value, not an aggregate), keep more specific information about
00184         // stores.
00185         if (GS.StoredType != GlobalStatus::isStored) {
00186           if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
00187             Value *StoredVal = SI->getOperand(0);
00188             if (StoredVal == GV->getInitializer()) {
00189               if (GS.StoredType < GlobalStatus::isInitializerStored)
00190                 GS.StoredType = GlobalStatus::isInitializerStored;
00191             } else if (isa<LoadInst>(StoredVal) &&
00192                        cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
00193               // G = G
00194               if (GS.StoredType < GlobalStatus::isInitializerStored)
00195                 GS.StoredType = GlobalStatus::isInitializerStored;
00196             } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
00197               GS.StoredType = GlobalStatus::isStoredOnce;
00198               GS.StoredOnceValue = StoredVal;
00199             } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
00200                        GS.StoredOnceValue == StoredVal) {
00201               // noop.
00202             } else {
00203               GS.StoredType = GlobalStatus::isStored;
00204             }
00205           } else {
00206             GS.StoredType = GlobalStatus::isStored;
00207           }
00208         }
00209       } else if (isa<GetElementPtrInst>(I)) {
00210         if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
00211       } else if (isa<SelectInst>(I)) {
00212         if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
00213       } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
00214         // PHI nodes we can check just like select or GEP instructions, but we
00215         // have to be careful about infinite recursion.
00216         if (PHIUsers.insert(PN))  // Not already visited.
00217           if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
00218         GS.HasPHIUser = true;
00219       } else if (isa<CmpInst>(I)) {
00220       } else if (isa<MemCpyInst>(I) || isa<MemMoveInst>(I)) {
00221         if (I->getOperand(1) == V)
00222           GS.StoredType = GlobalStatus::isStored;
00223         if (I->getOperand(2) == V)
00224           GS.isLoaded = true;
00225       } else if (isa<MemSetInst>(I)) {
00226         assert(I->getOperand(1) == V && "Memset only takes one pointer!");
00227         GS.StoredType = GlobalStatus::isStored;
00228       } else {
00229         return true;  // Any other non-load instruction might take address!
00230       }
00231     } else if (Constant *C = dyn_cast<Constant>(*UI)) {
00232       GS.HasNonInstructionUser = true;
00233       // We might have a dead and dangling constant hanging off of here.
00234       if (!ConstantIsDead(C))
00235         return true;
00236     } else {
00237       GS.HasNonInstructionUser = true;
00238       // Otherwise must be some other user.
00239       return true;
00240     }
00241 
00242   return false;
00243 }
00244 
00245 static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
00246   ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
00247   if (!CI) return 0;
00248   unsigned IdxV = CI->getZExtValue();
00249 
00250   if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
00251     if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
00252   } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
00253     if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
00254   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) {
00255     if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
00256   } else if (isa<ConstantAggregateZero>(Agg)) {
00257     if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
00258       if (IdxV < STy->getNumElements())
00259         return Constant::getNullValue(STy->getElementType(IdxV));
00260     } else if (const SequentialType *STy =
00261                dyn_cast<SequentialType>(Agg->getType())) {
00262       return Constant::getNullValue(STy->getElementType());
00263     }
00264   } else if (isa<UndefValue>(Agg)) {
00265     if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
00266       if (IdxV < STy->getNumElements())
00267         return UndefValue::get(STy->getElementType(IdxV));
00268     } else if (const SequentialType *STy =
00269                dyn_cast<SequentialType>(Agg->getType())) {
00270       return UndefValue::get(STy->getElementType());
00271     }
00272   }
00273   return 0;
00274 }
00275 
00276 
00277 /// CleanupConstantGlobalUsers - We just marked GV constant.  Loop over all
00278 /// users of the global, cleaning up the obvious ones.  This is largely just a
00279 /// quick scan over the use list to clean up the easy and obvious cruft.  This
00280 /// returns true if it made a change.
00281 static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
00282   bool Changed = false;
00283   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
00284     User *U = *UI++;
00285 
00286     if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
00287       if (Init) {
00288         // Replace the load with the initializer.
00289         LI->replaceAllUsesWith(Init);
00290         LI->eraseFromParent();
00291         Changed = true;
00292       }
00293     } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
00294       // Store must be unreachable or storing Init into the global.
00295       SI->eraseFromParent();
00296       Changed = true;
00297     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
00298       if (CE->getOpcode() == Instruction::GetElementPtr) {
00299         Constant *SubInit = 0;
00300         if (Init)
00301           SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
00302         Changed |= CleanupConstantGlobalUsers(CE, SubInit);
00303       } else if (CE->getOpcode() == Instruction::BitCast && 
00304                  isa<PointerType>(CE->getType())) {
00305         // Pointer cast, delete any stores and memsets to the global.
00306         Changed |= CleanupConstantGlobalUsers(CE, 0);
00307       }
00308 
00309       if (CE->use_empty()) {
00310         CE->destroyConstant();
00311         Changed = true;
00312       }
00313     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
00314       // Do not transform "gepinst (gep constexpr (GV))" here, because forming
00315       // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
00316       // and will invalidate our notion of what Init is.
00317       Constant *SubInit = 0;
00318       if (!isa<ConstantExpr>(GEP->getOperand(0))) {
00319         ConstantExpr *CE = 
00320           dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
00321         if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
00322           SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
00323       }
00324       Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
00325 
00326       if (GEP->use_empty()) {
00327         GEP->eraseFromParent();
00328         Changed = true;
00329       }
00330     } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
00331       if (MI->getRawDest() == V) {
00332         MI->eraseFromParent();
00333         Changed = true;
00334       }
00335 
00336     } else if (Constant *C = dyn_cast<Constant>(U)) {
00337       // If we have a chain of dead constantexprs or other things dangling from
00338       // us, and if they are all dead, nuke them without remorse.
00339       if (ConstantIsDead(C)) {
00340         C->destroyConstant();
00341         // This could have invalidated UI, start over from scratch.
00342         CleanupConstantGlobalUsers(V, Init);
00343         return true;
00344       }
00345     }
00346   }
00347   return Changed;
00348 }
00349 
00350 /// isSafeSROAElementUse - Return true if the specified instruction is a safe
00351 /// user of a derived expression from a global that we want to SROA.
00352 static bool isSafeSROAElementUse(Value *V) {
00353   // We might have a dead and dangling constant hanging off of here.
00354   if (Constant *C = dyn_cast<Constant>(V))
00355     return ConstantIsDead(C);
00356   
00357   Instruction *I = dyn_cast<Instruction>(V);
00358   if (!I) return false;
00359 
00360   // Loads are ok.
00361   if (isa<LoadInst>(I)) return true;
00362 
00363   // Stores *to* the pointer are ok.
00364   if (StoreInst *SI = dyn_cast<StoreInst>(I))
00365     return SI->getOperand(0) != V;
00366     
00367   // Otherwise, it must be a GEP.
00368   GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
00369   if (GEPI == 0) return false;
00370   
00371   if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
00372       !cast<Constant>(GEPI->getOperand(1))->isNullValue())
00373     return false;
00374   
00375   for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
00376        I != E; ++I)
00377     if (!isSafeSROAElementUse(*I))
00378       return false;
00379   return true;
00380 }
00381 
00382 
00383 /// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
00384 /// Look at it and its uses and decide whether it is safe to SROA this global.
00385 ///
00386 static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
00387   // The user of the global must be a GEP Inst or a ConstantExpr GEP.
00388   if (!isa<GetElementPtrInst>(U) && 
00389       (!isa<ConstantExpr>(U) || 
00390        cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
00391     return false;
00392   
00393   // Check to see if this ConstantExpr GEP is SRA'able.  In particular, we
00394   // don't like < 3 operand CE's, and we don't like non-constant integer
00395   // indices.  This enforces that all uses are 'gep GV, 0, C, ...' for some
00396   // value of C.
00397   if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
00398       !cast<Constant>(U->getOperand(1))->isNullValue() ||
00399       !isa<ConstantInt>(U->getOperand(2)))
00400     return false;
00401 
00402   gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
00403   ++GEPI;  // Skip over the pointer index.
00404   
00405   // If this is a use of an array allocation, do a bit more checking for sanity.
00406   if (const ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
00407     uint64_t NumElements = AT->getNumElements();
00408     ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
00409     
00410     // Check to make sure that index falls within the array.  If not,
00411     // something funny is going on, so we won't do the optimization.
00412     //
00413     if (Idx->getZExtValue() >= NumElements)
00414       return false;
00415       
00416     // We cannot scalar repl this level of the array unless any array
00417     // sub-indices are in-range constants.  In particular, consider:
00418     // A[0][i].  We cannot know that the user isn't doing invalid things like
00419     // allowing i to index an out-of-range subscript that accesses A[1].
00420     //
00421     // Scalar replacing *just* the outer index of the array is probably not
00422     // going to be a win anyway, so just give up.
00423     for (++GEPI; // Skip array index.
00424          GEPI != E && (isa<ArrayType>(*GEPI) || isa<VectorType>(*GEPI));
00425          ++GEPI) {
00426       uint64_t NumElements;
00427       if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
00428         NumElements = SubArrayTy->getNumElements();
00429       else
00430         NumElements = cast<VectorType>(*GEPI)->getNumElements();
00431       
00432       ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
00433       if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
00434         return false;
00435     }
00436   }
00437 
00438   for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
00439     if (!isSafeSROAElementUse(*I))
00440       return false;
00441   return true;
00442 }
00443 
00444 /// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
00445 /// is safe for us to perform this transformation.
00446 ///
00447 static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
00448   for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
00449        UI != E; ++UI) {
00450     if (!IsUserOfGlobalSafeForSRA(*UI, GV))
00451       return false;
00452   }
00453   return true;
00454 }
00455  
00456 
00457 /// SRAGlobal - Perform scalar replacement of aggregates on the specified global
00458 /// variable.  This opens the door for other optimizations by exposing the
00459 /// behavior of the program in a more fine-grained way.  We have determined that
00460 /// this transformation is safe already.  We return the first global variable we
00461 /// insert so that the caller can reprocess it.
00462 static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD) {
00463   // Make sure this global only has simple uses that we can SRA.
00464   if (!GlobalUsersSafeToSRA(GV))
00465     return 0;
00466   
00467   assert(GV->hasLocalLinkage() && !GV->isConstant());
00468   Constant *Init = GV->getInitializer();
00469   const Type *Ty = Init->getType();
00470 
00471   std::vector<GlobalVariable*> NewGlobals;
00472   Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
00473 
00474   // Get the alignment of the global, either explicit or target-specific.
00475   unsigned StartAlignment = GV->getAlignment();
00476   if (StartAlignment == 0)
00477     StartAlignment = TD.getABITypeAlignment(GV->getType());
00478    
00479   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
00480     NewGlobals.reserve(STy->getNumElements());
00481     const StructLayout &Layout = *TD.getStructLayout(STy);
00482     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
00483       Constant *In = getAggregateConstantElement(Init,
00484                                             ConstantInt::get(Type::Int32Ty, i));
00485       assert(In && "Couldn't get element of initializer?");
00486       GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
00487                                                GlobalVariable::InternalLinkage,
00488                                                In, GV->getName()+"."+utostr(i),
00489                                                (Module *)NULL,
00490                                                GV->isThreadLocal(),
00491                                                GV->getType()->getAddressSpace());
00492       Globals.insert(GV, NGV);
00493       NewGlobals.push_back(NGV);
00494       
00495       // Calculate the known alignment of the field.  If the original aggregate
00496       // had 256 byte alignment for example, something might depend on that:
00497       // propagate info to each field.
00498       uint64_t FieldOffset = Layout.getElementOffset(i);
00499       unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
00500       if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
00501         NGV->setAlignment(NewAlign);
00502     }
00503   } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
00504     unsigned NumElements = 0;
00505     if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
00506       NumElements = ATy->getNumElements();
00507     else
00508       NumElements = cast<VectorType>(STy)->getNumElements();
00509 
00510     if (NumElements > 16 && GV->hasNUsesOrMore(16))
00511       return 0; // It's not worth it.
00512     NewGlobals.reserve(NumElements);
00513     
00514     uint64_t EltSize = TD.getTypePaddedSize(STy->getElementType());
00515     unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
00516     for (unsigned i = 0, e = NumElements; i != e; ++i) {
00517       Constant *In = getAggregateConstantElement(Init,
00518                                             ConstantInt::get(Type::Int32Ty, i));
00519       assert(In && "Couldn't get element of initializer?");
00520 
00521       GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
00522                                                GlobalVariable::InternalLinkage,
00523                                                In, GV->getName()+"."+utostr(i),
00524                                                (Module *)NULL,
00525                                                GV->isThreadLocal(),
00526                                                GV->getType()->getAddressSpace());
00527       Globals.insert(GV, NGV);
00528       NewGlobals.push_back(NGV);
00529       
00530       // Calculate the known alignment of the field.  If the original aggregate
00531       // had 256 byte alignment for example, something might depend on that:
00532       // propagate info to each field.
00533       unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
00534       if (NewAlign > EltAlign)
00535         NGV->setAlignment(NewAlign);
00536     }
00537   }
00538 
00539   if (NewGlobals.empty())
00540     return 0;
00541 
00542   DOUT << "PERFORMING GLOBAL SRA ON: " << *GV;
00543 
00544   Constant *NullInt = Constant::getNullValue(Type::Int32Ty);
00545 
00546   // Loop over all of the uses of the global, replacing the constantexpr geps,
00547   // with smaller constantexpr geps or direct references.
00548   while (!GV->use_empty()) {
00549     User *GEP = GV->use_back();
00550     assert(((isa<ConstantExpr>(GEP) &&
00551              cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
00552             isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
00553 
00554     // Ignore the 1th operand, which has to be zero or else the program is quite
00555     // broken (undefined).  Get the 2nd operand, which is the structure or array
00556     // index.
00557     unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
00558     if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
00559 
00560     Value *NewPtr = NewGlobals[Val];
00561 
00562     // Form a shorter GEP if needed.
00563     if (GEP->getNumOperands() > 3) {
00564       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
00565         SmallVector<Constant*, 8> Idxs;
00566         Idxs.push_back(NullInt);
00567         for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
00568           Idxs.push_back(CE->getOperand(i));
00569         NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr),
00570                                                 &Idxs[0], Idxs.size());
00571       } else {
00572         GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
00573         SmallVector<Value*, 8> Idxs;
00574         Idxs.push_back(NullInt);
00575         for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
00576           Idxs.push_back(GEPI->getOperand(i));
00577         NewPtr = GetElementPtrInst::Create(NewPtr, Idxs.begin(), Idxs.end(),
00578                                            GEPI->getName()+"."+utostr(Val), GEPI);
00579       }
00580     }
00581     GEP->replaceAllUsesWith(NewPtr);
00582 
00583     if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
00584       GEPI->eraseFromParent();
00585     else
00586       cast<ConstantExpr>(GEP)->destroyConstant();
00587   }
00588 
00589   // Delete the old global, now that it is dead.
00590   Globals.erase(GV);
00591   ++NumSRA;
00592 
00593   // Loop over the new globals array deleting any globals that are obviously
00594   // dead.  This can arise due to scalarization of a structure or an array that
00595   // has elements that are dead.
00596   unsigned FirstGlobal = 0;
00597   for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
00598     if (NewGlobals[i]->use_empty()) {
00599       Globals.erase(NewGlobals[i]);
00600       if (FirstGlobal == i) ++FirstGlobal;
00601     }
00602 
00603   return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
00604 }
00605 
00606 /// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
00607 /// value will trap if the value is dynamically null.  PHIs keeps track of any 
00608 /// phi nodes we've seen to avoid reprocessing them.
00609 static bool AllUsesOfValueWillTrapIfNull(Value *V,
00610                                          SmallPtrSet<PHINode*, 8> &PHIs) {
00611   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
00612     if (isa<LoadInst>(*UI)) {
00613       // Will trap.
00614     } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
00615       if (SI->getOperand(0) == V) {
00616         //cerr << "NONTRAPPING USE: " << **UI;
00617         return false;  // Storing the value.
00618       }
00619     } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
00620       if (CI->getOperand(0) != V) {
00621         //cerr << "NONTRAPPING USE: " << **UI;
00622         return false;  // Not calling the ptr
00623       }
00624     } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
00625       if (II->getOperand(0) != V) {
00626         //cerr << "NONTRAPPING USE: " << **UI;
00627         return false;  // Not calling the ptr
00628       }
00629     } else if (BitCastInst *CI = dyn_cast<BitCastInst>(*UI)) {
00630       if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
00631     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
00632       if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
00633     } else if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
00634       // If we've already seen this phi node, ignore it, it has already been
00635       // checked.
00636       if (PHIs.insert(PN))
00637         return AllUsesOfValueWillTrapIfNull(PN, PHIs);
00638     } else if (isa<ICmpInst>(*UI) &&
00639                isa<ConstantPointerNull>(UI->getOperand(1))) {
00640       // Ignore setcc X, null
00641     } else {
00642       //cerr << "NONTRAPPING USE: " << **UI;
00643       return false;
00644     }
00645   return true;
00646 }
00647 
00648 /// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
00649 /// from GV will trap if the loaded value is null.  Note that this also permits
00650 /// comparisons of the loaded value against null, as a special case.
00651 static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
00652   for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
00653     if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
00654       SmallPtrSet<PHINode*, 8> PHIs;
00655       if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
00656         return false;
00657     } else if (isa<StoreInst>(*UI)) {
00658       // Ignore stores to the global.
00659     } else {
00660       // We don't know or understand this user, bail out.
00661       //cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
00662       return false;
00663     }
00664 
00665   return true;
00666 }
00667 
00668 static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
00669   bool Changed = false;
00670   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
00671     Instruction *I = cast<Instruction>(*UI++);
00672     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
00673       LI->setOperand(0, NewV);
00674       Changed = true;
00675     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
00676       if (SI->getOperand(1) == V) {
00677         SI->setOperand(1, NewV);
00678         Changed = true;
00679       }
00680     } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
00681       if (I->getOperand(0) == V) {
00682         // Calling through the pointer!  Turn into a direct call, but be careful
00683         // that the pointer is not also being passed as an argument.
00684         I->setOperand(0, NewV);
00685         Changed = true;
00686         bool PassedAsArg = false;
00687         for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
00688           if (I->getOperand(i) == V) {
00689             PassedAsArg = true;
00690             I->setOperand(i, NewV);
00691           }
00692 
00693         if (PassedAsArg) {
00694           // Being passed as an argument also.  Be careful to not invalidate UI!
00695           UI = V->use_begin();
00696         }
00697       }
00698     } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
00699       Changed |= OptimizeAwayTrappingUsesOfValue(CI,
00700                                 ConstantExpr::getCast(CI->getOpcode(),
00701                                                       NewV, CI->getType()));
00702       if (CI->use_empty()) {
00703         Changed = true;
00704         CI->eraseFromParent();
00705       }
00706     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
00707       // Should handle GEP here.
00708       SmallVector<Constant*, 8> Idxs;
00709       Idxs.reserve(GEPI->getNumOperands()-1);
00710       for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
00711            i != e; ++i)
00712         if (Constant *C = dyn_cast<Constant>(*i))
00713           Idxs.push_back(C);
00714         else
00715           break;
00716       if (Idxs.size() == GEPI->getNumOperands()-1)
00717         Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
00718                                 ConstantExpr::getGetElementPtr(NewV, &Idxs[0],
00719                                                                Idxs.size()));
00720       if (GEPI->use_empty()) {
00721         Changed = true;
00722         GEPI->eraseFromParent();
00723       }
00724     }
00725   }
00726 
00727   return Changed;
00728 }
00729 
00730 
00731 /// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
00732 /// value stored into it.  If there are uses of the loaded value that would trap
00733 /// if the loaded value is dynamically null, then we know that they cannot be
00734 /// reachable with a null optimize away the load.
00735 static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
00736   bool Changed = false;
00737 
00738   // Keep track of whether we are able to remove all the uses of the global
00739   // other than the store that defines it.
00740   bool AllNonStoreUsesGone = true;
00741   
00742   // Replace all uses of loads with uses of uses of the stored value.
00743   for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
00744     User *GlobalUser = *GUI++;
00745     if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
00746       Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
00747       // If we were able to delete all uses of the loads
00748       if (LI->use_empty()) {
00749         LI->eraseFromParent();
00750         Changed = true;
00751       } else {
00752         AllNonStoreUsesGone = false;
00753       }
00754     } else if (isa<StoreInst>(GlobalUser)) {
00755       // Ignore the store that stores "LV" to the global.
00756       assert(GlobalUser->getOperand(1) == GV &&
00757              "Must be storing *to* the global");
00758     } else {
00759       AllNonStoreUsesGone = false;
00760 
00761       // If we get here we could have other crazy uses that are transitively
00762       // loaded.
00763       assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
00764               isa<ConstantExpr>(GlobalUser)) && "Only expect load and stores!");
00765     }
00766   }
00767 
00768   if (Changed) {
00769     DOUT << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV;
00770     ++NumGlobUses;
00771   }
00772 
00773   // If we nuked all of the loads, then none of the stores are needed either,
00774   // nor is the global.
00775   if (AllNonStoreUsesGone) {
00776     DOUT << "  *** GLOBAL NOW DEAD!\n";
00777     CleanupConstantGlobalUsers(GV, 0);
00778     if (GV->use_empty()) {
00779       GV->eraseFromParent();
00780       ++NumDeleted;
00781     }
00782     Changed = true;
00783   }
00784   return Changed;
00785 }
00786 
00787 /// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
00788 /// instructions that are foldable.
00789 static void ConstantPropUsersOf(Value *V) {
00790   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
00791     if (Instruction *I = dyn_cast<Instruction>(*UI++))
00792       if (Constant *NewC = ConstantFoldInstruction(I)) {
00793         I->replaceAllUsesWith(NewC);
00794 
00795         // Advance UI to the next non-I use to avoid invalidating it!
00796         // Instructions could multiply use V.
00797         while (UI != E && *UI == I)
00798           ++UI;
00799         I->eraseFromParent();
00800       }
00801 }
00802 
00803 /// OptimizeGlobalAddressOfMalloc - This function takes the specified global
00804 /// variable, and transforms the program as if it always contained the result of
00805 /// the specified malloc.  Because it is always the result of the specified
00806 /// malloc, there is no reason to actually DO the malloc.  Instead, turn the
00807 /// malloc into a global, and any loads of GV as uses of the new global.
00808 static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
00809                                                      MallocInst *MI) {
00810   DOUT << "PROMOTING MALLOC GLOBAL: " << *GV << "  MALLOC = " << *MI;
00811   ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
00812 
00813   if (NElements->getZExtValue() != 1) {
00814     // If we have an array allocation, transform it to a single element
00815     // allocation to make the code below simpler.
00816     Type *NewTy = ArrayType::get(MI->getAllocatedType(),
00817                                  NElements->getZExtValue());
00818     MallocInst *NewMI =
00819       new MallocInst(NewTy, Constant::getNullValue(Type::Int32Ty),
00820                      MI->getAlignment(), MI->getName(), MI);
00821     Value* Indices[2];
00822     Indices[0] = Indices[1] = Constant::getNullValue(Type::Int32Ty);
00823     Value *NewGEP = GetElementPtrInst::Create(NewMI, Indices, Indices + 2,
00824                                               NewMI->getName()+".el0", MI);
00825     MI->replaceAllUsesWith(NewGEP);
00826     MI->eraseFromParent();
00827     MI = NewMI;
00828   }
00829 
00830   // Create the new global variable.  The contents of the malloc'd memory is
00831   // undefined, so initialize with an undef value.
00832   Constant *Init = UndefValue::get(MI->getAllocatedType());
00833   GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false,
00834                                              GlobalValue::InternalLinkage, Init,
00835                                              GV->getName()+".body",
00836                                              (Module *)NULL,
00837                                              GV->isThreadLocal());
00838   // FIXME: This new global should have the alignment returned by malloc.  Code
00839   // could depend on malloc returning large alignment (on the mac, 16 bytes) but
00840   // this would only guarantee some lower alignment.
00841   GV->getParent()->getGlobalList().insert(GV, NewGV);
00842 
00843   // Anything that used the malloc now uses the global directly.
00844   MI->replaceAllUsesWith(NewGV);
00845 
00846   Constant *RepValue = NewGV;
00847   if (NewGV->getType() != GV->getType()->getElementType())
00848     RepValue = ConstantExpr::getBitCast(RepValue, 
00849                                         GV->getType()->getElementType());
00850 
00851   // If there is a comparison against null, we will insert a global bool to
00852   // keep track of whether the global was initialized yet or not.
00853   GlobalVariable *InitBool =
00854     new GlobalVariable(Type::Int1Ty, false, GlobalValue::InternalLinkage,
00855                        ConstantInt::getFalse(), GV->getName()+".init",
00856                        (Module *)NULL, GV->isThreadLocal());
00857   bool InitBoolUsed = false;
00858 
00859   // Loop over all uses of GV, processing them in turn.
00860   std::vector<StoreInst*> Stores;
00861   while (!GV->use_empty())
00862     if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
00863       while (!LI->use_empty()) {
00864         Use &LoadUse = LI->use_begin().getUse();
00865         if (!isa<ICmpInst>(LoadUse.getUser()))
00866           LoadUse = RepValue;
00867         else {
00868           ICmpInst *CI = cast<ICmpInst>(LoadUse.getUser());
00869           // Replace the cmp X, 0 with a use of the bool value.
00870           Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", CI);
00871           InitBoolUsed = true;
00872           switch (CI->getPredicate()) {
00873           default: assert(0 && "Unknown ICmp Predicate!");
00874           case ICmpInst::ICMP_ULT:
00875           case ICmpInst::ICMP_SLT:
00876             LV = ConstantInt::getFalse();   // X < null -> always false
00877             break;
00878           case ICmpInst::ICMP_ULE:
00879           case ICmpInst::ICMP_SLE:
00880           case ICmpInst::ICMP_EQ:
00881             LV = BinaryOperator::CreateNot(LV, "notinit", CI);
00882             break;
00883           case ICmpInst::ICMP_NE:
00884           case ICmpInst::ICMP_UGE:
00885           case ICmpInst::ICMP_SGE:
00886           case ICmpInst::ICMP_UGT:
00887           case ICmpInst::ICMP_SGT:
00888             break;  // no change.
00889           }
00890           CI->replaceAllUsesWith(LV);
00891           CI->eraseFromParent();
00892         }
00893       }
00894       LI->eraseFromParent();
00895     } else {
00896       StoreInst *SI = cast<StoreInst>(GV->use_back());
00897       // The global is initialized when the store to it occurs.
00898       new StoreInst(ConstantInt::getTrue(), InitBool, SI);
00899       SI->eraseFromParent();
00900     }
00901 
00902   // If the initialization boolean was used, insert it, otherwise delete it.
00903   if (!InitBoolUsed) {
00904     while (!InitBool->use_empty())  // Delete initializations
00905       cast<Instruction>(InitBool->use_back())->eraseFromParent();
00906     delete InitBool;
00907   } else
00908     GV->getParent()->getGlobalList().insert(GV, InitBool);
00909 
00910 
00911   // Now the GV is dead, nuke it and the malloc.
00912   GV->eraseFromParent();
00913   MI->eraseFromParent();
00914 
00915   // To further other optimizations, loop over all users of NewGV and try to
00916   // constant prop them.  This will promote GEP instructions with constant
00917   // indices into GEP constant-exprs, which will allow global-opt to hack on it.
00918   ConstantPropUsersOf(NewGV);
00919   if (RepValue != NewGV)
00920     ConstantPropUsersOf(RepValue);
00921 
00922   return NewGV;
00923 }
00924 
00925 /// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
00926 /// to make sure that there are no complex uses of V.  We permit simple things
00927 /// like dereferencing the pointer, but not storing through the address, unless
00928 /// it is to the specified global.
00929 static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
00930                                                       GlobalVariable *GV,
00931                                               SmallPtrSet<PHINode*, 8> &PHIs) {
00932   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
00933     Instruction *Inst = dyn_cast<Instruction>(*UI);
00934     if (Inst == 0) return false;
00935     
00936     if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
00937       continue; // Fine, ignore.
00938     }
00939     
00940     if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
00941       if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
00942         return false;  // Storing the pointer itself... bad.
00943       continue; // Otherwise, storing through it, or storing into GV... fine.
00944     }
00945     
00946     if (isa<GetElementPtrInst>(Inst)) {
00947       if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
00948         return false;
00949       continue;
00950     }
00951     
00952     if (PHINode *PN = dyn_cast<PHINode>(Inst)) {
00953       // PHIs are ok if all uses are ok.  Don't infinitely recurse through PHI
00954       // cycles.
00955       if (PHIs.insert(PN))
00956         if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
00957           return false;
00958       continue;
00959     }
00960     
00961     if (BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
00962       if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
00963         return false;
00964       continue;
00965     }
00966     
00967     return false;
00968   }
00969   return true;
00970 }
00971 
00972 /// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
00973 /// somewhere.  Transform all uses of the allocation into loads from the
00974 /// global and uses of the resultant pointer.  Further, delete the store into
00975 /// GV.  This assumes that these value pass the 
00976 /// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
00977 static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc, 
00978                                           GlobalVariable *GV) {
00979   while (!Alloc->use_empty()) {
00980     Instruction *U = cast<Instruction>(*Alloc->use_begin());
00981     Instruction *InsertPt = U;
00982     if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
00983       // If this is the store of the allocation into the global, remove it.
00984       if (SI->getOperand(1) == GV) {
00985         SI->eraseFromParent();
00986         continue;
00987       }
00988     } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
00989       // Insert the load in the corresponding predecessor, not right before the
00990       // PHI.
00991       InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
00992     } else if (isa<BitCastInst>(U)) {
00993       // Must be bitcast between the malloc and store to initialize the global.
00994       ReplaceUsesOfMallocWithGlobal(U, GV);
00995       U->eraseFromParent();
00996       continue;
00997     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
00998       // If this is a "GEP bitcast" and the user is a store to the global, then
00999       // just process it as a bitcast.
01000       if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
01001         if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
01002           if (SI->getOperand(1) == GV) {
01003             // Must be bitcast GEP between the malloc and store to initialize
01004             // the global.
01005             ReplaceUsesOfMallocWithGlobal(GEPI, GV);
01006             GEPI->eraseFromParent();
01007             continue;
01008           }
01009     }
01010       
01011     // Insert a load from the global, and use it instead of the malloc.
01012     Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
01013     U->replaceUsesOfWith(Alloc, NL);
01014   }
01015 }
01016 
01017 /// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
01018 /// of a load) are simple enough to perform heap SRA on.  This permits GEP's
01019 /// that index through the array and struct field, icmps of null, and PHIs.
01020 static bool LoadUsesSimpleEnoughForHeapSRA(Value *V,
01021                                      SmallPtrSet<PHINode*, 32> &LoadUsingPHIs) {
01022   // We permit two users of the load: setcc comparing against the null
01023   // pointer, and a getelementptr of a specific form.
01024   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
01025     Instruction *User = cast<Instruction>(*UI);
01026     
01027     // Comparison against null is ok.
01028     if (ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
01029       if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
01030         return false;
01031       continue;
01032     }
01033     
01034     // getelementptr is also ok, but only a simple form.
01035     if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
01036       // Must index into the array and into the struct.
01037       if (GEPI->getNumOperands() < 3)
01038         return false;
01039       
01040       // Otherwise the GEP is ok.
01041       continue;
01042     }
01043     
01044     if (PHINode *PN = dyn_cast<PHINode>(User)) {
01045       // If we have already recursively analyzed this PHI, then it is safe.
01046       if (LoadUsingPHIs.insert(PN))
01047         continue;
01048       
01049       // Make sure all uses of the PHI are simple enough to transform.
01050       if (!LoadUsesSimpleEnoughForHeapSRA(PN, LoadUsingPHIs))
01051         return false;
01052       
01053       continue;
01054     }
01055     
01056     // Otherwise we don't know what this is, not ok.
01057     return false;
01058   }
01059   
01060   return true;
01061 }
01062 
01063 
01064 /// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
01065 /// GV are simple enough to perform HeapSRA, return true.
01066 static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(GlobalVariable *GV,
01067                                                     MallocInst *MI) {
01068   SmallPtrSet<PHINode*, 32> LoadUsingPHIs;
01069   for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E; 
01070        ++UI)
01071     if (LoadInst *LI = dyn_cast<LoadInst>(*UI))
01072       if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs))
01073         return false;
01074   
01075   // If we reach here, we know that all uses of the loads and transitive uses
01076   // (through PHI nodes) are simple enough to transform.  However, we don't know
01077   // that all inputs the to the PHI nodes are in the same equivalence sets. 
01078   // Check to verify that all operands of the PHIs are either PHIS that can be
01079   // transformed, loads from GV, or MI itself.
01080   for (SmallPtrSet<PHINode*, 32>::iterator I = LoadUsingPHIs.begin(),
01081        E = LoadUsingPHIs.end(); I != E; ++I) {
01082     PHINode *PN = *I;
01083     for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
01084       Value *InVal = PN->getIncomingValue(op);
01085       
01086       // PHI of the stored value itself is ok.
01087       if (InVal == MI) continue;
01088       
01089       if (PHINode *InPN = dyn_cast<PHINode>(InVal)) {
01090         // One of the PHIs in our set is (optimistically) ok.
01091         if (LoadUsingPHIs.count(InPN))
01092           continue;
01093         return false;
01094       }
01095       
01096       // Load from GV is ok.
01097       if (LoadInst *LI = dyn_cast<LoadInst>(InVal))
01098         if (LI->getOperand(0) == GV)
01099           continue;
01100       
01101       // UNDEF? NULL?
01102       
01103       // Anything else is rejected.
01104       return false;
01105     }
01106   }
01107   
01108   return true;
01109 }
01110 
01111 static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
01112                DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
01113                    std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
01114   std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
01115   
01116   if (FieldNo >= FieldVals.size())
01117     FieldVals.resize(FieldNo+1);
01118   
01119   // If we already have this value, just reuse the previously scalarized
01120   // version.
01121   if (Value *FieldVal = FieldVals[FieldNo])
01122     return FieldVal;
01123   
01124   // Depending on what instruction this is, we have several cases.
01125   Value *Result;
01126   if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
01127     // This is a scalarized version of the load from the global.  Just create
01128     // a new Load of the scalarized global.
01129     Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
01130                                            InsertedScalarizedValues,
01131                                            PHIsToRewrite),
01132                           LI->getName()+".f" + utostr(FieldNo), LI);
01133   } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
01134     // PN's type is pointer to struct.  Make a new PHI of pointer to struct
01135     // field.
01136     const StructType *ST = 
01137       cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
01138     
01139     Result =PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
01140                             PN->getName()+".f"+utostr(FieldNo), PN);
01141     PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
01142   } else {
01143     assert(0 && "Unknown usable value");
01144     Result = 0;
01145   }
01146   
01147   return FieldVals[FieldNo] = Result;
01148 }
01149 
01150 /// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
01151 /// the load, rewrite the derived value to use the HeapSRoA'd load.
01152 static void RewriteHeapSROALoadUser(Instruction *LoadUser, 
01153              DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
01154                    std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
01155   // If this is a comparison against null, handle it.
01156   if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
01157     assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
01158     // If we have a setcc of the loaded pointer, we can use a setcc of any
01159     // field.
01160     Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
01161                                    InsertedScalarizedValues, PHIsToRewrite);
01162     
01163     Value *New = new ICmpInst(SCI->getPredicate(), NPtr,
01164                               Constant::getNullValue(NPtr->getType()),
01165                               SCI->getName(), SCI);
01166     SCI->replaceAllUsesWith(New);
01167     SCI->eraseFromParent();
01168     return;
01169   }
01170   
01171   // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
01172   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
01173     assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
01174            && "Unexpected GEPI!");
01175   
01176     // Load the pointer for this field.
01177     unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
01178     Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
01179                                      InsertedScalarizedValues, PHIsToRewrite);
01180     
01181     // Create the new GEP idx vector.
01182     SmallVector<Value*, 8> GEPIdx;
01183     GEPIdx.push_back(GEPI->getOperand(1));
01184     GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
01185     
01186     Value *NGEPI = GetElementPtrInst::Create(NewPtr,
01187                                              GEPIdx.begin(), GEPIdx.end(),
01188                                              GEPI->getName(), GEPI);
01189     GEPI->replaceAllUsesWith(NGEPI);
01190     GEPI->eraseFromParent();
01191     return;
01192   }
01193 
01194   // Recursively transform the users of PHI nodes.  This will lazily create the
01195   // PHIs that are needed for individual elements.  Keep track of what PHIs we
01196   // see in InsertedScalarizedValues so that we don't get infinite loops (very
01197   // antisocial).  If the PHI is already in InsertedScalarizedValues, it has
01198   // already been seen first by another load, so its uses have already been
01199   // processed.
01200   PHINode *PN = cast<PHINode>(LoadUser);
01201   bool Inserted;
01202   DenseMap<Value*, std::vector<Value*> >::iterator InsertPos;
01203   tie(InsertPos, Inserted) =
01204     InsertedScalarizedValues.insert(std::make_pair(PN, std::vector<Value*>()));
01205   if (!Inserted) return;
01206   
01207   // If this is the first time we've seen this PHI, recursively process all
01208   // users.
01209   for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
01210     Instruction *User = cast<Instruction>(*UI++);
01211     RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
01212   }
01213 }
01214 
01215 /// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global.  Ptr
01216 /// is a value loaded from the global.  Eliminate all uses of Ptr, making them
01217 /// use FieldGlobals instead.  All uses of loaded values satisfy
01218 /// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
01219 static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load, 
01220                DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
01221                    std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
01222   for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
01223        UI != E; ) {
01224     Instruction *User = cast<Instruction>(*UI++);
01225     RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
01226   }
01227   
01228   if (Load->use_empty()) {
01229     Load->eraseFromParent();
01230     InsertedScalarizedValues.erase(Load);
01231   }
01232 }
01233 
01234 /// PerformHeapAllocSRoA - MI is an allocation of an array of structures.  Break
01235 /// it up into multiple allocations of arrays of the fields.
01236 static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, MallocInst *MI){
01237   DOUT << "SROA HEAP ALLOC: " << *GV << "  MALLOC = " << *MI;
01238   const StructType *STy = cast<StructType>(MI->getAllocatedType());
01239 
01240   // There is guaranteed to be at least one use of the malloc (storing
01241   // it into GV).  If there are other uses, change them to be uses of
01242   // the global to simplify later code.  This also deletes the store
01243   // into GV.
01244   ReplaceUsesOfMallocWithGlobal(MI, GV);
01245   
01246   // Okay, at this point, there are no users of the malloc.  Insert N
01247   // new mallocs at the same place as MI, and N globals.
01248   std::vector<Value*> FieldGlobals;
01249   std::vector<MallocInst*> FieldMallocs;
01250   
01251   for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
01252     const Type *FieldTy = STy->getElementType(FieldNo);
01253     const Type *PFieldTy = PointerType::getUnqual(FieldTy);
01254     
01255     GlobalVariable *NGV =
01256       new GlobalVariable(PFieldTy, false, GlobalValue::InternalLinkage,
01257                          Constant::getNullValue(PFieldTy),
01258                          GV->getName() + ".f" + utostr(FieldNo), GV,
01259                          GV->isThreadLocal());
01260     FieldGlobals.push_back(NGV);
01261     
01262     MallocInst *NMI = new MallocInst(FieldTy, MI->getArraySize(),
01263                                      MI->getName() + ".f" + utostr(FieldNo),MI);
01264     FieldMallocs.push_back(NMI);
01265     new StoreInst(NMI, NGV, MI);
01266   }
01267   
01268   // The tricky aspect of this transformation is handling the case when malloc
01269   // fails.  In the original code, malloc failing would set the result pointer
01270   // of malloc to null.  In this case, some mallocs could succeed and others
01271   // could fail.  As such, we emit code that looks like this:
01272   //    F0 = malloc(field0)
01273   //    F1 = malloc(field1)
01274   //    F2 = malloc(field2)
01275   //    if (F0 == 0 || F1 == 0 || F2 == 0) {
01276   //      if (F0) { free(F0); F0 = 0; }
01277   //      if (F1) { free(F1); F1 = 0; }
01278   //      if (F2) { free(F2); F2 = 0; }
01279   //    }
01280   Value *RunningOr = 0;
01281   for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
01282     Value *Cond = new ICmpInst(ICmpInst::ICMP_EQ, FieldMallocs[i],
01283                              Constant::getNullValue(FieldMallocs[i]->getType()),
01284                                   "isnull", MI);
01285     if (!RunningOr)
01286       RunningOr = Cond;   // First seteq
01287     else
01288       RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", MI);
01289   }
01290 
01291   // Split the basic block at the old malloc.
01292   BasicBlock *OrigBB = MI->getParent();
01293   BasicBlock *ContBB = OrigBB->splitBasicBlock(MI, "malloc_cont");
01294   
01295   // Create the block to check the first condition.  Put all these blocks at the
01296   // end of the function as they are unlikely to be executed.
01297   BasicBlock *NullPtrBlock = BasicBlock::Create("malloc_ret_null",
01298                                                 OrigBB->getParent());
01299   
01300   // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
01301   // branch on RunningOr.
01302   OrigBB->getTerminator()->eraseFromParent();
01303   BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
01304   
01305   // Within the NullPtrBlock, we need to emit a comparison and branch for each
01306   // pointer, because some may be null while others are not.
01307   for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
01308     Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
01309     Value *Cmp = new ICmpInst(ICmpInst::ICMP_NE, GVVal, 
01310                               Constant::getNullValue(GVVal->getType()),
01311                               "tmp", NullPtrBlock);
01312     BasicBlock *FreeBlock = BasicBlock::Create("free_it", OrigBB->getParent());
01313     BasicBlock *NextBlock = BasicBlock::Create("next", OrigBB->getParent());
01314     BranchInst::Create(FreeBlock, NextBlock, Cmp, NullPtrBlock);
01315 
01316     // Fill in FreeBlock.
01317     new FreeInst(GVVal, FreeBlock);
01318     new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
01319                   FreeBlock);
01320     BranchInst::Create(NextBlock, FreeBlock);
01321     
01322     NullPtrBlock = NextBlock;
01323   }
01324   
01325   BranchInst::Create(ContBB, NullPtrBlock);
01326   
01327   // MI is no longer needed, remove it.
01328   MI->eraseFromParent();
01329 
01330   /// InsertedScalarizedLoads - As we process loads, if we can't immediately
01331   /// update all uses of the load, keep track of what scalarized loads are
01332   /// inserted for a given load.
01333   DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
01334   InsertedScalarizedValues[GV] = FieldGlobals;
01335   
01336   std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
01337   
01338   // Okay, the malloc site is completely handled.  All of the uses of GV are now
01339   // loads, and all uses of those loads are simple.  Rewrite them to use loads
01340   // of the per-field globals instead.
01341   for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
01342     Instruction *User = cast<Instruction>(*UI++);
01343     
01344     if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
01345       RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
01346       continue;
01347     }
01348     
01349     // Must be a store of null.
01350     StoreInst *SI = cast<StoreInst>(User);
01351     assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
01352            "Unexpected heap-sra user!");
01353     
01354     // Insert a store of null into each global.
01355     for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
01356       const PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
01357       Constant *Null = Constant::getNullValue(PT->getElementType());
01358       new StoreInst(Null, FieldGlobals[i], SI);
01359     }
01360     // Erase the original store.
01361     SI->eraseFromParent();
01362   }
01363 
01364   // While we have PHIs that are interesting to rewrite, do it.
01365   while (!PHIsToRewrite.empty()) {
01366     PHINode *PN = PHIsToRewrite.back().first;
01367     unsigned FieldNo = PHIsToRewrite.back().second;
01368     PHIsToRewrite.pop_back();
01369     PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
01370     assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
01371 
01372     // Add all the incoming values.  This can materialize more phis.
01373     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
01374       Value *InVal = PN->getIncomingValue(i);
01375       InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
01376                                PHIsToRewrite);
01377       FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
01378     }
01379   }
01380   
01381   // Drop all inter-phi links and any loads that made it this far.
01382   for (DenseMap<Value*, std::vector<Value*> >::iterator
01383        I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
01384        I != E; ++I) {
01385     if (PHINode *PN = dyn_cast<PHINode>(I->first))
01386       PN->dropAllReferences();
01387     else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
01388       LI->dropAllReferences();
01389   }
01390   
01391   // Delete all the phis and loads now that inter-references are dead.
01392   for (DenseMap<Value*, std::vector<Value*> >::iterator
01393        I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
01394        I != E; ++I) {
01395     if (PHINode *PN = dyn_cast<PHINode>(I->first))
01396       PN->eraseFromParent();
01397     else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
01398       LI->eraseFromParent();
01399   }
01400   
01401   // The old global is now dead, remove it.
01402   GV->eraseFromParent();
01403 
01404   ++NumHeapSRA;
01405   return cast<GlobalVariable>(FieldGlobals[0]);
01406 }
01407 
01408 /// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
01409 /// pointer global variable with a single value stored it that is a malloc or
01410 /// cast of malloc.
01411 static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
01412                                                MallocInst *MI,
01413                                                Module::global_iterator &GVI,
01414                                                TargetData &TD) {
01415   // If this is a malloc of an abstract type, don't touch it.
01416   if (!MI->getAllocatedType()->isSized())
01417     return false;
01418   
01419   // We can't optimize this global unless all uses of it are *known* to be
01420   // of the malloc value, not of the null initializer value (consider a use
01421   // that compares the global's value against zero to see if the malloc has
01422   // been reached).  To do this, we check to see if all uses of the global
01423   // would trap if the global were null: this proves that they must all
01424   // happen after the malloc.
01425   if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
01426     return false;
01427   
01428   // We can't optimize this if the malloc itself is used in a complex way,
01429   // for example, being stored into multiple globals.  This allows the
01430   // malloc to be stored into the specified global, loaded setcc'd, and
01431   // GEP'd.  These are all things we could transform to using the global
01432   // for.
01433   {
01434     SmallPtrSet<PHINode*, 8> PHIs;
01435     if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV, PHIs))
01436       return false;
01437   }
01438   
01439   
01440   // If we have a global that is only initialized with a fixed size malloc,
01441   // transform the program to use global memory instead of malloc'd memory.
01442   // This eliminates dynamic allocation, avoids an indirection accessing the
01443   // data, and exposes the resultant global to further GlobalOpt.
01444   if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize())) {
01445     // Restrict this transformation to only working on small allocations
01446     // (2048 bytes currently), as we don't want to introduce a 16M global or
01447     // something.
01448     if (NElements->getZExtValue()*
01449         TD.getTypePaddedSize(MI->getAllocatedType()) < 2048) {
01450       GVI = OptimizeGlobalAddressOfMalloc(GV, MI);
01451       return true;
01452     }
01453   }
01454   
01455   // If the allocation is an array of structures, consider transforming this
01456   // into multiple malloc'd arrays, one for each field.  This is basically
01457   // SRoA for malloc'd memory.
01458   const Type *AllocTy = MI->getAllocatedType();
01459   
01460   // If this is an allocation of a fixed size array of structs, analyze as a
01461   // variable size array.  malloc [100 x struct],1 -> malloc struct, 100
01462   if (!MI->isArrayAllocation())
01463     if (const ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
01464       AllocTy = AT->getElementType();
01465   
01466   if (const StructType *AllocSTy = dyn_cast<StructType>(AllocTy)) {
01467     // This the structure has an unreasonable number of fields, leave it
01468     // alone.
01469     if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
01470         AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, MI)) {
01471       
01472       // If this is a fixed size array, transform the Malloc to be an alloc of
01473       // structs.  malloc [100 x struct],1 -> malloc struct, 100
01474       if (const ArrayType *AT = dyn_cast<ArrayType>(MI->getAllocatedType())) {
01475         MallocInst *NewMI = 
01476           new MallocInst(AllocSTy, 
01477                          ConstantInt::get(Type::Int32Ty, AT->getNumElements()),
01478                          "", MI);
01479         NewMI->takeName(MI);
01480         Value *Cast = new BitCastInst(NewMI, MI->getType(), "tmp", MI);
01481         MI->replaceAllUsesWith(Cast);
01482         MI->eraseFromParent();
01483         MI = NewMI;
01484       }
01485       
01486       GVI = PerformHeapAllocSRoA(GV, MI);
01487       return true;
01488     }
01489   }
01490   
01491   return false;
01492 }  
01493 
01494 // OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
01495 // that only one value (besides its initializer) is ever stored to the global.
01496 static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
01497                                      Module::global_iterator &GVI,
01498                                      TargetData &TD) {
01499   // Ignore no-op GEPs and bitcasts.
01500   StoredOnceVal = StoredOnceVal->stripPointerCasts();
01501 
01502   // If we are dealing with a pointer global that is initialized to null and
01503   // only has one (non-null) value stored into it, then we can optimize any
01504   // users of the loaded value (often calls and loads) that would trap if the
01505   // value was null.
01506   if (isa<PointerType>(GV->getInitializer()->getType()) &&
01507       GV->getInitializer()->isNullValue()) {
01508     if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
01509       if (GV->getInitializer()->getType() != SOVC->getType())
01510         SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
01511 
01512       // Optimize away any trapping uses of the loaded value.
01513       if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
01514         return true;
01515     } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
01516       if (TryToOptimizeStoreOfMallocToGlobal(GV, MI, GVI, TD))
01517         return true;
01518     }
01519   }
01520 
01521   return false;
01522 }
01523 
01524 /// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
01525 /// two values ever stored into GV are its initializer and OtherVal.  See if we
01526 /// can shrink the global into a boolean and select between the two values
01527 /// whenever it is used.  This exposes the values to other scalar optimizations.
01528 static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
01529   const Type *GVElType = GV->getType()->getElementType();
01530   
01531   // If GVElType is already i1, it is already shrunk.  If the type of the GV is
01532   // an FP value or vector, don't do this optimization because a select between
01533   // them is very expensive and unlikely to lead to later simplification.
01534   if (GVElType == Type::Int1Ty || GVElType->isFloatingPoint() ||
01535       isa<VectorType>(GVElType))
01536     return false;
01537   
01538   // Walk the use list of the global seeing if all the uses are load or store.
01539   // If there is anything else, bail out.
01540   for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I)
01541     if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
01542       return false;
01543   
01544   DOUT << "   *** SHRINKING TO BOOL: " << *GV;
01545   
01546   // Create the new global, initializing it to false.
01547   GlobalVariable *NewGV = new GlobalVariable(Type::Int1Ty, false,
01548          GlobalValue::InternalLinkage, ConstantInt::getFalse(),
01549                                              GV->getName()+".b",
01550                                              (Module *)NULL,
01551                                              GV->isThreadLocal());
01552   GV->getParent()->getGlobalList().insert(GV, NewGV);
01553 
01554   Constant *InitVal = GV->getInitializer();
01555   assert(InitVal->getType() != Type::Int1Ty && "No reason to shrink to bool!");
01556 
01557   // If initialized to zero and storing one into the global, we can use a cast
01558   // instead of a select to synthesize the desired value.
01559   bool IsOneZero = false;
01560   if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
01561     IsOneZero = InitVal->isNullValue() && CI->isOne();
01562 
01563   while (!GV->use_empty()) {
01564     Instruction *UI = cast<Instruction>(GV->use_back());
01565     if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
01566       // Change the store into a boolean store.
01567       bool StoringOther = SI->getOperand(0) == OtherVal;
01568       // Only do this if we weren't storing a loaded value.
01569       Value *StoreVal;
01570       if (StoringOther || SI->getOperand(0) == InitVal)
01571         StoreVal = ConstantInt::get(Type::Int1Ty, StoringOther);
01572       else {
01573         // Otherwise, we are storing a previously loaded copy.  To do this,
01574         // change the copy from copying the original value to just copying the
01575         // bool.
01576         Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
01577 
01578         // If we're already replaced the input, StoredVal will be a cast or
01579         // select instruction.  If not, it will be a load of the original
01580         // global.
01581         if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
01582           assert(LI->getOperand(0) == GV && "Not a copy!");
01583           // Insert a new load, to preserve the saved value.
01584           StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
01585         } else {
01586           assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
01587                  "This is not a form that we understand!");
01588           StoreVal = StoredVal->getOperand(0);
01589           assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
01590         }
01591       }
01592       new StoreInst(StoreVal, NewGV, SI);
01593     } else {
01594       // Change the load into a load of bool then a select.
01595       LoadInst *LI = cast<LoadInst>(UI);
01596       LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
01597       Value *NSI;
01598       if (IsOneZero)
01599         NSI = new ZExtInst(NLI, LI->getType(), "", LI);
01600       else
01601         NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
01602       NSI->takeName(LI);
01603       LI->replaceAllUsesWith(NSI);
01604     }
01605     UI->eraseFromParent();
01606   }
01607 
01608   GV->eraseFromParent();
01609   return true;
01610 }
01611 
01612 
01613 /// ProcessInternalGlobal - Analyze the specified global variable and optimize
01614 /// it if possible.  If we make a change, return true.
01615 bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
01616                                       Module::global_iterator &GVI) {
01617   SmallPtrSet<PHINode*, 16> PHIUsers;
01618   GlobalStatus GS;
01619   GV->removeDeadConstantUsers();
01620 
01621   if (GV->use_empty()) {
01622     DOUT << "GLOBAL DEAD: " << *GV;
01623     GV->eraseFromParent();
01624     ++NumDeleted;
01625     return true;
01626   }
01627 
01628   if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
01629 #if 0
01630     cerr << "Global: " << *GV;
01631     cerr << "  isLoaded = " << GS.isLoaded << "\n";
01632     cerr << "  StoredType = ";
01633     switch (GS.StoredType) {
01634     case GlobalStatus::NotStored: cerr << "NEVER STORED\n"; break;
01635     case GlobalStatus::isInitializerStored: cerr << "INIT STORED\n"; break;
01636     case GlobalStatus::isStoredOnce: cerr << "STORED ONCE\n"; break;
01637     case GlobalStatus::isStored: cerr << "stored\n"; break;
01638     }
01639     if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
01640       cerr << "  StoredOnceValue = " << *GS.StoredOnceValue << "\n";
01641     if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
01642       cerr << "  AccessingFunction = " << GS.AccessingFunction->getName()
01643                 << "\n";
01644     cerr << "  HasMultipleAccessingFunctions =  "
01645               << GS.HasMultipleAccessingFunctions << "\n";
01646     cerr << "  HasNonInstructionUser = " << GS.HasNonInstructionUser<<"\n";
01647     cerr << "\n";
01648 #endif
01649     
01650     // If this is a first class global and has only one accessing function
01651     // and this function is main (which we know is not recursive we can make
01652     // this global a local variable) we replace the global with a local alloca
01653     // in this function.
01654     //
01655     // NOTE: It doesn't make sense to promote non single-value types since we
01656     // are just replacing static memory to stack memory.
01657     if (!GS.HasMultipleAccessingFunctions &&
01658         GS.AccessingFunction && !GS.HasNonInstructionUser &&
01659         GV->getType()->getElementType()->isSingleValueType() &&
01660         GS.AccessingFunction->getName() == "main" &&
01661         GS.AccessingFunction->hasExternalLinkage()) {
01662       DOUT << "LOCALIZING GLOBAL: " << *GV;
01663       Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
01664       const Type* ElemTy = GV->getType()->getElementType();
01665       // FIXME: Pass Global's alignment when globals have alignment
01666       AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
01667       if (!isa<UndefValue>(GV->getInitializer()))
01668         new StoreInst(GV->getInitializer(), Alloca, FirstI);
01669 
01670       GV->replaceAllUsesWith(Alloca);
01671       GV->eraseFromParent();
01672       ++NumLocalized;
01673       return true;
01674     }
01675     
01676     // If the global is never loaded (but may be stored to), it is dead.
01677     // Delete it now.
01678     if (!GS.isLoaded) {
01679       DOUT << "GLOBAL NEVER LOADED: " << *GV;
01680 
01681       // Delete any stores we can find to the global.  We may not be able to
01682       // make it completely dead though.
01683       bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
01684 
01685       // If the global is dead now, delete it.
01686       if (GV->use_empty()) {
01687         GV->eraseFromParent();
01688         ++NumDeleted;
01689         Changed = true;
01690       }
01691       return Changed;
01692 
01693     } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
01694       DOUT << "MARKING CONSTANT: " << *GV;
01695       GV->setConstant(true);
01696 
01697       // Clean up any obviously simplifiable users now.
01698       CleanupConstantGlobalUsers(GV, GV->getInitializer());
01699 
01700       // If the global is dead now, just nuke it.
01701       if (GV->use_empty()) {
01702         DOUT << "   *** Marking constant allowed us to simplify "
01703              << "all users and delete global!\n";
01704         GV->eraseFromParent();
01705         ++NumDeleted;
01706       }
01707 
01708       ++NumMarked;
01709       return true;
01710     } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
01711       if (GlobalVariable *FirstNewGV = SRAGlobal(GV, 
01712                                                  getAnalysis<TargetData>())) {
01713         GVI = FirstNewGV;  // Don't skip the newly produced globals!
01714         return true;
01715       }
01716     } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
01717       // If the initial value for the global was an undef value, and if only
01718       // one other value was stored into it, we can just change the
01719       // initializer to be the stored value, then delete all stores to the
01720       // global.  This allows us to mark it constant.
01721       if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
01722         if (isa<UndefValue>(GV->getInitializer())) {
01723           // Change the initial value here.
01724           GV->setInitializer(SOVConstant);
01725 
01726           // Clean up any obviously simplifiable users now.
01727           CleanupConstantGlobalUsers(GV, GV->getInitializer());
01728 
01729           if (GV->use_empty()) {
01730             DOUT << "   *** Substituting initializer allowed us to "
01731                  << "simplify all users and delete global!\n";
01732             GV->eraseFromParent();
01733             ++NumDeleted;
01734           } else {
01735             GVI = GV;
01736           }
01737           ++NumSubstitute;
01738           return true;
01739         }
01740 
01741       // Try to optimize globals based on the knowledge that only one value
01742       // (besides its initializer) is ever stored to the global.
01743       if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
01744                                    getAnalysis<TargetData>()))
01745         return true;
01746 
01747       // Otherwise, if the global was not a boolean, we can shrink it to be a
01748       // boolean.
01749       if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
01750         if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
01751           ++NumShrunkToBool;
01752           return true;
01753         }
01754     }
01755   }
01756   return false;
01757 }
01758 
01759 /// OnlyCalledDirectly - Return true if the specified function is only called
01760 /// directly.  In other words, its address is never taken.
01761 static bool OnlyCalledDirectly(Function *F) {
01762   for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
01763     Instruction *User = dyn_cast<Instruction>(*UI);
01764     if (!User) return false;
01765     if (!isa<CallInst>(User) && !isa<InvokeInst>(User)) return false;
01766 
01767     // See if the function address is passed as an argument.
01768     for (User::op_iterator i = User->op_begin() + 1, e = User->op_end();
01769          i != e; ++i)
01770       if (*i == F) return false;
01771   }
01772   return true;
01773 }
01774 
01775 /// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
01776 /// function, changing them to FastCC.
01777 static void ChangeCalleesToFastCall(Function *F) {
01778   for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
01779     CallSite User(cast<Instruction>(*UI));
01780     User.setCallingConv(CallingConv::Fast);
01781   }
01782 }
01783 
01784 static AttrListPtr StripNest(const AttrListPtr &Attrs) {
01785   for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
01786     if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
01787       continue;
01788 
01789     // There can be only one.
01790     return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
01791   }
01792 
01793   return Attrs;
01794 }
01795 
01796 static void RemoveNestAttribute(Function *F) {
01797   F->setAttributes(StripNest(F->getAttributes()));
01798   for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
01799     CallSite User(cast<Instruction>(*UI));
01800     User.setAttributes(StripNest(User.getAttributes()));
01801   }
01802 }
01803 
01804 bool GlobalOpt::OptimizeFunctions(Module &M) {
01805   bool Changed = false;
01806   // Optimize functions.
01807   for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
01808     Function *F = FI++;
01809     F->removeDeadConstantUsers();
01810     if (F->use_empty() && (F->hasLocalLinkage() ||
01811                            F->hasLinkOnceLinkage())) {
01812       M.getFunctionList().erase(F);
01813       Changed = true;
01814       ++NumFnDeleted;
01815     } else if (F->hasLocalLinkage()) {
01816       if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
01817           OnlyCalledDirectly(F)) {
01818         // If this function has C calling conventions, is not a varargs
01819         // function, and is only called directly, promote it to use the Fast
01820         // calling convention.
01821         F->setCallingConv(CallingConv::Fast);
01822         ChangeCalleesToFastCall(F);
01823         ++NumFastCallFns;
01824         Changed = true;
01825       }
01826 
01827       if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
01828           OnlyCalledDirectly(F)) {
01829         // The function is not used by a trampoline intrinsic, so it is safe
01830         // to remove the 'nest' attribute.
01831         RemoveNestAttribute(F);
01832         ++NumNestRemoved;
01833         Changed = true;
01834       }
01835     }
01836   }
01837   return Changed;
01838 }
01839 
01840 bool GlobalOpt::OptimizeGlobalVars(Module &M) {
01841   bool Changed = false;
01842   for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
01843        GVI != E; ) {
01844     GlobalVariable *GV = GVI++;
01845     if (!GV->isConstant() && GV->hasLocalLinkage() &&
01846         GV->hasInitializer())
01847       Changed |= ProcessInternalGlobal(GV, GVI);
01848   }
01849   return Changed;
01850 }
01851 
01852 /// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
01853 /// initializers have an init priority of 65535.
01854 GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
01855   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
01856        I != E; ++I)
01857     if (I->getName() == "llvm.global_ctors") {
01858       // Found it, verify it's an array of { int, void()* }.
01859       const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
01860       if (!ATy) return 0;
01861       const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
01862       if (!STy || STy->getNumElements() != 2 ||
01863           STy->getElementType(0) != Type::Int32Ty) return 0;
01864       const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
01865       if (!PFTy) return 0;
01866       const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
01867       if (!FTy || FTy->getReturnType() != Type::VoidTy || FTy->isVarArg() ||
01868           FTy->getNumParams() != 0)
01869         return 0;
01870       
01871       // Verify that the initializer is simple enough for us to handle.
01872       if (!I->hasInitializer()) return 0;
01873       ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
01874       if (!CA) return 0;
01875       for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
01876         if (ConstantStruct *CS = dyn_cast<ConstantStruct>(*i)) {
01877           if (isa<ConstantPointerNull>(CS->getOperand(1)))
01878             continue;
01879 
01880           // Must have a function or null ptr.
01881           if (!isa<Function>(CS->getOperand(1)))
01882             return 0;
01883           
01884           // Init priority must be standard.
01885           ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
01886           if (!CI || CI->getZExtValue() != 65535)
01887             return 0;
01888         } else {
01889           return 0;
01890         }
01891       
01892       return I;
01893     }
01894   return 0;
01895 }
01896 
01897 /// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
01898 /// return a list of the functions and null terminator as a vector.
01899 static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
01900   ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
01901   std::vector<Function*> Result;
01902   Result.reserve(CA->getNumOperands());
01903   for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
01904     ConstantStruct *CS = cast<ConstantStruct>(*i);
01905     Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
01906   }
01907   return Result;
01908 }
01909 
01910 /// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
01911 /// specified array, returning the new global to use.
01912 static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL, 
01913                                           const std::vector<Function*> &Ctors) {
01914   // If we made a change, reassemble the initializer list.
01915   std::vector<Constant*> CSVals;
01916   CSVals.push_back(ConstantInt::get(Type::Int32Ty, 65535));
01917   CSVals.push_back(0);
01918   
01919   // Create the new init list.
01920   std::vector<Constant*> CAList;
01921   for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
01922     if (Ctors[i]) {
01923       CSVals[1] = Ctors[i];
01924     } else {
01925       const Type *FTy = FunctionType::get(Type::VoidTy,
01926                                           std::vector<const Type*>(), false);
01927       const PointerType *PFTy = PointerType::getUnqual(FTy);
01928       CSVals[1] = Constant::getNullValue(PFTy);
01929       CSVals[0] = ConstantInt::get(Type::Int32Ty, 2147483647);
01930     }
01931     CAList.push_back(ConstantStruct::get(CSVals));
01932   }
01933   
01934   // Create the array initializer.
01935   const Type *StructTy =
01936     cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
01937   Constant *CA = ConstantArray::get(ArrayType::get(StructTy, CAList.size()),
01938                                     CAList);
01939   
01940   // If we didn't change the number of elements, don't create a new GV.
01941   if (CA->getType() == GCL->getInitializer()->getType()) {
01942     GCL->setInitializer(CA);
01943     return GCL;
01944   }
01945   
01946   // Create the new global and insert it next to the existing list.
01947   GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
01948                                            GCL->getLinkage(), CA, "",
01949                                            (Module *)NULL,
01950                                            GCL->isThreadLocal());
01951   GCL->getParent()->getGlobalList().insert(GCL, NGV);
01952   NGV->takeName(GCL);
01953   
01954   // Nuke the old list, replacing any uses with the new one.
01955   if (!GCL->use_empty()) {
01956     Constant *V = NGV;
01957     if (V->getType() != GCL->getType())
01958       V = ConstantExpr::getBitCast(V, GCL->getType());
01959     GCL->replaceAllUsesWith(V);
01960   }
01961   GCL->eraseFromParent();
01962   
01963   if (Ctors.size())
01964     return NGV;
01965   else
01966     return 0;
01967 }
01968 
01969 
01970 static Constant *getVal(DenseMap<Value*, Constant*> &ComputedValues,
01971                         Value *V) {
01972   if (Constant *CV = dyn_cast<Constant>(V)) return CV;
01973   Constant *R = ComputedValues[V];
01974   assert(R && "Reference to an uncomputed value!");
01975   return R;
01976 }
01977 
01978 /// isSimpleEnoughPointerToCommit - Return true if this constant is simple
01979 /// enough for us to understand.  In particular, if it is a cast of something,
01980 /// we punt.  We basically just support direct accesses to globals and GEP's of
01981 /// globals.  This should be kept up to date with CommitValueTo.
01982 static bool isSimpleEnoughPointerToCommit(Constant *C) {
01983   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
01984     if (!GV->hasExternalLinkage() && !GV->hasLocalLinkage())
01985       return false;  // do not allow weak/linkonce/dllimport/dllexport linkage.
01986     return !GV->isDeclaration();  // reject external globals.
01987   }
01988   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
01989     // Handle a constantexpr gep.
01990     if (CE->getOpcode() == Instruction::GetElementPtr &&
01991         isa<GlobalVariable>(CE->getOperand(0))) {
01992       GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
01993       if (!GV->hasExternalLinkage() && !GV->hasLocalLinkage())
01994         return false;  // do not allow weak/linkonce/dllimport/dllexport linkage.
01995       return GV->hasInitializer() &&
01996              ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
01997     }
01998   return false;
01999 }
02000 
02001 /// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
02002 /// initializer.  This returns 'Init' modified to reflect 'Val' stored into it.
02003 /// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
02004 static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
02005                                    ConstantExpr *Addr, unsigned OpNo) {
02006   // Base case of the recursion.
02007   if (OpNo == Addr->getNumOperands()) {
02008     assert(Val->getType() == Init->getType() && "Type mismatch!");
02009     return Val;
02010   }
02011   
02012   if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
02013     std::vector<Constant*> Elts;
02014 
02015     // Break up the constant into its elements.
02016     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
02017       for (User::op_iterator i = CS->op_begin(), e = CS->op_end(); i != e; ++i)
02018         Elts.push_back(cast<Constant>(*i));
02019     } else if (isa<ConstantAggregateZero>(Init)) {
02020       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
02021         Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
02022     } else if (isa<UndefValue>(Init)) {
02023       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
02024         Elts.push_back(UndefValue::get(STy->getElementType(i)));
02025     } else {
02026       assert(0 && "This code is out of sync with "
02027              " ConstantFoldLoadThroughGEPConstantExpr");
02028     }
02029     
02030     // Replace the element that we are supposed to.
02031     ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
02032     unsigned Idx = CU->getZExtValue();
02033     assert(Idx < STy->getNumElements() && "Struct index out of range!");
02034     Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
02035     
02036     // Return the modified struct.
02037     return ConstantStruct::get(&Elts[0], Elts.size(), STy->isPacked());
02038   } else {
02039     ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
02040     const ArrayType *ATy = cast<ArrayType>(Init->getType());
02041 
02042     // Break up the array into elements.
02043     std::vector<Constant*> Elts;
02044     if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
02045       for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
02046         Elts.push_back(cast<Constant>(*i));
02047     } else if (isa<ConstantAggregateZero>(Init)) {
02048       Constant *Elt = Constant::getNullValue(ATy->getElementType());
02049       Elts.assign(ATy->getNumElements(), Elt);
02050     } else if (isa<UndefValue>(Init)) {
02051       Constant *Elt = UndefValue::get(ATy->getElementType());
02052       Elts.assign(ATy->getNumElements(), Elt);
02053     } else {
02054       assert(0 && "This code is out of sync with "
02055              " ConstantFoldLoadThroughGEPConstantExpr");
02056     }
02057     
02058     assert(CI->getZExtValue() < ATy->getNumElements());
02059     Elts[CI->getZExtValue()] =
02060       EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
02061     return ConstantArray::get(ATy, Elts);
02062   }    
02063 }
02064 
02065 /// CommitValueTo - We have decided that Addr (which satisfies the predicate
02066 /// isSimpleEnoughPointerToCommit) should get Val as its value.  Make it happen.
02067 static void CommitValueTo(Constant *Val, Constant *Addr) {
02068   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
02069     assert(GV->hasInitializer());
02070     GV->setInitializer(Val);
02071     return;
02072   }
02073   
02074   ConstantExpr *CE = cast<ConstantExpr>(Addr);
02075   GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
02076   
02077   Constant *Init = GV->getInitializer();
02078   Init = EvaluateStoreInto(Init, Val, CE, 2);
02079   GV->setInitializer(Init);
02080 }
02081 
02082 /// ComputeLoadResult - Return the value that would be computed by a load from
02083 /// P after the stores reflected by 'memory' have been performed.  If we can't
02084 /// decide, return null.
02085 static Constant *ComputeLoadResult(Constant *P,
02086                                 const DenseMap<Constant*, Constant*> &Memory) {
02087   // If this memory location has been recently stored, use the stored value: it
02088   // is the most up-to-date.
02089   DenseMap<Constant*, Constant*>::const_iterator I = Memory.find(P);
02090   if (I != Memory.end()) return I->second;
02091  
02092   // Access it.
02093   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
02094     if (GV->hasInitializer())
02095       return GV->getInitializer();
02096     return 0;
02097   }
02098   
02099   // Handle a constantexpr getelementptr.
02100   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
02101     if (CE->getOpcode() == Instruction::GetElementPtr &&
02102         isa<GlobalVariable>(CE->getOperand(0))) {
02103       GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
02104       if (GV->hasInitializer())
02105         return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
02106     }
02107 
02108   return 0;  // don't know how to evaluate.
02109 }
02110 
02111 /// EvaluateFunction - Evaluate a call to function F, returning true if
02112 /// successful, false if we can't evaluate it.  ActualArgs contains the formal
02113 /// arguments for the function.
02114 static bool EvaluateFunction(Function *F, Constant *&RetVal,
02115                              const std::vector<Constant*> &ActualArgs,
02116                              std::vector<Function*> &CallStack,
02117                              DenseMap<Constant*, Constant*> &MutatedMemory,
02118                              std::vector<GlobalVariable*> &AllocaTmps) {
02119   // Check to see if this function is already executing (recursion).  If so,
02120   // bail out.  TODO: we might want to accept limited recursion.
02121   if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
02122     return false;
02123   
02124   CallStack.push_back(F);
02125   
02126   /// Values - As we compute SSA register values, we store their contents here.
02127   DenseMap<Value*, Constant*> Values;
02128   
02129   // Initialize arguments to the incoming values specified.
02130   unsigned ArgNo = 0;
02131   for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
02132        ++AI, ++ArgNo)
02133     Values[AI] = ActualArgs[ArgNo];
02134 
02135   /// ExecutedBlocks - We only handle non-looping, non-recursive code.  As such,
02136   /// we can only evaluate any one basic block at most once.  This set keeps
02137   /// track of what we have executed so we can detect recursive cases etc.
02138   SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
02139   
02140   // CurInst - The current instruction we're evaluating.
02141   BasicBlock::iterator CurInst = F->begin()->begin();
02142   
02143   // This is the main evaluation loop.
02144   while (1) {
02145     Constant *InstResult = 0;
02146     
02147     if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
02148       if (SI->isVolatile()) return false;  // no volatile accesses.
02149       Constant *Ptr = getVal(Values, SI->getOperand(1));
02150       if (!isSimpleEnoughPointerToCommit(Ptr))
02151         // If this is too complex for us to commit, reject it.
02152         return false;
02153       Constant *Val = getVal(Values, SI->getOperand(0));
02154       MutatedMemory[Ptr] = Val;
02155     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
02156       InstResult = ConstantExpr::get(BO->getOpcode(),
02157                                      getVal(Values, BO->getOperand(0)),
02158                                      getVal(Values, BO->getOperand(1)));
02159     } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
02160       InstResult = ConstantExpr::getCompare(CI->getPredicate(),
02161                                             getVal(Values, CI->getOperand(0)),
02162                                             getVal(Values, CI->getOperand(1)));
02163     } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
02164       InstResult = ConstantExpr::getCast(CI->getOpcode(),
02165                                          getVal(Values, CI->getOperand(0)),
02166                                          CI->getType());
02167     } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
02168       InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
02169                                            getVal(Values, SI->getOperand(1)),
02170                                            getVal(Values, SI->getOperand(2)));
02171     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
02172       Constant *P = getVal(Values, GEP->getOperand(0));
02173       SmallVector<Constant*, 8> GEPOps;
02174       for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
02175            i != e; ++i)
02176         GEPOps.push_back(getVal(Values, *i));
02177       InstResult = ConstantExpr::getGetElementPtr(P, &GEPOps[0], GEPOps.size());
02178     } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
02179       if (LI->isVolatile()) return false;  // no volatile accesses.
02180       InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
02181                                      MutatedMemory);
02182       if (InstResult == 0) return false; // Could not evaluate load.
02183     } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
02184       if (AI->isArrayAllocation()) return false;  // Cannot handle array allocs.
02185       const Type *Ty = AI->getType()->getElementType();
02186       AllocaTmps.push_back(new GlobalVariable(Ty, false,
02187                                               GlobalValue::InternalLinkage,
02188                                               UndefValue::get(Ty),
02189                                               AI->getName()));
02190       InstResult = AllocaTmps.back();     
02191     } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
02192       // Cannot handle inline asm.
02193       if (isa<InlineAsm>(CI->getOperand(0))) return false;
02194 
02195       // Resolve function pointers.
02196       Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
02197       if (!Callee) return false;  // Cannot resolve.
02198 
02199       std::vector<Constant*> Formals;
02200       for (User::op_iterator i = CI->op_begin() + 1, e = CI->op_end();
02201            i != e; ++i)
02202         Formals.push_back(getVal(Values, *i));
02203       
02204       if (Callee->isDeclaration()) {
02205         // If this is a function we can constant fold, do it.
02206         if (Constant *C = ConstantFoldCall(Callee, &Formals[0],
02207                                            Formals.size())) {
02208           InstResult = C;
02209         } else {
02210           return false;
02211         }
02212       } else {
02213         if (Callee->getFunctionType()->isVarArg())
02214           return false;
02215         
02216         Constant *RetVal;
02217         
02218         // Execute the call, if successful, use the return value.
02219         if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
02220                               MutatedMemory, AllocaTmps))
02221           return false;
02222         InstResult = RetVal;
02223       }
02224     } else if (isa<TerminatorInst>(CurInst)) {
02225       BasicBlock *NewBB = 0;
02226       if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
02227         if (BI->isUnconditional()) {
02228           NewBB = BI->getSuccessor(0);
02229         } else {
02230           ConstantInt *Cond =
02231             dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
02232           if (!Cond) return false;  // Cannot determine.
02233 
02234           NewBB = BI->getSuccessor(!Cond->getZExtValue());          
02235         }
02236       } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
02237         ConstantInt *Val =
02238           dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
02239         if (!Val) return false;  // Cannot determine.
02240         NewBB = SI->getSuccessor(SI->findCaseValue(Val));
02241       } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
02242         if (RI->getNumOperands())
02243           RetVal = getVal(Values, RI->getOperand(0));
02244         
02245         CallStack.pop_back();  // return from fn.
02246         return true;  // We succeeded at evaluating this ctor!
02247       } else {
02248         // invoke, unwind, unreachable.
02249         return false;  // Cannot handle this terminator.
02250       }
02251       
02252       // Okay, we succeeded in evaluating this control flow.  See if we have
02253       // executed the new block before.  If so, we have a looping function,
02254       // which we cannot evaluate in reasonable time.
02255       if (!ExecutedBlocks.insert(NewBB))
02256         return false;  // looped!
02257       
02258       // Okay, we have never been in this block before.  Check to see if there
02259       // are any PHI nodes.  If so, evaluate them with information about where
02260       // we came from.
02261       BasicBlock *OldBB = CurInst->getParent();
02262       CurInst = NewBB->begin();
02263       PHINode *PN;
02264       for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
02265         Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
02266 
02267       // Do NOT increment CurInst.  We know that the terminator had no value.
02268       continue;
02269     } else {
02270       // Did not know how to evaluate this!
02271       return false;
02272     }
02273     
02274     if (!CurInst->use_empty())
02275       Values[CurInst] = InstResult;
02276     
02277     // Advance program counter.
02278     ++CurInst;
02279   }
02280 }
02281 
02282 /// EvaluateStaticConstructor - Evaluate static constructors in the function, if
02283 /// we can.  Return true if we can, false otherwise.
02284 static bool EvaluateStaticConstructor(Function *F) {
02285   /// MutatedMemory - For each store we execute, we update this map.  Loads
02286   /// check this to get the most up-to-date value.  If evaluation is successful,
02287   /// this state is committed to the process.
02288   DenseMap<Constant*, Constant*> MutatedMemory;
02289 
02290   /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
02291   /// to represent its body.  This vector is needed so we can delete the
02292   /// temporary globals when we are done.
02293   std::vector<GlobalVariable*> AllocaTmps;
02294   
02295   /// CallStack - This is used to detect recursion.  In pathological situations
02296   /// we could hit exponential behavior, but at least there is nothing
02297   /// unbounded.
02298   std::vector<Function*> CallStack;
02299 
02300   // Call the function.
02301   Constant *RetValDummy;
02302   bool EvalSuccess = EvaluateFunction(F, RetValDummy, std::vector<Constant*>(),
02303                                        CallStack, MutatedMemory, AllocaTmps);
02304   if (EvalSuccess) {
02305     // We succeeded at evaluation: commit the result.
02306     DOUT << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
02307          << F->getName() << "' to " << MutatedMemory.size()
02308          << " stores.\n";
02309     for (DenseMap<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
02310          E = MutatedMemory.end(); I != E; ++I)
02311       CommitValueTo(I->second, I->first);
02312   }
02313   
02314   // At this point, we are done interpreting.  If we created any 'alloca'
02315   // temporaries, release them now.
02316   while (!AllocaTmps.empty()) {
02317     GlobalVariable *Tmp = AllocaTmps.back();
02318     AllocaTmps.pop_back();
02319     
02320     // If there are still users of the alloca, the program is doing something
02321     // silly, e.g. storing the address of the alloca somewhere and using it
02322     // later.  Since this is undefined, we'll just make it be null.
02323     if (!Tmp->use_empty())
02324       Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
02325     delete Tmp;
02326   }
02327   
02328   return EvalSuccess;
02329 }
02330 
02331 
02332 
02333 /// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
02334 /// Return true if anything changed.
02335 bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
02336   std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
02337   bool MadeChange = false;
02338   if (Ctors.empty()) return false;
02339   
02340   // Loop over global ctors, optimizing them when we can.
02341   for (unsigned i = 0; i != Ctors.size(); ++i) {
02342     Function *F = Ctors[i];
02343     // Found a null terminator in the middle of the list, prune off the rest of
02344     // the list.
02345     if (F == 0) {
02346       if (i != Ctors.size()-1) {
02347         Ctors.resize(i+1);
02348         MadeChange = true;
02349       }
02350       break;
02351     }
02352     
02353     // We cannot simplify external ctor functions.
02354     if (F->empty()) continue;
02355     
02356     // If we can evaluate the ctor at compile time, do.
02357     if (EvaluateStaticConstructor(F)) {
02358       Ctors.erase(Ctors.begin()+i);
02359       MadeChange = true;
02360       --i;
02361       ++NumCtorsEvaluated;
02362       continue;
02363     }
02364   }
02365   
02366   if (!MadeChange) return false;
02367   
02368   GCL = InstallGlobalCtors(GCL, Ctors);
02369   return true;
02370 }
02371 
02372 bool GlobalOpt::ResolveAliases(Module &M) {
02373   bool Changed = false;
02374 
02375   for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
02376        I != E; ++I) {
02377     if (I->use_empty())
02378       continue;
02379 
02380     if (const GlobalValue *GV = I->resolveAliasedGlobal())
02381       if (GV != I) {
02382         I->replaceAllUsesWith(const_cast<GlobalValue*>(GV));
02383         Changed = true;
02384       }
02385   }
02386 
02387   return Changed;
02388 }
02389 
02390 bool GlobalOpt::runOnModule(Module &M) {
02391   bool Changed = false;
02392   
02393   // Try to find the llvm.globalctors list.
02394   GlobalVariable *GlobalCtors = FindGlobalCtors(M);
02395 
02396   bool LocalChange = true;
02397   while (LocalChange) {
02398     LocalChange = false;
02399     
02400     // Delete functions that are trivially dead, ccc -> fastcc
02401     LocalChange |= OptimizeFunctions(M);
02402     
02403     // Optimize global_ctors list.
02404     if (GlobalCtors)
02405       LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
02406     
02407     // Optimize non-address-taken globals.
02408     LocalChange |= OptimizeGlobalVars(M);
02409 
02410     // Resolve aliases, when possible.
02411     LocalChange |= ResolveAliases(M);
02412     Changed |= LocalChange;
02413   }
02414   
02415   // TODO: Move all global ctors functions to the end of the module for code
02416   // layout.
02417   
02418   return Changed;
02419 }