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