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");
42 struct GlobalOpt : public ModulePass {
43 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
44 AU.addRequired<TargetData>();
47 bool runOnModule(Module &M);
50 bool ProcessInternalGlobal(GlobalVariable *GV, Module::giterator &GVI);
53 RegisterOpt<GlobalOpt> X("globalopt", "Global Variable Optimizer");
56 ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
58 /// GlobalStatus - As we analyze each global, keep track of some information
59 /// about it. If we find out that the address of the global is taken, none of
60 /// this info will be accurate.
62 /// isLoaded - True if the global is ever loaded. If the global isn't ever
63 /// loaded it can be deleted.
66 /// StoredType - Keep track of what stores to the global look like.
69 /// NotStored - There is no store to this global. It can thus be marked
73 /// isInitializerStored - This global is stored to, but the only thing
74 /// stored is the constant it was initialized with. This is only tracked
75 /// for scalar globals.
78 /// isStoredOnce - This global is stored to, but only its initializer and
79 /// one other value is ever stored to it. If this global isStoredOnce, we
80 /// track the value stored to it in StoredOnceValue below. This is only
81 /// tracked for scalar globals.
84 /// isStored - This global is stored to by multiple values or something else
85 /// that we cannot track.
89 /// StoredOnceValue - If only one value (besides the initializer constant) is
90 /// ever stored to this global, keep track of what value it is.
91 Value *StoredOnceValue;
93 /// isNotSuitableForSRA - Keep track of whether any SRA preventing users of
94 /// the global exist. Such users include GEP instruction with variable
95 /// indexes, and non-gep/load/store users like constant expr casts.
96 bool isNotSuitableForSRA;
98 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
99 isNotSuitableForSRA(false) {}
104 /// ConstantIsDead - Return true if the specified constant is (transitively)
105 /// dead. The constant may be used by other constants (e.g. constant arrays and
106 /// constant exprs) as long as they are dead, but it cannot be used by anything
108 static bool ConstantIsDead(Constant *C) {
109 if (isa<GlobalValue>(C)) return false;
111 for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
112 if (Constant *CU = dyn_cast<Constant>(*UI)) {
113 if (!ConstantIsDead(CU)) return false;
120 /// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
121 /// structure. If the global has its address taken, return true to indicate we
122 /// can't do anything with it.
124 static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
125 std::set<PHINode*> &PHIUsers) {
126 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
127 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
128 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
129 if (CE->getOpcode() != Instruction::GetElementPtr)
130 GS.isNotSuitableForSRA = true;
131 else if (!GS.isNotSuitableForSRA) {
132 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
133 // don't like < 3 operand CE's, and we don't like non-constant integer
135 if (CE->getNumOperands() < 3 || !CE->getOperand(1)->isNullValue())
136 GS.isNotSuitableForSRA = true;
138 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
139 if (!isa<ConstantInt>(CE->getOperand(i))) {
140 GS.isNotSuitableForSRA = true;
146 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
147 if (isa<LoadInst>(I)) {
149 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
150 // Don't allow a store OF the address, only stores TO the address.
151 if (SI->getOperand(0) == V) return true;
153 // If this is a direct store to the global (i.e., the global is a scalar
154 // value, not an aggregate), keep more specific information about
156 if (GS.StoredType != GlobalStatus::isStored)
157 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
158 Value *StoredVal = SI->getOperand(0);
159 if (StoredVal == GV->getInitializer()) {
160 if (GS.StoredType < GlobalStatus::isInitializerStored)
161 GS.StoredType = GlobalStatus::isInitializerStored;
162 } else if (isa<LoadInst>(StoredVal) &&
163 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
165 if (GS.StoredType < GlobalStatus::isInitializerStored)
166 GS.StoredType = GlobalStatus::isInitializerStored;
167 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
168 GS.StoredType = GlobalStatus::isStoredOnce;
169 GS.StoredOnceValue = StoredVal;
170 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
171 GS.StoredOnceValue == StoredVal) {
174 GS.StoredType = GlobalStatus::isStored;
177 GS.StoredType = GlobalStatus::isStored;
179 } else if (I->getOpcode() == Instruction::GetElementPtr) {
180 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
182 // If the first two indices are constants, this can be SRA'd.
183 if (isa<GlobalVariable>(I->getOperand(0))) {
184 if (I->getNumOperands() < 3 || !isa<Constant>(I->getOperand(1)) ||
185 !cast<Constant>(I->getOperand(1))->isNullValue() ||
186 !isa<ConstantInt>(I->getOperand(2)))
187 GS.isNotSuitableForSRA = true;
188 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I->getOperand(0))){
189 if (CE->getOpcode() != Instruction::GetElementPtr ||
190 CE->getNumOperands() < 3 || I->getNumOperands() < 2 ||
191 !isa<Constant>(I->getOperand(0)) ||
192 !cast<Constant>(I->getOperand(0))->isNullValue())
193 GS.isNotSuitableForSRA = true;
195 GS.isNotSuitableForSRA = true;
197 } else if (I->getOpcode() == Instruction::Select) {
198 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
199 GS.isNotSuitableForSRA = true;
200 } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
201 // PHI nodes we can check just like select or GEP instructions, but we
202 // have to be careful about infinite recursion.
203 if (PHIUsers.insert(PN).second) // Not already visited.
204 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
205 GS.isNotSuitableForSRA = true;
206 } else if (isa<SetCondInst>(I)) {
207 GS.isNotSuitableForSRA = true;
209 return true; // Any other non-load instruction might take address!
211 } else if (Constant *C = dyn_cast<Constant>(*UI)) {
212 // We might have a dead and dangling constant hanging off of here.
213 if (!ConstantIsDead(C))
216 // Otherwise must be a global or some other user.
223 static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
224 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
226 uint64_t IdxV = CI->getRawValue();
228 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
229 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
230 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
231 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
232 } else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Agg)) {
233 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
234 } else if (isa<ConstantAggregateZero>(Agg)) {
235 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
236 if (IdxV < STy->getNumElements())
237 return Constant::getNullValue(STy->getElementType(IdxV));
238 } else if (const SequentialType *STy =
239 dyn_cast<SequentialType>(Agg->getType())) {
240 return Constant::getNullValue(STy->getElementType());
242 } else if (isa<UndefValue>(Agg)) {
243 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
244 if (IdxV < STy->getNumElements())
245 return UndefValue::get(STy->getElementType(IdxV));
246 } else if (const SequentialType *STy =
247 dyn_cast<SequentialType>(Agg->getType())) {
248 return UndefValue::get(STy->getElementType());
254 static Constant *TraverseGEPInitializer(User *GEP, Constant *Init) {
255 if (GEP->getNumOperands() == 1 ||
256 !isa<Constant>(GEP->getOperand(1)) ||
257 !cast<Constant>(GEP->getOperand(1))->isNullValue())
260 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i) {
261 ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
263 Init = getAggregateConstantElement(Init, Idx);
264 if (Init == 0) return 0;
269 /// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
270 /// users of the global, cleaning up the obvious ones. This is largely just a
271 /// quick scan over the use list to clean up the easy and obvious cruft. This
272 /// returns true if it made a change.
273 static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
274 bool Changed = false;
275 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
278 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
279 // Replace the load with the initializer.
280 LI->replaceAllUsesWith(Init);
281 LI->eraseFromParent();
283 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
284 // Store must be unreachable or storing Init into the global.
285 SI->eraseFromParent();
287 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
288 if (CE->getOpcode() == Instruction::GetElementPtr) {
289 if (Constant *SubInit = TraverseGEPInitializer(CE, Init))
290 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
291 if (CE->use_empty()) {
292 CE->destroyConstant();
296 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
297 if (Constant *SubInit = TraverseGEPInitializer(GEP, Init))
298 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
300 // If this GEP has variable indexes, we should still be able to delete
301 // any stores through it.
302 for (Value::use_iterator GUI = GEP->use_begin(), E = GEP->use_end();
304 if (StoreInst *SI = dyn_cast<StoreInst>(*GUI++)) {
305 SI->eraseFromParent();
310 if (GEP->use_empty()) {
311 GEP->eraseFromParent();
314 } else if (Constant *C = dyn_cast<Constant>(U)) {
315 // If we have a chain of dead constantexprs or other things dangling from
316 // us, and if they are all dead, nuke them without remorse.
317 if (ConstantIsDead(C)) {
318 C->destroyConstant();
319 // This could have incalidated UI, start over from scratch.x
320 CleanupConstantGlobalUsers(V, Init);
328 /// SRAGlobal - Perform scalar replacement of aggregates on the specified global
329 /// variable. This opens the door for other optimizations by exposing the
330 /// behavior of the program in a more fine-grained way. We have determined that
331 /// this transformation is safe already. We return the first global variable we
332 /// insert so that the caller can reprocess it.
333 static GlobalVariable *SRAGlobal(GlobalVariable *GV) {
334 assert(GV->hasInternalLinkage() && !GV->isConstant());
335 Constant *Init = GV->getInitializer();
336 const Type *Ty = Init->getType();
338 std::vector<GlobalVariable*> NewGlobals;
339 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
341 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
342 NewGlobals.reserve(STy->getNumElements());
343 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
344 Constant *In = getAggregateConstantElement(Init,
345 ConstantUInt::get(Type::UIntTy, i));
346 assert(In && "Couldn't get element of initializer?");
347 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
348 GlobalVariable::InternalLinkage,
349 In, GV->getName()+"."+utostr(i));
350 Globals.insert(GV, NGV);
351 NewGlobals.push_back(NGV);
353 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
354 unsigned NumElements = 0;
355 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
356 NumElements = ATy->getNumElements();
357 else if (const PackedType *PTy = dyn_cast<PackedType>(STy))
358 NumElements = PTy->getNumElements();
360 assert(0 && "Unknown aggregate sequential type!");
362 if (NumElements > 16 && GV->use_size() > 16) return 0; // It's not worth it.
363 NewGlobals.reserve(NumElements);
364 for (unsigned i = 0, e = NumElements; i != e; ++i) {
365 Constant *In = getAggregateConstantElement(Init,
366 ConstantUInt::get(Type::UIntTy, i));
367 assert(In && "Couldn't get element of initializer?");
369 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
370 GlobalVariable::InternalLinkage,
371 In, GV->getName()+"."+utostr(i));
372 Globals.insert(GV, NGV);
373 NewGlobals.push_back(NGV);
377 if (NewGlobals.empty())
380 DEBUG(std::cerr << "PERFORMING GLOBAL SRA ON: " << *GV);
382 Constant *NullInt = Constant::getNullValue(Type::IntTy);
384 // Loop over all of the uses of the global, replacing the constantexpr geps,
385 // with smaller constantexpr geps or direct references.
386 while (!GV->use_empty()) {
387 User *GEP = GV->use_back();
388 assert(((isa<ConstantExpr>(GEP) &&
389 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
390 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
392 // Ignore the 1th operand, which has to be zero or else the program is quite
393 // broken (undefined). Get the 2nd operand, which is the structure or array
395 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getRawValue();
396 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
398 Value *NewPtr = NewGlobals[Val];
400 // Form a shorter GEP if needed.
401 if (GEP->getNumOperands() > 3)
402 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
403 std::vector<Constant*> Idxs;
404 Idxs.push_back(NullInt);
405 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
406 Idxs.push_back(CE->getOperand(i));
407 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
409 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
410 std::vector<Value*> Idxs;
411 Idxs.push_back(NullInt);
412 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
413 Idxs.push_back(GEPI->getOperand(i));
414 NewPtr = new GetElementPtrInst(NewPtr, Idxs,
415 GEPI->getName()+"."+utostr(Val), GEPI);
417 GEP->replaceAllUsesWith(NewPtr);
419 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
420 GEPI->eraseFromParent();
422 cast<ConstantExpr>(GEP)->destroyConstant();
425 // Delete the old global, now that it is dead.
429 // Loop over the new globals array deleting any globals that are obviously
430 // dead. This can arise due to scalarization of a structure or an array that
431 // has elements that are dead.
432 unsigned FirstGlobal = 0;
433 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
434 if (NewGlobals[i]->use_empty()) {
435 Globals.erase(NewGlobals[i]);
436 if (FirstGlobal == i) ++FirstGlobal;
439 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
442 /// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
443 /// value will trap if the value is dynamically null.
444 static bool AllUsesOfValueWillTrapIfNull(Value *V) {
445 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
446 if (isa<LoadInst>(*UI)) {
448 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
449 if (SI->getOperand(0) == V) {
450 //std::cerr << "NONTRAPPING USE: " << **UI;
451 return false; // Storing the value.
453 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
454 if (CI->getOperand(0) != V) {
455 //std::cerr << "NONTRAPPING USE: " << **UI;
456 return false; // Not calling the ptr
458 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
459 if (II->getOperand(0) != V) {
460 //std::cerr << "NONTRAPPING USE: " << **UI;
461 return false; // Not calling the ptr
463 } else if (CastInst *CI = dyn_cast<CastInst>(*UI)) {
464 if (!AllUsesOfValueWillTrapIfNull(CI)) return false;
465 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
466 if (!AllUsesOfValueWillTrapIfNull(GEPI)) return false;
467 } else if (isa<SetCondInst>(*UI) &&
468 isa<ConstantPointerNull>(UI->getOperand(1))) {
469 // Ignore setcc X, null
471 //std::cerr << "NONTRAPPING USE: " << **UI;
477 /// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
478 /// from GV will trap if the loaded value is null. Note that this also permits
479 /// comparisons of the loaded value against null, as a special case.
480 static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
481 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
482 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
483 if (!AllUsesOfValueWillTrapIfNull(LI))
485 } else if (isa<StoreInst>(*UI)) {
486 // Ignore stores to the global.
488 // We don't know or understand this user, bail out.
489 //std::cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
496 static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
497 bool Changed = false;
498 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
499 Instruction *I = cast<Instruction>(*UI++);
500 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
501 LI->setOperand(0, NewV);
503 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
504 if (SI->getOperand(1) == V) {
505 SI->setOperand(1, NewV);
508 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
509 if (I->getOperand(0) == V) {
510 // Calling through the pointer! Turn into a direct call, but be careful
511 // that the pointer is not also being passed as an argument.
512 I->setOperand(0, NewV);
514 bool PassedAsArg = false;
515 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
516 if (I->getOperand(i) == V) {
518 I->setOperand(i, NewV);
522 // Being passed as an argument also. Be careful to not invalidate UI!
526 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
527 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
528 ConstantExpr::getCast(NewV, CI->getType()));
529 if (CI->use_empty()) {
531 CI->eraseFromParent();
533 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
534 // Should handle GEP here.
535 std::vector<Constant*> Indices;
536 Indices.reserve(GEPI->getNumOperands()-1);
537 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
538 if (Constant *C = dyn_cast<Constant>(GEPI->getOperand(i)))
539 Indices.push_back(C);
542 if (Indices.size() == GEPI->getNumOperands()-1)
543 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
544 ConstantExpr::getGetElementPtr(NewV, Indices));
545 if (GEPI->use_empty()) {
547 GEPI->eraseFromParent();
556 /// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
557 /// value stored into it. If there are uses of the loaded value that would trap
558 /// if the loaded value is dynamically null, then we know that they cannot be
559 /// reachable with a null optimize away the load.
560 static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
561 std::vector<LoadInst*> Loads;
562 bool Changed = false;
564 // Replace all uses of loads with uses of uses of the stored value.
565 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end();
567 if (LoadInst *LI = dyn_cast<LoadInst>(*GUI)) {
569 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
571 assert(isa<StoreInst>(*GUI) && "Only expect load and stores!");
575 DEBUG(std::cerr << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
579 // Delete all of the loads we can, keeping track of whether we nuked them all!
580 bool AllLoadsGone = true;
581 while (!Loads.empty()) {
582 LoadInst *L = Loads.back();
583 if (L->use_empty()) {
584 L->eraseFromParent();
587 AllLoadsGone = false;
592 // If we nuked all of the loads, then none of the stores are needed either,
593 // nor is the global.
595 DEBUG(std::cerr << " *** GLOBAL NOW DEAD!\n");
596 CleanupConstantGlobalUsers(GV, 0);
597 if (GV->use_empty()) {
598 GV->eraseFromParent();
606 /// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
607 /// instructions that are foldable.
608 static void ConstantPropUsersOf(Value *V) {
609 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
610 if (Instruction *I = dyn_cast<Instruction>(*UI++))
611 if (Constant *NewC = ConstantFoldInstruction(I)) {
612 I->replaceAllUsesWith(NewC);
614 // Back up UI to avoid invalidating it!
615 bool AtBegin = false;
616 if (UI == V->use_begin())
620 I->eraseFromParent();
628 /// OptimizeGlobalAddressOfMalloc - This function takes the specified global
629 /// variable, and transforms the program as if it always contained the result of
630 /// the specified malloc. Because it is always the result of the specified
631 /// malloc, there is no reason to actually DO the malloc. Instead, turn the
632 /// malloc into a global, and any laods of GV as uses of the new global.
633 static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
635 DEBUG(std::cerr << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " <<*MI);
636 ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
638 if (NElements->getRawValue() != 1) {
639 // If we have an array allocation, transform it to a single element
640 // allocation to make the code below simpler.
641 Type *NewTy = ArrayType::get(MI->getAllocatedType(),
642 NElements->getRawValue());
644 new MallocInst(NewTy, Constant::getNullValue(Type::UIntTy),
646 std::vector<Value*> Indices;
647 Indices.push_back(Constant::getNullValue(Type::IntTy));
648 Indices.push_back(Indices[0]);
649 Value *NewGEP = new GetElementPtrInst(NewMI, Indices,
650 NewMI->getName()+".el0", MI);
651 MI->replaceAllUsesWith(NewGEP);
652 MI->eraseFromParent();
656 // Create the new global variable. The contents of the malloc'd memory is
657 // undefined, so initialize with an undef value.
658 Constant *Init = UndefValue::get(MI->getAllocatedType());
659 GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false,
660 GlobalValue::InternalLinkage, Init,
661 GV->getName()+".body");
662 GV->getParent()->getGlobalList().insert(GV, NewGV);
664 // Anything that used the malloc now uses the global directly.
665 MI->replaceAllUsesWith(NewGV);
667 Constant *RepValue = NewGV;
668 if (NewGV->getType() != GV->getType()->getElementType())
669 RepValue = ConstantExpr::getCast(RepValue, GV->getType()->getElementType());
671 // If there is a comparison against null, we will insert a global bool to
672 // keep track of whether the global was initialized yet or not.
673 GlobalVariable *InitBool = 0;
675 // Loop over all uses of GV, processing them in turn.
676 while (!GV->use_empty())
677 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
678 while (!LI->use_empty()) {
679 // FIXME: the iterator should expose a getUse() method.
680 Use &LoadUse = *(const iplist<Use>::iterator&)LI->use_begin();
681 if (!isa<SetCondInst>(LoadUse.getUser()))
685 InitBool = new GlobalVariable(Type::BoolTy, false,
686 GlobalValue::InternalLinkage,
688 GV->getName()+".init");
689 GV->getParent()->getGlobalList().insert(GV, InitBool);
690 // The global is initialized when the malloc is run.
691 new StoreInst(ConstantBool::True, InitBool, MI);
693 // Replace the setcc X, 0 with a use of the bool value.
694 SetCondInst *SCI = cast<SetCondInst>(LoadUse.getUser());
695 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", SCI);
696 switch (SCI->getOpcode()) {
697 default: assert(0 && "Unknown opcode!");
698 case Instruction::SetLT:
699 LV = ConstantBool::False; // X < null -> always false
701 case Instruction::SetEQ:
702 case Instruction::SetLE:
703 LV = BinaryOperator::createNot(LV, "notinit", SCI);
705 case Instruction::SetNE:
706 case Instruction::SetGE:
707 case Instruction::SetGT:
710 SCI->replaceAllUsesWith(LV);
711 SCI->eraseFromParent();
714 LI->eraseFromParent();
716 StoreInst *SI = cast<StoreInst>(GV->use_back());
717 SI->eraseFromParent();
720 // Now the GV is dead, nuke it and the malloc.
721 GV->eraseFromParent();
722 MI->eraseFromParent();
724 // To further other optimizations, loop over all users of NewGV and try to
725 // constant prop them. This will promote GEP instructions with constant
726 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
727 ConstantPropUsersOf(NewGV);
728 if (RepValue != NewGV)
729 ConstantPropUsersOf(RepValue);
734 // OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
735 // that only one value (besides its initializer) is ever stored to the global.
736 static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
737 Module::giterator &GVI, TargetData &TD) {
738 if (CastInst *CI = dyn_cast<CastInst>(StoredOnceVal))
739 StoredOnceVal = CI->getOperand(0);
740 else if (GetElementPtrInst *GEPI =dyn_cast<GetElementPtrInst>(StoredOnceVal)){
741 // "getelementptr Ptr, 0, 0, 0" is really just a cast.
742 bool IsJustACast = true;
743 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
744 if (!isa<Constant>(GEPI->getOperand(i)) ||
745 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
750 StoredOnceVal = GEPI->getOperand(0);
753 // If we are dealing with a pointer global that is initialized to null and
754 // only has one (non-null) value stored into it, then we can optimize any
755 // users of the loaded value (often calls and loads) that would trap if the
757 if (isa<PointerType>(GV->getInitializer()->getType()) &&
758 GV->getInitializer()->isNullValue()) {
759 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
760 if (GV->getInitializer()->getType() != SOVC->getType())
761 SOVC = ConstantExpr::getCast(SOVC, GV->getInitializer()->getType());
763 // Optimize away any trapping uses of the loaded value.
764 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
766 } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
767 // If we have a global that is only initialized with a fixed size malloc,
768 // and if all users of the malloc trap, and if the malloc'd address is not
769 // put anywhere else, transform the program to use global memory instead
770 // of malloc'd memory. This eliminates dynamic allocation (good) and
771 // exposes the resultant global to further GlobalOpt (even better). Note
772 // that we restrict this transformation to only working on small
773 // allocations (2048 bytes currently), as we don't want to introduce a 16M
774 // global or something.
775 if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize()))
776 if (MI->getAllocatedType()->isSized() &&
777 NElements->getRawValue()*
778 TD.getTypeSize(MI->getAllocatedType()) < 2048 &&
779 AllUsesOfLoadedValueWillTrapIfNull(GV)) {
780 // FIXME: do more correctness checking to make sure the result of the
781 // malloc isn't squirrelled away somewhere.
782 GVI = OptimizeGlobalAddressOfMalloc(GV, MI);
791 /// ProcessInternalGlobal - Analyze the specified global variable and optimize
792 /// it if possible. If we make a change, return true.
793 bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
794 Module::giterator &GVI) {
795 std::set<PHINode*> PHIUsers;
798 GV->removeDeadConstantUsers();
800 if (GV->use_empty()) {
801 DEBUG(std::cerr << "GLOBAL DEAD: " << *GV);
802 GV->eraseFromParent();
807 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
808 // If the global is never loaded (but may be stored to), it is dead.
811 DEBUG(std::cerr << "GLOBAL NEVER LOADED: " << *GV);
813 // Delete any stores we can find to the global. We may not be able to
814 // make it completely dead though.
815 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
817 // If the global is dead now, delete it.
818 if (GV->use_empty()) {
819 GV->eraseFromParent();
825 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
826 DEBUG(std::cerr << "MARKING CONSTANT: " << *GV);
827 GV->setConstant(true);
829 // Clean up any obviously simplifiable users now.
830 CleanupConstantGlobalUsers(GV, GV->getInitializer());
832 // If the global is dead now, just nuke it.
833 if (GV->use_empty()) {
834 DEBUG(std::cerr << " *** Marking constant allowed us to simplify "
835 "all users and delete global!\n");
836 GV->eraseFromParent();
842 } else if (!GS.isNotSuitableForSRA &&
843 !GV->getInitializer()->getType()->isFirstClassType()) {
844 if (GlobalVariable *FirstNewGV = SRAGlobal(GV)) {
845 GVI = FirstNewGV; // Don't skip the newly produced globals!
848 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
849 // If the initial value for the global was an undef value, and if only one
850 // other value was stored into it, we can just change the initializer to
851 // be an undef value, then delete all stores to the global. This allows
852 // us to mark it constant.
853 if (isa<UndefValue>(GV->getInitializer()) &&
854 isa<Constant>(GS.StoredOnceValue)) {
855 // Change the initial value here.
856 GV->setInitializer(cast<Constant>(GS.StoredOnceValue));
858 // Clean up any obviously simplifiable users now.
859 CleanupConstantGlobalUsers(GV, GV->getInitializer());
861 if (GV->use_empty()) {
862 DEBUG(std::cerr << " *** Substituting initializer allowed us to "
863 "simplify all users and delete global!\n");
864 GV->eraseFromParent();
873 // Try to optimize globals based on the knowledge that only one value
874 // (besides its initializer) is ever stored to the global.
875 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
876 getAnalysis<TargetData>()))
884 bool GlobalOpt::runOnModule(Module &M) {
885 bool Changed = false;
887 // As a prepass, delete functions that are trivially dead.
888 bool LocalChange = true;
889 while (LocalChange) {
891 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
893 F->removeDeadConstantUsers();
894 if (F->use_empty() && (F->hasInternalLinkage() ||
895 F->hasLinkOnceLinkage())) {
896 M.getFunctionList().erase(F);
901 Changed |= LocalChange;
905 while (LocalChange) {
907 for (Module::giterator GVI = M.gbegin(), E = M.gend(); GVI != E;) {
908 GlobalVariable *GV = GVI++;
909 if (!GV->isConstant() && GV->hasInternalLinkage() &&
910 GV->hasInitializer())
911 LocalChange |= ProcessInternalGlobal(GV, GVI);
913 Changed |= LocalChange;