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