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