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