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