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