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