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