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