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