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