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