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