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