1 //===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source 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/Constants.h"
19 #include "llvm/DerivedTypes.h"
20 #include "llvm/Instructions.h"
21 #include "llvm/Module.h"
22 #include "llvm/Pass.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Transforms/Utils/Local.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/ADT/StringExtras.h"
33 Statistic<> NumMarked ("globalopt", "Number of globals marked constant");
34 Statistic<> NumSRA ("globalopt", "Number of aggregate globals broken "
36 Statistic<> NumSubstitute("globalopt",
37 "Number of globals with initializers stored into them");
38 Statistic<> NumDeleted ("globalopt", "Number of globals deleted");
39 Statistic<> NumFnDeleted("globalopt", "Number of functions deleted");
40 Statistic<> NumGlobUses ("globalopt", "Number of global uses devirtualized");
41 Statistic<> NumLocalized("globalopt", "Number of globals localized");
42 Statistic<> NumShrunkToBool("globalopt",
43 "Number of global vars shrunk to booleans");
45 struct GlobalOpt : public ModulePass {
46 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
47 AU.addRequired<TargetData>();
50 bool runOnModule(Module &M);
53 bool ProcessInternalGlobal(GlobalVariable *GV, Module::giterator &GVI);
56 RegisterOpt<GlobalOpt> X("globalopt", "Global Variable Optimizer");
59 ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
61 /// GlobalStatus - As we analyze each global, keep track of some information
62 /// about it. If we find out that the address of the global is taken, none of
63 /// this info will be accurate.
65 /// isLoaded - True if the global is ever loaded. If the global isn't ever
66 /// loaded it can be deleted.
69 /// StoredType - Keep track of what stores to the global look like.
72 /// NotStored - There is no store to this global. It can thus be marked
76 /// isInitializerStored - This global is stored to, but the only thing
77 /// stored is the constant it was initialized with. This is only tracked
78 /// for scalar globals.
81 /// isStoredOnce - This global is stored to, but only its initializer and
82 /// one other value is ever stored to it. If this global isStoredOnce, we
83 /// track the value stored to it in StoredOnceValue below. This is only
84 /// tracked for scalar globals.
87 /// isStored - This global is stored to by multiple values or something else
88 /// that we cannot track.
92 /// StoredOnceValue - If only one value (besides the initializer constant) is
93 /// ever stored to this global, keep track of what value it is.
94 Value *StoredOnceValue;
96 // AccessingFunction/HasMultipleAccessingFunctions - These start out
97 // null/false. When the first accessing function is noticed, it is recorded.
98 // When a second different accessing function is noticed,
99 // HasMultipleAccessingFunctions is set to true.
100 Function *AccessingFunction;
101 bool HasMultipleAccessingFunctions;
103 /// isNotSuitableForSRA - Keep track of whether any SRA preventing users of
104 /// the global exist. Such users include GEP instruction with variable
105 /// indexes, and non-gep/load/store users like constant expr casts.
106 bool isNotSuitableForSRA;
108 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
109 AccessingFunction(0), HasMultipleAccessingFunctions(false),
110 isNotSuitableForSRA(false) {}
115 /// ConstantIsDead - Return true if the specified constant is (transitively)
116 /// dead. The constant may be used by other constants (e.g. constant arrays and
117 /// constant exprs) as long as they are dead, but it cannot be used by anything
119 static bool ConstantIsDead(Constant *C) {
120 if (isa<GlobalValue>(C)) return false;
122 for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
123 if (Constant *CU = dyn_cast<Constant>(*UI)) {
124 if (!ConstantIsDead(CU)) return false;
131 /// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
132 /// structure. If the global has its address taken, return true to indicate we
133 /// can't do anything with it.
135 static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
136 std::set<PHINode*> &PHIUsers) {
137 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
138 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
139 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
140 if (CE->getOpcode() != Instruction::GetElementPtr)
141 GS.isNotSuitableForSRA = true;
142 else if (!GS.isNotSuitableForSRA) {
143 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
144 // don't like < 3 operand CE's, and we don't like non-constant integer
146 if (CE->getNumOperands() < 3 || !CE->getOperand(1)->isNullValue())
147 GS.isNotSuitableForSRA = true;
149 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
150 if (!isa<ConstantInt>(CE->getOperand(i))) {
151 GS.isNotSuitableForSRA = true;
157 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
158 if (!GS.HasMultipleAccessingFunctions) {
159 Function *F = I->getParent()->getParent();
160 if (GS.AccessingFunction == 0)
161 GS.AccessingFunction = F;
162 else if (GS.AccessingFunction != F)
163 GS.HasMultipleAccessingFunctions = true;
165 if (isa<LoadInst>(I)) {
167 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
168 // Don't allow a store OF the address, only stores TO the address.
169 if (SI->getOperand(0) == V) return true;
171 // If this is a direct store to the global (i.e., the global is a scalar
172 // value, not an aggregate), keep more specific information about
174 if (GS.StoredType != GlobalStatus::isStored)
175 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
176 Value *StoredVal = SI->getOperand(0);
177 if (StoredVal == GV->getInitializer()) {
178 if (GS.StoredType < GlobalStatus::isInitializerStored)
179 GS.StoredType = GlobalStatus::isInitializerStored;
180 } else if (isa<LoadInst>(StoredVal) &&
181 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
183 if (GS.StoredType < GlobalStatus::isInitializerStored)
184 GS.StoredType = GlobalStatus::isInitializerStored;
185 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
186 GS.StoredType = GlobalStatus::isStoredOnce;
187 GS.StoredOnceValue = StoredVal;
188 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
189 GS.StoredOnceValue == StoredVal) {
192 GS.StoredType = GlobalStatus::isStored;
195 GS.StoredType = GlobalStatus::isStored;
197 } else if (I->getOpcode() == Instruction::GetElementPtr) {
198 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
200 // If the first two indices are constants, this can be SRA'd.
201 if (isa<GlobalVariable>(I->getOperand(0))) {
202 if (I->getNumOperands() < 3 || !isa<Constant>(I->getOperand(1)) ||
203 !cast<Constant>(I->getOperand(1))->isNullValue() ||
204 !isa<ConstantInt>(I->getOperand(2)))
205 GS.isNotSuitableForSRA = true;
206 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I->getOperand(0))){
207 if (CE->getOpcode() != Instruction::GetElementPtr ||
208 CE->getNumOperands() < 3 || I->getNumOperands() < 2 ||
209 !isa<Constant>(I->getOperand(0)) ||
210 !cast<Constant>(I->getOperand(0))->isNullValue())
211 GS.isNotSuitableForSRA = true;
213 GS.isNotSuitableForSRA = true;
215 } else if (I->getOpcode() == Instruction::Select) {
216 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
217 GS.isNotSuitableForSRA = true;
218 } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
219 // PHI nodes we can check just like select or GEP instructions, but we
220 // have to be careful about infinite recursion.
221 if (PHIUsers.insert(PN).second) // Not already visited.
222 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
223 GS.isNotSuitableForSRA = true;
224 } else if (isa<SetCondInst>(I)) {
225 GS.isNotSuitableForSRA = true;
227 return true; // Any other non-load instruction might take address!
229 } else if (Constant *C = dyn_cast<Constant>(*UI)) {
230 // We might have a dead and dangling constant hanging off of here.
231 if (!ConstantIsDead(C))
234 // Otherwise must be a global or some other user.
241 static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
242 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
244 unsigned IdxV = (unsigned)CI->getRawValue();
246 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
247 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
248 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
249 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
250 } else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Agg)) {
251 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
252 } else if (isa<ConstantAggregateZero>(Agg)) {
253 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
254 if (IdxV < STy->getNumElements())
255 return Constant::getNullValue(STy->getElementType(IdxV));
256 } else if (const SequentialType *STy =
257 dyn_cast<SequentialType>(Agg->getType())) {
258 return Constant::getNullValue(STy->getElementType());
260 } else if (isa<UndefValue>(Agg)) {
261 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
262 if (IdxV < STy->getNumElements())
263 return UndefValue::get(STy->getElementType(IdxV));
264 } else if (const SequentialType *STy =
265 dyn_cast<SequentialType>(Agg->getType())) {
266 return UndefValue::get(STy->getElementType());
272 static Constant *TraverseGEPInitializer(User *GEP, Constant *Init) {
273 if (GEP->getNumOperands() == 1 ||
274 !isa<Constant>(GEP->getOperand(1)) ||
275 !cast<Constant>(GEP->getOperand(1))->isNullValue())
278 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) {
279 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
281 Init = getAggregateConstantElement(Init, Idx);
282 if (Init == 0) return 0;
287 /// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
288 /// users of the global, cleaning up the obvious ones. This is largely just a
289 /// quick scan over the use list to clean up the easy and obvious cruft. This
290 /// returns true if it made a change.
291 static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
292 bool Changed = false;
293 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
296 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
297 // Replace the load with the initializer.
298 LI->replaceAllUsesWith(Init);
299 LI->eraseFromParent();
301 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
302 // Store must be unreachable or storing Init into the global.
303 SI->eraseFromParent();
305 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
306 if (CE->getOpcode() == Instruction::GetElementPtr) {
307 if (Constant *SubInit = TraverseGEPInitializer(CE, Init))
308 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
309 if (CE->use_empty()) {
310 CE->destroyConstant();
314 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
315 if (Constant *SubInit = TraverseGEPInitializer(GEP, Init))
316 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
318 // If this GEP has variable indexes, we should still be able to delete
319 // any stores through it.
320 for (Value::use_iterator GUI = GEP->use_begin(), E = GEP->use_end();
322 if (StoreInst *SI = dyn_cast<StoreInst>(*GUI++)) {
323 SI->eraseFromParent();
328 if (GEP->use_empty()) {
329 GEP->eraseFromParent();
332 } else if (Constant *C = dyn_cast<Constant>(U)) {
333 // If we have a chain of dead constantexprs or other things dangling from
334 // us, and if they are all dead, nuke them without remorse.
335 if (ConstantIsDead(C)) {
336 C->destroyConstant();
337 // This could have incalidated UI, start over from scratch.x
338 CleanupConstantGlobalUsers(V, Init);
346 /// SRAGlobal - Perform scalar replacement of aggregates on the specified global
347 /// variable. This opens the door for other optimizations by exposing the
348 /// behavior of the program in a more fine-grained way. We have determined that
349 /// this transformation is safe already. We return the first global variable we
350 /// insert so that the caller can reprocess it.
351 static GlobalVariable *SRAGlobal(GlobalVariable *GV) {
352 assert(GV->hasInternalLinkage() && !GV->isConstant());
353 Constant *Init = GV->getInitializer();
354 const Type *Ty = Init->getType();
356 std::vector<GlobalVariable*> NewGlobals;
357 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
359 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
360 NewGlobals.reserve(STy->getNumElements());
361 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
362 Constant *In = getAggregateConstantElement(Init,
363 ConstantUInt::get(Type::UIntTy, i));
364 assert(In && "Couldn't get element of initializer?");
365 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
366 GlobalVariable::InternalLinkage,
367 In, GV->getName()+"."+utostr(i));
368 Globals.insert(GV, NGV);
369 NewGlobals.push_back(NGV);
371 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
372 unsigned NumElements = 0;
373 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
374 NumElements = ATy->getNumElements();
375 else if (const PackedType *PTy = dyn_cast<PackedType>(STy))
376 NumElements = PTy->getNumElements();
378 assert(0 && "Unknown aggregate sequential type!");
380 if (NumElements > 16 && GV->hasNUsesOrMore(16))
381 return 0; // It's not worth it.
382 NewGlobals.reserve(NumElements);
383 for (unsigned i = 0, e = NumElements; i != e; ++i) {
384 Constant *In = getAggregateConstantElement(Init,
385 ConstantUInt::get(Type::UIntTy, i));
386 assert(In && "Couldn't get element of initializer?");
388 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
389 GlobalVariable::InternalLinkage,
390 In, GV->getName()+"."+utostr(i));
391 Globals.insert(GV, NGV);
392 NewGlobals.push_back(NGV);
396 if (NewGlobals.empty())
399 DEBUG(std::cerr << "PERFORMING GLOBAL SRA ON: " << *GV);
401 Constant *NullInt = Constant::getNullValue(Type::IntTy);
403 // Loop over all of the uses of the global, replacing the constantexpr geps,
404 // with smaller constantexpr geps or direct references.
405 while (!GV->use_empty()) {
406 User *GEP = GV->use_back();
407 assert(((isa<ConstantExpr>(GEP) &&
408 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
409 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
411 // Ignore the 1th operand, which has to be zero or else the program is quite
412 // broken (undefined). Get the 2nd operand, which is the structure or array
415 (unsigned)cast<ConstantInt>(GEP->getOperand(2))->getRawValue();
416 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
418 Value *NewPtr = NewGlobals[Val];
420 // Form a shorter GEP if needed.
421 if (GEP->getNumOperands() > 3)
422 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
423 std::vector<Constant*> Idxs;
424 Idxs.push_back(NullInt);
425 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
426 Idxs.push_back(CE->getOperand(i));
427 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
429 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
430 std::vector<Value*> Idxs;
431 Idxs.push_back(NullInt);
432 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
433 Idxs.push_back(GEPI->getOperand(i));
434 NewPtr = new GetElementPtrInst(NewPtr, Idxs,
435 GEPI->getName()+"."+utostr(Val), GEPI);
437 GEP->replaceAllUsesWith(NewPtr);
439 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
440 GEPI->eraseFromParent();
442 cast<ConstantExpr>(GEP)->destroyConstant();
445 // Delete the old global, now that it is dead.
449 // Loop over the new globals array deleting any globals that are obviously
450 // dead. This can arise due to scalarization of a structure or an array that
451 // has elements that are dead.
452 unsigned FirstGlobal = 0;
453 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
454 if (NewGlobals[i]->use_empty()) {
455 Globals.erase(NewGlobals[i]);
456 if (FirstGlobal == i) ++FirstGlobal;
459 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
462 /// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
463 /// value will trap if the value is dynamically null.
464 static bool AllUsesOfValueWillTrapIfNull(Value *V) {
465 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
466 if (isa<LoadInst>(*UI)) {
468 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
469 if (SI->getOperand(0) == V) {
470 //std::cerr << "NONTRAPPING USE: " << **UI;
471 return false; // Storing the value.
473 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
474 if (CI->getOperand(0) != V) {
475 //std::cerr << "NONTRAPPING USE: " << **UI;
476 return false; // Not calling the ptr
478 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
479 if (II->getOperand(0) != V) {
480 //std::cerr << "NONTRAPPING USE: " << **UI;
481 return false; // Not calling the ptr
483 } else if (CastInst *CI = dyn_cast<CastInst>(*UI)) {
484 if (!AllUsesOfValueWillTrapIfNull(CI)) return false;
485 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
486 if (!AllUsesOfValueWillTrapIfNull(GEPI)) return false;
487 } else if (isa<SetCondInst>(*UI) &&
488 isa<ConstantPointerNull>(UI->getOperand(1))) {
489 // Ignore setcc X, null
491 //std::cerr << "NONTRAPPING USE: " << **UI;
497 /// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
498 /// from GV will trap if the loaded value is null. Note that this also permits
499 /// comparisons of the loaded value against null, as a special case.
500 static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
501 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
502 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
503 if (!AllUsesOfValueWillTrapIfNull(LI))
505 } else if (isa<StoreInst>(*UI)) {
506 // Ignore stores to the global.
508 // We don't know or understand this user, bail out.
509 //std::cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
516 static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
517 bool Changed = false;
518 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
519 Instruction *I = cast<Instruction>(*UI++);
520 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
521 LI->setOperand(0, NewV);
523 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
524 if (SI->getOperand(1) == V) {
525 SI->setOperand(1, NewV);
528 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
529 if (I->getOperand(0) == V) {
530 // Calling through the pointer! Turn into a direct call, but be careful
531 // that the pointer is not also being passed as an argument.
532 I->setOperand(0, NewV);
534 bool PassedAsArg = false;
535 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
536 if (I->getOperand(i) == V) {
538 I->setOperand(i, NewV);
542 // Being passed as an argument also. Be careful to not invalidate UI!
546 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
547 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
548 ConstantExpr::getCast(NewV, CI->getType()));
549 if (CI->use_empty()) {
551 CI->eraseFromParent();
553 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
554 // Should handle GEP here.
555 std::vector<Constant*> Indices;
556 Indices.reserve(GEPI->getNumOperands()-1);
557 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
558 if (Constant *C = dyn_cast<Constant>(GEPI->getOperand(i)))
559 Indices.push_back(C);
562 if (Indices.size() == GEPI->getNumOperands()-1)
563 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
564 ConstantExpr::getGetElementPtr(NewV, Indices));
565 if (GEPI->use_empty()) {
567 GEPI->eraseFromParent();
576 /// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
577 /// value stored into it. If there are uses of the loaded value that would trap
578 /// if the loaded value is dynamically null, then we know that they cannot be
579 /// reachable with a null optimize away the load.
580 static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
581 std::vector<LoadInst*> Loads;
582 bool Changed = false;
584 // Replace all uses of loads with uses of uses of the stored value.
585 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end();
587 if (LoadInst *LI = dyn_cast<LoadInst>(*GUI)) {
589 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
591 assert(isa<StoreInst>(*GUI) && "Only expect load and stores!");
595 DEBUG(std::cerr << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
599 // Delete all of the loads we can, keeping track of whether we nuked them all!
600 bool AllLoadsGone = true;
601 while (!Loads.empty()) {
602 LoadInst *L = Loads.back();
603 if (L->use_empty()) {
604 L->eraseFromParent();
607 AllLoadsGone = false;
612 // If we nuked all of the loads, then none of the stores are needed either,
613 // nor is the global.
615 DEBUG(std::cerr << " *** GLOBAL NOW DEAD!\n");
616 CleanupConstantGlobalUsers(GV, 0);
617 if (GV->use_empty()) {
618 GV->eraseFromParent();
626 /// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
627 /// instructions that are foldable.
628 static void ConstantPropUsersOf(Value *V) {
629 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
630 if (Instruction *I = dyn_cast<Instruction>(*UI++))
631 if (Constant *NewC = ConstantFoldInstruction(I)) {
632 I->replaceAllUsesWith(NewC);
634 // Advance UI to the next non-I use to avoid invalidating it!
635 // Instructions could multiply use V.
636 while (UI != E && *UI == I)
638 I->eraseFromParent();
642 /// OptimizeGlobalAddressOfMalloc - This function takes the specified global
643 /// variable, and transforms the program as if it always contained the result of
644 /// the specified malloc. Because it is always the result of the specified
645 /// malloc, there is no reason to actually DO the malloc. Instead, turn the
646 /// malloc into a global, and any laods of GV as uses of the new global.
647 static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
649 DEBUG(std::cerr << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " <<*MI);
650 ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
652 if (NElements->getRawValue() != 1) {
653 // If we have an array allocation, transform it to a single element
654 // allocation to make the code below simpler.
655 Type *NewTy = ArrayType::get(MI->getAllocatedType(),
656 (unsigned)NElements->getRawValue());
658 new MallocInst(NewTy, Constant::getNullValue(Type::UIntTy),
660 std::vector<Value*> Indices;
661 Indices.push_back(Constant::getNullValue(Type::IntTy));
662 Indices.push_back(Indices[0]);
663 Value *NewGEP = new GetElementPtrInst(NewMI, Indices,
664 NewMI->getName()+".el0", MI);
665 MI->replaceAllUsesWith(NewGEP);
666 MI->eraseFromParent();
670 // Create the new global variable. The contents of the malloc'd memory is
671 // undefined, so initialize with an undef value.
672 Constant *Init = UndefValue::get(MI->getAllocatedType());
673 GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false,
674 GlobalValue::InternalLinkage, Init,
675 GV->getName()+".body");
676 GV->getParent()->getGlobalList().insert(GV, NewGV);
678 // Anything that used the malloc now uses the global directly.
679 MI->replaceAllUsesWith(NewGV);
681 Constant *RepValue = NewGV;
682 if (NewGV->getType() != GV->getType()->getElementType())
683 RepValue = ConstantExpr::getCast(RepValue, GV->getType()->getElementType());
685 // If there is a comparison against null, we will insert a global bool to
686 // keep track of whether the global was initialized yet or not.
687 GlobalVariable *InitBool =
688 new GlobalVariable(Type::BoolTy, false, GlobalValue::InternalLinkage,
689 ConstantBool::False, GV->getName()+".init");
690 bool InitBoolUsed = false;
692 // Loop over all uses of GV, processing them in turn.
693 std::vector<StoreInst*> Stores;
694 while (!GV->use_empty())
695 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
696 while (!LI->use_empty()) {
697 Use &LoadUse = LI->use_begin().getUse();
698 if (!isa<SetCondInst>(LoadUse.getUser()))
701 // Replace the setcc X, 0 with a use of the bool value.
702 SetCondInst *SCI = cast<SetCondInst>(LoadUse.getUser());
703 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", SCI);
705 switch (SCI->getOpcode()) {
706 default: assert(0 && "Unknown opcode!");
707 case Instruction::SetLT:
708 LV = ConstantBool::False; // X < null -> always false
710 case Instruction::SetEQ:
711 case Instruction::SetLE:
712 LV = BinaryOperator::createNot(LV, "notinit", SCI);
714 case Instruction::SetNE:
715 case Instruction::SetGE:
716 case Instruction::SetGT:
719 SCI->replaceAllUsesWith(LV);
720 SCI->eraseFromParent();
723 LI->eraseFromParent();
725 StoreInst *SI = cast<StoreInst>(GV->use_back());
726 // The global is initialized when the store to it occurs.
727 new StoreInst(ConstantBool::True, InitBool, SI);
728 SI->eraseFromParent();
731 // If the initialization boolean was used, insert it, otherwise delete it.
733 while (!InitBool->use_empty()) // Delete initializations
734 cast<Instruction>(InitBool->use_back())->eraseFromParent();
737 GV->getParent()->getGlobalList().insert(GV, InitBool);
740 // Now the GV is dead, nuke it and the malloc.
741 GV->eraseFromParent();
742 MI->eraseFromParent();
744 // To further other optimizations, loop over all users of NewGV and try to
745 // constant prop them. This will promote GEP instructions with constant
746 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
747 ConstantPropUsersOf(NewGV);
748 if (RepValue != NewGV)
749 ConstantPropUsersOf(RepValue);
754 /// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
755 /// to make sure that there are no complex uses of V. We permit simple things
756 /// like dereferencing the pointer, but not storing through the address, unless
757 /// it is to the specified global.
758 static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
759 GlobalVariable *GV) {
760 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI)
761 if (isa<LoadInst>(*UI) || isa<SetCondInst>(*UI)) {
763 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
764 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
765 return false; // Storing the pointer itself... bad.
766 // Otherwise, storing through it, or storing into GV... fine.
767 } else if (isa<GetElementPtrInst>(*UI) || isa<SelectInst>(*UI)) {
768 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(cast<Instruction>(*UI),GV))
777 // OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
778 // that only one value (besides its initializer) is ever stored to the global.
779 static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
780 Module::giterator &GVI, TargetData &TD) {
781 if (CastInst *CI = dyn_cast<CastInst>(StoredOnceVal))
782 StoredOnceVal = CI->getOperand(0);
783 else if (GetElementPtrInst *GEPI =dyn_cast<GetElementPtrInst>(StoredOnceVal)){
784 // "getelementptr Ptr, 0, 0, 0" is really just a cast.
785 bool IsJustACast = true;
786 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
787 if (!isa<Constant>(GEPI->getOperand(i)) ||
788 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
793 StoredOnceVal = GEPI->getOperand(0);
796 // If we are dealing with a pointer global that is initialized to null and
797 // only has one (non-null) value stored into it, then we can optimize any
798 // users of the loaded value (often calls and loads) that would trap if the
800 if (isa<PointerType>(GV->getInitializer()->getType()) &&
801 GV->getInitializer()->isNullValue()) {
802 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
803 if (GV->getInitializer()->getType() != SOVC->getType())
804 SOVC = ConstantExpr::getCast(SOVC, GV->getInitializer()->getType());
806 // Optimize away any trapping uses of the loaded value.
807 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
809 } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
810 // If we have a global that is only initialized with a fixed size malloc,
811 // and if all users of the malloc trap, and if the malloc'd address is not
812 // put anywhere else, transform the program to use global memory instead
813 // of malloc'd memory. This eliminates dynamic allocation (good) and
814 // exposes the resultant global to further GlobalOpt (even better). Note
815 // that we restrict this transformation to only working on small
816 // allocations (2048 bytes currently), as we don't want to introduce a 16M
817 // global or something.
818 if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize()))
819 if (MI->getAllocatedType()->isSized() &&
820 NElements->getRawValue()*
821 TD.getTypeSize(MI->getAllocatedType()) < 2048 &&
822 AllUsesOfLoadedValueWillTrapIfNull(GV) &&
823 ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV)) {
824 GVI = OptimizeGlobalAddressOfMalloc(GV, MI);
833 /// ShrinkGlobalToBoolean - At this point, we have learned that the only two
834 /// values ever stored into GV are its initializer and OtherVal.
835 static void ShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
836 // Create the new global, initializing it to false.
837 GlobalVariable *NewGV = new GlobalVariable(Type::BoolTy, false,
838 GlobalValue::InternalLinkage, ConstantBool::False, GV->getName()+".b");
839 GV->getParent()->getGlobalList().insert(GV, NewGV);
841 Constant *InitVal = GV->getInitializer();
842 assert(InitVal->getType() != Type::BoolTy && "No reason to shrink to bool!");
844 // If initialized to zero and storing one into the global, we can use a cast
845 // instead of a select to synthesize the desired value.
846 bool IsOneZero = false;
847 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
848 IsOneZero = InitVal->isNullValue() && CI->equalsInt(1);
850 while (!GV->use_empty()) {
851 Instruction *UI = cast<Instruction>(GV->use_back());
852 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
853 // Change the store into a boolean store.
854 bool StoringOther = SI->getOperand(0) == OtherVal;
855 // Only do this if we weren't storing a loaded value.
857 if (StoringOther || SI->getOperand(0) == InitVal)
858 StoreVal = ConstantBool::get(StoringOther);
860 // Otherwise, we are storing a previously loaded copy. To do this,
861 // change the copy from copying the original value to just copying the
863 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
865 // If we're already replaced the input, StoredVal will be a cast or
866 // select instruction. If not, it will be a load of the original
868 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
869 assert(LI->getOperand(0) == GV && "Not a copy!");
870 // Insert a new load, to preserve the saved value.
871 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
873 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
874 "This is not a form that we understand!");
875 StoreVal = StoredVal->getOperand(0);
876 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
879 new StoreInst(StoreVal, NewGV, SI);
880 } else if (!UI->use_empty()) {
881 // Change the load into a load of bool then a select.
882 LoadInst *LI = cast<LoadInst>(UI);
884 std::string Name = LI->getName(); LI->setName("");
885 LoadInst *NLI = new LoadInst(NewGV, Name+".b", LI);
888 NSI = new CastInst(NLI, LI->getType(), Name, LI);
890 NSI = new SelectInst(NLI, OtherVal, InitVal, Name, LI);
891 LI->replaceAllUsesWith(NSI);
893 UI->eraseFromParent();
896 GV->eraseFromParent();
900 /// ProcessInternalGlobal - Analyze the specified global variable and optimize
901 /// it if possible. If we make a change, return true.
902 bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
903 Module::giterator &GVI) {
904 std::set<PHINode*> PHIUsers;
907 GV->removeDeadConstantUsers();
909 if (GV->use_empty()) {
910 DEBUG(std::cerr << "GLOBAL DEAD: " << *GV);
911 GV->eraseFromParent();
916 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
917 // If this is a first class global and has only one accessing function
918 // and this function is main (which we know is not recursive we can make
919 // this global a local variable) we replace the global with a local alloca
922 // NOTE: It doesn't make sense to promote non first class types since we
923 // are just replacing static memory to stack memory.
924 if (!GS.HasMultipleAccessingFunctions &&
925 GS.AccessingFunction &&
926 GV->getType()->getElementType()->isFirstClassType() &&
927 GS.AccessingFunction->getName() == "main" &&
928 GS.AccessingFunction->hasExternalLinkage()) {
929 DEBUG(std::cerr << "LOCALIZING GLOBAL: " << *GV);
930 Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
931 const Type* ElemTy = GV->getType()->getElementType();
932 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
933 if (!isa<UndefValue>(GV->getInitializer()))
934 new StoreInst(GV->getInitializer(), Alloca, FirstI);
936 GV->replaceAllUsesWith(Alloca);
937 GV->eraseFromParent();
941 // If the global is never loaded (but may be stored to), it is dead.
944 DEBUG(std::cerr << "GLOBAL NEVER LOADED: " << *GV);
946 // Delete any stores we can find to the global. We may not be able to
947 // make it completely dead though.
948 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
950 // If the global is dead now, delete it.
951 if (GV->use_empty()) {
952 GV->eraseFromParent();
958 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
959 DEBUG(std::cerr << "MARKING CONSTANT: " << *GV);
960 GV->setConstant(true);
962 // Clean up any obviously simplifiable users now.
963 CleanupConstantGlobalUsers(GV, GV->getInitializer());
965 // If the global is dead now, just nuke it.
966 if (GV->use_empty()) {
967 DEBUG(std::cerr << " *** Marking constant allowed us to simplify "
968 "all users and delete global!\n");
969 GV->eraseFromParent();
975 } else if (!GS.isNotSuitableForSRA &&
976 !GV->getInitializer()->getType()->isFirstClassType()) {
977 if (GlobalVariable *FirstNewGV = SRAGlobal(GV)) {
978 GVI = FirstNewGV; // Don't skip the newly produced globals!
981 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
982 // If the initial value for the global was an undef value, and if only
983 // one other value was stored into it, we can just change the
984 // initializer to be an undef value, then delete all stores to the
985 // global. This allows us to mark it constant.
986 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
987 if (isa<UndefValue>(GV->getInitializer())) {
988 // Change the initial value here.
989 GV->setInitializer(SOVConstant);
991 // Clean up any obviously simplifiable users now.
992 CleanupConstantGlobalUsers(GV, GV->getInitializer());
994 if (GV->use_empty()) {
995 DEBUG(std::cerr << " *** Substituting initializer allowed us to "
996 "simplify all users and delete global!\n");
997 GV->eraseFromParent();
1006 // Try to optimize globals based on the knowledge that only one value
1007 // (besides its initializer) is ever stored to the global.
1008 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1009 getAnalysis<TargetData>()))
1012 // Otherwise, if the global was not a boolean, we can shrink it to be a
1014 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1015 if (GV->getType()->getElementType() != Type::BoolTy &&
1016 !GV->getType()->getElementType()->isFloatingPoint()) {
1017 DEBUG(std::cerr << " *** SHRINKING TO BOOL: " << *GV);
1018 ShrinkGlobalToBoolean(GV, SOVConstant);
1028 bool GlobalOpt::runOnModule(Module &M) {
1029 bool Changed = false;
1031 // As a prepass, delete functions that are trivially dead.
1032 bool LocalChange = true;
1033 while (LocalChange) {
1034 LocalChange = false;
1035 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1037 F->removeDeadConstantUsers();
1038 if (F->use_empty() && (F->hasInternalLinkage() ||
1039 F->hasLinkOnceLinkage())) {
1040 M.getFunctionList().erase(F);
1045 Changed |= LocalChange;
1049 while (LocalChange) {
1050 LocalChange = false;
1051 for (Module::giterator GVI = M.gbegin(), E = M.gend(); GVI != E;) {
1052 GlobalVariable *GV = GVI++;
1053 if (!GV->isConstant() && GV->hasInternalLinkage() &&
1054 GV->hasInitializer())
1055 LocalChange |= ProcessInternalGlobal(GV, GVI);
1057 Changed |= LocalChange;