use CallSite to access calls vs. invokes uniformly
[oota-llvm.git] / lib / Transforms / IPO / GlobalOpt.cpp
1 //===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass transforms simple global variables that never have their address
11 // taken.  If obviously true, it marks read/write globals as constant, deletes
12 // variables only stored to, etc.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #define DEBUG_TYPE "globalopt"
17 #include "llvm/Transforms/IPO.h"
18 #include "llvm/CallingConv.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/IntrinsicInst.h"
23 #include "llvm/Module.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Analysis/ConstantFolding.h"
26 #include "llvm/Analysis/MemoryBuiltins.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Support/CallSite.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/GetElementPtrTypeIterator.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/ADT/DenseMap.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/SmallVector.h"
37 #include "llvm/ADT/Statistic.h"
38 #include "llvm/ADT/STLExtras.h"
39 #include <algorithm>
40 using namespace llvm;
41
42 STATISTIC(NumMarked    , "Number of globals marked constant");
43 STATISTIC(NumSRA       , "Number of aggregate globals broken into scalars");
44 STATISTIC(NumHeapSRA   , "Number of heap objects SRA'd");
45 STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
46 STATISTIC(NumDeleted   , "Number of globals deleted");
47 STATISTIC(NumFnDeleted , "Number of functions deleted");
48 STATISTIC(NumGlobUses  , "Number of global uses devirtualized");
49 STATISTIC(NumLocalized , "Number of globals localized");
50 STATISTIC(NumShrunkToBool  , "Number of global vars shrunk to booleans");
51 STATISTIC(NumFastCallFns   , "Number of functions converted to fastcc");
52 STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
53 STATISTIC(NumNestRemoved   , "Number of nest attributes removed");
54 STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
55 STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
56
57 namespace {
58   struct GlobalOpt : public ModulePass {
59     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
60     }
61     static char ID; // Pass identification, replacement for typeid
62     GlobalOpt() : ModulePass(&ID) {}
63
64     bool runOnModule(Module &M);
65
66   private:
67     GlobalVariable *FindGlobalCtors(Module &M);
68     bool OptimizeFunctions(Module &M);
69     bool OptimizeGlobalVars(Module &M);
70     bool OptimizeGlobalAliases(Module &M);
71     bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
72     bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
73   };
74 }
75
76 char GlobalOpt::ID = 0;
77 static RegisterPass<GlobalOpt> X("globalopt", "Global Variable Optimizer");
78
79 ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
80
81 namespace {
82
83 /// GlobalStatus - As we analyze each global, keep track of some information
84 /// about it.  If we find out that the address of the global is taken, none of
85 /// this info will be accurate.
86 struct GlobalStatus {
87   /// isLoaded - True if the global is ever loaded.  If the global isn't ever
88   /// loaded it can be deleted.
89   bool isLoaded;
90
91   /// StoredType - Keep track of what stores to the global look like.
92   ///
93   enum StoredType {
94     /// NotStored - There is no store to this global.  It can thus be marked
95     /// constant.
96     NotStored,
97
98     /// isInitializerStored - This global is stored to, but the only thing
99     /// stored is the constant it was initialized with.  This is only tracked
100     /// for scalar globals.
101     isInitializerStored,
102
103     /// isStoredOnce - This global is stored to, but only its initializer and
104     /// one other value is ever stored to it.  If this global isStoredOnce, we
105     /// track the value stored to it in StoredOnceValue below.  This is only
106     /// tracked for scalar globals.
107     isStoredOnce,
108
109     /// isStored - This global is stored to by multiple values or something else
110     /// that we cannot track.
111     isStored
112   } StoredType;
113
114   /// StoredOnceValue - If only one value (besides the initializer constant) is
115   /// ever stored to this global, keep track of what value it is.
116   Value *StoredOnceValue;
117
118   /// AccessingFunction/HasMultipleAccessingFunctions - These start out
119   /// null/false.  When the first accessing function is noticed, it is recorded.
120   /// When a second different accessing function is noticed,
121   /// HasMultipleAccessingFunctions is set to true.
122   const Function *AccessingFunction;
123   bool HasMultipleAccessingFunctions;
124
125   /// HasNonInstructionUser - Set to true if this global has a user that is not
126   /// an instruction (e.g. a constant expr or GV initializer).
127   bool HasNonInstructionUser;
128
129   /// HasPHIUser - Set to true if this global has a user that is a PHI node.
130   bool HasPHIUser;
131   
132   GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
133                    AccessingFunction(0), HasMultipleAccessingFunctions(false),
134                    HasNonInstructionUser(false), HasPHIUser(false) {}
135 };
136
137 }
138
139 // SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
140 // by constants itself.  Note that constants cannot be cyclic, so this test is
141 // pretty easy to implement recursively.
142 //
143 static bool SafeToDestroyConstant(const Constant *C) {
144   if (isa<GlobalValue>(C)) return false;
145
146   for (Value::const_use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
147     if (const Constant *CU = dyn_cast<Constant>(*UI)) {
148       if (!SafeToDestroyConstant(CU)) return false;
149     } else
150       return false;
151   return true;
152 }
153
154
155 /// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
156 /// structure.  If the global has its address taken, return true to indicate we
157 /// can't do anything with it.
158 ///
159 static bool AnalyzeGlobal(const Value *V, GlobalStatus &GS,
160                           SmallPtrSet<const PHINode*, 16> &PHIUsers) {
161   for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
162     if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
163       GS.HasNonInstructionUser = true;
164
165       if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
166
167     } else if (const Instruction *I = dyn_cast<Instruction>(*UI)) {
168       if (!GS.HasMultipleAccessingFunctions) {
169         const Function *F = I->getParent()->getParent();
170         if (GS.AccessingFunction == 0)
171           GS.AccessingFunction = F;
172         else if (GS.AccessingFunction != F)
173           GS.HasMultipleAccessingFunctions = true;
174       }
175       if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
176         GS.isLoaded = true;
177         if (LI->isVolatile()) return true;  // Don't hack on volatile loads.
178       } else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) {
179         // Don't allow a store OF the address, only stores TO the address.
180         if (SI->getOperand(0) == V) return true;
181
182         if (SI->isVolatile()) return true;  // Don't hack on volatile stores.
183
184         // If this is a direct store to the global (i.e., the global is a scalar
185         // value, not an aggregate), keep more specific information about
186         // stores.
187         if (GS.StoredType != GlobalStatus::isStored) {
188           if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
189             Value *StoredVal = SI->getOperand(0);
190             if (StoredVal == GV->getInitializer()) {
191               if (GS.StoredType < GlobalStatus::isInitializerStored)
192                 GS.StoredType = GlobalStatus::isInitializerStored;
193             } else if (isa<LoadInst>(StoredVal) &&
194                        cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
195               if (GS.StoredType < GlobalStatus::isInitializerStored)
196                 GS.StoredType = GlobalStatus::isInitializerStored;
197             } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
198               GS.StoredType = GlobalStatus::isStoredOnce;
199               GS.StoredOnceValue = StoredVal;
200             } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
201                        GS.StoredOnceValue == StoredVal) {
202               // noop.
203             } else {
204               GS.StoredType = GlobalStatus::isStored;
205             }
206           } else {
207             GS.StoredType = GlobalStatus::isStored;
208           }
209         }
210       } else if (isa<GetElementPtrInst>(I)) {
211         if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
212       } else if (isa<SelectInst>(I)) {
213         if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
214       } else if (const PHINode *PN = dyn_cast<PHINode>(I)) {
215         // PHI nodes we can check just like select or GEP instructions, but we
216         // have to be careful about infinite recursion.
217         if (PHIUsers.insert(PN))  // Not already visited.
218           if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
219         GS.HasPHIUser = true;
220       } else if (isa<CmpInst>(I)) {
221       } else if (isa<MemTransferInst>(I)) {
222         if (I->getOperand(1) == V)
223           GS.StoredType = GlobalStatus::isStored;
224         if (I->getOperand(2) == V)
225           GS.isLoaded = true;
226       } else if (isa<MemSetInst>(I)) {
227         assert(I->getOperand(1) == V && "Memset only takes one pointer!");
228         GS.StoredType = GlobalStatus::isStored;
229       } else {
230         return true;  // Any other non-load instruction might take address!
231       }
232     } else if (const Constant *C = dyn_cast<Constant>(*UI)) {
233       GS.HasNonInstructionUser = true;
234       // We might have a dead and dangling constant hanging off of here.
235       if (!SafeToDestroyConstant(C))
236         return true;
237     } else {
238       GS.HasNonInstructionUser = true;
239       // Otherwise must be some other user.
240       return true;
241     }
242
243   return false;
244 }
245
246 static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
247   ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
248   if (!CI) return 0;
249   unsigned IdxV = CI->getZExtValue();
250
251   if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
252     if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
253   } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
254     if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
255   } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) {
256     if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
257   } else if (isa<ConstantAggregateZero>(Agg)) {
258     if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
259       if (IdxV < STy->getNumElements())
260         return Constant::getNullValue(STy->getElementType(IdxV));
261     } else if (const SequentialType *STy =
262                dyn_cast<SequentialType>(Agg->getType())) {
263       return Constant::getNullValue(STy->getElementType());
264     }
265   } else if (isa<UndefValue>(Agg)) {
266     if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
267       if (IdxV < STy->getNumElements())
268         return UndefValue::get(STy->getElementType(IdxV));
269     } else if (const SequentialType *STy =
270                dyn_cast<SequentialType>(Agg->getType())) {
271       return UndefValue::get(STy->getElementType());
272     }
273   }
274   return 0;
275 }
276
277
278 /// CleanupConstantGlobalUsers - We just marked GV constant.  Loop over all
279 /// users of the global, cleaning up the obvious ones.  This is largely just a
280 /// quick scan over the use list to clean up the easy and obvious cruft.  This
281 /// returns true if it made a change.
282 static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
283   bool Changed = false;
284   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
285     User *U = *UI++;
286
287     if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
288       if (Init) {
289         // Replace the load with the initializer.
290         LI->replaceAllUsesWith(Init);
291         LI->eraseFromParent();
292         Changed = true;
293       }
294     } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
295       // Store must be unreachable or storing Init into the global.
296       SI->eraseFromParent();
297       Changed = true;
298     } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
299       if (CE->getOpcode() == Instruction::GetElementPtr) {
300         Constant *SubInit = 0;
301         if (Init)
302           SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
303         Changed |= CleanupConstantGlobalUsers(CE, SubInit);
304       } else if (CE->getOpcode() == Instruction::BitCast && 
305                  CE->getType()->isPointerTy()) {
306         // Pointer cast, delete any stores and memsets to the global.
307         Changed |= CleanupConstantGlobalUsers(CE, 0);
308       }
309
310       if (CE->use_empty()) {
311         CE->destroyConstant();
312         Changed = true;
313       }
314     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
315       // Do not transform "gepinst (gep constexpr (GV))" here, because forming
316       // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
317       // and will invalidate our notion of what Init is.
318       Constant *SubInit = 0;
319       if (!isa<ConstantExpr>(GEP->getOperand(0))) {
320         ConstantExpr *CE = 
321           dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
322         if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
323           SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
324       }
325       Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
326
327       if (GEP->use_empty()) {
328         GEP->eraseFromParent();
329         Changed = true;
330       }
331     } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
332       if (MI->getRawDest() == V) {
333         MI->eraseFromParent();
334         Changed = true;
335       }
336
337     } else if (Constant *C = dyn_cast<Constant>(U)) {
338       // If we have a chain of dead constantexprs or other things dangling from
339       // us, and if they are all dead, nuke them without remorse.
340       if (SafeToDestroyConstant(C)) {
341         C->destroyConstant();
342         // This could have invalidated UI, start over from scratch.
343         CleanupConstantGlobalUsers(V, Init);
344         return true;
345       }
346     }
347   }
348   return Changed;
349 }
350
351 /// isSafeSROAElementUse - Return true if the specified instruction is a safe
352 /// user of a derived expression from a global that we want to SROA.
353 static bool isSafeSROAElementUse(Value *V) {
354   // We might have a dead and dangling constant hanging off of here.
355   if (Constant *C = dyn_cast<Constant>(V))
356     return SafeToDestroyConstant(C);
357   
358   Instruction *I = dyn_cast<Instruction>(V);
359   if (!I) return false;
360
361   // Loads are ok.
362   if (isa<LoadInst>(I)) return true;
363
364   // Stores *to* the pointer are ok.
365   if (StoreInst *SI = dyn_cast<StoreInst>(I))
366     return SI->getOperand(0) != V;
367     
368   // Otherwise, it must be a GEP.
369   GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
370   if (GEPI == 0) return false;
371   
372   if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
373       !cast<Constant>(GEPI->getOperand(1))->isNullValue())
374     return false;
375   
376   for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
377        I != E; ++I)
378     if (!isSafeSROAElementUse(*I))
379       return false;
380   return true;
381 }
382
383
384 /// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
385 /// Look at it and its uses and decide whether it is safe to SROA this global.
386 ///
387 static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
388   // The user of the global must be a GEP Inst or a ConstantExpr GEP.
389   if (!isa<GetElementPtrInst>(U) && 
390       (!isa<ConstantExpr>(U) || 
391        cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
392     return false;
393   
394   // Check to see if this ConstantExpr GEP is SRA'able.  In particular, we
395   // don't like < 3 operand CE's, and we don't like non-constant integer
396   // indices.  This enforces that all uses are 'gep GV, 0, C, ...' for some
397   // value of C.
398   if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
399       !cast<Constant>(U->getOperand(1))->isNullValue() ||
400       !isa<ConstantInt>(U->getOperand(2)))
401     return false;
402
403   gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
404   ++GEPI;  // Skip over the pointer index.
405   
406   // If this is a use of an array allocation, do a bit more checking for sanity.
407   if (const ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
408     uint64_t NumElements = AT->getNumElements();
409     ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
410     
411     // Check to make sure that index falls within the array.  If not,
412     // something funny is going on, so we won't do the optimization.
413     //
414     if (Idx->getZExtValue() >= NumElements)
415       return false;
416       
417     // We cannot scalar repl this level of the array unless any array
418     // sub-indices are in-range constants.  In particular, consider:
419     // A[0][i].  We cannot know that the user isn't doing invalid things like
420     // allowing i to index an out-of-range subscript that accesses A[1].
421     //
422     // Scalar replacing *just* the outer index of the array is probably not
423     // going to be a win anyway, so just give up.
424     for (++GEPI; // Skip array index.
425          GEPI != E;
426          ++GEPI) {
427       uint64_t NumElements;
428       if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
429         NumElements = SubArrayTy->getNumElements();
430       else if (const VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
431         NumElements = SubVectorTy->getNumElements();
432       else {
433         assert((*GEPI)->isStructTy() &&
434                "Indexed GEP type is not array, vector, or struct!");
435         continue;
436       }
437       
438       ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
439       if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
440         return false;
441     }
442   }
443
444   for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
445     if (!isSafeSROAElementUse(*I))
446       return false;
447   return true;
448 }
449
450 /// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
451 /// is safe for us to perform this transformation.
452 ///
453 static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
454   for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
455        UI != E; ++UI) {
456     if (!IsUserOfGlobalSafeForSRA(*UI, GV))
457       return false;
458   }
459   return true;
460 }
461  
462
463 /// SRAGlobal - Perform scalar replacement of aggregates on the specified global
464 /// variable.  This opens the door for other optimizations by exposing the
465 /// behavior of the program in a more fine-grained way.  We have determined that
466 /// this transformation is safe already.  We return the first global variable we
467 /// insert so that the caller can reprocess it.
468 static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD) {
469   // Make sure this global only has simple uses that we can SRA.
470   if (!GlobalUsersSafeToSRA(GV))
471     return 0;
472   
473   assert(GV->hasLocalLinkage() && !GV->isConstant());
474   Constant *Init = GV->getInitializer();
475   const Type *Ty = Init->getType();
476
477   std::vector<GlobalVariable*> NewGlobals;
478   Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
479
480   // Get the alignment of the global, either explicit or target-specific.
481   unsigned StartAlignment = GV->getAlignment();
482   if (StartAlignment == 0)
483     StartAlignment = TD.getABITypeAlignment(GV->getType());
484    
485   if (const StructType *STy = dyn_cast<StructType>(Ty)) {
486     NewGlobals.reserve(STy->getNumElements());
487     const StructLayout &Layout = *TD.getStructLayout(STy);
488     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
489       Constant *In = getAggregateConstantElement(Init,
490                     ConstantInt::get(Type::getInt32Ty(STy->getContext()), i));
491       assert(In && "Couldn't get element of initializer?");
492       GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
493                                                GlobalVariable::InternalLinkage,
494                                                In, GV->getName()+"."+Twine(i),
495                                                GV->isThreadLocal(),
496                                               GV->getType()->getAddressSpace());
497       Globals.insert(GV, NGV);
498       NewGlobals.push_back(NGV);
499       
500       // Calculate the known alignment of the field.  If the original aggregate
501       // had 256 byte alignment for example, something might depend on that:
502       // propagate info to each field.
503       uint64_t FieldOffset = Layout.getElementOffset(i);
504       unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
505       if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
506         NGV->setAlignment(NewAlign);
507     }
508   } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
509     unsigned NumElements = 0;
510     if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
511       NumElements = ATy->getNumElements();
512     else
513       NumElements = cast<VectorType>(STy)->getNumElements();
514
515     if (NumElements > 16 && GV->hasNUsesOrMore(16))
516       return 0; // It's not worth it.
517     NewGlobals.reserve(NumElements);
518     
519     uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
520     unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
521     for (unsigned i = 0, e = NumElements; i != e; ++i) {
522       Constant *In = getAggregateConstantElement(Init,
523                     ConstantInt::get(Type::getInt32Ty(Init->getContext()), i));
524       assert(In && "Couldn't get element of initializer?");
525
526       GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
527                                                GlobalVariable::InternalLinkage,
528                                                In, GV->getName()+"."+Twine(i),
529                                                GV->isThreadLocal(),
530                                               GV->getType()->getAddressSpace());
531       Globals.insert(GV, NGV);
532       NewGlobals.push_back(NGV);
533       
534       // Calculate the known alignment of the field.  If the original aggregate
535       // had 256 byte alignment for example, something might depend on that:
536       // propagate info to each field.
537       unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
538       if (NewAlign > EltAlign)
539         NGV->setAlignment(NewAlign);
540     }
541   }
542
543   if (NewGlobals.empty())
544     return 0;
545   
546   DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
547
548   Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
549
550   // Loop over all of the uses of the global, replacing the constantexpr geps,
551   // with smaller constantexpr geps or direct references.
552   while (!GV->use_empty()) {
553     User *GEP = GV->use_back();
554     assert(((isa<ConstantExpr>(GEP) &&
555              cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
556             isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
557
558     // Ignore the 1th operand, which has to be zero or else the program is quite
559     // broken (undefined).  Get the 2nd operand, which is the structure or array
560     // index.
561     unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
562     if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
563
564     Value *NewPtr = NewGlobals[Val];
565
566     // Form a shorter GEP if needed.
567     if (GEP->getNumOperands() > 3) {
568       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
569         SmallVector<Constant*, 8> Idxs;
570         Idxs.push_back(NullInt);
571         for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
572           Idxs.push_back(CE->getOperand(i));
573         NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr),
574                                                 &Idxs[0], Idxs.size());
575       } else {
576         GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
577         SmallVector<Value*, 8> Idxs;
578         Idxs.push_back(NullInt);
579         for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
580           Idxs.push_back(GEPI->getOperand(i));
581         NewPtr = GetElementPtrInst::Create(NewPtr, Idxs.begin(), Idxs.end(),
582                                            GEPI->getName()+"."+Twine(Val),GEPI);
583       }
584     }
585     GEP->replaceAllUsesWith(NewPtr);
586
587     if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
588       GEPI->eraseFromParent();
589     else
590       cast<ConstantExpr>(GEP)->destroyConstant();
591   }
592
593   // Delete the old global, now that it is dead.
594   Globals.erase(GV);
595   ++NumSRA;
596
597   // Loop over the new globals array deleting any globals that are obviously
598   // dead.  This can arise due to scalarization of a structure or an array that
599   // has elements that are dead.
600   unsigned FirstGlobal = 0;
601   for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
602     if (NewGlobals[i]->use_empty()) {
603       Globals.erase(NewGlobals[i]);
604       if (FirstGlobal == i) ++FirstGlobal;
605     }
606
607   return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
608 }
609
610 /// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
611 /// value will trap if the value is dynamically null.  PHIs keeps track of any 
612 /// phi nodes we've seen to avoid reprocessing them.
613 static bool AllUsesOfValueWillTrapIfNull(Value *V,
614                                          SmallPtrSet<PHINode*, 8> &PHIs) {
615   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
616     if (isa<LoadInst>(*UI)) {
617       // Will trap.
618     } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
619       if (SI->getOperand(0) == V) {
620         //cerr << "NONTRAPPING USE: " << **UI;
621         return false;  // Storing the value.
622       }
623     } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
624       if (CI->getCalledValue() != V) {
625         //cerr << "NONTRAPPING USE: " << **UI;
626         return false;  // Not calling the ptr
627       }
628     } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
629       if (II->getCalledValue() != V) {
630         //cerr << "NONTRAPPING USE: " << **UI;
631         return false;  // Not calling the ptr
632       }
633     } else if (BitCastInst *CI = dyn_cast<BitCastInst>(*UI)) {
634       if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
635     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
636       if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
637     } else if (PHINode *PN = dyn_cast<PHINode>(*UI)) {
638       // If we've already seen this phi node, ignore it, it has already been
639       // checked.
640       if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
641         return false;
642     } else if (isa<ICmpInst>(*UI) &&
643                isa<ConstantPointerNull>(UI->getOperand(1))) {
644       // Ignore icmp X, null
645     } else {
646       //cerr << "NONTRAPPING USE: " << **UI;
647       return false;
648     }
649   return true;
650 }
651
652 /// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
653 /// from GV will trap if the loaded value is null.  Note that this also permits
654 /// comparisons of the loaded value against null, as a special case.
655 static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
656   for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
657     if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
658       SmallPtrSet<PHINode*, 8> PHIs;
659       if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
660         return false;
661     } else if (isa<StoreInst>(*UI)) {
662       // Ignore stores to the global.
663     } else {
664       // We don't know or understand this user, bail out.
665       //cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
666       return false;
667     }
668
669   return true;
670 }
671
672 static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
673   bool Changed = false;
674   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
675     Instruction *I = cast<Instruction>(*UI++);
676     if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
677       LI->setOperand(0, NewV);
678       Changed = true;
679     } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
680       if (SI->getOperand(1) == V) {
681         SI->setOperand(1, NewV);
682         Changed = true;
683       }
684     } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
685       CallSite CS(I);
686       if (CS.getCalledValue() == V) {
687         // Calling through the pointer!  Turn into a direct call, but be careful
688         // that the pointer is not also being passed as an argument.
689         CS.setCalledFunction(NewV);
690         Changed = true;
691         bool PassedAsArg = false;
692         for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
693           if (CS.getArgument(i) == V) {
694             PassedAsArg = true;
695             CS.setArgument(i, NewV);
696           }
697
698         if (PassedAsArg) {
699           // Being passed as an argument also.  Be careful to not invalidate UI!
700           UI = V->use_begin();
701         }
702       }
703     } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
704       Changed |= OptimizeAwayTrappingUsesOfValue(CI,
705                                 ConstantExpr::getCast(CI->getOpcode(),
706                                                       NewV, CI->getType()));
707       if (CI->use_empty()) {
708         Changed = true;
709         CI->eraseFromParent();
710       }
711     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
712       // Should handle GEP here.
713       SmallVector<Constant*, 8> Idxs;
714       Idxs.reserve(GEPI->getNumOperands()-1);
715       for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
716            i != e; ++i)
717         if (Constant *C = dyn_cast<Constant>(*i))
718           Idxs.push_back(C);
719         else
720           break;
721       if (Idxs.size() == GEPI->getNumOperands()-1)
722         Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
723                           ConstantExpr::getGetElementPtr(NewV, &Idxs[0],
724                                                         Idxs.size()));
725       if (GEPI->use_empty()) {
726         Changed = true;
727         GEPI->eraseFromParent();
728       }
729     }
730   }
731
732   return Changed;
733 }
734
735
736 /// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
737 /// value stored into it.  If there are uses of the loaded value that would trap
738 /// if the loaded value is dynamically null, then we know that they cannot be
739 /// reachable with a null optimize away the load.
740 static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
741   bool Changed = false;
742
743   // Keep track of whether we are able to remove all the uses of the global
744   // other than the store that defines it.
745   bool AllNonStoreUsesGone = true;
746   
747   // Replace all uses of loads with uses of uses of the stored value.
748   for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
749     User *GlobalUser = *GUI++;
750     if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
751       Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
752       // If we were able to delete all uses of the loads
753       if (LI->use_empty()) {
754         LI->eraseFromParent();
755         Changed = true;
756       } else {
757         AllNonStoreUsesGone = false;
758       }
759     } else if (isa<StoreInst>(GlobalUser)) {
760       // Ignore the store that stores "LV" to the global.
761       assert(GlobalUser->getOperand(1) == GV &&
762              "Must be storing *to* the global");
763     } else {
764       AllNonStoreUsesGone = false;
765
766       // If we get here we could have other crazy uses that are transitively
767       // loaded.
768       assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
769               isa<ConstantExpr>(GlobalUser)) && "Only expect load and stores!");
770     }
771   }
772
773   if (Changed) {
774     DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
775     ++NumGlobUses;
776   }
777
778   // If we nuked all of the loads, then none of the stores are needed either,
779   // nor is the global.
780   if (AllNonStoreUsesGone) {
781     DEBUG(dbgs() << "  *** GLOBAL NOW DEAD!\n");
782     CleanupConstantGlobalUsers(GV, 0);
783     if (GV->use_empty()) {
784       GV->eraseFromParent();
785       ++NumDeleted;
786     }
787     Changed = true;
788   }
789   return Changed;
790 }
791
792 /// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
793 /// instructions that are foldable.
794 static void ConstantPropUsersOf(Value *V) {
795   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
796     if (Instruction *I = dyn_cast<Instruction>(*UI++))
797       if (Constant *NewC = ConstantFoldInstruction(I)) {
798         I->replaceAllUsesWith(NewC);
799
800         // Advance UI to the next non-I use to avoid invalidating it!
801         // Instructions could multiply use V.
802         while (UI != E && *UI == I)
803           ++UI;
804         I->eraseFromParent();
805       }
806 }
807
808 /// OptimizeGlobalAddressOfMalloc - This function takes the specified global
809 /// variable, and transforms the program as if it always contained the result of
810 /// the specified malloc.  Because it is always the result of the specified
811 /// malloc, there is no reason to actually DO the malloc.  Instead, turn the
812 /// malloc into a global, and any loads of GV as uses of the new global.
813 static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
814                                                      CallInst *CI,
815                                                      const Type *AllocTy,
816                                                      ConstantInt *NElements,
817                                                      TargetData* TD) {
818   DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << "  CALL = " << *CI << '\n');
819   
820   const Type *GlobalType;
821   if (NElements->getZExtValue() == 1)
822     GlobalType = AllocTy;
823   else
824     // If we have an array allocation, the global variable is of an array.
825     GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
826
827   // Create the new global variable.  The contents of the malloc'd memory is
828   // undefined, so initialize with an undef value.
829   GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(), 
830                                              GlobalType, false,
831                                              GlobalValue::InternalLinkage,
832                                              UndefValue::get(GlobalType),
833                                              GV->getName()+".body",
834                                              GV,
835                                              GV->isThreadLocal());
836   
837   // If there are bitcast users of the malloc (which is typical, usually we have
838   // a malloc + bitcast) then replace them with uses of the new global.  Update
839   // other users to use the global as well.
840   BitCastInst *TheBC = 0;
841   while (!CI->use_empty()) {
842     Instruction *User = cast<Instruction>(CI->use_back());
843     if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
844       if (BCI->getType() == NewGV->getType()) {
845         BCI->replaceAllUsesWith(NewGV);
846         BCI->eraseFromParent();
847       } else {
848         BCI->setOperand(0, NewGV);
849       }
850     } else {
851       if (TheBC == 0)
852         TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
853       User->replaceUsesOfWith(CI, TheBC);
854     }
855   }
856   
857   Constant *RepValue = NewGV;
858   if (NewGV->getType() != GV->getType()->getElementType())
859     RepValue = ConstantExpr::getBitCast(RepValue, 
860                                         GV->getType()->getElementType());
861
862   // If there is a comparison against null, we will insert a global bool to
863   // keep track of whether the global was initialized yet or not.
864   GlobalVariable *InitBool =
865     new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
866                        GlobalValue::InternalLinkage,
867                        ConstantInt::getFalse(GV->getContext()),
868                        GV->getName()+".init", GV->isThreadLocal());
869   bool InitBoolUsed = false;
870
871   // Loop over all uses of GV, processing them in turn.
872   while (!GV->use_empty()) {
873     if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
874       // The global is initialized when the store to it occurs.
875       new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, SI);
876       SI->eraseFromParent();
877       continue;
878     }
879     
880     LoadInst *LI = cast<LoadInst>(GV->use_back());
881     while (!LI->use_empty()) {
882       Use &LoadUse = LI->use_begin().getUse();
883       if (!isa<ICmpInst>(LoadUse.getUser())) {
884         LoadUse = RepValue;
885         continue;
886       }
887       
888       ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
889       // Replace the cmp X, 0 with a use of the bool value.
890       Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", ICI);
891       InitBoolUsed = true;
892       switch (ICI->getPredicate()) {
893       default: llvm_unreachable("Unknown ICmp Predicate!");
894       case ICmpInst::ICMP_ULT:
895       case ICmpInst::ICMP_SLT:   // X < null -> always false
896         LV = ConstantInt::getFalse(GV->getContext());
897         break;
898       case ICmpInst::ICMP_ULE:
899       case ICmpInst::ICMP_SLE:
900       case ICmpInst::ICMP_EQ:
901         LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
902         break;
903       case ICmpInst::ICMP_NE:
904       case ICmpInst::ICMP_UGE:
905       case ICmpInst::ICMP_SGE:
906       case ICmpInst::ICMP_UGT:
907       case ICmpInst::ICMP_SGT:
908         break;  // no change.
909       }
910       ICI->replaceAllUsesWith(LV);
911       ICI->eraseFromParent();
912     }
913     LI->eraseFromParent();
914   }
915
916   // If the initialization boolean was used, insert it, otherwise delete it.
917   if (!InitBoolUsed) {
918     while (!InitBool->use_empty())  // Delete initializations
919       cast<StoreInst>(InitBool->use_back())->eraseFromParent();
920     delete InitBool;
921   } else
922     GV->getParent()->getGlobalList().insert(GV, InitBool);
923
924   // Now the GV is dead, nuke it and the malloc..
925   GV->eraseFromParent();
926   CI->eraseFromParent();
927
928   // To further other optimizations, loop over all users of NewGV and try to
929   // constant prop them.  This will promote GEP instructions with constant
930   // indices into GEP constant-exprs, which will allow global-opt to hack on it.
931   ConstantPropUsersOf(NewGV);
932   if (RepValue != NewGV)
933     ConstantPropUsersOf(RepValue);
934
935   return NewGV;
936 }
937
938 /// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
939 /// to make sure that there are no complex uses of V.  We permit simple things
940 /// like dereferencing the pointer, but not storing through the address, unless
941 /// it is to the specified global.
942 static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
943                                                       GlobalVariable *GV,
944                                               SmallPtrSet<PHINode*, 8> &PHIs) {
945   for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
946     Instruction *Inst = cast<Instruction>(*UI);
947     
948     if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
949       continue; // Fine, ignore.
950     }
951     
952     if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
953       if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
954         return false;  // Storing the pointer itself... bad.
955       continue; // Otherwise, storing through it, or storing into GV... fine.
956     }
957     
958     if (isa<GetElementPtrInst>(Inst)) {
959       if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
960         return false;
961       continue;
962     }
963     
964     if (PHINode *PN = dyn_cast<PHINode>(Inst)) {
965       // PHIs are ok if all uses are ok.  Don't infinitely recurse through PHI
966       // cycles.
967       if (PHIs.insert(PN))
968         if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
969           return false;
970       continue;
971     }
972     
973     if (BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
974       if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
975         return false;
976       continue;
977     }
978     
979     return false;
980   }
981   return true;
982 }
983
984 /// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
985 /// somewhere.  Transform all uses of the allocation into loads from the
986 /// global and uses of the resultant pointer.  Further, delete the store into
987 /// GV.  This assumes that these value pass the 
988 /// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
989 static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc, 
990                                           GlobalVariable *GV) {
991   while (!Alloc->use_empty()) {
992     Instruction *U = cast<Instruction>(*Alloc->use_begin());
993     Instruction *InsertPt = U;
994     if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
995       // If this is the store of the allocation into the global, remove it.
996       if (SI->getOperand(1) == GV) {
997         SI->eraseFromParent();
998         continue;
999       }
1000     } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1001       // Insert the load in the corresponding predecessor, not right before the
1002       // PHI.
1003       InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
1004     } else if (isa<BitCastInst>(U)) {
1005       // Must be bitcast between the malloc and store to initialize the global.
1006       ReplaceUsesOfMallocWithGlobal(U, GV);
1007       U->eraseFromParent();
1008       continue;
1009     } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1010       // If this is a "GEP bitcast" and the user is a store to the global, then
1011       // just process it as a bitcast.
1012       if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1013         if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1014           if (SI->getOperand(1) == GV) {
1015             // Must be bitcast GEP between the malloc and store to initialize
1016             // the global.
1017             ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1018             GEPI->eraseFromParent();
1019             continue;
1020           }
1021     }
1022       
1023     // Insert a load from the global, and use it instead of the malloc.
1024     Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
1025     U->replaceUsesOfWith(Alloc, NL);
1026   }
1027 }
1028
1029 /// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1030 /// of a load) are simple enough to perform heap SRA on.  This permits GEP's
1031 /// that index through the array and struct field, icmps of null, and PHIs.
1032 static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
1033                               SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
1034                               SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
1035   // We permit two users of the load: setcc comparing against the null
1036   // pointer, and a getelementptr of a specific form.
1037   for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI){
1038     const Instruction *User = cast<Instruction>(*UI);
1039     
1040     // Comparison against null is ok.
1041     if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
1042       if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1043         return false;
1044       continue;
1045     }
1046     
1047     // getelementptr is also ok, but only a simple form.
1048     if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1049       // Must index into the array and into the struct.
1050       if (GEPI->getNumOperands() < 3)
1051         return false;
1052       
1053       // Otherwise the GEP is ok.
1054       continue;
1055     }
1056     
1057     if (const PHINode *PN = dyn_cast<PHINode>(User)) {
1058       if (!LoadUsingPHIsPerLoad.insert(PN))
1059         // This means some phi nodes are dependent on each other.
1060         // Avoid infinite looping!
1061         return false;
1062       if (!LoadUsingPHIs.insert(PN))
1063         // If we have already analyzed this PHI, then it is safe.
1064         continue;
1065       
1066       // Make sure all uses of the PHI are simple enough to transform.
1067       if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1068                                           LoadUsingPHIs, LoadUsingPHIsPerLoad))
1069         return false;
1070       
1071       continue;
1072     }
1073     
1074     // Otherwise we don't know what this is, not ok.
1075     return false;
1076   }
1077   
1078   return true;
1079 }
1080
1081
1082 /// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1083 /// GV are simple enough to perform HeapSRA, return true.
1084 static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
1085                                                     Instruction *StoredVal) {
1086   SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1087   SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
1088   for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E; 
1089        ++UI)
1090     if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1091       if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1092                                           LoadUsingPHIsPerLoad))
1093         return false;
1094       LoadUsingPHIsPerLoad.clear();
1095     }
1096   
1097   // If we reach here, we know that all uses of the loads and transitive uses
1098   // (through PHI nodes) are simple enough to transform.  However, we don't know
1099   // that all inputs the to the PHI nodes are in the same equivalence sets. 
1100   // Check to verify that all operands of the PHIs are either PHIS that can be
1101   // transformed, loads from GV, or MI itself.
1102   for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin(),
1103        E = LoadUsingPHIs.end(); I != E; ++I) {
1104     const PHINode *PN = *I;
1105     for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1106       Value *InVal = PN->getIncomingValue(op);
1107       
1108       // PHI of the stored value itself is ok.
1109       if (InVal == StoredVal) continue;
1110       
1111       if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
1112         // One of the PHIs in our set is (optimistically) ok.
1113         if (LoadUsingPHIs.count(InPN))
1114           continue;
1115         return false;
1116       }
1117       
1118       // Load from GV is ok.
1119       if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
1120         if (LI->getOperand(0) == GV)
1121           continue;
1122       
1123       // UNDEF? NULL?
1124       
1125       // Anything else is rejected.
1126       return false;
1127     }
1128   }
1129   
1130   return true;
1131 }
1132
1133 static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1134                DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1135                    std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1136   std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
1137   
1138   if (FieldNo >= FieldVals.size())
1139     FieldVals.resize(FieldNo+1);
1140   
1141   // If we already have this value, just reuse the previously scalarized
1142   // version.
1143   if (Value *FieldVal = FieldVals[FieldNo])
1144     return FieldVal;
1145   
1146   // Depending on what instruction this is, we have several cases.
1147   Value *Result;
1148   if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1149     // This is a scalarized version of the load from the global.  Just create
1150     // a new Load of the scalarized global.
1151     Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1152                                            InsertedScalarizedValues,
1153                                            PHIsToRewrite),
1154                           LI->getName()+".f"+Twine(FieldNo), LI);
1155   } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1156     // PN's type is pointer to struct.  Make a new PHI of pointer to struct
1157     // field.
1158     const StructType *ST = 
1159       cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
1160     
1161     Result =
1162      PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
1163                      PN->getName()+".f"+Twine(FieldNo), PN);
1164     PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1165   } else {
1166     llvm_unreachable("Unknown usable value");
1167     Result = 0;
1168   }
1169   
1170   return FieldVals[FieldNo] = Result;
1171 }
1172
1173 /// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1174 /// the load, rewrite the derived value to use the HeapSRoA'd load.
1175 static void RewriteHeapSROALoadUser(Instruction *LoadUser, 
1176              DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1177                    std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1178   // If this is a comparison against null, handle it.
1179   if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1180     assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1181     // If we have a setcc of the loaded pointer, we can use a setcc of any
1182     // field.
1183     Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
1184                                    InsertedScalarizedValues, PHIsToRewrite);
1185     
1186     Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
1187                               Constant::getNullValue(NPtr->getType()), 
1188                               SCI->getName());
1189     SCI->replaceAllUsesWith(New);
1190     SCI->eraseFromParent();
1191     return;
1192   }
1193   
1194   // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
1195   if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1196     assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1197            && "Unexpected GEPI!");
1198   
1199     // Load the pointer for this field.
1200     unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
1201     Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
1202                                      InsertedScalarizedValues, PHIsToRewrite);
1203     
1204     // Create the new GEP idx vector.
1205     SmallVector<Value*, 8> GEPIdx;
1206     GEPIdx.push_back(GEPI->getOperand(1));
1207     GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
1208     
1209     Value *NGEPI = GetElementPtrInst::Create(NewPtr,
1210                                              GEPIdx.begin(), GEPIdx.end(),
1211                                              GEPI->getName(), GEPI);
1212     GEPI->replaceAllUsesWith(NGEPI);
1213     GEPI->eraseFromParent();
1214     return;
1215   }
1216
1217   // Recursively transform the users of PHI nodes.  This will lazily create the
1218   // PHIs that are needed for individual elements.  Keep track of what PHIs we
1219   // see in InsertedScalarizedValues so that we don't get infinite loops (very
1220   // antisocial).  If the PHI is already in InsertedScalarizedValues, it has
1221   // already been seen first by another load, so its uses have already been
1222   // processed.
1223   PHINode *PN = cast<PHINode>(LoadUser);
1224   bool Inserted;
1225   DenseMap<Value*, std::vector<Value*> >::iterator InsertPos;
1226   tie(InsertPos, Inserted) =
1227     InsertedScalarizedValues.insert(std::make_pair(PN, std::vector<Value*>()));
1228   if (!Inserted) return;
1229   
1230   // If this is the first time we've seen this PHI, recursively process all
1231   // users.
1232   for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1233     Instruction *User = cast<Instruction>(*UI++);
1234     RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
1235   }
1236 }
1237
1238 /// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global.  Ptr
1239 /// is a value loaded from the global.  Eliminate all uses of Ptr, making them
1240 /// use FieldGlobals instead.  All uses of loaded values satisfy
1241 /// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
1242 static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load, 
1243                DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1244                    std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1245   for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
1246        UI != E; ) {
1247     Instruction *User = cast<Instruction>(*UI++);
1248     RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
1249   }
1250   
1251   if (Load->use_empty()) {
1252     Load->eraseFromParent();
1253     InsertedScalarizedValues.erase(Load);
1254   }
1255 }
1256
1257 /// PerformHeapAllocSRoA - CI is an allocation of an array of structures.  Break
1258 /// it up into multiple allocations of arrays of the fields.
1259 static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
1260                                             Value* NElems, TargetData *TD) {
1261   DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << "  MALLOC = " << *CI << '\n');
1262   const Type* MAT = getMallocAllocatedType(CI);
1263   const StructType *STy = cast<StructType>(MAT);
1264
1265   // There is guaranteed to be at least one use of the malloc (storing
1266   // it into GV).  If there are other uses, change them to be uses of
1267   // the global to simplify later code.  This also deletes the store
1268   // into GV.
1269   ReplaceUsesOfMallocWithGlobal(CI, GV);
1270
1271   // Okay, at this point, there are no users of the malloc.  Insert N
1272   // new mallocs at the same place as CI, and N globals.
1273   std::vector<Value*> FieldGlobals;
1274   std::vector<Value*> FieldMallocs;
1275   
1276   for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
1277     const Type *FieldTy = STy->getElementType(FieldNo);
1278     const PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
1279     
1280     GlobalVariable *NGV =
1281       new GlobalVariable(*GV->getParent(),
1282                          PFieldTy, false, GlobalValue::InternalLinkage,
1283                          Constant::getNullValue(PFieldTy),
1284                          GV->getName() + ".f" + Twine(FieldNo), GV,
1285                          GV->isThreadLocal());
1286     FieldGlobals.push_back(NGV);
1287     
1288     unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
1289     if (const StructType *ST = dyn_cast<StructType>(FieldTy))
1290       TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
1291     const Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
1292     Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1293                                         ConstantInt::get(IntPtrTy, TypeSize),
1294                                         NElems,
1295                                         CI->getName() + ".f" + Twine(FieldNo));
1296     FieldMallocs.push_back(NMI);
1297     new StoreInst(NMI, NGV, CI);
1298   }
1299   
1300   // The tricky aspect of this transformation is handling the case when malloc
1301   // fails.  In the original code, malloc failing would set the result pointer
1302   // of malloc to null.  In this case, some mallocs could succeed and others
1303   // could fail.  As such, we emit code that looks like this:
1304   //    F0 = malloc(field0)
1305   //    F1 = malloc(field1)
1306   //    F2 = malloc(field2)
1307   //    if (F0 == 0 || F1 == 0 || F2 == 0) {
1308   //      if (F0) { free(F0); F0 = 0; }
1309   //      if (F1) { free(F1); F1 = 0; }
1310   //      if (F2) { free(F2); F2 = 0; }
1311   //    }
1312   // The malloc can also fail if its argument is too large.
1313   Constant *ConstantZero = ConstantInt::get(CI->getOperand(1)->getType(), 0);
1314   Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getOperand(1),
1315                                   ConstantZero, "isneg");
1316   for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
1317     Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1318                              Constant::getNullValue(FieldMallocs[i]->getType()),
1319                                "isnull");
1320     RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
1321   }
1322
1323   // Split the basic block at the old malloc.
1324   BasicBlock *OrigBB = CI->getParent();
1325   BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
1326   
1327   // Create the block to check the first condition.  Put all these blocks at the
1328   // end of the function as they are unlikely to be executed.
1329   BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1330                                                 "malloc_ret_null",
1331                                                 OrigBB->getParent());
1332   
1333   // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1334   // branch on RunningOr.
1335   OrigBB->getTerminator()->eraseFromParent();
1336   BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
1337   
1338   // Within the NullPtrBlock, we need to emit a comparison and branch for each
1339   // pointer, because some may be null while others are not.
1340   for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1341     Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
1342     Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal, 
1343                               Constant::getNullValue(GVVal->getType()),
1344                               "tmp");
1345     BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
1346                                                OrigBB->getParent());
1347     BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
1348                                                OrigBB->getParent());
1349     Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1350                                          Cmp, NullPtrBlock);
1351
1352     // Fill in FreeBlock.
1353     CallInst::CreateFree(GVVal, BI);
1354     new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1355                   FreeBlock);
1356     BranchInst::Create(NextBlock, FreeBlock);
1357     
1358     NullPtrBlock = NextBlock;
1359   }
1360   
1361   BranchInst::Create(ContBB, NullPtrBlock);
1362
1363   // CI is no longer needed, remove it.
1364   CI->eraseFromParent();
1365
1366   /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1367   /// update all uses of the load, keep track of what scalarized loads are
1368   /// inserted for a given load.
1369   DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1370   InsertedScalarizedValues[GV] = FieldGlobals;
1371   
1372   std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
1373   
1374   // Okay, the malloc site is completely handled.  All of the uses of GV are now
1375   // loads, and all uses of those loads are simple.  Rewrite them to use loads
1376   // of the per-field globals instead.
1377   for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1378     Instruction *User = cast<Instruction>(*UI++);
1379     
1380     if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1381       RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
1382       continue;
1383     }
1384     
1385     // Must be a store of null.
1386     StoreInst *SI = cast<StoreInst>(User);
1387     assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1388            "Unexpected heap-sra user!");
1389     
1390     // Insert a store of null into each global.
1391     for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1392       const PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
1393       Constant *Null = Constant::getNullValue(PT->getElementType());
1394       new StoreInst(Null, FieldGlobals[i], SI);
1395     }
1396     // Erase the original store.
1397     SI->eraseFromParent();
1398   }
1399
1400   // While we have PHIs that are interesting to rewrite, do it.
1401   while (!PHIsToRewrite.empty()) {
1402     PHINode *PN = PHIsToRewrite.back().first;
1403     unsigned FieldNo = PHIsToRewrite.back().second;
1404     PHIsToRewrite.pop_back();
1405     PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1406     assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1407
1408     // Add all the incoming values.  This can materialize more phis.
1409     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1410       Value *InVal = PN->getIncomingValue(i);
1411       InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
1412                                PHIsToRewrite);
1413       FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1414     }
1415   }
1416   
1417   // Drop all inter-phi links and any loads that made it this far.
1418   for (DenseMap<Value*, std::vector<Value*> >::iterator
1419        I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1420        I != E; ++I) {
1421     if (PHINode *PN = dyn_cast<PHINode>(I->first))
1422       PN->dropAllReferences();
1423     else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1424       LI->dropAllReferences();
1425   }
1426   
1427   // Delete all the phis and loads now that inter-references are dead.
1428   for (DenseMap<Value*, std::vector<Value*> >::iterator
1429        I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1430        I != E; ++I) {
1431     if (PHINode *PN = dyn_cast<PHINode>(I->first))
1432       PN->eraseFromParent();
1433     else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1434       LI->eraseFromParent();
1435   }
1436   
1437   // The old global is now dead, remove it.
1438   GV->eraseFromParent();
1439
1440   ++NumHeapSRA;
1441   return cast<GlobalVariable>(FieldGlobals[0]);
1442 }
1443
1444 /// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1445 /// pointer global variable with a single value stored it that is a malloc or
1446 /// cast of malloc.
1447 static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
1448                                                CallInst *CI,
1449                                                const Type *AllocTy,
1450                                                Module::global_iterator &GVI,
1451                                                TargetData *TD) {
1452   // If this is a malloc of an abstract type, don't touch it.
1453   if (!AllocTy->isSized())
1454     return false;
1455
1456   // We can't optimize this global unless all uses of it are *known* to be
1457   // of the malloc value, not of the null initializer value (consider a use
1458   // that compares the global's value against zero to see if the malloc has
1459   // been reached).  To do this, we check to see if all uses of the global
1460   // would trap if the global were null: this proves that they must all
1461   // happen after the malloc.
1462   if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1463     return false;
1464
1465   // We can't optimize this if the malloc itself is used in a complex way,
1466   // for example, being stored into multiple globals.  This allows the
1467   // malloc to be stored into the specified global, loaded setcc'd, and
1468   // GEP'd.  These are all things we could transform to using the global
1469   // for.
1470   {
1471     SmallPtrSet<PHINode*, 8> PHIs;
1472     if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1473       return false;
1474   }  
1475
1476   // If we have a global that is only initialized with a fixed size malloc,
1477   // transform the program to use global memory instead of malloc'd memory.
1478   // This eliminates dynamic allocation, avoids an indirection accessing the
1479   // data, and exposes the resultant global to further GlobalOpt.
1480   // We cannot optimize the malloc if we cannot determine malloc array size.
1481   if (Value *NElems = getMallocArraySize(CI, TD, true)) {
1482     if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1483       // Restrict this transformation to only working on small allocations
1484       // (2048 bytes currently), as we don't want to introduce a 16M global or
1485       // something.
1486       if (TD && 
1487           NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
1488         GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD);
1489         return true;
1490       }
1491   
1492     // If the allocation is an array of structures, consider transforming this
1493     // into multiple malloc'd arrays, one for each field.  This is basically
1494     // SRoA for malloc'd memory.
1495
1496     // If this is an allocation of a fixed size array of structs, analyze as a
1497     // variable size array.  malloc [100 x struct],1 -> malloc struct, 100
1498     if (NElems == ConstantInt::get(CI->getOperand(1)->getType(), 1))
1499       if (const ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
1500         AllocTy = AT->getElementType();
1501   
1502     if (const StructType *AllocSTy = dyn_cast<StructType>(AllocTy)) {
1503       // This the structure has an unreasonable number of fields, leave it
1504       // alone.
1505       if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1506           AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1507
1508         // If this is a fixed size array, transform the Malloc to be an alloc of
1509         // structs.  malloc [100 x struct],1 -> malloc struct, 100
1510         if (const ArrayType *AT =
1511                               dyn_cast<ArrayType>(getMallocAllocatedType(CI))) {
1512           const Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
1513           unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
1514           Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1515           Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1516           Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1517                                                        AllocSize, NumElements,
1518                                                        CI->getName());
1519           Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1520           CI->replaceAllUsesWith(Cast);
1521           CI->eraseFromParent();
1522           CI = dyn_cast<BitCastInst>(Malloc) ?
1523                extractMallocCallFromBitCast(Malloc) : cast<CallInst>(Malloc);
1524         }
1525       
1526         GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, true),TD);
1527         return true;
1528       }
1529     }
1530   }
1531   
1532   return false;
1533 }  
1534
1535 // OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1536 // that only one value (besides its initializer) is ever stored to the global.
1537 static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
1538                                      Module::global_iterator &GVI,
1539                                      TargetData *TD) {
1540   // Ignore no-op GEPs and bitcasts.
1541   StoredOnceVal = StoredOnceVal->stripPointerCasts();
1542
1543   // If we are dealing with a pointer global that is initialized to null and
1544   // only has one (non-null) value stored into it, then we can optimize any
1545   // users of the loaded value (often calls and loads) that would trap if the
1546   // value was null.
1547   if (GV->getInitializer()->getType()->isPointerTy() &&
1548       GV->getInitializer()->isNullValue()) {
1549     if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1550       if (GV->getInitializer()->getType() != SOVC->getType())
1551         SOVC = 
1552          ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
1553
1554       // Optimize away any trapping uses of the loaded value.
1555       if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
1556         return true;
1557     } else if (CallInst *CI = extractMallocCall(StoredOnceVal)) {
1558       const Type* MallocType = getMallocAllocatedType(CI);
1559       if (MallocType && TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType, 
1560                                                            GVI, TD))
1561         return true;
1562     }
1563   }
1564
1565   return false;
1566 }
1567
1568 /// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1569 /// two values ever stored into GV are its initializer and OtherVal.  See if we
1570 /// can shrink the global into a boolean and select between the two values
1571 /// whenever it is used.  This exposes the values to other scalar optimizations.
1572 static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
1573   const Type *GVElType = GV->getType()->getElementType();
1574   
1575   // If GVElType is already i1, it is already shrunk.  If the type of the GV is
1576   // an FP value, pointer or vector, don't do this optimization because a select
1577   // between them is very expensive and unlikely to lead to later
1578   // simplification.  In these cases, we typically end up with "cond ? v1 : v2"
1579   // where v1 and v2 both require constant pool loads, a big loss.
1580   if (GVElType == Type::getInt1Ty(GV->getContext()) ||
1581       GVElType->isFloatingPointTy() ||
1582       GVElType->isPointerTy() || GVElType->isVectorTy())
1583     return false;
1584   
1585   // Walk the use list of the global seeing if all the uses are load or store.
1586   // If there is anything else, bail out.
1587   for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I)
1588     if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
1589       return false;
1590   
1591   DEBUG(dbgs() << "   *** SHRINKING TO BOOL: " << *GV);
1592   
1593   // Create the new global, initializing it to false.
1594   GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1595                                              false,
1596                                              GlobalValue::InternalLinkage, 
1597                                         ConstantInt::getFalse(GV->getContext()),
1598                                              GV->getName()+".b",
1599                                              GV->isThreadLocal());
1600   GV->getParent()->getGlobalList().insert(GV, NewGV);
1601
1602   Constant *InitVal = GV->getInitializer();
1603   assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
1604          "No reason to shrink to bool!");
1605
1606   // If initialized to zero and storing one into the global, we can use a cast
1607   // instead of a select to synthesize the desired value.
1608   bool IsOneZero = false;
1609   if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
1610     IsOneZero = InitVal->isNullValue() && CI->isOne();
1611
1612   while (!GV->use_empty()) {
1613     Instruction *UI = cast<Instruction>(GV->use_back());
1614     if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
1615       // Change the store into a boolean store.
1616       bool StoringOther = SI->getOperand(0) == OtherVal;
1617       // Only do this if we weren't storing a loaded value.
1618       Value *StoreVal;
1619       if (StoringOther || SI->getOperand(0) == InitVal)
1620         StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1621                                     StoringOther);
1622       else {
1623         // Otherwise, we are storing a previously loaded copy.  To do this,
1624         // change the copy from copying the original value to just copying the
1625         // bool.
1626         Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1627
1628         // If we're already replaced the input, StoredVal will be a cast or
1629         // select instruction.  If not, it will be a load of the original
1630         // global.
1631         if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1632           assert(LI->getOperand(0) == GV && "Not a copy!");
1633           // Insert a new load, to preserve the saved value.
1634           StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1635         } else {
1636           assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1637                  "This is not a form that we understand!");
1638           StoreVal = StoredVal->getOperand(0);
1639           assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1640         }
1641       }
1642       new StoreInst(StoreVal, NewGV, SI);
1643     } else {
1644       // Change the load into a load of bool then a select.
1645       LoadInst *LI = cast<LoadInst>(UI);
1646       LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
1647       Value *NSI;
1648       if (IsOneZero)
1649         NSI = new ZExtInst(NLI, LI->getType(), "", LI);
1650       else
1651         NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
1652       NSI->takeName(LI);
1653       LI->replaceAllUsesWith(NSI);
1654     }
1655     UI->eraseFromParent();
1656   }
1657
1658   GV->eraseFromParent();
1659   return true;
1660 }
1661
1662
1663 /// ProcessInternalGlobal - Analyze the specified global variable and optimize
1664 /// it if possible.  If we make a change, return true.
1665 bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1666                                       Module::global_iterator &GVI) {
1667   SmallPtrSet<const PHINode*, 16> PHIUsers;
1668   GlobalStatus GS;
1669   GV->removeDeadConstantUsers();
1670
1671   if (GV->use_empty()) {
1672     DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
1673     GV->eraseFromParent();
1674     ++NumDeleted;
1675     return true;
1676   }
1677
1678   if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
1679 #if 0
1680     DEBUG(dbgs() << "Global: " << *GV);
1681     DEBUG(dbgs() << "  isLoaded = " << GS.isLoaded << "\n");
1682     DEBUG(dbgs() << "  StoredType = ");
1683     switch (GS.StoredType) {
1684     case GlobalStatus::NotStored: DEBUG(dbgs() << "NEVER STORED\n"); break;
1685     case GlobalStatus::isInitializerStored: DEBUG(dbgs() << "INIT STORED\n");
1686                                             break;
1687     case GlobalStatus::isStoredOnce: DEBUG(dbgs() << "STORED ONCE\n"); break;
1688     case GlobalStatus::isStored: DEBUG(dbgs() << "stored\n"); break;
1689     }
1690     if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
1691       DEBUG(dbgs() << "  StoredOnceValue = " << *GS.StoredOnceValue << "\n");
1692     if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
1693       DEBUG(dbgs() << "  AccessingFunction = " << GS.AccessingFunction->getName()
1694                   << "\n");
1695     DEBUG(dbgs() << "  HasMultipleAccessingFunctions =  "
1696                  << GS.HasMultipleAccessingFunctions << "\n");
1697     DEBUG(dbgs() << "  HasNonInstructionUser = " 
1698                  << GS.HasNonInstructionUser<<"\n");
1699     DEBUG(dbgs() << "\n");
1700 #endif
1701     
1702     // If this is a first class global and has only one accessing function
1703     // and this function is main (which we know is not recursive we can make
1704     // this global a local variable) we replace the global with a local alloca
1705     // in this function.
1706     //
1707     // NOTE: It doesn't make sense to promote non single-value types since we
1708     // are just replacing static memory to stack memory.
1709     //
1710     // If the global is in different address space, don't bring it to stack.
1711     if (!GS.HasMultipleAccessingFunctions &&
1712         GS.AccessingFunction && !GS.HasNonInstructionUser &&
1713         GV->getType()->getElementType()->isSingleValueType() &&
1714         GS.AccessingFunction->getName() == "main" &&
1715         GS.AccessingFunction->hasExternalLinkage() &&
1716         GV->getType()->getAddressSpace() == 0) {
1717       DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
1718       Instruction& FirstI = const_cast<Instruction&>(*GS.AccessingFunction
1719                                                      ->getEntryBlock().begin());
1720       const Type* ElemTy = GV->getType()->getElementType();
1721       // FIXME: Pass Global's alignment when globals have alignment
1722       AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI);
1723       if (!isa<UndefValue>(GV->getInitializer()))
1724         new StoreInst(GV->getInitializer(), Alloca, &FirstI);
1725
1726       GV->replaceAllUsesWith(Alloca);
1727       GV->eraseFromParent();
1728       ++NumLocalized;
1729       return true;
1730     }
1731     
1732     // If the global is never loaded (but may be stored to), it is dead.
1733     // Delete it now.
1734     if (!GS.isLoaded) {
1735       DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
1736
1737       // Delete any stores we can find to the global.  We may not be able to
1738       // make it completely dead though.
1739       bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
1740
1741       // If the global is dead now, delete it.
1742       if (GV->use_empty()) {
1743         GV->eraseFromParent();
1744         ++NumDeleted;
1745         Changed = true;
1746       }
1747       return Changed;
1748
1749     } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1750       DEBUG(dbgs() << "MARKING CONSTANT: " << *GV);
1751       GV->setConstant(true);
1752
1753       // Clean up any obviously simplifiable users now.
1754       CleanupConstantGlobalUsers(GV, GV->getInitializer());
1755
1756       // If the global is dead now, just nuke it.
1757       if (GV->use_empty()) {
1758         DEBUG(dbgs() << "   *** Marking constant allowed us to simplify "
1759                      << "all users and delete global!\n");
1760         GV->eraseFromParent();
1761         ++NumDeleted;
1762       }
1763
1764       ++NumMarked;
1765       return true;
1766     } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
1767       if (TargetData *TD = getAnalysisIfAvailable<TargetData>())
1768         if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
1769           GVI = FirstNewGV;  // Don't skip the newly produced globals!
1770           return true;
1771         }
1772     } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
1773       // If the initial value for the global was an undef value, and if only
1774       // one other value was stored into it, we can just change the
1775       // initializer to be the stored value, then delete all stores to the
1776       // global.  This allows us to mark it constant.
1777       if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1778         if (isa<UndefValue>(GV->getInitializer())) {
1779           // Change the initial value here.
1780           GV->setInitializer(SOVConstant);
1781
1782           // Clean up any obviously simplifiable users now.
1783           CleanupConstantGlobalUsers(GV, GV->getInitializer());
1784
1785           if (GV->use_empty()) {
1786             DEBUG(dbgs() << "   *** Substituting initializer allowed us to "
1787                          << "simplify all users and delete global!\n");
1788             GV->eraseFromParent();
1789             ++NumDeleted;
1790           } else {
1791             GVI = GV;
1792           }
1793           ++NumSubstitute;
1794           return true;
1795         }
1796
1797       // Try to optimize globals based on the knowledge that only one value
1798       // (besides its initializer) is ever stored to the global.
1799       if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1800                                    getAnalysisIfAvailable<TargetData>()))
1801         return true;
1802
1803       // Otherwise, if the global was not a boolean, we can shrink it to be a
1804       // boolean.
1805       if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1806         if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
1807           ++NumShrunkToBool;
1808           return true;
1809         }
1810     }
1811   }
1812   return false;
1813 }
1814
1815 /// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1816 /// function, changing them to FastCC.
1817 static void ChangeCalleesToFastCall(Function *F) {
1818   for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1819     CallSite User(cast<Instruction>(*UI));
1820     User.setCallingConv(CallingConv::Fast);
1821   }
1822 }
1823
1824 static AttrListPtr StripNest(const AttrListPtr &Attrs) {
1825   for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
1826     if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
1827       continue;
1828
1829     // There can be only one.
1830     return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
1831   }
1832
1833   return Attrs;
1834 }
1835
1836 static void RemoveNestAttribute(Function *F) {
1837   F->setAttributes(StripNest(F->getAttributes()));
1838   for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1839     CallSite User(cast<Instruction>(*UI));
1840     User.setAttributes(StripNest(User.getAttributes()));
1841   }
1842 }
1843
1844 bool GlobalOpt::OptimizeFunctions(Module &M) {
1845   bool Changed = false;
1846   // Optimize functions.
1847   for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1848     Function *F = FI++;
1849     // Functions without names cannot be referenced outside this module.
1850     if (!F->hasName() && !F->isDeclaration())
1851       F->setLinkage(GlobalValue::InternalLinkage);
1852     F->removeDeadConstantUsers();
1853     if (F->use_empty() && (F->hasLocalLinkage() || F->hasLinkOnceLinkage())) {
1854       F->eraseFromParent();
1855       Changed = true;
1856       ++NumFnDeleted;
1857     } else if (F->hasLocalLinkage()) {
1858       if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
1859           !F->hasAddressTaken()) {
1860         // If this function has C calling conventions, is not a varargs
1861         // function, and is only called directly, promote it to use the Fast
1862         // calling convention.
1863         F->setCallingConv(CallingConv::Fast);
1864         ChangeCalleesToFastCall(F);
1865         ++NumFastCallFns;
1866         Changed = true;
1867       }
1868
1869       if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
1870           !F->hasAddressTaken()) {
1871         // The function is not used by a trampoline intrinsic, so it is safe
1872         // to remove the 'nest' attribute.
1873         RemoveNestAttribute(F);
1874         ++NumNestRemoved;
1875         Changed = true;
1876       }
1877     }
1878   }
1879   return Changed;
1880 }
1881
1882 bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1883   bool Changed = false;
1884   for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1885        GVI != E; ) {
1886     GlobalVariable *GV = GVI++;
1887     // Global variables without names cannot be referenced outside this module.
1888     if (!GV->hasName() && !GV->isDeclaration())
1889       GV->setLinkage(GlobalValue::InternalLinkage);
1890     // Simplify the initializer.
1891     if (GV->hasInitializer())
1892       if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
1893         TargetData *TD = getAnalysisIfAvailable<TargetData>();
1894         Constant *New = ConstantFoldConstantExpression(CE, TD);
1895         if (New && New != CE)
1896           GV->setInitializer(New);
1897       }
1898     // Do more involved optimizations if the global is internal.
1899     if (!GV->isConstant() && GV->hasLocalLinkage() &&
1900         GV->hasInitializer())
1901       Changed |= ProcessInternalGlobal(GV, GVI);
1902   }
1903   return Changed;
1904 }
1905
1906 /// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1907 /// initializers have an init priority of 65535.
1908 GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
1909   for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1910        I != E; ++I)
1911     if (I->getName() == "llvm.global_ctors") {
1912       // Found it, verify it's an array of { int, void()* }.
1913       const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1914       if (!ATy) return 0;
1915       const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1916       if (!STy || STy->getNumElements() != 2 ||
1917           !STy->getElementType(0)->isIntegerTy(32)) return 0;
1918       const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1919       if (!PFTy) return 0;
1920       const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
1921       if (!FTy || !FTy->getReturnType()->isVoidTy() ||
1922           FTy->isVarArg() || FTy->getNumParams() != 0)
1923         return 0;
1924       
1925       // Verify that the initializer is simple enough for us to handle.
1926       if (!I->hasDefinitiveInitializer()) return 0;
1927       ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1928       if (!CA) return 0;
1929       for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
1930         if (ConstantStruct *CS = dyn_cast<ConstantStruct>(*i)) {
1931           if (isa<ConstantPointerNull>(CS->getOperand(1)))
1932             continue;
1933
1934           // Must have a function or null ptr.
1935           if (!isa<Function>(CS->getOperand(1)))
1936             return 0;
1937           
1938           // Init priority must be standard.
1939           ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
1940           if (!CI || CI->getZExtValue() != 65535)
1941             return 0;
1942         } else {
1943           return 0;
1944         }
1945       
1946       return I;
1947     }
1948   return 0;
1949 }
1950
1951 /// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1952 /// return a list of the functions and null terminator as a vector.
1953 static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1954   ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1955   std::vector<Function*> Result;
1956   Result.reserve(CA->getNumOperands());
1957   for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1958     ConstantStruct *CS = cast<ConstantStruct>(*i);
1959     Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1960   }
1961   return Result;
1962 }
1963
1964 /// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1965 /// specified array, returning the new global to use.
1966 static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL, 
1967                                           const std::vector<Function*> &Ctors) {
1968   // If we made a change, reassemble the initializer list.
1969   std::vector<Constant*> CSVals;
1970   CSVals.push_back(ConstantInt::get(Type::getInt32Ty(GCL->getContext()),65535));
1971   CSVals.push_back(0);
1972   
1973   // Create the new init list.
1974   std::vector<Constant*> CAList;
1975   for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
1976     if (Ctors[i]) {
1977       CSVals[1] = Ctors[i];
1978     } else {
1979       const Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
1980                                           false);
1981       const PointerType *PFTy = PointerType::getUnqual(FTy);
1982       CSVals[1] = Constant::getNullValue(PFTy);
1983       CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
1984                                    2147483647);
1985     }
1986     CAList.push_back(ConstantStruct::get(GCL->getContext(), CSVals, false));
1987   }
1988   
1989   // Create the array initializer.
1990   const Type *StructTy =
1991       cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
1992   Constant *CA = ConstantArray::get(ArrayType::get(StructTy, 
1993                                                    CAList.size()), CAList);
1994   
1995   // If we didn't change the number of elements, don't create a new GV.
1996   if (CA->getType() == GCL->getInitializer()->getType()) {
1997     GCL->setInitializer(CA);
1998     return GCL;
1999   }
2000   
2001   // Create the new global and insert it next to the existing list.
2002   GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
2003                                            GCL->getLinkage(), CA, "",
2004                                            GCL->isThreadLocal());
2005   GCL->getParent()->getGlobalList().insert(GCL, NGV);
2006   NGV->takeName(GCL);
2007   
2008   // Nuke the old list, replacing any uses with the new one.
2009   if (!GCL->use_empty()) {
2010     Constant *V = NGV;
2011     if (V->getType() != GCL->getType())
2012       V = ConstantExpr::getBitCast(V, GCL->getType());
2013     GCL->replaceAllUsesWith(V);
2014   }
2015   GCL->eraseFromParent();
2016   
2017   if (Ctors.size())
2018     return NGV;
2019   else
2020     return 0;
2021 }
2022
2023
2024 static Constant *getVal(DenseMap<Value*, Constant*> &ComputedValues,
2025                         Value *V) {
2026   if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2027   Constant *R = ComputedValues[V];
2028   assert(R && "Reference to an uncomputed value!");
2029   return R;
2030 }
2031
2032 /// isSimpleEnoughPointerToCommit - Return true if this constant is simple
2033 /// enough for us to understand.  In particular, if it is a cast of something,
2034 /// we punt.  We basically just support direct accesses to globals and GEP's of
2035 /// globals.  This should be kept up to date with CommitValueTo.
2036 static bool isSimpleEnoughPointerToCommit(Constant *C) {
2037   // Conservatively, avoid aggregate types. This is because we don't
2038   // want to worry about them partially overlapping other stores.
2039   if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2040     return false;
2041
2042   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
2043     // Do not allow weak/linkonce/dllimport/dllexport linkage or
2044     // external globals.
2045     return GV->hasDefinitiveInitializer();
2046
2047   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
2048     // Handle a constantexpr gep.
2049     if (CE->getOpcode() == Instruction::GetElementPtr &&
2050         isa<GlobalVariable>(CE->getOperand(0)) &&
2051         cast<GEPOperator>(CE)->isInBounds()) {
2052       GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2053       // Do not allow weak/linkonce/dllimport/dllexport linkage or
2054       // external globals.
2055       if (!GV->hasDefinitiveInitializer())
2056         return false;
2057
2058       // The first index must be zero.
2059       ConstantInt *CI = dyn_cast<ConstantInt>(*next(CE->op_begin()));
2060       if (!CI || !CI->isZero()) return false;
2061
2062       // The remaining indices must be compile-time known integers within the
2063       // notional bounds of the corresponding static array types.
2064       if (!CE->isGEPWithNoNotionalOverIndexing())
2065         return false;
2066
2067       return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
2068     }
2069   return false;
2070 }
2071
2072 /// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2073 /// initializer.  This returns 'Init' modified to reflect 'Val' stored into it.
2074 /// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2075 static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
2076                                    ConstantExpr *Addr, unsigned OpNo) {
2077   // Base case of the recursion.
2078   if (OpNo == Addr->getNumOperands()) {
2079     assert(Val->getType() == Init->getType() && "Type mismatch!");
2080     return Val;
2081   }
2082   
2083   std::vector<Constant*> Elts;
2084   if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2085
2086     // Break up the constant into its elements.
2087     if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2088       for (User::op_iterator i = CS->op_begin(), e = CS->op_end(); i != e; ++i)
2089         Elts.push_back(cast<Constant>(*i));
2090     } else if (isa<ConstantAggregateZero>(Init)) {
2091       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2092         Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
2093     } else if (isa<UndefValue>(Init)) {
2094       for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2095         Elts.push_back(UndefValue::get(STy->getElementType(i)));
2096     } else {
2097       llvm_unreachable("This code is out of sync with "
2098              " ConstantFoldLoadThroughGEPConstantExpr");
2099     }
2100     
2101     // Replace the element that we are supposed to.
2102     ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2103     unsigned Idx = CU->getZExtValue();
2104     assert(Idx < STy->getNumElements() && "Struct index out of range!");
2105     Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
2106     
2107     // Return the modified struct.
2108     return ConstantStruct::get(Init->getContext(), &Elts[0], Elts.size(),
2109                                STy->isPacked());
2110   } else {
2111     ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
2112     const SequentialType *InitTy = cast<SequentialType>(Init->getType());
2113
2114     uint64_t NumElts;
2115     if (const ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
2116       NumElts = ATy->getNumElements();
2117     else
2118       NumElts = cast<VectorType>(InitTy)->getNumElements();
2119     
2120     
2121     // Break up the array into elements.
2122     if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2123       for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
2124         Elts.push_back(cast<Constant>(*i));
2125     } else if (ConstantVector *CV = dyn_cast<ConstantVector>(Init)) {
2126       for (User::op_iterator i = CV->op_begin(), e = CV->op_end(); i != e; ++i)
2127         Elts.push_back(cast<Constant>(*i));
2128     } else if (isa<ConstantAggregateZero>(Init)) {
2129       Elts.assign(NumElts, Constant::getNullValue(InitTy->getElementType()));
2130     } else {
2131       assert(isa<UndefValue>(Init) && "This code is out of sync with "
2132              " ConstantFoldLoadThroughGEPConstantExpr");
2133       Elts.assign(NumElts, UndefValue::get(InitTy->getElementType()));
2134     }
2135     
2136     assert(CI->getZExtValue() < NumElts);
2137     Elts[CI->getZExtValue()] =
2138       EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
2139     
2140     if (Init->getType()->isArrayTy())
2141       return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2142     else
2143       return ConstantVector::get(&Elts[0], Elts.size());
2144   }    
2145 }
2146
2147 /// CommitValueTo - We have decided that Addr (which satisfies the predicate
2148 /// isSimpleEnoughPointerToCommit) should get Val as its value.  Make it happen.
2149 static void CommitValueTo(Constant *Val, Constant *Addr) {
2150   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2151     assert(GV->hasInitializer());
2152     GV->setInitializer(Val);
2153     return;
2154   }
2155
2156   ConstantExpr *CE = cast<ConstantExpr>(Addr);
2157   GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2158   GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
2159 }
2160
2161 /// ComputeLoadResult - Return the value that would be computed by a load from
2162 /// P after the stores reflected by 'memory' have been performed.  If we can't
2163 /// decide, return null.
2164 static Constant *ComputeLoadResult(Constant *P,
2165                                 const DenseMap<Constant*, Constant*> &Memory) {
2166   // If this memory location has been recently stored, use the stored value: it
2167   // is the most up-to-date.
2168   DenseMap<Constant*, Constant*>::const_iterator I = Memory.find(P);
2169   if (I != Memory.end()) return I->second;
2170  
2171   // Access it.
2172   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
2173     if (GV->hasDefinitiveInitializer())
2174       return GV->getInitializer();
2175     return 0;
2176   }
2177   
2178   // Handle a constantexpr getelementptr.
2179   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2180     if (CE->getOpcode() == Instruction::GetElementPtr &&
2181         isa<GlobalVariable>(CE->getOperand(0))) {
2182       GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2183       if (GV->hasDefinitiveInitializer())
2184         return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
2185     }
2186
2187   return 0;  // don't know how to evaluate.
2188 }
2189
2190 /// EvaluateFunction - Evaluate a call to function F, returning true if
2191 /// successful, false if we can't evaluate it.  ActualArgs contains the formal
2192 /// arguments for the function.
2193 static bool EvaluateFunction(Function *F, Constant *&RetVal,
2194                              const SmallVectorImpl<Constant*> &ActualArgs,
2195                              std::vector<Function*> &CallStack,
2196                              DenseMap<Constant*, Constant*> &MutatedMemory,
2197                              std::vector<GlobalVariable*> &AllocaTmps) {
2198   // Check to see if this function is already executing (recursion).  If so,
2199   // bail out.  TODO: we might want to accept limited recursion.
2200   if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2201     return false;
2202   
2203   CallStack.push_back(F);
2204   
2205   /// Values - As we compute SSA register values, we store their contents here.
2206   DenseMap<Value*, Constant*> Values;
2207   
2208   // Initialize arguments to the incoming values specified.
2209   unsigned ArgNo = 0;
2210   for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2211        ++AI, ++ArgNo)
2212     Values[AI] = ActualArgs[ArgNo];
2213
2214   /// ExecutedBlocks - We only handle non-looping, non-recursive code.  As such,
2215   /// we can only evaluate any one basic block at most once.  This set keeps
2216   /// track of what we have executed so we can detect recursive cases etc.
2217   SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
2218   
2219   // CurInst - The current instruction we're evaluating.
2220   BasicBlock::iterator CurInst = F->begin()->begin();
2221   
2222   // This is the main evaluation loop.
2223   while (1) {
2224     Constant *InstResult = 0;
2225     
2226     if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
2227       if (SI->isVolatile()) return false;  // no volatile accesses.
2228       Constant *Ptr = getVal(Values, SI->getOperand(1));
2229       if (!isSimpleEnoughPointerToCommit(Ptr))
2230         // If this is too complex for us to commit, reject it.
2231         return false;
2232       Constant *Val = getVal(Values, SI->getOperand(0));
2233       MutatedMemory[Ptr] = Val;
2234     } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
2235       InstResult = ConstantExpr::get(BO->getOpcode(),
2236                                      getVal(Values, BO->getOperand(0)),
2237                                      getVal(Values, BO->getOperand(1)));
2238     } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
2239       InstResult = ConstantExpr::getCompare(CI->getPredicate(),
2240                                             getVal(Values, CI->getOperand(0)),
2241                                             getVal(Values, CI->getOperand(1)));
2242     } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
2243       InstResult = ConstantExpr::getCast(CI->getOpcode(),
2244                                          getVal(Values, CI->getOperand(0)),
2245                                          CI->getType());
2246     } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
2247       InstResult =
2248             ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
2249                                            getVal(Values, SI->getOperand(1)),
2250                                            getVal(Values, SI->getOperand(2)));
2251     } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
2252       Constant *P = getVal(Values, GEP->getOperand(0));
2253       SmallVector<Constant*, 8> GEPOps;
2254       for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2255            i != e; ++i)
2256         GEPOps.push_back(getVal(Values, *i));
2257       InstResult = cast<GEPOperator>(GEP)->isInBounds() ?
2258           ConstantExpr::getInBoundsGetElementPtr(P, &GEPOps[0], GEPOps.size()) :
2259           ConstantExpr::getGetElementPtr(P, &GEPOps[0], GEPOps.size());
2260     } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
2261       if (LI->isVolatile()) return false;  // no volatile accesses.
2262       InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
2263                                      MutatedMemory);
2264       if (InstResult == 0) return false; // Could not evaluate load.
2265     } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
2266       if (AI->isArrayAllocation()) return false;  // Cannot handle array allocs.
2267       const Type *Ty = AI->getType()->getElementType();
2268       AllocaTmps.push_back(new GlobalVariable(Ty, false,
2269                                               GlobalValue::InternalLinkage,
2270                                               UndefValue::get(Ty),
2271                                               AI->getName()));
2272       InstResult = AllocaTmps.back();     
2273     } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
2274
2275       // Debug info can safely be ignored here.
2276       if (isa<DbgInfoIntrinsic>(CI)) {
2277         ++CurInst;
2278         continue;
2279       }
2280
2281       // Cannot handle inline asm.
2282       if (isa<InlineAsm>(CI->getOperand(0))) return false;
2283
2284       // Resolve function pointers.
2285       Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
2286       if (!Callee) return false;  // Cannot resolve.
2287
2288       SmallVector<Constant*, 8> Formals;
2289       for (User::op_iterator i = CI->op_begin() + 1, e = CI->op_end();
2290            i != e; ++i)
2291         Formals.push_back(getVal(Values, *i));
2292
2293       if (Callee->isDeclaration()) {
2294         // If this is a function we can constant fold, do it.
2295         if (Constant *C = ConstantFoldCall(Callee, Formals.data(),
2296                                            Formals.size())) {
2297           InstResult = C;
2298         } else {
2299           return false;
2300         }
2301       } else {
2302         if (Callee->getFunctionType()->isVarArg())
2303           return false;
2304         
2305         Constant *RetVal;
2306         // Execute the call, if successful, use the return value.
2307         if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
2308                               MutatedMemory, AllocaTmps))
2309           return false;
2310         InstResult = RetVal;
2311       }
2312     } else if (isa<TerminatorInst>(CurInst)) {
2313       BasicBlock *NewBB = 0;
2314       if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2315         if (BI->isUnconditional()) {
2316           NewBB = BI->getSuccessor(0);
2317         } else {
2318           ConstantInt *Cond =
2319             dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
2320           if (!Cond) return false;  // Cannot determine.
2321
2322           NewBB = BI->getSuccessor(!Cond->getZExtValue());          
2323         }
2324       } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2325         ConstantInt *Val =
2326           dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
2327         if (!Val) return false;  // Cannot determine.
2328         NewBB = SI->getSuccessor(SI->findCaseValue(Val));
2329       } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
2330         Value *Val = getVal(Values, IBI->getAddress())->stripPointerCasts();
2331         if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
2332           NewBB = BA->getBasicBlock();
2333         else
2334           return false;  // Cannot determine.
2335       } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
2336         if (RI->getNumOperands())
2337           RetVal = getVal(Values, RI->getOperand(0));
2338         
2339         CallStack.pop_back();  // return from fn.
2340         return true;  // We succeeded at evaluating this ctor!
2341       } else {
2342         // invoke, unwind, unreachable.
2343         return false;  // Cannot handle this terminator.
2344       }
2345       
2346       // Okay, we succeeded in evaluating this control flow.  See if we have
2347       // executed the new block before.  If so, we have a looping function,
2348       // which we cannot evaluate in reasonable time.
2349       if (!ExecutedBlocks.insert(NewBB))
2350         return false;  // looped!
2351       
2352       // Okay, we have never been in this block before.  Check to see if there
2353       // are any PHI nodes.  If so, evaluate them with information about where
2354       // we came from.
2355       BasicBlock *OldBB = CurInst->getParent();
2356       CurInst = NewBB->begin();
2357       PHINode *PN;
2358       for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2359         Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
2360
2361       // Do NOT increment CurInst.  We know that the terminator had no value.
2362       continue;
2363     } else {
2364       // Did not know how to evaluate this!
2365       return false;
2366     }
2367     
2368     if (!CurInst->use_empty())
2369       Values[CurInst] = InstResult;
2370     
2371     // Advance program counter.
2372     ++CurInst;
2373   }
2374 }
2375
2376 /// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2377 /// we can.  Return true if we can, false otherwise.
2378 static bool EvaluateStaticConstructor(Function *F) {
2379   /// MutatedMemory - For each store we execute, we update this map.  Loads
2380   /// check this to get the most up-to-date value.  If evaluation is successful,
2381   /// this state is committed to the process.
2382   DenseMap<Constant*, Constant*> MutatedMemory;
2383
2384   /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2385   /// to represent its body.  This vector is needed so we can delete the
2386   /// temporary globals when we are done.
2387   std::vector<GlobalVariable*> AllocaTmps;
2388   
2389   /// CallStack - This is used to detect recursion.  In pathological situations
2390   /// we could hit exponential behavior, but at least there is nothing
2391   /// unbounded.
2392   std::vector<Function*> CallStack;
2393
2394   // Call the function.
2395   Constant *RetValDummy;
2396   bool EvalSuccess = EvaluateFunction(F, RetValDummy,
2397                                       SmallVector<Constant*, 0>(), CallStack,
2398                                       MutatedMemory, AllocaTmps);
2399   if (EvalSuccess) {
2400     // We succeeded at evaluation: commit the result.
2401     DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
2402           << F->getName() << "' to " << MutatedMemory.size()
2403           << " stores.\n");
2404     for (DenseMap<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
2405          E = MutatedMemory.end(); I != E; ++I)
2406       CommitValueTo(I->second, I->first);
2407   }
2408   
2409   // At this point, we are done interpreting.  If we created any 'alloca'
2410   // temporaries, release them now.
2411   while (!AllocaTmps.empty()) {
2412     GlobalVariable *Tmp = AllocaTmps.back();
2413     AllocaTmps.pop_back();
2414     
2415     // If there are still users of the alloca, the program is doing something
2416     // silly, e.g. storing the address of the alloca somewhere and using it
2417     // later.  Since this is undefined, we'll just make it be null.
2418     if (!Tmp->use_empty())
2419       Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2420     delete Tmp;
2421   }
2422   
2423   return EvalSuccess;
2424 }
2425
2426
2427
2428 /// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2429 /// Return true if anything changed.
2430 bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2431   std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2432   bool MadeChange = false;
2433   if (Ctors.empty()) return false;
2434   
2435   // Loop over global ctors, optimizing them when we can.
2436   for (unsigned i = 0; i != Ctors.size(); ++i) {
2437     Function *F = Ctors[i];
2438     // Found a null terminator in the middle of the list, prune off the rest of
2439     // the list.
2440     if (F == 0) {
2441       if (i != Ctors.size()-1) {
2442         Ctors.resize(i+1);
2443         MadeChange = true;
2444       }
2445       break;
2446     }
2447     
2448     // We cannot simplify external ctor functions.
2449     if (F->empty()) continue;
2450     
2451     // If we can evaluate the ctor at compile time, do.
2452     if (EvaluateStaticConstructor(F)) {
2453       Ctors.erase(Ctors.begin()+i);
2454       MadeChange = true;
2455       --i;
2456       ++NumCtorsEvaluated;
2457       continue;
2458     }
2459   }
2460   
2461   if (!MadeChange) return false;
2462   
2463   GCL = InstallGlobalCtors(GCL, Ctors);
2464   return true;
2465 }
2466
2467 bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
2468   bool Changed = false;
2469
2470   for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
2471        I != E;) {
2472     Module::alias_iterator J = I++;
2473     // Aliases without names cannot be referenced outside this module.
2474     if (!J->hasName() && !J->isDeclaration())
2475       J->setLinkage(GlobalValue::InternalLinkage);
2476     // If the aliasee may change at link time, nothing can be done - bail out.
2477     if (J->mayBeOverridden())
2478       continue;
2479
2480     Constant *Aliasee = J->getAliasee();
2481     GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
2482     Target->removeDeadConstantUsers();
2483     bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2484
2485     // Make all users of the alias use the aliasee instead.
2486     if (!J->use_empty()) {
2487       J->replaceAllUsesWith(Aliasee);
2488       ++NumAliasesResolved;
2489       Changed = true;
2490     }
2491
2492     // If the alias is externally visible, we may still be able to simplify it.
2493     if (!J->hasLocalLinkage()) {
2494       // If the aliasee has internal linkage, give it the name and linkage
2495       // of the alias, and delete the alias.  This turns:
2496       //   define internal ... @f(...)
2497       //   @a = alias ... @f
2498       // into:
2499       //   define ... @a(...)
2500       if (!Target->hasLocalLinkage())
2501         continue;
2502
2503       // Do not perform the transform if multiple aliases potentially target the
2504       // aliasee.  This check also ensures that it is safe to replace the section
2505       // and other attributes of the aliasee with those of the alias.
2506       if (!hasOneUse)
2507         continue;
2508
2509       // Give the aliasee the name, linkage and other attributes of the alias.
2510       Target->takeName(J);
2511       Target->setLinkage(J->getLinkage());
2512       Target->GlobalValue::copyAttributesFrom(J);
2513     }
2514
2515     // Delete the alias.
2516     M.getAliasList().erase(J);
2517     ++NumAliasesRemoved;
2518     Changed = true;
2519   }
2520
2521   return Changed;
2522 }
2523
2524 bool GlobalOpt::runOnModule(Module &M) {
2525   bool Changed = false;
2526   
2527   // Try to find the llvm.globalctors list.
2528   GlobalVariable *GlobalCtors = FindGlobalCtors(M);
2529
2530   bool LocalChange = true;
2531   while (LocalChange) {
2532     LocalChange = false;
2533     
2534     // Delete functions that are trivially dead, ccc -> fastcc
2535     LocalChange |= OptimizeFunctions(M);
2536     
2537     // Optimize global_ctors list.
2538     if (GlobalCtors)
2539       LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
2540     
2541     // Optimize non-address-taken globals.
2542     LocalChange |= OptimizeGlobalVars(M);
2543
2544     // Resolve aliases, when possible.
2545     LocalChange |= OptimizeGlobalAliases(M);
2546     Changed |= LocalChange;
2547   }
2548   
2549   // TODO: Move all global ctors functions to the end of the module for code
2550   // layout.
2551   
2552   return Changed;
2553 }