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