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