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