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