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