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