1 //===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass transforms simple global variables that never have their address
11 // taken. If obviously true, it marks read/write globals as constant, deletes
12 // variables only stored to, etc.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "globalopt"
17 #include "llvm/Transforms/IPO.h"
18 #include "llvm/CallingConv.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/IntrinsicInst.h"
23 #include "llvm/Module.h"
24 #include "llvm/Operator.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Analysis/ConstantFolding.h"
27 #include "llvm/Analysis/MemoryBuiltins.h"
28 #include "llvm/Target/TargetData.h"
29 #include "llvm/Target/TargetLibraryInfo.h"
30 #include "llvm/Support/CallSite.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/GetElementPtrTypeIterator.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/ADT/DenseMap.h"
37 #include "llvm/ADT/SmallPtrSet.h"
38 #include "llvm/ADT/SmallVector.h"
39 #include "llvm/ADT/Statistic.h"
40 #include "llvm/ADT/STLExtras.h"
44 STATISTIC(NumMarked , "Number of globals marked constant");
45 STATISTIC(NumUnnamed , "Number of globals marked unnamed_addr");
46 STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
47 STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
48 STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
49 STATISTIC(NumDeleted , "Number of globals deleted");
50 STATISTIC(NumFnDeleted , "Number of functions deleted");
51 STATISTIC(NumGlobUses , "Number of global uses devirtualized");
52 STATISTIC(NumLocalized , "Number of globals localized");
53 STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
54 STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
55 STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
56 STATISTIC(NumNestRemoved , "Number of nest attributes removed");
57 STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
58 STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
59 STATISTIC(NumCXXDtorsRemoved, "Number of global C++ destructors removed");
63 struct GlobalOpt : public ModulePass {
64 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
65 AU.addRequired<TargetLibraryInfo>();
67 static char ID; // Pass identification, replacement for typeid
68 GlobalOpt() : ModulePass(ID) {
69 initializeGlobalOptPass(*PassRegistry::getPassRegistry());
72 bool runOnModule(Module &M);
75 GlobalVariable *FindGlobalCtors(Module &M);
76 bool OptimizeFunctions(Module &M);
77 bool OptimizeGlobalVars(Module &M);
78 bool OptimizeGlobalAliases(Module &M);
79 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
80 bool ProcessGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
81 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI,
82 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
83 const GlobalStatus &GS);
84 bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn);
87 TargetLibraryInfo *TLI;
91 char GlobalOpt::ID = 0;
92 INITIALIZE_PASS_BEGIN(GlobalOpt, "globalopt",
93 "Global Variable Optimizer", false, false)
94 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo)
95 INITIALIZE_PASS_END(GlobalOpt, "globalopt",
96 "Global Variable Optimizer", false, false)
98 ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
102 /// GlobalStatus - As we analyze each global, keep track of some information
103 /// about it. If we find out that the address of the global is taken, none of
104 /// this info will be accurate.
105 struct GlobalStatus {
106 /// isCompared - True if the global's address is used in a comparison.
109 /// isLoaded - True if the global is ever loaded. If the global isn't ever
110 /// loaded it can be deleted.
113 /// StoredType - Keep track of what stores to the global look like.
116 /// NotStored - There is no store to this global. It can thus be marked
120 /// isInitializerStored - This global is stored to, but the only thing
121 /// stored is the constant it was initialized with. This is only tracked
122 /// for scalar globals.
125 /// isStoredOnce - This global is stored to, but only its initializer and
126 /// one other value is ever stored to it. If this global isStoredOnce, we
127 /// track the value stored to it in StoredOnceValue below. This is only
128 /// tracked for scalar globals.
131 /// isStored - This global is stored to by multiple values or something else
132 /// that we cannot track.
136 /// StoredOnceValue - If only one value (besides the initializer constant) is
137 /// ever stored to this global, keep track of what value it is.
138 Value *StoredOnceValue;
140 /// AccessingFunction/HasMultipleAccessingFunctions - These start out
141 /// null/false. When the first accessing function is noticed, it is recorded.
142 /// When a second different accessing function is noticed,
143 /// HasMultipleAccessingFunctions is set to true.
144 const Function *AccessingFunction;
145 bool HasMultipleAccessingFunctions;
147 /// HasNonInstructionUser - Set to true if this global has a user that is not
148 /// an instruction (e.g. a constant expr or GV initializer).
149 bool HasNonInstructionUser;
151 /// HasPHIUser - Set to true if this global has a user that is a PHI node.
154 /// AtomicOrdering - Set to the strongest atomic ordering requirement.
155 AtomicOrdering Ordering;
157 GlobalStatus() : isCompared(false), isLoaded(false), StoredType(NotStored),
158 StoredOnceValue(0), AccessingFunction(0),
159 HasMultipleAccessingFunctions(false),
160 HasNonInstructionUser(false), HasPHIUser(false),
161 Ordering(NotAtomic) {}
166 /// StrongerOrdering - Return the stronger of the two ordering. If the two
167 /// orderings are acquire and release, then return AcquireRelease.
169 static AtomicOrdering StrongerOrdering(AtomicOrdering X, AtomicOrdering Y) {
170 if (X == Acquire && Y == Release) return AcquireRelease;
171 if (Y == Acquire && X == Release) return AcquireRelease;
172 return (AtomicOrdering)std::max(X, Y);
175 /// SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
176 /// by constants itself. Note that constants cannot be cyclic, so this test is
177 /// pretty easy to implement recursively.
179 static bool SafeToDestroyConstant(const Constant *C) {
180 if (isa<GlobalValue>(C)) return false;
182 for (Value::const_use_iterator UI = C->use_begin(), E = C->use_end(); UI != E;
184 if (const Constant *CU = dyn_cast<Constant>(*UI)) {
185 if (!SafeToDestroyConstant(CU)) return false;
192 /// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
193 /// structure. If the global has its address taken, return true to indicate we
194 /// can't do anything with it.
196 static bool AnalyzeGlobal(const Value *V, GlobalStatus &GS,
197 SmallPtrSet<const PHINode*, 16> &PHIUsers) {
198 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
201 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
202 GS.HasNonInstructionUser = true;
204 // If the result of the constantexpr isn't pointer type, then we won't
205 // know to expect it in various places. Just reject early.
206 if (!isa<PointerType>(CE->getType())) return true;
208 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
209 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
210 if (!GS.HasMultipleAccessingFunctions) {
211 const Function *F = I->getParent()->getParent();
212 if (GS.AccessingFunction == 0)
213 GS.AccessingFunction = F;
214 else if (GS.AccessingFunction != F)
215 GS.HasMultipleAccessingFunctions = true;
217 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
219 // Don't hack on volatile loads.
220 if (LI->isVolatile()) return true;
221 GS.Ordering = StrongerOrdering(GS.Ordering, LI->getOrdering());
222 } else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) {
223 // Don't allow a store OF the address, only stores TO the address.
224 if (SI->getOperand(0) == V) return true;
226 // Don't hack on volatile stores.
227 if (SI->isVolatile()) return true;
228 GS.Ordering = StrongerOrdering(GS.Ordering, SI->getOrdering());
230 // If this is a direct store to the global (i.e., the global is a scalar
231 // value, not an aggregate), keep more specific information about
233 if (GS.StoredType != GlobalStatus::isStored) {
234 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(
235 SI->getOperand(1))) {
236 Value *StoredVal = SI->getOperand(0);
237 if (StoredVal == GV->getInitializer()) {
238 if (GS.StoredType < GlobalStatus::isInitializerStored)
239 GS.StoredType = GlobalStatus::isInitializerStored;
240 } else if (isa<LoadInst>(StoredVal) &&
241 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
242 if (GS.StoredType < GlobalStatus::isInitializerStored)
243 GS.StoredType = GlobalStatus::isInitializerStored;
244 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
245 GS.StoredType = GlobalStatus::isStoredOnce;
246 GS.StoredOnceValue = StoredVal;
247 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
248 GS.StoredOnceValue == StoredVal) {
251 GS.StoredType = GlobalStatus::isStored;
254 GS.StoredType = GlobalStatus::isStored;
257 } else if (isa<BitCastInst>(I)) {
258 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
259 } else if (isa<GetElementPtrInst>(I)) {
260 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
261 } else if (isa<SelectInst>(I)) {
262 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
263 } else if (const PHINode *PN = dyn_cast<PHINode>(I)) {
264 // PHI nodes we can check just like select or GEP instructions, but we
265 // have to be careful about infinite recursion.
266 if (PHIUsers.insert(PN)) // Not already visited.
267 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
268 GS.HasPHIUser = true;
269 } else if (isa<CmpInst>(I)) {
270 GS.isCompared = true;
271 } else if (const MemTransferInst *MTI = dyn_cast<MemTransferInst>(I)) {
272 if (MTI->isVolatile()) return true;
273 if (MTI->getArgOperand(0) == V)
274 GS.StoredType = GlobalStatus::isStored;
275 if (MTI->getArgOperand(1) == V)
277 } else if (const MemSetInst *MSI = dyn_cast<MemSetInst>(I)) {
278 assert(MSI->getArgOperand(0) == V && "Memset only takes one pointer!");
279 if (MSI->isVolatile()) return true;
280 GS.StoredType = GlobalStatus::isStored;
282 return true; // Any other non-load instruction might take address!
284 } else if (const Constant *C = dyn_cast<Constant>(U)) {
285 GS.HasNonInstructionUser = true;
286 // We might have a dead and dangling constant hanging off of here.
287 if (!SafeToDestroyConstant(C))
290 GS.HasNonInstructionUser = true;
291 // Otherwise must be some other user.
299 /// isLeakCheckerRoot - Is this global variable possibly used by a leak checker
300 /// as a root? If so, we might not really want to eliminate the stores to it.
301 static bool isLeakCheckerRoot(GlobalVariable *GV) {
302 // A global variable is a root if it is a pointer, or could plausibly contain
303 // a pointer. There are two challenges; one is that we could have a struct
304 // the has an inner member which is a pointer. We recurse through the type to
305 // detect these (up to a point). The other is that we may actually be a union
306 // of a pointer and another type, and so our LLVM type is an integer which
307 // gets converted into a pointer, or our type is an [i8 x #] with a pointer
308 // potentially contained here.
310 if (GV->hasPrivateLinkage())
313 SmallVector<Type *, 4> Types;
314 Types.push_back(cast<PointerType>(GV->getType())->getElementType());
318 Type *Ty = Types.pop_back_val();
319 switch (Ty->getTypeID()) {
321 case Type::PointerTyID: return true;
322 case Type::ArrayTyID:
323 case Type::VectorTyID: {
324 SequentialType *STy = cast<SequentialType>(Ty);
325 Types.push_back(STy->getElementType());
328 case Type::StructTyID: {
329 StructType *STy = cast<StructType>(Ty);
330 if (STy->isOpaque()) return true;
331 for (StructType::element_iterator I = STy->element_begin(),
332 E = STy->element_end(); I != E; ++I) {
334 if (isa<PointerType>(InnerTy)) return true;
335 if (isa<CompositeType>(InnerTy))
336 Types.push_back(InnerTy);
341 if (--Limit == 0) return true;
342 } while (!Types.empty());
346 /// Given a value that is stored to a global but never read, determine whether
347 /// it's safe to remove the store and the chain of computation that feeds the
349 static bool IsSafeComputationToRemove(Value *V) {
351 if (isa<Constant>(V))
355 if (isa<LoadInst>(V) || isa<Argument>(V) || isa<GlobalValue>(V))
357 if (isAllocationFn(V))
360 Instruction *I = cast<Instruction>(V);
361 if (I->mayHaveSideEffects())
363 if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(I)) {
364 if (!GEP->hasAllConstantIndices())
366 } else if (I->getNumOperands() != 1) {
370 V = I->getOperand(0);
374 /// CleanupPointerRootUsers - This GV is a pointer root. Loop over all users
375 /// of the global and clean up any that obviously don't assign the global a
376 /// value that isn't dynamically allocated.
378 static bool CleanupPointerRootUsers(GlobalVariable *GV) {
379 // A brief explanation of leak checkers. The goal is to find bugs where
380 // pointers are forgotten, causing an accumulating growth in memory
381 // usage over time. The common strategy for leak checkers is to whitelist the
382 // memory pointed to by globals at exit. This is popular because it also
383 // solves another problem where the main thread of a C++ program may shut down
384 // before other threads that are still expecting to use those globals. To
385 // handle that case, we expect the program may create a singleton and never
388 bool Changed = false;
390 // If Dead[n].first is the only use of a malloc result, we can delete its
391 // chain of computation and the store to the global in Dead[n].second.
392 SmallVector<std::pair<Instruction *, Instruction *>, 32> Dead;
394 // Constants can't be pointers to dynamically allocated memory.
395 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
398 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
399 Value *V = SI->getValueOperand();
400 if (isa<Constant>(V)) {
402 SI->eraseFromParent();
403 } else if (Instruction *I = dyn_cast<Instruction>(V)) {
405 Dead.push_back(std::make_pair(I, SI));
407 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(U)) {
408 if (isa<Constant>(MSI->getValue())) {
410 MSI->eraseFromParent();
411 } else if (Instruction *I = dyn_cast<Instruction>(MSI->getValue())) {
413 Dead.push_back(std::make_pair(I, MSI));
415 } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(U)) {
416 GlobalVariable *MemSrc = dyn_cast<GlobalVariable>(MTI->getSource());
417 if (MemSrc && MemSrc->isConstant()) {
419 MTI->eraseFromParent();
420 } else if (Instruction *I = dyn_cast<Instruction>(MemSrc)) {
422 Dead.push_back(std::make_pair(I, MTI));
424 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
425 if (CE->use_empty()) {
426 CE->destroyConstant();
429 } else if (Constant *C = dyn_cast<Constant>(U)) {
430 if (SafeToDestroyConstant(C)) {
431 C->destroyConstant();
432 // This could have invalidated UI, start over from scratch.
434 CleanupPointerRootUsers(GV);
440 for (int i = 0, e = Dead.size(); i != e; ++i) {
441 if (IsSafeComputationToRemove(Dead[i].first)) {
442 Dead[i].second->eraseFromParent();
443 Instruction *I = Dead[i].first;
445 Instruction *J = dyn_cast<Instruction>(I->getOperand(0));
446 I->eraseFromParent();
450 } while (!isAllocationFn(I));
451 I->eraseFromParent();
458 /// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
459 /// users of the global, cleaning up the obvious ones. This is largely just a
460 /// quick scan over the use list to clean up the easy and obvious cruft. This
461 /// returns true if it made a change.
462 static bool CleanupConstantGlobalUsers(Value *V, Constant *Init,
463 TargetData *TD, TargetLibraryInfo *TLI) {
464 bool Changed = false;
465 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
468 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
470 // Replace the load with the initializer.
471 LI->replaceAllUsesWith(Init);
472 LI->eraseFromParent();
475 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
476 // Store must be unreachable or storing Init into the global.
477 SI->eraseFromParent();
479 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
480 if (CE->getOpcode() == Instruction::GetElementPtr) {
481 Constant *SubInit = 0;
483 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
484 Changed |= CleanupConstantGlobalUsers(CE, SubInit, TD, TLI);
485 } else if (CE->getOpcode() == Instruction::BitCast &&
486 CE->getType()->isPointerTy()) {
487 // Pointer cast, delete any stores and memsets to the global.
488 Changed |= CleanupConstantGlobalUsers(CE, 0, TD, TLI);
491 if (CE->use_empty()) {
492 CE->destroyConstant();
495 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
496 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
497 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
498 // and will invalidate our notion of what Init is.
499 Constant *SubInit = 0;
500 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
502 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP, TD, TLI));
503 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
504 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
506 // If the initializer is an all-null value and we have an inbounds GEP,
507 // we already know what the result of any load from that GEP is.
508 // TODO: Handle splats.
509 if (Init && isa<ConstantAggregateZero>(Init) && GEP->isInBounds())
510 SubInit = Constant::getNullValue(GEP->getType()->getElementType());
512 Changed |= CleanupConstantGlobalUsers(GEP, SubInit, TD, TLI);
514 if (GEP->use_empty()) {
515 GEP->eraseFromParent();
518 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
519 if (MI->getRawDest() == V) {
520 MI->eraseFromParent();
524 } else if (Constant *C = dyn_cast<Constant>(U)) {
525 // If we have a chain of dead constantexprs or other things dangling from
526 // us, and if they are all dead, nuke them without remorse.
527 if (SafeToDestroyConstant(C)) {
528 C->destroyConstant();
529 // This could have invalidated UI, start over from scratch.
530 CleanupConstantGlobalUsers(V, Init, TD, TLI);
538 /// isSafeSROAElementUse - Return true if the specified instruction is a safe
539 /// user of a derived expression from a global that we want to SROA.
540 static bool isSafeSROAElementUse(Value *V) {
541 // We might have a dead and dangling constant hanging off of here.
542 if (Constant *C = dyn_cast<Constant>(V))
543 return SafeToDestroyConstant(C);
545 Instruction *I = dyn_cast<Instruction>(V);
546 if (!I) return false;
549 if (isa<LoadInst>(I)) return true;
551 // Stores *to* the pointer are ok.
552 if (StoreInst *SI = dyn_cast<StoreInst>(I))
553 return SI->getOperand(0) != V;
555 // Otherwise, it must be a GEP.
556 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
557 if (GEPI == 0) return false;
559 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
560 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
563 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
565 if (!isSafeSROAElementUse(*I))
571 /// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
572 /// Look at it and its uses and decide whether it is safe to SROA this global.
574 static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
575 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
576 if (!isa<GetElementPtrInst>(U) &&
577 (!isa<ConstantExpr>(U) ||
578 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
581 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
582 // don't like < 3 operand CE's, and we don't like non-constant integer
583 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
585 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
586 !cast<Constant>(U->getOperand(1))->isNullValue() ||
587 !isa<ConstantInt>(U->getOperand(2)))
590 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
591 ++GEPI; // Skip over the pointer index.
593 // If this is a use of an array allocation, do a bit more checking for sanity.
594 if (ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
595 uint64_t NumElements = AT->getNumElements();
596 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
598 // Check to make sure that index falls within the array. If not,
599 // something funny is going on, so we won't do the optimization.
601 if (Idx->getZExtValue() >= NumElements)
604 // We cannot scalar repl this level of the array unless any array
605 // sub-indices are in-range constants. In particular, consider:
606 // A[0][i]. We cannot know that the user isn't doing invalid things like
607 // allowing i to index an out-of-range subscript that accesses A[1].
609 // Scalar replacing *just* the outer index of the array is probably not
610 // going to be a win anyway, so just give up.
611 for (++GEPI; // Skip array index.
614 uint64_t NumElements;
615 if (ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
616 NumElements = SubArrayTy->getNumElements();
617 else if (VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
618 NumElements = SubVectorTy->getNumElements();
620 assert((*GEPI)->isStructTy() &&
621 "Indexed GEP type is not array, vector, or struct!");
625 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
626 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
631 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
632 if (!isSafeSROAElementUse(*I))
637 /// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
638 /// is safe for us to perform this transformation.
640 static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
641 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
643 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
650 /// SRAGlobal - Perform scalar replacement of aggregates on the specified global
651 /// variable. This opens the door for other optimizations by exposing the
652 /// behavior of the program in a more fine-grained way. We have determined that
653 /// this transformation is safe already. We return the first global variable we
654 /// insert so that the caller can reprocess it.
655 static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD) {
656 // Make sure this global only has simple uses that we can SRA.
657 if (!GlobalUsersSafeToSRA(GV))
660 assert(GV->hasLocalLinkage() && !GV->isConstant());
661 Constant *Init = GV->getInitializer();
662 Type *Ty = Init->getType();
664 std::vector<GlobalVariable*> NewGlobals;
665 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
667 // Get the alignment of the global, either explicit or target-specific.
668 unsigned StartAlignment = GV->getAlignment();
669 if (StartAlignment == 0)
670 StartAlignment = TD.getABITypeAlignment(GV->getType());
672 if (StructType *STy = dyn_cast<StructType>(Ty)) {
673 NewGlobals.reserve(STy->getNumElements());
674 const StructLayout &Layout = *TD.getStructLayout(STy);
675 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
676 Constant *In = Init->getAggregateElement(i);
677 assert(In && "Couldn't get element of initializer?");
678 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
679 GlobalVariable::InternalLinkage,
680 In, GV->getName()+"."+Twine(i),
681 GV->getThreadLocalMode(),
682 GV->getType()->getAddressSpace());
683 Globals.insert(GV, NGV);
684 NewGlobals.push_back(NGV);
686 // Calculate the known alignment of the field. If the original aggregate
687 // had 256 byte alignment for example, something might depend on that:
688 // propagate info to each field.
689 uint64_t FieldOffset = Layout.getElementOffset(i);
690 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
691 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
692 NGV->setAlignment(NewAlign);
694 } else if (SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
695 unsigned NumElements = 0;
696 if (ArrayType *ATy = dyn_cast<ArrayType>(STy))
697 NumElements = ATy->getNumElements();
699 NumElements = cast<VectorType>(STy)->getNumElements();
701 if (NumElements > 16 && GV->hasNUsesOrMore(16))
702 return 0; // It's not worth it.
703 NewGlobals.reserve(NumElements);
705 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
706 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
707 for (unsigned i = 0, e = NumElements; i != e; ++i) {
708 Constant *In = Init->getAggregateElement(i);
709 assert(In && "Couldn't get element of initializer?");
711 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
712 GlobalVariable::InternalLinkage,
713 In, GV->getName()+"."+Twine(i),
714 GV->getThreadLocalMode(),
715 GV->getType()->getAddressSpace());
716 Globals.insert(GV, NGV);
717 NewGlobals.push_back(NGV);
719 // Calculate the known alignment of the field. If the original aggregate
720 // had 256 byte alignment for example, something might depend on that:
721 // propagate info to each field.
722 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
723 if (NewAlign > EltAlign)
724 NGV->setAlignment(NewAlign);
728 if (NewGlobals.empty())
731 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
733 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
735 // Loop over all of the uses of the global, replacing the constantexpr geps,
736 // with smaller constantexpr geps or direct references.
737 while (!GV->use_empty()) {
738 User *GEP = GV->use_back();
739 assert(((isa<ConstantExpr>(GEP) &&
740 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
741 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
743 // Ignore the 1th operand, which has to be zero or else the program is quite
744 // broken (undefined). Get the 2nd operand, which is the structure or array
746 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
747 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
749 Value *NewPtr = NewGlobals[Val];
751 // Form a shorter GEP if needed.
752 if (GEP->getNumOperands() > 3) {
753 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
754 SmallVector<Constant*, 8> Idxs;
755 Idxs.push_back(NullInt);
756 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
757 Idxs.push_back(CE->getOperand(i));
758 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
760 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
761 SmallVector<Value*, 8> Idxs;
762 Idxs.push_back(NullInt);
763 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
764 Idxs.push_back(GEPI->getOperand(i));
765 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs,
766 GEPI->getName()+"."+Twine(Val),GEPI);
769 GEP->replaceAllUsesWith(NewPtr);
771 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
772 GEPI->eraseFromParent();
774 cast<ConstantExpr>(GEP)->destroyConstant();
777 // Delete the old global, now that it is dead.
781 // Loop over the new globals array deleting any globals that are obviously
782 // dead. This can arise due to scalarization of a structure or an array that
783 // has elements that are dead.
784 unsigned FirstGlobal = 0;
785 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
786 if (NewGlobals[i]->use_empty()) {
787 Globals.erase(NewGlobals[i]);
788 if (FirstGlobal == i) ++FirstGlobal;
791 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
794 /// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
795 /// value will trap if the value is dynamically null. PHIs keeps track of any
796 /// phi nodes we've seen to avoid reprocessing them.
797 static bool AllUsesOfValueWillTrapIfNull(const Value *V,
798 SmallPtrSet<const PHINode*, 8> &PHIs) {
799 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
803 if (isa<LoadInst>(U)) {
805 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
806 if (SI->getOperand(0) == V) {
807 //cerr << "NONTRAPPING USE: " << *U;
808 return false; // Storing the value.
810 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
811 if (CI->getCalledValue() != V) {
812 //cerr << "NONTRAPPING USE: " << *U;
813 return false; // Not calling the ptr
815 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
816 if (II->getCalledValue() != V) {
817 //cerr << "NONTRAPPING USE: " << *U;
818 return false; // Not calling the ptr
820 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
821 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
822 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
823 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
824 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
825 // If we've already seen this phi node, ignore it, it has already been
827 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
829 } else if (isa<ICmpInst>(U) &&
830 isa<ConstantPointerNull>(UI->getOperand(1))) {
831 // Ignore icmp X, null
833 //cerr << "NONTRAPPING USE: " << *U;
840 /// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
841 /// from GV will trap if the loaded value is null. Note that this also permits
842 /// comparisons of the loaded value against null, as a special case.
843 static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
844 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
848 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
849 SmallPtrSet<const PHINode*, 8> PHIs;
850 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
852 } else if (isa<StoreInst>(U)) {
853 // Ignore stores to the global.
855 // We don't know or understand this user, bail out.
856 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
863 static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
864 bool Changed = false;
865 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
866 Instruction *I = cast<Instruction>(*UI++);
867 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
868 LI->setOperand(0, NewV);
870 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
871 if (SI->getOperand(1) == V) {
872 SI->setOperand(1, NewV);
875 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
877 if (CS.getCalledValue() == V) {
878 // Calling through the pointer! Turn into a direct call, but be careful
879 // that the pointer is not also being passed as an argument.
880 CS.setCalledFunction(NewV);
882 bool PassedAsArg = false;
883 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
884 if (CS.getArgument(i) == V) {
886 CS.setArgument(i, NewV);
890 // Being passed as an argument also. Be careful to not invalidate UI!
894 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
895 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
896 ConstantExpr::getCast(CI->getOpcode(),
897 NewV, CI->getType()));
898 if (CI->use_empty()) {
900 CI->eraseFromParent();
902 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
903 // Should handle GEP here.
904 SmallVector<Constant*, 8> Idxs;
905 Idxs.reserve(GEPI->getNumOperands()-1);
906 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
908 if (Constant *C = dyn_cast<Constant>(*i))
912 if (Idxs.size() == GEPI->getNumOperands()-1)
913 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
914 ConstantExpr::getGetElementPtr(NewV, Idxs));
915 if (GEPI->use_empty()) {
917 GEPI->eraseFromParent();
926 /// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
927 /// value stored into it. If there are uses of the loaded value that would trap
928 /// if the loaded value is dynamically null, then we know that they cannot be
929 /// reachable with a null optimize away the load.
930 static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV,
932 TargetLibraryInfo *TLI) {
933 bool Changed = false;
935 // Keep track of whether we are able to remove all the uses of the global
936 // other than the store that defines it.
937 bool AllNonStoreUsesGone = true;
939 // Replace all uses of loads with uses of uses of the stored value.
940 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
941 User *GlobalUser = *GUI++;
942 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
943 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
944 // If we were able to delete all uses of the loads
945 if (LI->use_empty()) {
946 LI->eraseFromParent();
949 AllNonStoreUsesGone = false;
951 } else if (isa<StoreInst>(GlobalUser)) {
952 // Ignore the store that stores "LV" to the global.
953 assert(GlobalUser->getOperand(1) == GV &&
954 "Must be storing *to* the global");
956 AllNonStoreUsesGone = false;
958 // If we get here we could have other crazy uses that are transitively
960 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
961 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser)) &&
962 "Only expect load and stores!");
967 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
971 // If we nuked all of the loads, then none of the stores are needed either,
972 // nor is the global.
973 if (AllNonStoreUsesGone) {
974 if (isLeakCheckerRoot(GV)) {
975 Changed |= CleanupPointerRootUsers(GV);
978 CleanupConstantGlobalUsers(GV, 0, TD, TLI);
980 if (GV->use_empty()) {
981 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
983 GV->eraseFromParent();
990 /// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
991 /// instructions that are foldable.
992 static void ConstantPropUsersOf(Value *V,
993 TargetData *TD, TargetLibraryInfo *TLI) {
994 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
995 if (Instruction *I = dyn_cast<Instruction>(*UI++))
996 if (Constant *NewC = ConstantFoldInstruction(I, TD, TLI)) {
997 I->replaceAllUsesWith(NewC);
999 // Advance UI to the next non-I use to avoid invalidating it!
1000 // Instructions could multiply use V.
1001 while (UI != E && *UI == I)
1003 I->eraseFromParent();
1007 /// OptimizeGlobalAddressOfMalloc - This function takes the specified global
1008 /// variable, and transforms the program as if it always contained the result of
1009 /// the specified malloc. Because it is always the result of the specified
1010 /// malloc, there is no reason to actually DO the malloc. Instead, turn the
1011 /// malloc into a global, and any loads of GV as uses of the new global.
1012 static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
1015 ConstantInt *NElements,
1017 TargetLibraryInfo *TLI) {
1018 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
1021 if (NElements->getZExtValue() == 1)
1022 GlobalType = AllocTy;
1024 // If we have an array allocation, the global variable is of an array.
1025 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
1027 // Create the new global variable. The contents of the malloc'd memory is
1028 // undefined, so initialize with an undef value.
1029 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
1031 GlobalValue::InternalLinkage,
1032 UndefValue::get(GlobalType),
1033 GV->getName()+".body",
1035 GV->getThreadLocalMode());
1037 // If there are bitcast users of the malloc (which is typical, usually we have
1038 // a malloc + bitcast) then replace them with uses of the new global. Update
1039 // other users to use the global as well.
1040 BitCastInst *TheBC = 0;
1041 while (!CI->use_empty()) {
1042 Instruction *User = cast<Instruction>(CI->use_back());
1043 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
1044 if (BCI->getType() == NewGV->getType()) {
1045 BCI->replaceAllUsesWith(NewGV);
1046 BCI->eraseFromParent();
1048 BCI->setOperand(0, NewGV);
1052 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
1053 User->replaceUsesOfWith(CI, TheBC);
1057 Constant *RepValue = NewGV;
1058 if (NewGV->getType() != GV->getType()->getElementType())
1059 RepValue = ConstantExpr::getBitCast(RepValue,
1060 GV->getType()->getElementType());
1062 // If there is a comparison against null, we will insert a global bool to
1063 // keep track of whether the global was initialized yet or not.
1064 GlobalVariable *InitBool =
1065 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
1066 GlobalValue::InternalLinkage,
1067 ConstantInt::getFalse(GV->getContext()),
1068 GV->getName()+".init", GV->getThreadLocalMode());
1069 bool InitBoolUsed = false;
1071 // Loop over all uses of GV, processing them in turn.
1072 while (!GV->use_empty()) {
1073 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
1074 // The global is initialized when the store to it occurs.
1075 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, false, 0,
1076 SI->getOrdering(), SI->getSynchScope(), SI);
1077 SI->eraseFromParent();
1081 LoadInst *LI = cast<LoadInst>(GV->use_back());
1082 while (!LI->use_empty()) {
1083 Use &LoadUse = LI->use_begin().getUse();
1084 if (!isa<ICmpInst>(LoadUse.getUser())) {
1089 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
1090 // Replace the cmp X, 0 with a use of the bool value.
1091 // Sink the load to where the compare was, if atomic rules allow us to.
1092 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", false, 0,
1093 LI->getOrdering(), LI->getSynchScope(),
1094 LI->isUnordered() ? (Instruction*)ICI : LI);
1095 InitBoolUsed = true;
1096 switch (ICI->getPredicate()) {
1097 default: llvm_unreachable("Unknown ICmp Predicate!");
1098 case ICmpInst::ICMP_ULT:
1099 case ICmpInst::ICMP_SLT: // X < null -> always false
1100 LV = ConstantInt::getFalse(GV->getContext());
1102 case ICmpInst::ICMP_ULE:
1103 case ICmpInst::ICMP_SLE:
1104 case ICmpInst::ICMP_EQ:
1105 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
1107 case ICmpInst::ICMP_NE:
1108 case ICmpInst::ICMP_UGE:
1109 case ICmpInst::ICMP_SGE:
1110 case ICmpInst::ICMP_UGT:
1111 case ICmpInst::ICMP_SGT:
1112 break; // no change.
1114 ICI->replaceAllUsesWith(LV);
1115 ICI->eraseFromParent();
1117 LI->eraseFromParent();
1120 // If the initialization boolean was used, insert it, otherwise delete it.
1121 if (!InitBoolUsed) {
1122 while (!InitBool->use_empty()) // Delete initializations
1123 cast<StoreInst>(InitBool->use_back())->eraseFromParent();
1126 GV->getParent()->getGlobalList().insert(GV, InitBool);
1128 // Now the GV is dead, nuke it and the malloc..
1129 GV->eraseFromParent();
1130 CI->eraseFromParent();
1132 // To further other optimizations, loop over all users of NewGV and try to
1133 // constant prop them. This will promote GEP instructions with constant
1134 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
1135 ConstantPropUsersOf(NewGV, TD, TLI);
1136 if (RepValue != NewGV)
1137 ConstantPropUsersOf(RepValue, TD, TLI);
1142 /// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
1143 /// to make sure that there are no complex uses of V. We permit simple things
1144 /// like dereferencing the pointer, but not storing through the address, unless
1145 /// it is to the specified global.
1146 static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
1147 const GlobalVariable *GV,
1148 SmallPtrSet<const PHINode*, 8> &PHIs) {
1149 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
1151 const Instruction *Inst = cast<Instruction>(*UI);
1153 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
1154 continue; // Fine, ignore.
1157 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1158 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
1159 return false; // Storing the pointer itself... bad.
1160 continue; // Otherwise, storing through it, or storing into GV... fine.
1163 // Must index into the array and into the struct.
1164 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
1165 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
1170 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
1171 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
1173 if (PHIs.insert(PN))
1174 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
1179 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
1180 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
1190 /// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
1191 /// somewhere. Transform all uses of the allocation into loads from the
1192 /// global and uses of the resultant pointer. Further, delete the store into
1193 /// GV. This assumes that these value pass the
1194 /// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
1195 static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
1196 GlobalVariable *GV) {
1197 while (!Alloc->use_empty()) {
1198 Instruction *U = cast<Instruction>(*Alloc->use_begin());
1199 Instruction *InsertPt = U;
1200 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1201 // If this is the store of the allocation into the global, remove it.
1202 if (SI->getOperand(1) == GV) {
1203 SI->eraseFromParent();
1206 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1207 // Insert the load in the corresponding predecessor, not right before the
1209 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
1210 } else if (isa<BitCastInst>(U)) {
1211 // Must be bitcast between the malloc and store to initialize the global.
1212 ReplaceUsesOfMallocWithGlobal(U, GV);
1213 U->eraseFromParent();
1215 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1216 // If this is a "GEP bitcast" and the user is a store to the global, then
1217 // just process it as a bitcast.
1218 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1219 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1220 if (SI->getOperand(1) == GV) {
1221 // Must be bitcast GEP between the malloc and store to initialize
1223 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1224 GEPI->eraseFromParent();
1229 // Insert a load from the global, and use it instead of the malloc.
1230 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
1231 U->replaceUsesOfWith(Alloc, NL);
1235 /// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1236 /// of a load) are simple enough to perform heap SRA on. This permits GEP's
1237 /// that index through the array and struct field, icmps of null, and PHIs.
1238 static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
1239 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
1240 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
1241 // We permit two users of the load: setcc comparing against the null
1242 // pointer, and a getelementptr of a specific form.
1243 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
1245 const Instruction *User = cast<Instruction>(*UI);
1247 // Comparison against null is ok.
1248 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
1249 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1254 // getelementptr is also ok, but only a simple form.
1255 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1256 // Must index into the array and into the struct.
1257 if (GEPI->getNumOperands() < 3)
1260 // Otherwise the GEP is ok.
1264 if (const PHINode *PN = dyn_cast<PHINode>(User)) {
1265 if (!LoadUsingPHIsPerLoad.insert(PN))
1266 // This means some phi nodes are dependent on each other.
1267 // Avoid infinite looping!
1269 if (!LoadUsingPHIs.insert(PN))
1270 // If we have already analyzed this PHI, then it is safe.
1273 // Make sure all uses of the PHI are simple enough to transform.
1274 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1275 LoadUsingPHIs, LoadUsingPHIsPerLoad))
1281 // Otherwise we don't know what this is, not ok.
1289 /// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1290 /// GV are simple enough to perform HeapSRA, return true.
1291 static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
1292 Instruction *StoredVal) {
1293 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1294 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
1295 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1297 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1298 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1299 LoadUsingPHIsPerLoad))
1301 LoadUsingPHIsPerLoad.clear();
1304 // If we reach here, we know that all uses of the loads and transitive uses
1305 // (through PHI nodes) are simple enough to transform. However, we don't know
1306 // that all inputs the to the PHI nodes are in the same equivalence sets.
1307 // Check to verify that all operands of the PHIs are either PHIS that can be
1308 // transformed, loads from GV, or MI itself.
1309 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin()
1310 , E = LoadUsingPHIs.end(); I != E; ++I) {
1311 const PHINode *PN = *I;
1312 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1313 Value *InVal = PN->getIncomingValue(op);
1315 // PHI of the stored value itself is ok.
1316 if (InVal == StoredVal) continue;
1318 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
1319 // One of the PHIs in our set is (optimistically) ok.
1320 if (LoadUsingPHIs.count(InPN))
1325 // Load from GV is ok.
1326 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
1327 if (LI->getOperand(0) == GV)
1332 // Anything else is rejected.
1340 static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1341 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1342 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1343 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
1345 if (FieldNo >= FieldVals.size())
1346 FieldVals.resize(FieldNo+1);
1348 // If we already have this value, just reuse the previously scalarized
1350 if (Value *FieldVal = FieldVals[FieldNo])
1353 // Depending on what instruction this is, we have several cases.
1355 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1356 // This is a scalarized version of the load from the global. Just create
1357 // a new Load of the scalarized global.
1358 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1359 InsertedScalarizedValues,
1361 LI->getName()+".f"+Twine(FieldNo), LI);
1362 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1363 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1366 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
1369 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
1370 PN->getNumIncomingValues(),
1371 PN->getName()+".f"+Twine(FieldNo), PN);
1373 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1375 llvm_unreachable("Unknown usable value");
1378 return FieldVals[FieldNo] = Result;
1381 /// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1382 /// the load, rewrite the derived value to use the HeapSRoA'd load.
1383 static void RewriteHeapSROALoadUser(Instruction *LoadUser,
1384 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1385 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1386 // If this is a comparison against null, handle it.
1387 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1388 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1389 // If we have a setcc of the loaded pointer, we can use a setcc of any
1391 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
1392 InsertedScalarizedValues, PHIsToRewrite);
1394 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
1395 Constant::getNullValue(NPtr->getType()),
1397 SCI->replaceAllUsesWith(New);
1398 SCI->eraseFromParent();
1402 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
1403 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1404 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1405 && "Unexpected GEPI!");
1407 // Load the pointer for this field.
1408 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
1409 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
1410 InsertedScalarizedValues, PHIsToRewrite);
1412 // Create the new GEP idx vector.
1413 SmallVector<Value*, 8> GEPIdx;
1414 GEPIdx.push_back(GEPI->getOperand(1));
1415 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
1417 Value *NGEPI = GetElementPtrInst::Create(NewPtr, GEPIdx,
1418 GEPI->getName(), GEPI);
1419 GEPI->replaceAllUsesWith(NGEPI);
1420 GEPI->eraseFromParent();
1424 // Recursively transform the users of PHI nodes. This will lazily create the
1425 // PHIs that are needed for individual elements. Keep track of what PHIs we
1426 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1427 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1428 // already been seen first by another load, so its uses have already been
1430 PHINode *PN = cast<PHINode>(LoadUser);
1431 if (!InsertedScalarizedValues.insert(std::make_pair(PN,
1432 std::vector<Value*>())).second)
1435 // If this is the first time we've seen this PHI, recursively process all
1437 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1438 Instruction *User = cast<Instruction>(*UI++);
1439 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
1443 /// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1444 /// is a value loaded from the global. Eliminate all uses of Ptr, making them
1445 /// use FieldGlobals instead. All uses of loaded values satisfy
1446 /// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
1447 static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
1448 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1449 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1450 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
1452 Instruction *User = cast<Instruction>(*UI++);
1453 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
1456 if (Load->use_empty()) {
1457 Load->eraseFromParent();
1458 InsertedScalarizedValues.erase(Load);
1462 /// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1463 /// it up into multiple allocations of arrays of the fields.
1464 static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
1465 Value *NElems, TargetData *TD) {
1466 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
1467 Type *MAT = getMallocAllocatedType(CI);
1468 StructType *STy = cast<StructType>(MAT);
1470 // There is guaranteed to be at least one use of the malloc (storing
1471 // it into GV). If there are other uses, change them to be uses of
1472 // the global to simplify later code. This also deletes the store
1474 ReplaceUsesOfMallocWithGlobal(CI, GV);
1476 // Okay, at this point, there are no users of the malloc. Insert N
1477 // new mallocs at the same place as CI, and N globals.
1478 std::vector<Value*> FieldGlobals;
1479 std::vector<Value*> FieldMallocs;
1481 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
1482 Type *FieldTy = STy->getElementType(FieldNo);
1483 PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
1485 GlobalVariable *NGV =
1486 new GlobalVariable(*GV->getParent(),
1487 PFieldTy, false, GlobalValue::InternalLinkage,
1488 Constant::getNullValue(PFieldTy),
1489 GV->getName() + ".f" + Twine(FieldNo), GV,
1490 GV->getThreadLocalMode());
1491 FieldGlobals.push_back(NGV);
1493 unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
1494 if (StructType *ST = dyn_cast<StructType>(FieldTy))
1495 TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
1496 Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
1497 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1498 ConstantInt::get(IntPtrTy, TypeSize),
1500 CI->getName() + ".f" + Twine(FieldNo));
1501 FieldMallocs.push_back(NMI);
1502 new StoreInst(NMI, NGV, CI);
1505 // The tricky aspect of this transformation is handling the case when malloc
1506 // fails. In the original code, malloc failing would set the result pointer
1507 // of malloc to null. In this case, some mallocs could succeed and others
1508 // could fail. As such, we emit code that looks like this:
1509 // F0 = malloc(field0)
1510 // F1 = malloc(field1)
1511 // F2 = malloc(field2)
1512 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1513 // if (F0) { free(F0); F0 = 0; }
1514 // if (F1) { free(F1); F1 = 0; }
1515 // if (F2) { free(F2); F2 = 0; }
1517 // The malloc can also fail if its argument is too large.
1518 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1519 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
1520 ConstantZero, "isneg");
1521 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
1522 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1523 Constant::getNullValue(FieldMallocs[i]->getType()),
1525 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
1528 // Split the basic block at the old malloc.
1529 BasicBlock *OrigBB = CI->getParent();
1530 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
1532 // Create the block to check the first condition. Put all these blocks at the
1533 // end of the function as they are unlikely to be executed.
1534 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1536 OrigBB->getParent());
1538 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1539 // branch on RunningOr.
1540 OrigBB->getTerminator()->eraseFromParent();
1541 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
1543 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1544 // pointer, because some may be null while others are not.
1545 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1546 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
1547 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
1548 Constant::getNullValue(GVVal->getType()));
1549 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
1550 OrigBB->getParent());
1551 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
1552 OrigBB->getParent());
1553 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1556 // Fill in FreeBlock.
1557 CallInst::CreateFree(GVVal, BI);
1558 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1560 BranchInst::Create(NextBlock, FreeBlock);
1562 NullPtrBlock = NextBlock;
1565 BranchInst::Create(ContBB, NullPtrBlock);
1567 // CI is no longer needed, remove it.
1568 CI->eraseFromParent();
1570 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1571 /// update all uses of the load, keep track of what scalarized loads are
1572 /// inserted for a given load.
1573 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1574 InsertedScalarizedValues[GV] = FieldGlobals;
1576 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
1578 // Okay, the malloc site is completely handled. All of the uses of GV are now
1579 // loads, and all uses of those loads are simple. Rewrite them to use loads
1580 // of the per-field globals instead.
1581 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1582 Instruction *User = cast<Instruction>(*UI++);
1584 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1585 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
1589 // Must be a store of null.
1590 StoreInst *SI = cast<StoreInst>(User);
1591 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1592 "Unexpected heap-sra user!");
1594 // Insert a store of null into each global.
1595 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1596 PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
1597 Constant *Null = Constant::getNullValue(PT->getElementType());
1598 new StoreInst(Null, FieldGlobals[i], SI);
1600 // Erase the original store.
1601 SI->eraseFromParent();
1604 // While we have PHIs that are interesting to rewrite, do it.
1605 while (!PHIsToRewrite.empty()) {
1606 PHINode *PN = PHIsToRewrite.back().first;
1607 unsigned FieldNo = PHIsToRewrite.back().second;
1608 PHIsToRewrite.pop_back();
1609 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1610 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1612 // Add all the incoming values. This can materialize more phis.
1613 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1614 Value *InVal = PN->getIncomingValue(i);
1615 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
1617 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1621 // Drop all inter-phi links and any loads that made it this far.
1622 for (DenseMap<Value*, std::vector<Value*> >::iterator
1623 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1625 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1626 PN->dropAllReferences();
1627 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1628 LI->dropAllReferences();
1631 // Delete all the phis and loads now that inter-references are dead.
1632 for (DenseMap<Value*, std::vector<Value*> >::iterator
1633 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1635 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1636 PN->eraseFromParent();
1637 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1638 LI->eraseFromParent();
1641 // The old global is now dead, remove it.
1642 GV->eraseFromParent();
1645 return cast<GlobalVariable>(FieldGlobals[0]);
1648 /// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1649 /// pointer global variable with a single value stored it that is a malloc or
1651 static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
1654 AtomicOrdering Ordering,
1655 Module::global_iterator &GVI,
1657 TargetLibraryInfo *TLI) {
1661 // If this is a malloc of an abstract type, don't touch it.
1662 if (!AllocTy->isSized())
1665 // We can't optimize this global unless all uses of it are *known* to be
1666 // of the malloc value, not of the null initializer value (consider a use
1667 // that compares the global's value against zero to see if the malloc has
1668 // been reached). To do this, we check to see if all uses of the global
1669 // would trap if the global were null: this proves that they must all
1670 // happen after the malloc.
1671 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1674 // We can't optimize this if the malloc itself is used in a complex way,
1675 // for example, being stored into multiple globals. This allows the
1676 // malloc to be stored into the specified global, loaded icmp'd, and
1677 // GEP'd. These are all things we could transform to using the global
1679 SmallPtrSet<const PHINode*, 8> PHIs;
1680 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1683 // If we have a global that is only initialized with a fixed size malloc,
1684 // transform the program to use global memory instead of malloc'd memory.
1685 // This eliminates dynamic allocation, avoids an indirection accessing the
1686 // data, and exposes the resultant global to further GlobalOpt.
1687 // We cannot optimize the malloc if we cannot determine malloc array size.
1688 Value *NElems = getMallocArraySize(CI, TD, true);
1692 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1693 // Restrict this transformation to only working on small allocations
1694 // (2048 bytes currently), as we don't want to introduce a 16M global or
1696 if (NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
1697 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD, TLI);
1701 // If the allocation is an array of structures, consider transforming this
1702 // into multiple malloc'd arrays, one for each field. This is basically
1703 // SRoA for malloc'd memory.
1705 if (Ordering != NotAtomic)
1708 // If this is an allocation of a fixed size array of structs, analyze as a
1709 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
1710 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
1711 if (ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
1712 AllocTy = AT->getElementType();
1714 StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
1718 // This the structure has an unreasonable number of fields, leave it
1720 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1721 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1723 // If this is a fixed size array, transform the Malloc to be an alloc of
1724 // structs. malloc [100 x struct],1 -> malloc struct, 100
1725 if (ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI))) {
1726 Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
1727 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
1728 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1729 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1730 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1731 AllocSize, NumElements,
1733 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1734 CI->replaceAllUsesWith(Cast);
1735 CI->eraseFromParent();
1736 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Malloc))
1737 CI = cast<CallInst>(BCI->getOperand(0));
1739 CI = cast<CallInst>(Malloc);
1742 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, true), TD);
1749 // OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1750 // that only one value (besides its initializer) is ever stored to the global.
1751 static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
1752 AtomicOrdering Ordering,
1753 Module::global_iterator &GVI,
1754 TargetData *TD, TargetLibraryInfo *TLI) {
1755 // Ignore no-op GEPs and bitcasts.
1756 StoredOnceVal = StoredOnceVal->stripPointerCasts();
1758 // If we are dealing with a pointer global that is initialized to null and
1759 // only has one (non-null) value stored into it, then we can optimize any
1760 // users of the loaded value (often calls and loads) that would trap if the
1762 if (GV->getInitializer()->getType()->isPointerTy() &&
1763 GV->getInitializer()->isNullValue()) {
1764 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1765 if (GV->getInitializer()->getType() != SOVC->getType())
1766 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
1768 // Optimize away any trapping uses of the loaded value.
1769 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, TD, TLI))
1771 } else if (CallInst *CI = extractMallocCall(StoredOnceVal)) {
1772 Type *MallocType = getMallocAllocatedType(CI);
1774 TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType, Ordering, GVI,
1783 /// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1784 /// two values ever stored into GV are its initializer and OtherVal. See if we
1785 /// can shrink the global into a boolean and select between the two values
1786 /// whenever it is used. This exposes the values to other scalar optimizations.
1787 static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
1788 Type *GVElType = GV->getType()->getElementType();
1790 // If GVElType is already i1, it is already shrunk. If the type of the GV is
1791 // an FP value, pointer or vector, don't do this optimization because a select
1792 // between them is very expensive and unlikely to lead to later
1793 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1794 // where v1 and v2 both require constant pool loads, a big loss.
1795 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
1796 GVElType->isFloatingPointTy() ||
1797 GVElType->isPointerTy() || GVElType->isVectorTy())
1800 // Walk the use list of the global seeing if all the uses are load or store.
1801 // If there is anything else, bail out.
1802 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
1804 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
1808 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
1810 // Create the new global, initializing it to false.
1811 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1813 GlobalValue::InternalLinkage,
1814 ConstantInt::getFalse(GV->getContext()),
1816 GV->getThreadLocalMode());
1817 GV->getParent()->getGlobalList().insert(GV, NewGV);
1819 Constant *InitVal = GV->getInitializer();
1820 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
1821 "No reason to shrink to bool!");
1823 // If initialized to zero and storing one into the global, we can use a cast
1824 // instead of a select to synthesize the desired value.
1825 bool IsOneZero = false;
1826 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
1827 IsOneZero = InitVal->isNullValue() && CI->isOne();
1829 while (!GV->use_empty()) {
1830 Instruction *UI = cast<Instruction>(GV->use_back());
1831 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
1832 // Change the store into a boolean store.
1833 bool StoringOther = SI->getOperand(0) == OtherVal;
1834 // Only do this if we weren't storing a loaded value.
1836 if (StoringOther || SI->getOperand(0) == InitVal)
1837 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1840 // Otherwise, we are storing a previously loaded copy. To do this,
1841 // change the copy from copying the original value to just copying the
1843 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1845 // If we've already replaced the input, StoredVal will be a cast or
1846 // select instruction. If not, it will be a load of the original
1848 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1849 assert(LI->getOperand(0) == GV && "Not a copy!");
1850 // Insert a new load, to preserve the saved value.
1851 StoreVal = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1852 LI->getOrdering(), LI->getSynchScope(), LI);
1854 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1855 "This is not a form that we understand!");
1856 StoreVal = StoredVal->getOperand(0);
1857 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1860 new StoreInst(StoreVal, NewGV, false, 0,
1861 SI->getOrdering(), SI->getSynchScope(), SI);
1863 // Change the load into a load of bool then a select.
1864 LoadInst *LI = cast<LoadInst>(UI);
1865 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", false, 0,
1866 LI->getOrdering(), LI->getSynchScope(), LI);
1869 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
1871 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
1873 LI->replaceAllUsesWith(NSI);
1875 UI->eraseFromParent();
1878 GV->eraseFromParent();
1883 /// ProcessGlobal - Analyze the specified global variable and optimize it if
1884 /// possible. If we make a change, return true.
1885 bool GlobalOpt::ProcessGlobal(GlobalVariable *GV,
1886 Module::global_iterator &GVI) {
1887 if (!GV->isDiscardableIfUnused())
1890 // Do more involved optimizations if the global is internal.
1891 GV->removeDeadConstantUsers();
1893 if (GV->use_empty()) {
1894 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
1895 GV->eraseFromParent();
1900 if (!GV->hasLocalLinkage())
1903 SmallPtrSet<const PHINode*, 16> PHIUsers;
1906 if (AnalyzeGlobal(GV, GS, PHIUsers))
1909 if (!GS.isCompared && !GV->hasUnnamedAddr()) {
1910 GV->setUnnamedAddr(true);
1914 if (GV->isConstant() || !GV->hasInitializer())
1917 return ProcessInternalGlobal(GV, GVI, PHIUsers, GS);
1920 /// ProcessInternalGlobal - Analyze the specified global variable and optimize
1921 /// it if possible. If we make a change, return true.
1922 bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1923 Module::global_iterator &GVI,
1924 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
1925 const GlobalStatus &GS) {
1926 // If this is a first class global and has only one accessing function
1927 // and this function is main (which we know is not recursive we can make
1928 // this global a local variable) we replace the global with a local alloca
1929 // in this function.
1931 // NOTE: It doesn't make sense to promote non single-value types since we
1932 // are just replacing static memory to stack memory.
1934 // If the global is in different address space, don't bring it to stack.
1935 if (!GS.HasMultipleAccessingFunctions &&
1936 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1937 GV->getType()->getElementType()->isSingleValueType() &&
1938 GS.AccessingFunction->getName() == "main" &&
1939 GS.AccessingFunction->hasExternalLinkage() &&
1940 GV->getType()->getAddressSpace() == 0) {
1941 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
1942 Instruction &FirstI = const_cast<Instruction&>(*GS.AccessingFunction
1943 ->getEntryBlock().begin());
1944 Type *ElemTy = GV->getType()->getElementType();
1945 // FIXME: Pass Global's alignment when globals have alignment
1946 AllocaInst *Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI);
1947 if (!isa<UndefValue>(GV->getInitializer()))
1948 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
1950 GV->replaceAllUsesWith(Alloca);
1951 GV->eraseFromParent();
1956 // If the global is never loaded (but may be stored to), it is dead.
1959 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
1962 if (isLeakCheckerRoot(GV)) {
1963 // Delete any constant stores to the global.
1964 Changed = CleanupPointerRootUsers(GV);
1966 // Delete any stores we can find to the global. We may not be able to
1967 // make it completely dead though.
1968 Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
1971 // If the global is dead now, delete it.
1972 if (GV->use_empty()) {
1973 GV->eraseFromParent();
1979 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1980 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV);
1981 GV->setConstant(true);
1983 // Clean up any obviously simplifiable users now.
1984 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
1986 // If the global is dead now, just nuke it.
1987 if (GV->use_empty()) {
1988 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
1989 << "all users and delete global!\n");
1990 GV->eraseFromParent();
1996 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
1997 if (TargetData *TD = getAnalysisIfAvailable<TargetData>())
1998 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
1999 GVI = FirstNewGV; // Don't skip the newly produced globals!
2002 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
2003 // If the initial value for the global was an undef value, and if only
2004 // one other value was stored into it, we can just change the
2005 // initializer to be the stored value, then delete all stores to the
2006 // global. This allows us to mark it constant.
2007 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
2008 if (isa<UndefValue>(GV->getInitializer())) {
2009 // Change the initial value here.
2010 GV->setInitializer(SOVConstant);
2012 // Clean up any obviously simplifiable users now.
2013 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI);
2015 if (GV->use_empty()) {
2016 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
2017 << "simplify all users and delete global!\n");
2018 GV->eraseFromParent();
2027 // Try to optimize globals based on the knowledge that only one value
2028 // (besides its initializer) is ever stored to the global.
2029 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GS.Ordering, GVI,
2033 // Otherwise, if the global was not a boolean, we can shrink it to be a
2035 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
2036 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
2045 /// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
2046 /// function, changing them to FastCC.
2047 static void ChangeCalleesToFastCall(Function *F) {
2048 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
2049 if (isa<BlockAddress>(*UI))
2051 CallSite User(cast<Instruction>(*UI));
2052 User.setCallingConv(CallingConv::Fast);
2056 static AttrListPtr StripNest(const AttrListPtr &Attrs) {
2057 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
2058 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
2061 // There can be only one.
2062 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
2068 static void RemoveNestAttribute(Function *F) {
2069 F->setAttributes(StripNest(F->getAttributes()));
2070 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
2071 if (isa<BlockAddress>(*UI))
2073 CallSite User(cast<Instruction>(*UI));
2074 User.setAttributes(StripNest(User.getAttributes()));
2078 bool GlobalOpt::OptimizeFunctions(Module &M) {
2079 bool Changed = false;
2080 // Optimize functions.
2081 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
2083 // Functions without names cannot be referenced outside this module.
2084 if (!F->hasName() && !F->isDeclaration())
2085 F->setLinkage(GlobalValue::InternalLinkage);
2086 F->removeDeadConstantUsers();
2087 if (F->isDefTriviallyDead()) {
2088 F->eraseFromParent();
2091 } else if (F->hasLocalLinkage()) {
2092 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
2093 !F->hasAddressTaken()) {
2094 // If this function has C calling conventions, is not a varargs
2095 // function, and is only called directly, promote it to use the Fast
2096 // calling convention.
2097 F->setCallingConv(CallingConv::Fast);
2098 ChangeCalleesToFastCall(F);
2103 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
2104 !F->hasAddressTaken()) {
2105 // The function is not used by a trampoline intrinsic, so it is safe
2106 // to remove the 'nest' attribute.
2107 RemoveNestAttribute(F);
2116 bool GlobalOpt::OptimizeGlobalVars(Module &M) {
2117 bool Changed = false;
2118 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
2120 GlobalVariable *GV = GVI++;
2121 // Global variables without names cannot be referenced outside this module.
2122 if (!GV->hasName() && !GV->isDeclaration())
2123 GV->setLinkage(GlobalValue::InternalLinkage);
2124 // Simplify the initializer.
2125 if (GV->hasInitializer())
2126 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
2127 Constant *New = ConstantFoldConstantExpression(CE, TD, TLI);
2128 if (New && New != CE)
2129 GV->setInitializer(New);
2132 Changed |= ProcessGlobal(GV, GVI);
2137 /// FindGlobalCtors - Find the llvm.global_ctors list, verifying that all
2138 /// initializers have an init priority of 65535.
2139 GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
2140 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
2141 if (GV == 0) return 0;
2143 // Verify that the initializer is simple enough for us to handle. We are
2144 // only allowed to optimize the initializer if it is unique.
2145 if (!GV->hasUniqueInitializer()) return 0;
2147 if (isa<ConstantAggregateZero>(GV->getInitializer()))
2149 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
2151 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
2152 if (isa<ConstantAggregateZero>(*i))
2154 ConstantStruct *CS = cast<ConstantStruct>(*i);
2155 if (isa<ConstantPointerNull>(CS->getOperand(1)))
2158 // Must have a function or null ptr.
2159 if (!isa<Function>(CS->getOperand(1)))
2162 // Init priority must be standard.
2163 ConstantInt *CI = cast<ConstantInt>(CS->getOperand(0));
2164 if (CI->getZExtValue() != 65535)
2171 /// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
2172 /// return a list of the functions and null terminator as a vector.
2173 static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
2174 if (GV->getInitializer()->isNullValue())
2175 return std::vector<Function*>();
2176 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
2177 std::vector<Function*> Result;
2178 Result.reserve(CA->getNumOperands());
2179 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
2180 ConstantStruct *CS = cast<ConstantStruct>(*i);
2181 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
2186 /// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
2187 /// specified array, returning the new global to use.
2188 static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
2189 const std::vector<Function*> &Ctors) {
2190 // If we made a change, reassemble the initializer list.
2191 Constant *CSVals[2];
2192 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()), 65535);
2195 StructType *StructTy =
2197 cast<ArrayType>(GCL->getType()->getElementType())->getElementType());
2199 // Create the new init list.
2200 std::vector<Constant*> CAList;
2201 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
2203 CSVals[1] = Ctors[i];
2205 Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
2207 PointerType *PFTy = PointerType::getUnqual(FTy);
2208 CSVals[1] = Constant::getNullValue(PFTy);
2209 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
2212 CAList.push_back(ConstantStruct::get(StructTy, CSVals));
2215 // Create the array initializer.
2216 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
2217 CAList.size()), CAList);
2219 // If we didn't change the number of elements, don't create a new GV.
2220 if (CA->getType() == GCL->getInitializer()->getType()) {
2221 GCL->setInitializer(CA);
2225 // Create the new global and insert it next to the existing list.
2226 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
2227 GCL->getLinkage(), CA, "",
2228 GCL->getThreadLocalMode());
2229 GCL->getParent()->getGlobalList().insert(GCL, NGV);
2232 // Nuke the old list, replacing any uses with the new one.
2233 if (!GCL->use_empty()) {
2235 if (V->getType() != GCL->getType())
2236 V = ConstantExpr::getBitCast(V, GCL->getType());
2237 GCL->replaceAllUsesWith(V);
2239 GCL->eraseFromParent();
2249 isSimpleEnoughValueToCommit(Constant *C,
2250 SmallPtrSet<Constant*, 8> &SimpleConstants,
2251 const TargetData *TD);
2254 /// isSimpleEnoughValueToCommit - Return true if the specified constant can be
2255 /// handled by the code generator. We don't want to generate something like:
2256 /// void *X = &X/42;
2257 /// because the code generator doesn't have a relocation that can handle that.
2259 /// This function should be called if C was not found (but just got inserted)
2260 /// in SimpleConstants to avoid having to rescan the same constants all the
2262 static bool isSimpleEnoughValueToCommitHelper(Constant *C,
2263 SmallPtrSet<Constant*, 8> &SimpleConstants,
2264 const TargetData *TD) {
2265 // Simple integer, undef, constant aggregate zero, global addresses, etc are
2267 if (C->getNumOperands() == 0 || isa<BlockAddress>(C) ||
2268 isa<GlobalValue>(C))
2271 // Aggregate values are safe if all their elements are.
2272 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
2273 isa<ConstantVector>(C)) {
2274 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
2275 Constant *Op = cast<Constant>(C->getOperand(i));
2276 if (!isSimpleEnoughValueToCommit(Op, SimpleConstants, TD))
2282 // We don't know exactly what relocations are allowed in constant expressions,
2283 // so we allow &global+constantoffset, which is safe and uniformly supported
2285 ConstantExpr *CE = cast<ConstantExpr>(C);
2286 switch (CE->getOpcode()) {
2287 case Instruction::BitCast:
2288 // Bitcast is fine if the casted value is fine.
2289 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
2291 case Instruction::IntToPtr:
2292 case Instruction::PtrToInt:
2293 // int <=> ptr is fine if the int type is the same size as the
2295 if (!TD || TD->getTypeSizeInBits(CE->getType()) !=
2296 TD->getTypeSizeInBits(CE->getOperand(0)->getType()))
2298 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
2300 // GEP is fine if it is simple + constant offset.
2301 case Instruction::GetElementPtr:
2302 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2303 if (!isa<ConstantInt>(CE->getOperand(i)))
2305 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
2307 case Instruction::Add:
2308 // We allow simple+cst.
2309 if (!isa<ConstantInt>(CE->getOperand(1)))
2311 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD);
2317 isSimpleEnoughValueToCommit(Constant *C,
2318 SmallPtrSet<Constant*, 8> &SimpleConstants,
2319 const TargetData *TD) {
2320 // If we already checked this constant, we win.
2321 if (!SimpleConstants.insert(C)) return true;
2322 // Check the constant.
2323 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, TD);
2327 /// isSimpleEnoughPointerToCommit - Return true if this constant is simple
2328 /// enough for us to understand. In particular, if it is a cast to anything
2329 /// other than from one pointer type to another pointer type, we punt.
2330 /// We basically just support direct accesses to globals and GEP's of
2331 /// globals. This should be kept up to date with CommitValueTo.
2332 static bool isSimpleEnoughPointerToCommit(Constant *C) {
2333 // Conservatively, avoid aggregate types. This is because we don't
2334 // want to worry about them partially overlapping other stores.
2335 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2338 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
2339 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2340 // external globals.
2341 return GV->hasUniqueInitializer();
2343 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2344 // Handle a constantexpr gep.
2345 if (CE->getOpcode() == Instruction::GetElementPtr &&
2346 isa<GlobalVariable>(CE->getOperand(0)) &&
2347 cast<GEPOperator>(CE)->isInBounds()) {
2348 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2349 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2350 // external globals.
2351 if (!GV->hasUniqueInitializer())
2354 // The first index must be zero.
2355 ConstantInt *CI = dyn_cast<ConstantInt>(*llvm::next(CE->op_begin()));
2356 if (!CI || !CI->isZero()) return false;
2358 // The remaining indices must be compile-time known integers within the
2359 // notional bounds of the corresponding static array types.
2360 if (!CE->isGEPWithNoNotionalOverIndexing())
2363 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
2365 // A constantexpr bitcast from a pointer to another pointer is a no-op,
2366 // and we know how to evaluate it by moving the bitcast from the pointer
2367 // operand to the value operand.
2368 } else if (CE->getOpcode() == Instruction::BitCast &&
2369 isa<GlobalVariable>(CE->getOperand(0))) {
2370 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2371 // external globals.
2372 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
2379 /// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2380 /// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2381 /// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2382 static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
2383 ConstantExpr *Addr, unsigned OpNo) {
2384 // Base case of the recursion.
2385 if (OpNo == Addr->getNumOperands()) {
2386 assert(Val->getType() == Init->getType() && "Type mismatch!");
2390 SmallVector<Constant*, 32> Elts;
2391 if (StructType *STy = dyn_cast<StructType>(Init->getType())) {
2392 // Break up the constant into its elements.
2393 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2394 Elts.push_back(Init->getAggregateElement(i));
2396 // Replace the element that we are supposed to.
2397 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2398 unsigned Idx = CU->getZExtValue();
2399 assert(Idx < STy->getNumElements() && "Struct index out of range!");
2400 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
2402 // Return the modified struct.
2403 return ConstantStruct::get(STy, Elts);
2406 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
2407 SequentialType *InitTy = cast<SequentialType>(Init->getType());
2410 if (ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
2411 NumElts = ATy->getNumElements();
2413 NumElts = InitTy->getVectorNumElements();
2415 // Break up the array into elements.
2416 for (uint64_t i = 0, e = NumElts; i != e; ++i)
2417 Elts.push_back(Init->getAggregateElement(i));
2419 assert(CI->getZExtValue() < NumElts);
2420 Elts[CI->getZExtValue()] =
2421 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
2423 if (Init->getType()->isArrayTy())
2424 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2425 return ConstantVector::get(Elts);
2428 /// CommitValueTo - We have decided that Addr (which satisfies the predicate
2429 /// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
2430 static void CommitValueTo(Constant *Val, Constant *Addr) {
2431 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2432 assert(GV->hasInitializer());
2433 GV->setInitializer(Val);
2437 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2438 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2439 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
2444 /// Evaluator - This class evaluates LLVM IR, producing the Constant
2445 /// representing each SSA instruction. Changes to global variables are stored
2446 /// in a mapping that can be iterated over after the evaluation is complete.
2447 /// Once an evaluation call fails, the evaluation object should not be reused.
2450 Evaluator(const TargetData *TD, const TargetLibraryInfo *TLI)
2451 : TD(TD), TLI(TLI) {
2452 ValueStack.push_back(new DenseMap<Value*, Constant*>);
2456 DeleteContainerPointers(ValueStack);
2457 while (!AllocaTmps.empty()) {
2458 GlobalVariable *Tmp = AllocaTmps.back();
2459 AllocaTmps.pop_back();
2461 // If there are still users of the alloca, the program is doing something
2462 // silly, e.g. storing the address of the alloca somewhere and using it
2463 // later. Since this is undefined, we'll just make it be null.
2464 if (!Tmp->use_empty())
2465 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2470 /// EvaluateFunction - Evaluate a call to function F, returning true if
2471 /// successful, false if we can't evaluate it. ActualArgs contains the formal
2472 /// arguments for the function.
2473 bool EvaluateFunction(Function *F, Constant *&RetVal,
2474 const SmallVectorImpl<Constant*> &ActualArgs);
2476 /// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2477 /// successful, false if we can't evaluate it. NewBB returns the next BB that
2478 /// control flows into, or null upon return.
2479 bool EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB);
2481 Constant *getVal(Value *V) {
2482 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2483 Constant *R = ValueStack.back()->lookup(V);
2484 assert(R && "Reference to an uncomputed value!");
2488 void setVal(Value *V, Constant *C) {
2489 ValueStack.back()->operator[](V) = C;
2492 const DenseMap<Constant*, Constant*> &getMutatedMemory() const {
2493 return MutatedMemory;
2496 const SmallPtrSet<GlobalVariable*, 8> &getInvariants() const {
2501 Constant *ComputeLoadResult(Constant *P);
2503 /// ValueStack - As we compute SSA register values, we store their contents
2504 /// here. The back of the vector contains the current function and the stack
2505 /// contains the values in the calling frames.
2506 SmallVector<DenseMap<Value*, Constant*>*, 4> ValueStack;
2508 /// CallStack - This is used to detect recursion. In pathological situations
2509 /// we could hit exponential behavior, but at least there is nothing
2511 SmallVector<Function*, 4> CallStack;
2513 /// MutatedMemory - For each store we execute, we update this map. Loads
2514 /// check this to get the most up-to-date value. If evaluation is successful,
2515 /// this state is committed to the process.
2516 DenseMap<Constant*, Constant*> MutatedMemory;
2518 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2519 /// to represent its body. This vector is needed so we can delete the
2520 /// temporary globals when we are done.
2521 SmallVector<GlobalVariable*, 32> AllocaTmps;
2523 /// Invariants - These global variables have been marked invariant by the
2524 /// static constructor.
2525 SmallPtrSet<GlobalVariable*, 8> Invariants;
2527 /// SimpleConstants - These are constants we have checked and know to be
2528 /// simple enough to live in a static initializer of a global.
2529 SmallPtrSet<Constant*, 8> SimpleConstants;
2531 const TargetData *TD;
2532 const TargetLibraryInfo *TLI;
2535 } // anonymous namespace
2537 /// ComputeLoadResult - Return the value that would be computed by a load from
2538 /// P after the stores reflected by 'memory' have been performed. If we can't
2539 /// decide, return null.
2540 Constant *Evaluator::ComputeLoadResult(Constant *P) {
2541 // If this memory location has been recently stored, use the stored value: it
2542 // is the most up-to-date.
2543 DenseMap<Constant*, Constant*>::const_iterator I = MutatedMemory.find(P);
2544 if (I != MutatedMemory.end()) return I->second;
2547 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
2548 if (GV->hasDefinitiveInitializer())
2549 return GV->getInitializer();
2553 // Handle a constantexpr getelementptr.
2554 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2555 if (CE->getOpcode() == Instruction::GetElementPtr &&
2556 isa<GlobalVariable>(CE->getOperand(0))) {
2557 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2558 if (GV->hasDefinitiveInitializer())
2559 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
2562 return 0; // don't know how to evaluate.
2565 /// EvaluateBlock - Evaluate all instructions in block BB, returning true if
2566 /// successful, false if we can't evaluate it. NewBB returns the next BB that
2567 /// control flows into, or null upon return.
2568 bool Evaluator::EvaluateBlock(BasicBlock::iterator CurInst,
2569 BasicBlock *&NextBB) {
2570 // This is the main evaluation loop.
2572 Constant *InstResult = 0;
2574 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
2575 if (!SI->isSimple()) return false; // no volatile/atomic accesses.
2576 Constant *Ptr = getVal(SI->getOperand(1));
2577 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2578 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
2579 if (!isSimpleEnoughPointerToCommit(Ptr))
2580 // If this is too complex for us to commit, reject it.
2583 Constant *Val = getVal(SI->getOperand(0));
2585 // If this might be too difficult for the backend to handle (e.g. the addr
2586 // of one global variable divided by another) then we can't commit it.
2587 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, TD))
2590 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2591 if (CE->getOpcode() == Instruction::BitCast) {
2592 // If we're evaluating a store through a bitcast, then we need
2593 // to pull the bitcast off the pointer type and push it onto the
2595 Ptr = CE->getOperand(0);
2597 Type *NewTy = cast<PointerType>(Ptr->getType())->getElementType();
2599 // In order to push the bitcast onto the stored value, a bitcast
2600 // from NewTy to Val's type must be legal. If it's not, we can try
2601 // introspecting NewTy to find a legal conversion.
2602 while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) {
2603 // If NewTy is a struct, we can convert the pointer to the struct
2604 // into a pointer to its first member.
2605 // FIXME: This could be extended to support arrays as well.
2606 if (StructType *STy = dyn_cast<StructType>(NewTy)) {
2607 NewTy = STy->getTypeAtIndex(0U);
2609 IntegerType *IdxTy = IntegerType::get(NewTy->getContext(), 32);
2610 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
2611 Constant * const IdxList[] = {IdxZero, IdxZero};
2613 Ptr = ConstantExpr::getGetElementPtr(Ptr, IdxList);
2614 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2615 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
2617 // If we can't improve the situation by introspecting NewTy,
2618 // we have to give up.
2624 // If we found compatible types, go ahead and push the bitcast
2625 // onto the stored value.
2626 Val = ConstantExpr::getBitCast(Val, NewTy);
2629 MutatedMemory[Ptr] = Val;
2630 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
2631 InstResult = ConstantExpr::get(BO->getOpcode(),
2632 getVal(BO->getOperand(0)),
2633 getVal(BO->getOperand(1)));
2634 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
2635 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
2636 getVal(CI->getOperand(0)),
2637 getVal(CI->getOperand(1)));
2638 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
2639 InstResult = ConstantExpr::getCast(CI->getOpcode(),
2640 getVal(CI->getOperand(0)),
2642 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
2643 InstResult = ConstantExpr::getSelect(getVal(SI->getOperand(0)),
2644 getVal(SI->getOperand(1)),
2645 getVal(SI->getOperand(2)));
2646 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
2647 Constant *P = getVal(GEP->getOperand(0));
2648 SmallVector<Constant*, 8> GEPOps;
2649 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2651 GEPOps.push_back(getVal(*i));
2653 ConstantExpr::getGetElementPtr(P, GEPOps,
2654 cast<GEPOperator>(GEP)->isInBounds());
2655 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
2656 if (!LI->isSimple()) return false; // no volatile/atomic accesses.
2657 Constant *Ptr = getVal(LI->getOperand(0));
2658 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2659 Ptr = ConstantFoldConstantExpression(CE, TD, TLI);
2660 InstResult = ComputeLoadResult(Ptr);
2661 if (InstResult == 0) return false; // Could not evaluate load.
2662 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
2663 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
2664 Type *Ty = AI->getType()->getElementType();
2665 AllocaTmps.push_back(new GlobalVariable(Ty, false,
2666 GlobalValue::InternalLinkage,
2667 UndefValue::get(Ty),
2669 InstResult = AllocaTmps.back();
2670 } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) {
2671 CallSite CS(CurInst);
2673 // Debug info can safely be ignored here.
2674 if (isa<DbgInfoIntrinsic>(CS.getInstruction())) {
2679 // Cannot handle inline asm.
2680 if (isa<InlineAsm>(CS.getCalledValue())) return false;
2682 if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CS.getInstruction())) {
2683 if (MemSetInst *MSI = dyn_cast<MemSetInst>(II)) {
2684 if (MSI->isVolatile()) return false;
2685 Constant *Ptr = getVal(MSI->getDest());
2686 Constant *Val = getVal(MSI->getValue());
2687 Constant *DestVal = ComputeLoadResult(getVal(Ptr));
2688 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) {
2689 // This memset is a no-op.
2695 if (II->getIntrinsicID() == Intrinsic::lifetime_start ||
2696 II->getIntrinsicID() == Intrinsic::lifetime_end) {
2701 if (II->getIntrinsicID() == Intrinsic::invariant_start) {
2702 // We don't insert an entry into Values, as it doesn't have a
2703 // meaningful return value.
2704 if (!II->use_empty())
2706 ConstantInt *Size = cast<ConstantInt>(II->getArgOperand(0));
2707 Value *PtrArg = getVal(II->getArgOperand(1));
2708 Value *Ptr = PtrArg->stripPointerCasts();
2709 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
2710 Type *ElemTy = cast<PointerType>(GV->getType())->getElementType();
2711 if (!Size->isAllOnesValue() &&
2712 Size->getValue().getLimitedValue() >=
2713 TD->getTypeStoreSize(ElemTy))
2714 Invariants.insert(GV);
2716 // Continue even if we do nothing.
2723 // Resolve function pointers.
2724 Function *Callee = dyn_cast<Function>(getVal(CS.getCalledValue()));
2725 if (!Callee || Callee->mayBeOverridden())
2726 return false; // Cannot resolve.
2728 SmallVector<Constant*, 8> Formals;
2729 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end(); i != e; ++i)
2730 Formals.push_back(getVal(*i));
2732 if (Callee->isDeclaration()) {
2733 // If this is a function we can constant fold, do it.
2734 if (Constant *C = ConstantFoldCall(Callee, Formals, TLI)) {
2740 if (Callee->getFunctionType()->isVarArg())
2744 // Execute the call, if successful, use the return value.
2745 ValueStack.push_back(new DenseMap<Value*, Constant*>);
2746 if (!EvaluateFunction(Callee, RetVal, Formals))
2748 delete ValueStack.pop_back_val();
2749 InstResult = RetVal;
2751 } else if (isa<TerminatorInst>(CurInst)) {
2752 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2753 if (BI->isUnconditional()) {
2754 NextBB = BI->getSuccessor(0);
2757 dyn_cast<ConstantInt>(getVal(BI->getCondition()));
2758 if (!Cond) return false; // Cannot determine.
2760 NextBB = BI->getSuccessor(!Cond->getZExtValue());
2762 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2764 dyn_cast<ConstantInt>(getVal(SI->getCondition()));
2765 if (!Val) return false; // Cannot determine.
2766 NextBB = SI->findCaseValue(Val).getCaseSuccessor();
2767 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
2768 Value *Val = getVal(IBI->getAddress())->stripPointerCasts();
2769 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
2770 NextBB = BA->getBasicBlock();
2772 return false; // Cannot determine.
2773 } else if (isa<ReturnInst>(CurInst)) {
2776 // invoke, unwind, resume, unreachable.
2777 return false; // Cannot handle this terminator.
2780 // We succeeded at evaluating this block!
2783 // Did not know how to evaluate this!
2787 if (!CurInst->use_empty()) {
2788 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
2789 InstResult = ConstantFoldConstantExpression(CE, TD, TLI);
2791 setVal(CurInst, InstResult);
2794 // If we just processed an invoke, we finished evaluating the block.
2795 if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) {
2796 NextBB = II->getNormalDest();
2800 // Advance program counter.
2805 /// EvaluateFunction - Evaluate a call to function F, returning true if
2806 /// successful, false if we can't evaluate it. ActualArgs contains the formal
2807 /// arguments for the function.
2808 bool Evaluator::EvaluateFunction(Function *F, Constant *&RetVal,
2809 const SmallVectorImpl<Constant*> &ActualArgs) {
2810 // Check to see if this function is already executing (recursion). If so,
2811 // bail out. TODO: we might want to accept limited recursion.
2812 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2815 CallStack.push_back(F);
2817 // Initialize arguments to the incoming values specified.
2819 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2821 setVal(AI, ActualArgs[ArgNo]);
2823 // ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2824 // we can only evaluate any one basic block at most once. This set keeps
2825 // track of what we have executed so we can detect recursive cases etc.
2826 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
2828 // CurBB - The current basic block we're evaluating.
2829 BasicBlock *CurBB = F->begin();
2831 BasicBlock::iterator CurInst = CurBB->begin();
2834 BasicBlock *NextBB = 0; // Initialized to avoid compiler warnings.
2835 if (!EvaluateBlock(CurInst, NextBB))
2839 // Successfully running until there's no next block means that we found
2840 // the return. Fill it the return value and pop the call stack.
2841 ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator());
2842 if (RI->getNumOperands())
2843 RetVal = getVal(RI->getOperand(0));
2844 CallStack.pop_back();
2848 // Okay, we succeeded in evaluating this control flow. See if we have
2849 // executed the new block before. If so, we have a looping function,
2850 // which we cannot evaluate in reasonable time.
2851 if (!ExecutedBlocks.insert(NextBB))
2852 return false; // looped!
2854 // Okay, we have never been in this block before. Check to see if there
2855 // are any PHI nodes. If so, evaluate them with information about where
2858 for (CurInst = NextBB->begin();
2859 (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2860 setVal(PN, getVal(PN->getIncomingValueForBlock(CurBB)));
2862 // Advance to the next block.
2867 /// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2868 /// we can. Return true if we can, false otherwise.
2869 static bool EvaluateStaticConstructor(Function *F, const TargetData *TD,
2870 const TargetLibraryInfo *TLI) {
2871 // Call the function.
2872 Evaluator Eval(TD, TLI);
2873 Constant *RetValDummy;
2874 bool EvalSuccess = Eval.EvaluateFunction(F, RetValDummy,
2875 SmallVector<Constant*, 0>());
2878 // We succeeded at evaluation: commit the result.
2879 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
2880 << F->getName() << "' to " << Eval.getMutatedMemory().size()
2882 for (DenseMap<Constant*, Constant*>::const_iterator I =
2883 Eval.getMutatedMemory().begin(), E = Eval.getMutatedMemory().end();
2885 CommitValueTo(I->second, I->first);
2886 for (SmallPtrSet<GlobalVariable*, 8>::const_iterator I =
2887 Eval.getInvariants().begin(), E = Eval.getInvariants().end();
2889 (*I)->setConstant(true);
2895 /// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2896 /// Return true if anything changed.
2897 bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2898 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2899 bool MadeChange = false;
2900 if (Ctors.empty()) return false;
2902 // Loop over global ctors, optimizing them when we can.
2903 for (unsigned i = 0; i != Ctors.size(); ++i) {
2904 Function *F = Ctors[i];
2905 // Found a null terminator in the middle of the list, prune off the rest of
2908 if (i != Ctors.size()-1) {
2915 // We cannot simplify external ctor functions.
2916 if (F->empty()) continue;
2918 // If we can evaluate the ctor at compile time, do.
2919 if (EvaluateStaticConstructor(F, TD, TLI)) {
2920 Ctors.erase(Ctors.begin()+i);
2923 ++NumCtorsEvaluated;
2928 if (!MadeChange) return false;
2930 GCL = InstallGlobalCtors(GCL, Ctors);
2934 bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
2935 bool Changed = false;
2937 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
2939 Module::alias_iterator J = I++;
2940 // Aliases without names cannot be referenced outside this module.
2941 if (!J->hasName() && !J->isDeclaration())
2942 J->setLinkage(GlobalValue::InternalLinkage);
2943 // If the aliasee may change at link time, nothing can be done - bail out.
2944 if (J->mayBeOverridden())
2947 Constant *Aliasee = J->getAliasee();
2948 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
2949 Target->removeDeadConstantUsers();
2950 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2952 // Make all users of the alias use the aliasee instead.
2953 if (!J->use_empty()) {
2954 J->replaceAllUsesWith(Aliasee);
2955 ++NumAliasesResolved;
2959 // If the alias is externally visible, we may still be able to simplify it.
2960 if (!J->hasLocalLinkage()) {
2961 // If the aliasee has internal linkage, give it the name and linkage
2962 // of the alias, and delete the alias. This turns:
2963 // define internal ... @f(...)
2964 // @a = alias ... @f
2966 // define ... @a(...)
2967 if (!Target->hasLocalLinkage())
2970 // Do not perform the transform if multiple aliases potentially target the
2971 // aliasee. This check also ensures that it is safe to replace the section
2972 // and other attributes of the aliasee with those of the alias.
2976 // Give the aliasee the name, linkage and other attributes of the alias.
2977 Target->takeName(J);
2978 Target->setLinkage(J->getLinkage());
2979 Target->GlobalValue::copyAttributesFrom(J);
2982 // Delete the alias.
2983 M.getAliasList().erase(J);
2984 ++NumAliasesRemoved;
2991 static Function *FindCXAAtExit(Module &M, TargetLibraryInfo *TLI) {
2992 if (!TLI->has(LibFunc::cxa_atexit))
2995 Function *Fn = M.getFunction(TLI->getName(LibFunc::cxa_atexit));
3000 FunctionType *FTy = Fn->getFunctionType();
3002 // Checking that the function has the right return type, the right number of
3003 // parameters and that they all have pointer types should be enough.
3004 if (!FTy->getReturnType()->isIntegerTy() ||
3005 FTy->getNumParams() != 3 ||
3006 !FTy->getParamType(0)->isPointerTy() ||
3007 !FTy->getParamType(1)->isPointerTy() ||
3008 !FTy->getParamType(2)->isPointerTy())
3014 /// cxxDtorIsEmpty - Returns whether the given function is an empty C++
3015 /// destructor and can therefore be eliminated.
3016 /// Note that we assume that other optimization passes have already simplified
3017 /// the code so we only look for a function with a single basic block, where
3018 /// the only allowed instructions are 'ret', 'call' to an empty C++ dtor and
3019 /// other side-effect free instructions.
3020 static bool cxxDtorIsEmpty(const Function &Fn,
3021 SmallPtrSet<const Function *, 8> &CalledFunctions) {
3022 // FIXME: We could eliminate C++ destructors if they're readonly/readnone and
3023 // nounwind, but that doesn't seem worth doing.
3024 if (Fn.isDeclaration())
3027 if (++Fn.begin() != Fn.end())
3030 const BasicBlock &EntryBlock = Fn.getEntryBlock();
3031 for (BasicBlock::const_iterator I = EntryBlock.begin(), E = EntryBlock.end();
3033 if (const CallInst *CI = dyn_cast<CallInst>(I)) {
3034 // Ignore debug intrinsics.
3035 if (isa<DbgInfoIntrinsic>(CI))
3038 const Function *CalledFn = CI->getCalledFunction();
3043 SmallPtrSet<const Function *, 8> NewCalledFunctions(CalledFunctions);
3045 // Don't treat recursive functions as empty.
3046 if (!NewCalledFunctions.insert(CalledFn))
3049 if (!cxxDtorIsEmpty(*CalledFn, NewCalledFunctions))
3051 } else if (isa<ReturnInst>(*I))
3052 return true; // We're done.
3053 else if (I->mayHaveSideEffects())
3054 return false; // Destructor with side effects, bail.
3060 bool GlobalOpt::OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) {
3061 /// Itanium C++ ABI p3.3.5:
3063 /// After constructing a global (or local static) object, that will require
3064 /// destruction on exit, a termination function is registered as follows:
3066 /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d );
3068 /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the
3069 /// call f(p) when DSO d is unloaded, before all such termination calls
3070 /// registered before this one. It returns zero if registration is
3071 /// successful, nonzero on failure.
3073 // This pass will look for calls to __cxa_atexit where the function is trivial
3075 bool Changed = false;
3077 for (Function::use_iterator I = CXAAtExitFn->use_begin(),
3078 E = CXAAtExitFn->use_end(); I != E;) {
3079 // We're only interested in calls. Theoretically, we could handle invoke
3080 // instructions as well, but neither llvm-gcc nor clang generate invokes
3082 CallInst *CI = dyn_cast<CallInst>(*I++);
3087 dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts());
3091 SmallPtrSet<const Function *, 8> CalledFunctions;
3092 if (!cxxDtorIsEmpty(*DtorFn, CalledFunctions))
3095 // Just remove the call.
3096 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType()));
3097 CI->eraseFromParent();
3099 ++NumCXXDtorsRemoved;
3107 bool GlobalOpt::runOnModule(Module &M) {
3108 bool Changed = false;
3110 TD = getAnalysisIfAvailable<TargetData>();
3111 TLI = &getAnalysis<TargetLibraryInfo>();
3113 // Try to find the llvm.globalctors list.
3114 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
3116 Function *CXAAtExitFn = FindCXAAtExit(M, TLI);
3118 bool LocalChange = true;
3119 while (LocalChange) {
3120 LocalChange = false;
3122 // Delete functions that are trivially dead, ccc -> fastcc
3123 LocalChange |= OptimizeFunctions(M);
3125 // Optimize global_ctors list.
3127 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
3129 // Optimize non-address-taken globals.
3130 LocalChange |= OptimizeGlobalVars(M);
3132 // Resolve aliases, when possible.
3133 LocalChange |= OptimizeGlobalAliases(M);
3135 // Try to remove trivial global destructors.
3137 LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn);
3139 Changed |= LocalChange;
3142 // TODO: Move all global ctors functions to the end of the module for code