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     if (!llvm::is_contained(AllCallsCold, CallerFunc))
2225       return false;
2226   }
2227   return true;
2228 }
2229 
2230 static void changeCallSitesToColdCC(Function *F) {
2231   for (User *U : F->users()) {
2232     if (isa<BlockAddress>(U))
2233       continue;
2234     cast<CallBase>(U)->setCallingConv(CallingConv::Cold);
2235   }
2236 }
2237 
2238 // This function iterates over all the call instructions in the input Function
2239 // and checks that all call sites are in cold blocks and are allowed to use the
2240 // coldcc calling convention.
2241 static bool
2242 hasOnlyColdCalls(Function &F,
2243                  function_ref<BlockFrequencyInfo &(Function &)> GetBFI) {
2244   for (BasicBlock &BB : F) {
2245     for (Instruction &I : BB) {
2246       if (CallInst *CI = dyn_cast<CallInst>(&I)) {
2247         // Skip over isline asm instructions since they aren't function calls.
2248         if (CI->isInlineAsm())
2249           continue;
2250         Function *CalledFn = CI->getCalledFunction();
2251         if (!CalledFn)
2252           return false;
2253         if (!CalledFn->hasLocalLinkage())
2254           return false;
2255         // Skip over instrinsics since they won't remain as function calls.
2256         if (CalledFn->getIntrinsicID() != Intrinsic::not_intrinsic)
2257           continue;
2258         // Check if it's valid to use coldcc calling convention.
2259         if (!hasChangeableCC(CalledFn) || CalledFn->isVarArg() ||
2260             CalledFn->hasAddressTaken())
2261           return false;
2262         BlockFrequencyInfo &CallerBFI = GetBFI(F);
2263         if (!isColdCallSite(*CI, CallerBFI))
2264           return false;
2265       }
2266     }
2267   }
2268   return true;
2269 }
2270 
2271 static bool hasMustTailCallers(Function *F) {
2272   for (User *U : F->users()) {
2273     CallBase *CB = dyn_cast<CallBase>(U);
2274     if (!CB) {
2275       assert(isa<BlockAddress>(U) &&
2276              "Expected either CallBase or BlockAddress");
2277       continue;
2278     }
2279     if (CB->isMustTailCall())
2280       return true;
2281   }
2282   return false;
2283 }
2284 
2285 static bool hasInvokeCallers(Function *F) {
2286   for (User *U : F->users())
2287     if (isa<InvokeInst>(U))
2288       return true;
2289   return false;
2290 }
2291 
2292 static void RemovePreallocated(Function *F) {
2293   RemoveAttribute(F, Attribute::Preallocated);
2294 
2295   auto *M = F->getParent();
2296 
2297   IRBuilder<> Builder(M->getContext());
2298 
2299   // Cannot modify users() while iterating over it, so make a copy.
2300   SmallVector<User *, 4> PreallocatedCalls(F->users());
2301   for (User *U : PreallocatedCalls) {
2302     CallBase *CB = dyn_cast<CallBase>(U);
2303     if (!CB)
2304       continue;
2305 
2306     assert(
2307         !CB->isMustTailCall() &&
2308         "Shouldn't call RemotePreallocated() on a musttail preallocated call");
2309     // Create copy of call without "preallocated" operand bundle.
2310     SmallVector<OperandBundleDef, 1> OpBundles;
2311     CB->getOperandBundlesAsDefs(OpBundles);
2312     CallBase *PreallocatedSetup = nullptr;
2313     for (auto *It = OpBundles.begin(); It != OpBundles.end(); ++It) {
2314       if (It->getTag() == "preallocated") {
2315         PreallocatedSetup = cast<CallBase>(*It->input_begin());
2316         OpBundles.erase(It);
2317         break;
2318       }
2319     }
2320     assert(PreallocatedSetup && "Did not find preallocated bundle");
2321     uint64_t ArgCount =
2322         cast<ConstantInt>(PreallocatedSetup->getArgOperand(0))->getZExtValue();
2323 
2324     assert((isa<CallInst>(CB) || isa<InvokeInst>(CB)) &&
2325            "Unknown indirect call type");
2326     CallBase *NewCB = CallBase::Create(CB, OpBundles, CB);
2327     CB->replaceAllUsesWith(NewCB);
2328     NewCB->takeName(CB);
2329     CB->eraseFromParent();
2330 
2331     Builder.SetInsertPoint(PreallocatedSetup);
2332     auto *StackSave =
2333         Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stacksave));
2334 
2335     Builder.SetInsertPoint(NewCB->getNextNonDebugInstruction());
2336     Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackrestore),
2337                        StackSave);
2338 
2339     // Replace @llvm.call.preallocated.arg() with alloca.
2340     // Cannot modify users() while iterating over it, so make a copy.
2341     // @llvm.call.preallocated.arg() can be called with the same index multiple
2342     // times. So for each @llvm.call.preallocated.arg(), we see if we have
2343     // already created a Value* for the index, and if not, create an alloca and
2344     // bitcast right after the @llvm.call.preallocated.setup() so that it
2345     // dominates all uses.
2346     SmallVector<Value *, 2> ArgAllocas(ArgCount);
2347     SmallVector<User *, 2> PreallocatedArgs(PreallocatedSetup->users());
2348     for (auto *User : PreallocatedArgs) {
2349       auto *UseCall = cast<CallBase>(User);
2350       assert(UseCall->getCalledFunction()->getIntrinsicID() ==
2351                  Intrinsic::call_preallocated_arg &&
2352              "preallocated token use was not a llvm.call.preallocated.arg");
2353       uint64_t AllocArgIndex =
2354           cast<ConstantInt>(UseCall->getArgOperand(1))->getZExtValue();
2355       Value *AllocaReplacement = ArgAllocas[AllocArgIndex];
2356       if (!AllocaReplacement) {
2357         auto AddressSpace = UseCall->getType()->getPointerAddressSpace();
2358         auto *ArgType = UseCall
2359                             ->getAttribute(AttributeList::FunctionIndex,
2360                                            Attribute::Preallocated)
2361                             .getValueAsType();
2362         auto *InsertBefore = PreallocatedSetup->getNextNonDebugInstruction();
2363         Builder.SetInsertPoint(InsertBefore);
2364         auto *Alloca =
2365             Builder.CreateAlloca(ArgType, AddressSpace, nullptr, "paarg");
2366         auto *BitCast = Builder.CreateBitCast(
2367             Alloca, Type::getInt8PtrTy(M->getContext()), UseCall->getName());
2368         ArgAllocas[AllocArgIndex] = BitCast;
2369         AllocaReplacement = BitCast;
2370       }
2371 
2372       UseCall->replaceAllUsesWith(AllocaReplacement);
2373       UseCall->eraseFromParent();
2374     }
2375     // Remove @llvm.call.preallocated.setup().
2376     cast<Instruction>(PreallocatedSetup)->eraseFromParent();
2377   }
2378 }
2379 
2380 static bool
2381 OptimizeFunctions(Module &M,
2382                   function_ref<TargetLibraryInfo &(Function &)> GetTLI,
2383                   function_ref<TargetTransformInfo &(Function &)> GetTTI,
2384                   function_ref<BlockFrequencyInfo &(Function &)> GetBFI,
2385                   function_ref<DominatorTree &(Function &)> LookupDomTree,
2386                   SmallPtrSetImpl<const Comdat *> &NotDiscardableComdats) {
2387 
2388   bool Changed = false;
2389 
2390   std::vector<Function *> AllCallsCold;
2391   for (Module::iterator FI = M.begin(), E = M.end(); FI != E;) {
2392     Function *F = &*FI++;
2393     if (hasOnlyColdCalls(*F, GetBFI))
2394       AllCallsCold.push_back(F);
2395   }
2396 
2397   // Optimize functions.
2398   for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
2399     Function *F = &*FI++;
2400 
2401     // Don't perform global opt pass on naked functions; we don't want fast
2402     // calling conventions for naked functions.
2403     if (F->hasFnAttribute(Attribute::Naked))
2404       continue;
2405 
2406     // Functions without names cannot be referenced outside this module.
2407     if (!F->hasName() && !F->isDeclaration() && !F->hasLocalLinkage())
2408       F->setLinkage(GlobalValue::InternalLinkage);
2409 
2410     if (deleteIfDead(*F, NotDiscardableComdats)) {
2411       Changed = true;
2412       continue;
2413     }
2414 
2415     // LLVM's definition of dominance allows instructions that are cyclic
2416     // in unreachable blocks, e.g.:
2417     // %pat = select i1 %condition, @global, i16* %pat
2418     // because any instruction dominates an instruction in a block that's
2419     // not reachable from entry.
2420     // So, remove unreachable blocks from the function, because a) there's
2421     // no point in analyzing them and b) GlobalOpt should otherwise grow
2422     // some more complicated logic to break these cycles.
2423     // Removing unreachable blocks might invalidate the dominator so we
2424     // recalculate it.
2425     if (!F->isDeclaration()) {
2426       if (removeUnreachableBlocks(*F)) {
2427         auto &DT = LookupDomTree(*F);
2428         DT.recalculate(*F);
2429         Changed = true;
2430       }
2431     }
2432 
2433     Changed |= processGlobal(*F, GetTLI, LookupDomTree);
2434 
2435     if (!F->hasLocalLinkage())
2436       continue;
2437 
2438     // If we have an inalloca parameter that we can safely remove the
2439     // inalloca attribute from, do so. This unlocks optimizations that
2440     // wouldn't be safe in the presence of inalloca.
2441     // FIXME: We should also hoist alloca affected by this to the entry
2442     // block if possible.
2443     if (F->getAttributes().hasAttrSomewhere(Attribute::InAlloca) &&
2444         !F->hasAddressTaken() && !hasMustTailCallers(F)) {
2445       RemoveAttribute(F, Attribute::InAlloca);
2446       Changed = true;
2447     }
2448 
2449     // FIXME: handle invokes
2450     // FIXME: handle musttail
2451     if (F->getAttributes().hasAttrSomewhere(Attribute::Preallocated)) {
2452       if (!F->hasAddressTaken() && !hasMustTailCallers(F) &&
2453           !hasInvokeCallers(F)) {
2454         RemovePreallocated(F);
2455         Changed = true;
2456       }
2457       continue;
2458     }
2459 
2460     if (hasChangeableCC(F) && !F->isVarArg() && !F->hasAddressTaken()) {
2461       NumInternalFunc++;
2462       TargetTransformInfo &TTI = GetTTI(*F);
2463       // Change the calling convention to coldcc if either stress testing is
2464       // enabled or the target would like to use coldcc on functions which are
2465       // cold at all call sites and the callers contain no other non coldcc
2466       // calls.
2467       if (EnableColdCCStressTest ||
2468           (TTI.useColdCCForColdCall(*F) &&
2469            isValidCandidateForColdCC(*F, GetBFI, AllCallsCold))) {
2470         F->setCallingConv(CallingConv::Cold);
2471         changeCallSitesToColdCC(F);
2472         Changed = true;
2473         NumColdCC++;
2474       }
2475     }
2476 
2477     if (hasChangeableCC(F) && !F->isVarArg() &&
2478         !F->hasAddressTaken()) {
2479       // If this function has a calling convention worth changing, is not a
2480       // varargs function, and is only called directly, promote it to use the
2481       // Fast calling convention.
2482       F->setCallingConv(CallingConv::Fast);
2483       ChangeCalleesToFastCall(F);
2484       ++NumFastCallFns;
2485       Changed = true;
2486     }
2487 
2488     if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
2489         !F->hasAddressTaken()) {
2490       // The function is not used by a trampoline intrinsic, so it is safe
2491       // to remove the 'nest' attribute.
2492       RemoveAttribute(F, Attribute::Nest);
2493       ++NumNestRemoved;
2494       Changed = true;
2495     }
2496   }
2497   return Changed;
2498 }
2499 
2500 static bool
2501 OptimizeGlobalVars(Module &M,
2502                    function_ref<TargetLibraryInfo &(Function &)> GetTLI,
2503                    function_ref<DominatorTree &(Function &)> LookupDomTree,
2504                    SmallPtrSetImpl<const Comdat *> &NotDiscardableComdats) {
2505   bool Changed = false;
2506 
2507   for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
2508        GVI != E; ) {
2509     GlobalVariable *GV = &*GVI++;
2510     // Global variables without names cannot be referenced outside this module.
2511     if (!GV->hasName() && !GV->isDeclaration() && !GV->hasLocalLinkage())
2512       GV->setLinkage(GlobalValue::InternalLinkage);
2513     // Simplify the initializer.
2514     if (GV->hasInitializer())
2515       if (auto *C = dyn_cast<Constant>(GV->getInitializer())) {
2516         auto &DL = M.getDataLayout();
2517         // TLI is not used in the case of a Constant, so use default nullptr
2518         // for that optional parameter, since we don't have a Function to
2519         // provide GetTLI anyway.
2520         Constant *New = ConstantFoldConstant(C, DL, /*TLI*/ nullptr);
2521         if (New != C)
2522           GV->setInitializer(New);
2523       }
2524 
2525     if (deleteIfDead(*GV, NotDiscardableComdats)) {
2526       Changed = true;
2527       continue;
2528     }
2529 
2530     Changed |= processGlobal(*GV, GetTLI, LookupDomTree);
2531   }
2532   return Changed;
2533 }
2534 
2535 /// Evaluate a piece of a constantexpr store into a global initializer.  This
2536 /// returns 'Init' modified to reflect 'Val' stored into it.  At this point, the
2537 /// GEP operands of Addr [0, OpNo) have been stepped into.
2538 static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
2539                                    ConstantExpr *Addr, unsigned OpNo) {
2540   // Base case of the recursion.
2541   if (OpNo == Addr->getNumOperands()) {
2542     assert(Val->getType() == Init->getType() && "Type mismatch!");
2543     return Val;
2544   }
2545 
2546   SmallVector<Constant*, 32> Elts;
2547   if (StructType *STy = dyn_cast<StructType>(Init->getType())) {
2548     // Break up the constant into its elements.
2549     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2550       Elts.push_back(Init->getAggregateElement(i));
2551 
2552     // Replace the element that we are supposed to.
2553     ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2554     unsigned Idx = CU->getZExtValue();
2555     assert(Idx < STy->getNumElements() && "Struct index out of range!");
2556     Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
2557 
2558     // Return the modified struct.
2559     return ConstantStruct::get(STy, Elts);
2560   }
2561 
2562   ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
2563   uint64_t NumElts;
2564   if (ArrayType *ATy = dyn_cast<ArrayType>(Init->getType()))
2565     NumElts = ATy->getNumElements();
2566   else
2567     NumElts = cast<FixedVectorType>(Init->getType())->getNumElements();
2568 
2569   // Break up the array into elements.
2570   for (uint64_t i = 0, e = NumElts; i != e; ++i)
2571     Elts.push_back(Init->getAggregateElement(i));
2572 
2573   assert(CI->getZExtValue() < NumElts);
2574   Elts[CI->getZExtValue()] =
2575     EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
2576 
2577   if (Init->getType()->isArrayTy())
2578     return ConstantArray::get(cast<ArrayType>(Init->getType()), Elts);
2579   return ConstantVector::get(Elts);
2580 }
2581 
2582 /// We have decided that Addr (which satisfies the predicate
2583 /// isSimpleEnoughPointerToCommit) should get Val as its value.  Make it happen.
2584 static void CommitValueTo(Constant *Val, Constant *Addr) {
2585   if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2586     assert(GV->hasInitializer());
2587     GV->setInitializer(Val);
2588     return;
2589   }
2590 
2591   ConstantExpr *CE = cast<ConstantExpr>(Addr);
2592   GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2593   GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
2594 }
2595 
2596 /// Given a map of address -> value, where addresses are expected to be some form
2597 /// of either a global or a constant GEP, set the initializer for the address to
2598 /// be the value. This performs mostly the same function as CommitValueTo()
2599 /// and EvaluateStoreInto() but is optimized to be more efficient for the common
2600 /// case where the set of addresses are GEPs sharing the same underlying global,
2601 /// processing the GEPs in batches rather than individually.
2602 ///
2603 /// To give an example, consider the following C++ code adapted from the clang
2604 /// regression tests:
2605 /// struct S {
2606 ///  int n = 10;
2607 ///  int m = 2 * n;
2608 ///  S(int a) : n(a) {}
2609 /// };
2610 ///
2611 /// template<typename T>
2612 /// struct U {
2613 ///  T *r = &q;
2614 ///  T q = 42;
2615 ///  U *p = this;
2616 /// };
2617 ///
2618 /// U<S> e;
2619 ///
2620 /// The global static constructor for 'e' will need to initialize 'r' and 'p' of
2621 /// the outer struct, while also initializing the inner 'q' structs 'n' and 'm'
2622 /// members. This batch algorithm will simply use general CommitValueTo() method
2623 /// to handle the complex nested S struct initialization of 'q', before
2624 /// processing the outermost members in a single batch. Using CommitValueTo() to
2625 /// handle member in the outer struct is inefficient when the struct/array is
2626 /// very large as we end up creating and destroy constant arrays for each
2627 /// initialization.
2628 /// For the above case, we expect the following IR to be generated:
2629 ///
2630 /// %struct.U = type { %struct.S*, %struct.S, %struct.U* }
2631 /// %struct.S = type { i32, i32 }
2632 /// @e = global %struct.U { %struct.S* gep inbounds (%struct.U, %struct.U* @e,
2633 ///                                                  i64 0, i32 1),
2634 ///                         %struct.S { i32 42, i32 84 }, %struct.U* @e }
2635 /// The %struct.S { i32 42, i32 84 } inner initializer is treated as a complex
2636 /// constant expression, while the other two elements of @e are "simple".
2637 static void BatchCommitValueTo(const DenseMap<Constant*, Constant*> &Mem) {
2638   SmallVector<std::pair<GlobalVariable*, Constant*>, 32> GVs;
2639   SmallVector<std::pair<ConstantExpr*, Constant*>, 32> ComplexCEs;
2640   SmallVector<std::pair<ConstantExpr*, Constant*>, 32> SimpleCEs;
2641   SimpleCEs.reserve(Mem.size());
2642 
2643   for (const auto &I : Mem) {
2644     if (auto *GV = dyn_cast<GlobalVariable>(I.first)) {
2645       GVs.push_back(std::make_pair(GV, I.second));
2646     } else {
2647       ConstantExpr *GEP = cast<ConstantExpr>(I.first);
2648       // We don't handle the deeply recursive case using the batch method.
2649       if (GEP->getNumOperands() > 3)
2650         ComplexCEs.push_back(std::make_pair(GEP, I.second));
2651       else
2652         SimpleCEs.push_back(std::make_pair(GEP, I.second));
2653     }
2654   }
2655 
2656   // The algorithm below doesn't handle cases like nested structs, so use the
2657   // slower fully general method if we have to.
2658   for (auto ComplexCE : ComplexCEs)
2659     CommitValueTo(ComplexCE.second, ComplexCE.first);
2660 
2661   for (auto GVPair : GVs) {
2662     assert(GVPair.first->hasInitializer());
2663     GVPair.first->setInitializer(GVPair.second);
2664   }
2665 
2666   if (SimpleCEs.empty())
2667     return;
2668 
2669   // We cache a single global's initializer elements in the case where the
2670   // subsequent address/val pair uses the same one. This avoids throwing away and
2671   // rebuilding the constant struct/vector/array just because one element is
2672   // modified at a time.
2673   SmallVector<Constant *, 32> Elts;
2674   Elts.reserve(SimpleCEs.size());
2675   GlobalVariable *CurrentGV = nullptr;
2676 
2677   auto commitAndSetupCache = [&](GlobalVariable *GV, bool Update) {
2678     Constant *Init = GV->getInitializer();
2679     Type *Ty = Init->getType();
2680     if (Update) {
2681       if (CurrentGV) {
2682         assert(CurrentGV && "Expected a GV to commit to!");
2683         Type *CurrentInitTy = CurrentGV->getInitializer()->getType();
2684         // We have a valid cache that needs to be committed.
2685         if (StructType *STy = dyn_cast<StructType>(CurrentInitTy))
2686           CurrentGV->setInitializer(ConstantStruct::get(STy, Elts));
2687         else if (ArrayType *ArrTy = dyn_cast<ArrayType>(CurrentInitTy))
2688           CurrentGV->setInitializer(ConstantArray::get(ArrTy, Elts));
2689         else
2690           CurrentGV->setInitializer(ConstantVector::get(Elts));
2691       }
2692       if (CurrentGV == GV)
2693         return;
2694       // Need to clear and set up cache for new initializer.
2695       CurrentGV = GV;
2696       Elts.clear();
2697       unsigned NumElts;
2698       if (auto *STy = dyn_cast<StructType>(Ty))
2699         NumElts = STy->getNumElements();
2700       else if (auto *ATy = dyn_cast<ArrayType>(Ty))
2701         NumElts = ATy->getNumElements();
2702       else
2703         NumElts = cast<FixedVectorType>(Ty)->getNumElements();
2704       for (unsigned i = 0, e = NumElts; i != e; ++i)
2705         Elts.push_back(Init->getAggregateElement(i));
2706     }
2707   };
2708 
2709   for (auto CEPair : SimpleCEs) {
2710     ConstantExpr *GEP = CEPair.first;
2711     Constant *Val = CEPair.second;
2712 
2713     GlobalVariable *GV = cast<GlobalVariable>(GEP->getOperand(0));
2714     commitAndSetupCache(GV, GV != CurrentGV);
2715     ConstantInt *CI = cast<ConstantInt>(GEP->getOperand(2));
2716     Elts[CI->getZExtValue()] = Val;
2717   }
2718   // The last initializer in the list needs to be committed, others
2719   // will be committed on a new initializer being processed.
2720   commitAndSetupCache(CurrentGV, true);
2721 }
2722 
2723 /// Evaluate static constructors in the function, if we can.  Return true if we
2724 /// can, false otherwise.
2725 static bool EvaluateStaticConstructor(Function *F, const DataLayout &DL,
2726                                       TargetLibraryInfo *TLI) {
2727   // Call the function.
2728   Evaluator Eval(DL, TLI);
2729   Constant *RetValDummy;
2730   bool EvalSuccess = Eval.EvaluateFunction(F, RetValDummy,
2731                                            SmallVector<Constant*, 0>());
2732 
2733   if (EvalSuccess) {
2734     ++NumCtorsEvaluated;
2735 
2736     // We succeeded at evaluation: commit the result.
2737     LLVM_DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
2738                       << F->getName() << "' to "
2739                       << Eval.getMutatedMemory().size() << " stores.\n");
2740     BatchCommitValueTo(Eval.getMutatedMemory());
2741     for (GlobalVariable *GV : Eval.getInvariants())
2742       GV->setConstant(true);
2743   }
2744 
2745   return EvalSuccess;
2746 }
2747 
2748 static int compareNames(Constant *const *A, Constant *const *B) {
2749   Value *AStripped = (*A)->stripPointerCasts();
2750   Value *BStripped = (*B)->stripPointerCasts();
2751   return AStripped->getName().compare(BStripped->getName());
2752 }
2753 
2754 static void setUsedInitializer(GlobalVariable &V,
2755                                const SmallPtrSetImpl<GlobalValue *> &Init) {
2756   if (Init.empty()) {
2757     V.eraseFromParent();
2758     return;
2759   }
2760 
2761   // Type of pointer to the array of pointers.
2762   PointerType *Int8PtrTy = Type::getInt8PtrTy(V.getContext(), 0);
2763 
2764   SmallVector<Constant *, 8> UsedArray;
2765   for (GlobalValue *GV : Init) {
2766     Constant *Cast
2767       = ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, Int8PtrTy);
2768     UsedArray.push_back(Cast);
2769   }
2770   // Sort to get deterministic order.
2771   array_pod_sort(UsedArray.begin(), UsedArray.end(), compareNames);
2772   ArrayType *ATy = ArrayType::get(Int8PtrTy, UsedArray.size());
2773 
2774   Module *M = V.getParent();
2775   V.removeFromParent();
2776   GlobalVariable *NV =
2777       new GlobalVariable(*M, ATy, false, GlobalValue::AppendingLinkage,
2778                          ConstantArray::get(ATy, UsedArray), "");
2779   NV->takeName(&V);
2780   NV->setSection("llvm.metadata");
2781   delete &V;
2782 }
2783 
2784 namespace {
2785 
2786 /// An easy to access representation of llvm.used and llvm.compiler.used.
2787 class LLVMUsed {
2788   SmallPtrSet<GlobalValue *, 8> Used;
2789   SmallPtrSet<GlobalValue *, 8> CompilerUsed;
2790   GlobalVariable *UsedV;
2791   GlobalVariable *CompilerUsedV;
2792 
2793 public:
2794   LLVMUsed(Module &M) {
2795     UsedV = collectUsedGlobalVariables(M, Used, false);
2796     CompilerUsedV = collectUsedGlobalVariables(M, CompilerUsed, true);
2797   }
2798 
2799   using iterator = SmallPtrSet<GlobalValue *, 8>::iterator;
2800   using used_iterator_range = iterator_range<iterator>;
2801 
2802   iterator usedBegin() { return Used.begin(); }
2803   iterator usedEnd() { return Used.end(); }
2804 
2805   used_iterator_range used() {
2806     return used_iterator_range(usedBegin(), usedEnd());
2807   }
2808 
2809   iterator compilerUsedBegin() { return CompilerUsed.begin(); }
2810   iterator compilerUsedEnd() { return CompilerUsed.end(); }
2811 
2812   used_iterator_range compilerUsed() {
2813     return used_iterator_range(compilerUsedBegin(), compilerUsedEnd());
2814   }
2815 
2816   bool usedCount(GlobalValue *GV) const { return Used.count(GV); }
2817 
2818   bool compilerUsedCount(GlobalValue *GV) const {
2819     return CompilerUsed.count(GV);
2820   }
2821 
2822   bool usedErase(GlobalValue *GV) { return Used.erase(GV); }
2823   bool compilerUsedErase(GlobalValue *GV) { return CompilerUsed.erase(GV); }
2824   bool usedInsert(GlobalValue *GV) { return Used.insert(GV).second; }
2825 
2826   bool compilerUsedInsert(GlobalValue *GV) {
2827     return CompilerUsed.insert(GV).second;
2828   }
2829 
2830   void syncVariablesAndSets() {
2831     if (UsedV)
2832       setUsedInitializer(*UsedV, Used);
2833     if (CompilerUsedV)
2834       setUsedInitializer(*CompilerUsedV, CompilerUsed);
2835   }
2836 };
2837 
2838 } // end anonymous namespace
2839 
2840 static bool hasUseOtherThanLLVMUsed(GlobalAlias &GA, const LLVMUsed &U) {
2841   if (GA.use_empty()) // No use at all.
2842     return false;
2843 
2844   assert((!U.usedCount(&GA) || !U.compilerUsedCount(&GA)) &&
2845          "We should have removed the duplicated "
2846          "element from llvm.compiler.used");
2847   if (!GA.hasOneUse())
2848     // Strictly more than one use. So at least one is not in llvm.used and
2849     // llvm.compiler.used.
2850     return true;
2851 
2852   // Exactly one use. Check if it is in llvm.used or llvm.compiler.used.
2853   return !U.usedCount(&GA) && !U.compilerUsedCount(&GA);
2854 }
2855 
2856 static bool hasMoreThanOneUseOtherThanLLVMUsed(GlobalValue &V,
2857                                                const LLVMUsed &U) {
2858   unsigned N = 2;
2859   assert((!U.usedCount(&V) || !U.compilerUsedCount(&V)) &&
2860          "We should have removed the duplicated "
2861          "element from llvm.compiler.used");
2862   if (U.usedCount(&V) || U.compilerUsedCount(&V))
2863     ++N;
2864   return V.hasNUsesOrMore(N);
2865 }
2866 
2867 static bool mayHaveOtherReferences(GlobalAlias &GA, const LLVMUsed &U) {
2868   if (!GA.hasLocalLinkage())
2869     return true;
2870 
2871   return U.usedCount(&GA) || U.compilerUsedCount(&GA);
2872 }
2873 
2874 static bool hasUsesToReplace(GlobalAlias &GA, const LLVMUsed &U,
2875                              bool &RenameTarget) {
2876   RenameTarget = false;
2877   bool Ret = false;
2878   if (hasUseOtherThanLLVMUsed(GA, U))
2879     Ret = true;
2880 
2881   // If the alias is externally visible, we may still be able to simplify it.
2882   if (!mayHaveOtherReferences(GA, U))
2883     return Ret;
2884 
2885   // If the aliasee has internal linkage, give it the name and linkage
2886   // of the alias, and delete the alias.  This turns:
2887   //   define internal ... @f(...)
2888   //   @a = alias ... @f
2889   // into:
2890   //   define ... @a(...)
2891   Constant *Aliasee = GA.getAliasee();
2892   GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
2893   if (!Target->hasLocalLinkage())
2894     return Ret;
2895 
2896   // Do not perform the transform if multiple aliases potentially target the
2897   // aliasee. This check also ensures that it is safe to replace the section
2898   // and other attributes of the aliasee with those of the alias.
2899   if (hasMoreThanOneUseOtherThanLLVMUsed(*Target, U))
2900     return Ret;
2901 
2902   RenameTarget = true;
2903   return true;
2904 }
2905 
2906 static bool
2907 OptimizeGlobalAliases(Module &M,
2908                       SmallPtrSetImpl<const Comdat *> &NotDiscardableComdats) {
2909   bool Changed = false;
2910   LLVMUsed Used(M);
2911 
2912   for (GlobalValue *GV : Used.used())
2913     Used.compilerUsedErase(GV);
2914 
2915   for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
2916        I != E;) {
2917     GlobalAlias *J = &*I++;
2918 
2919     // Aliases without names cannot be referenced outside this module.
2920     if (!J->hasName() && !J->isDeclaration() && !J->hasLocalLinkage())
2921       J->setLinkage(GlobalValue::InternalLinkage);
2922 
2923     if (deleteIfDead(*J, NotDiscardableComdats)) {
2924       Changed = true;
2925       continue;
2926     }
2927 
2928     // If the alias can change at link time, nothing can be done - bail out.
2929     if (J->isInterposable())
2930       continue;
2931 
2932     Constant *Aliasee = J->getAliasee();
2933     GlobalValue *Target = dyn_cast<GlobalValue>(Aliasee->stripPointerCasts());
2934     // We can't trivially replace the alias with the aliasee if the aliasee is
2935     // non-trivial in some way.
2936     // TODO: Try to handle non-zero GEPs of local aliasees.
2937     if (!Target)
2938       continue;
2939     Target->removeDeadConstantUsers();
2940 
2941     // Make all users of the alias use the aliasee instead.
2942     bool RenameTarget;
2943     if (!hasUsesToReplace(*J, Used, RenameTarget))
2944       continue;
2945 
2946     J->replaceAllUsesWith(ConstantExpr::getBitCast(Aliasee, J->getType()));
2947     ++NumAliasesResolved;
2948     Changed = true;
2949 
2950     if (RenameTarget) {
2951       // Give the aliasee the name, linkage and other attributes of the alias.
2952       Target->takeName(&*J);
2953       Target->setLinkage(J->getLinkage());
2954       Target->setDSOLocal(J->isDSOLocal());
2955       Target->setVisibility(J->getVisibility());
2956       Target->setDLLStorageClass(J->getDLLStorageClass());
2957 
2958       if (Used.usedErase(&*J))
2959         Used.usedInsert(Target);
2960 
2961       if (Used.compilerUsedErase(&*J))
2962         Used.compilerUsedInsert(Target);
2963     } else if (mayHaveOtherReferences(*J, Used))
2964       continue;
2965 
2966     // Delete the alias.
2967     M.getAliasList().erase(J);
2968     ++NumAliasesRemoved;
2969     Changed = true;
2970   }
2971 
2972   Used.syncVariablesAndSets();
2973 
2974   return Changed;
2975 }
2976 
2977 static Function *
2978 FindCXAAtExit(Module &M, function_ref<TargetLibraryInfo &(Function &)> GetTLI) {
2979   // Hack to get a default TLI before we have actual Function.
2980   auto FuncIter = M.begin();
2981   if (FuncIter == M.end())
2982     return nullptr;
2983   auto *TLI = &GetTLI(*FuncIter);
2984 
2985   LibFunc F = LibFunc_cxa_atexit;
2986   if (!TLI->has(F))
2987     return nullptr;
2988 
2989   Function *Fn = M.getFunction(TLI->getName(F));
2990   if (!Fn)
2991     return nullptr;
2992 
2993   // Now get the actual TLI for Fn.
2994   TLI = &GetTLI(*Fn);
2995 
2996   // Make sure that the function has the correct prototype.
2997   if (!TLI->getLibFunc(*Fn, F) || F != LibFunc_cxa_atexit)
2998     return nullptr;
2999 
3000   return Fn;
3001 }
3002 
3003 /// Returns whether the given function is an empty C++ destructor and can
3004 /// therefore be eliminated.
3005 /// Note that we assume that other optimization passes have already simplified
3006 /// the code so we simply check for 'ret'.
3007 static bool cxxDtorIsEmpty(const Function &Fn) {
3008   // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
3009   // nounwind, but that doesn't seem worth doing.
3010   if (Fn.isDeclaration())
3011     return false;
3012 
3013   for (auto &I : Fn.getEntryBlock()) {
3014     if (isa<DbgInfoIntrinsic>(I))
3015       continue;
3016     if (isa<ReturnInst>(I))
3017       return true;
3018     break;
3019   }
3020   return false;
3021 }
3022 
3023 static bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) {
3024   /// Itanium C++ ABI p3.3.5:
3025   ///
3026   ///   After constructing a global (or local static) object, that will require
3027   ///   destruction on exit, a termination function is registered as follows:
3028   ///
3029   ///   extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
3030   ///
3031   ///   This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
3032   ///   call f(p) when DSO d is unloaded, before all such termination calls
3033   ///   registered before this one. It returns zero if registration is
3034   ///   successful, nonzero on failure.
3035 
3036   // This pass will look for calls to __cxa_atexit where the function is trivial
3037   // and remove them.
3038   bool Changed = false;
3039 
3040   for (auto I = CXAAtExitFn->user_begin(), E = CXAAtExitFn->user_end();
3041        I != E;) {
3042     // We're only interested in calls. Theoretically, we could handle invoke
3043     // instructions as well, but neither llvm-gcc nor clang generate invokes
3044     // to __cxa_atexit.
3045     CallInst *CI = dyn_cast<CallInst>(*I++);
3046     if (!CI)
3047       continue;
3048 
3049     Function *DtorFn =
3050       dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts());
3051     if (!DtorFn || !cxxDtorIsEmpty(*DtorFn))
3052       continue;
3053 
3054     // Just remove the call.
3055     CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
3056     CI->eraseFromParent();
3057 
3058     ++NumCXXDtorsRemoved;
3059 
3060     Changed |= true;
3061   }
3062 
3063   return Changed;
3064 }
3065 
3066 static bool optimizeGlobalsInModule(
3067     Module &M, const DataLayout &DL,
3068     function_ref<TargetLibraryInfo &(Function &)> GetTLI,
3069     function_ref<TargetTransformInfo &(Function &)> GetTTI,
3070     function_ref<BlockFrequencyInfo &(Function &)> GetBFI,
3071     function_ref<DominatorTree &(Function &)> LookupDomTree) {
3072   SmallPtrSet<const Comdat *, 8> NotDiscardableComdats;
3073   bool Changed = false;
3074   bool LocalChange = true;
3075   while (LocalChange) {
3076     LocalChange = false;
3077 
3078     NotDiscardableComdats.clear();
3079     for (const GlobalVariable &GV : M.globals())
3080       if (const Comdat *C = GV.getComdat())
3081         if (!GV.isDiscardableIfUnused() || !GV.use_empty())
3082           NotDiscardableComdats.insert(C);
3083     for (Function &F : M)
3084       if (const Comdat *C = F.getComdat())
3085         if (!F.isDefTriviallyDead())
3086           NotDiscardableComdats.insert(C);
3087     for (GlobalAlias &GA : M.aliases())
3088       if (const Comdat *C = GA.getComdat())
3089         if (!GA.isDiscardableIfUnused() || !GA.use_empty())
3090           NotDiscardableComdats.insert(C);
3091 
3092     // Delete functions that are trivially dead, ccc -> fastcc
3093     LocalChange |= OptimizeFunctions(M, GetTLI, GetTTI, GetBFI, LookupDomTree,
3094                                      NotDiscardableComdats);
3095 
3096     // Optimize global_ctors list.
3097     LocalChange |= optimizeGlobalCtorsList(M, [&](Function *F) {
3098       return EvaluateStaticConstructor(F, DL, &GetTLI(*F));
3099     });
3100 
3101     // Optimize non-address-taken globals.
3102     LocalChange |=
3103         OptimizeGlobalVars(M, GetTLI, LookupDomTree, NotDiscardableComdats);
3104 
3105     // Resolve aliases, when possible.
3106     LocalChange |= OptimizeGlobalAliases(M, NotDiscardableComdats);
3107 
3108     // Try to remove trivial global destructors if they are not removed
3109     // already.
3110     Function *CXAAtExitFn = FindCXAAtExit(M, GetTLI);
3111     if (CXAAtExitFn)
3112       LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn);
3113 
3114     Changed |= LocalChange;
3115   }
3116 
3117   // TODO: Move all global ctors functions to the end of the module for code
3118   // layout.
3119 
3120   return Changed;
3121 }
3122 
3123 PreservedAnalyses GlobalOptPass::run(Module &M, ModuleAnalysisManager &AM) {
3124     auto &DL = M.getDataLayout();
3125     auto &FAM =
3126         AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
3127     auto LookupDomTree = [&FAM](Function &F) -> DominatorTree &{
3128       return FAM.getResult<DominatorTreeAnalysis>(F);
3129     };
3130     auto GetTLI = [&FAM](Function &F) -> TargetLibraryInfo & {
3131       return FAM.getResult<TargetLibraryAnalysis>(F);
3132     };
3133     auto GetTTI = [&FAM](Function &F) -> TargetTransformInfo & {
3134       return FAM.getResult<TargetIRAnalysis>(F);
3135     };
3136 
3137     auto GetBFI = [&FAM](Function &F) -> BlockFrequencyInfo & {
3138       return FAM.getResult<BlockFrequencyAnalysis>(F);
3139     };
3140 
3141     if (!optimizeGlobalsInModule(M, DL, GetTLI, GetTTI, GetBFI, LookupDomTree))
3142       return PreservedAnalyses::all();
3143     return PreservedAnalyses::none();
3144 }
3145 
3146 namespace {
3147 
3148 struct GlobalOptLegacyPass : public ModulePass {
3149   static char ID; // Pass identification, replacement for typeid
3150 
3151   GlobalOptLegacyPass() : ModulePass(ID) {
3152     initializeGlobalOptLegacyPassPass(*PassRegistry::getPassRegistry());
3153   }
3154 
3155   bool runOnModule(Module &M) override {
3156     if (skipModule(M))
3157       return false;
3158 
3159     auto &DL = M.getDataLayout();
3160     auto LookupDomTree = [this](Function &F) -> DominatorTree & {
3161       return this->getAnalysis<DominatorTreeWrapperPass>(F).getDomTree();
3162     };
3163     auto GetTLI = [this](Function &F) -> TargetLibraryInfo & {
3164       return this->getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
3165     };
3166     auto GetTTI = [this](Function &F) -> TargetTransformInfo & {
3167       return this->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
3168     };
3169 
3170     auto GetBFI = [this](Function &F) -> BlockFrequencyInfo & {
3171       return this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
3172     };
3173 
3174     return optimizeGlobalsInModule(M, DL, GetTLI, GetTTI, GetBFI,
3175                                    LookupDomTree);
3176   }
3177 
3178   void getAnalysisUsage(AnalysisUsage &AU) const override {
3179     AU.addRequired<TargetLibraryInfoWrapperPass>();
3180     AU.addRequired<TargetTransformInfoWrapperPass>();
3181     AU.addRequired<DominatorTreeWrapperPass>();
3182     AU.addRequired<BlockFrequencyInfoWrapperPass>();
3183   }
3184 };
3185 
3186 } // end anonymous namespace
3187 
3188 char GlobalOptLegacyPass::ID = 0;
3189 
3190 INITIALIZE_PASS_BEGIN(GlobalOptLegacyPass, "globalopt",
3191                       "Global Variable Optimizer", false, false)
3192 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
3193 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
3194 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
3195 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
3196 INITIALIZE_PASS_END(GlobalOptLegacyPass, "globalopt",
3197                     "Global Variable Optimizer", false, false)
3198 
3199 ModulePass *llvm::createGlobalOptimizerPass() {
3200   return new GlobalOptLegacyPass();
3201 }
3202