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