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