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/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/Pass.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Transforms/Utils/Local.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/ADT/StringExtras.h"
36 Statistic<> NumMarked ("globalopt", "Number of globals marked constant");
37 Statistic<> NumSRA ("globalopt", "Number of aggregate globals broken "
39 Statistic<> NumSubstitute("globalopt",
40 "Number of globals with initializers stored into them");
41 Statistic<> NumDeleted ("globalopt", "Number of globals deleted");
42 Statistic<> NumFnDeleted("globalopt", "Number of functions deleted");
43 Statistic<> NumGlobUses ("globalopt", "Number of global uses devirtualized");
44 Statistic<> NumLocalized("globalopt", "Number of globals localized");
45 Statistic<> NumShrunkToBool("globalopt",
46 "Number of global vars shrunk to booleans");
47 Statistic<> NumFastCallFns("globalopt",
48 "Number of functions converted to fastcc");
49 Statistic<> NumCtorsEvaluated("globalopt","Number of static ctors evaluated");
51 struct GlobalOpt : public ModulePass {
52 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
53 AU.addRequired<TargetData>();
56 bool runOnModule(Module &M);
59 GlobalVariable *FindGlobalCtors(Module &M);
60 bool OptimizeFunctions(Module &M);
61 bool OptimizeGlobalVars(Module &M);
62 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
63 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
66 RegisterPass<GlobalOpt> X("globalopt", "Global Variable Optimizer");
69 ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
71 /// GlobalStatus - As we analyze each global, keep track of some information
72 /// about it. If we find out that the address of the global is taken, none of
73 /// this info will be accurate.
75 /// isLoaded - True if the global is ever loaded. If the global isn't ever
76 /// loaded it can be deleted.
79 /// StoredType - Keep track of what stores to the global look like.
82 /// NotStored - There is no store to this global. It can thus be marked
86 /// isInitializerStored - This global is stored to, but the only thing
87 /// stored is the constant it was initialized with. This is only tracked
88 /// for scalar globals.
91 /// isStoredOnce - This global is stored to, but only its initializer and
92 /// one other value is ever stored to it. If this global isStoredOnce, we
93 /// track the value stored to it in StoredOnceValue below. This is only
94 /// tracked for scalar globals.
97 /// isStored - This global is stored to by multiple values or something else
98 /// that we cannot track.
102 /// StoredOnceValue - If only one value (besides the initializer constant) is
103 /// ever stored to this global, keep track of what value it is.
104 Value *StoredOnceValue;
106 // AccessingFunction/HasMultipleAccessingFunctions - These start out
107 // null/false. When the first accessing function is noticed, it is recorded.
108 // When a second different accessing function is noticed,
109 // HasMultipleAccessingFunctions is set to true.
110 Function *AccessingFunction;
111 bool HasMultipleAccessingFunctions;
113 // HasNonInstructionUser - Set to true if this global has a user that is not
114 // an instruction (e.g. a constant expr or GV initializer).
115 bool HasNonInstructionUser;
117 /// isNotSuitableForSRA - Keep track of whether any SRA preventing users of
118 /// the global exist. Such users include GEP instruction with variable
119 /// indexes, and non-gep/load/store users like constant expr casts.
120 bool isNotSuitableForSRA;
122 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
123 AccessingFunction(0), HasMultipleAccessingFunctions(false),
124 HasNonInstructionUser(false), isNotSuitableForSRA(false) {}
129 /// ConstantIsDead - Return true if the specified constant is (transitively)
130 /// dead. The constant may be used by other constants (e.g. constant arrays and
131 /// constant exprs) as long as they are dead, but it cannot be used by anything
133 static bool ConstantIsDead(Constant *C) {
134 if (isa<GlobalValue>(C)) return false;
136 for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
137 if (Constant *CU = dyn_cast<Constant>(*UI)) {
138 if (!ConstantIsDead(CU)) return false;
145 /// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
146 /// structure. If the global has its address taken, return true to indicate we
147 /// can't do anything with it.
149 static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
150 std::set<PHINode*> &PHIUsers) {
151 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
152 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
153 GS.HasNonInstructionUser = true;
155 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
156 if (CE->getOpcode() != Instruction::GetElementPtr)
157 GS.isNotSuitableForSRA = true;
158 else if (!GS.isNotSuitableForSRA) {
159 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
160 // don't like < 3 operand CE's, and we don't like non-constant integer
162 if (CE->getNumOperands() < 3 || !CE->getOperand(1)->isNullValue())
163 GS.isNotSuitableForSRA = true;
165 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
166 if (!isa<ConstantInt>(CE->getOperand(i))) {
167 GS.isNotSuitableForSRA = true;
173 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
174 if (!GS.HasMultipleAccessingFunctions) {
175 Function *F = I->getParent()->getParent();
176 if (GS.AccessingFunction == 0)
177 GS.AccessingFunction = F;
178 else if (GS.AccessingFunction != F)
179 GS.HasMultipleAccessingFunctions = true;
181 if (isa<LoadInst>(I)) {
183 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
184 // Don't allow a store OF the address, only stores TO the address.
185 if (SI->getOperand(0) == V) return true;
187 // If this is a direct store to the global (i.e., the global is a scalar
188 // value, not an aggregate), keep more specific information about
190 if (GS.StoredType != GlobalStatus::isStored)
191 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
192 Value *StoredVal = SI->getOperand(0);
193 if (StoredVal == GV->getInitializer()) {
194 if (GS.StoredType < GlobalStatus::isInitializerStored)
195 GS.StoredType = GlobalStatus::isInitializerStored;
196 } else if (isa<LoadInst>(StoredVal) &&
197 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
199 if (GS.StoredType < GlobalStatus::isInitializerStored)
200 GS.StoredType = GlobalStatus::isInitializerStored;
201 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
202 GS.StoredType = GlobalStatus::isStoredOnce;
203 GS.StoredOnceValue = StoredVal;
204 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
205 GS.StoredOnceValue == StoredVal) {
208 GS.StoredType = GlobalStatus::isStored;
211 GS.StoredType = GlobalStatus::isStored;
213 } else if (isa<GetElementPtrInst>(I)) {
214 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
216 // If the first two indices are constants, this can be SRA'd.
217 if (isa<GlobalVariable>(I->getOperand(0))) {
218 if (I->getNumOperands() < 3 || !isa<Constant>(I->getOperand(1)) ||
219 !cast<Constant>(I->getOperand(1))->isNullValue() ||
220 !isa<ConstantInt>(I->getOperand(2)))
221 GS.isNotSuitableForSRA = true;
222 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I->getOperand(0))){
223 if (CE->getOpcode() != Instruction::GetElementPtr ||
224 CE->getNumOperands() < 3 || I->getNumOperands() < 2 ||
225 !isa<Constant>(I->getOperand(0)) ||
226 !cast<Constant>(I->getOperand(0))->isNullValue())
227 GS.isNotSuitableForSRA = true;
229 GS.isNotSuitableForSRA = true;
231 } else if (isa<SelectInst>(I)) {
232 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
233 GS.isNotSuitableForSRA = true;
234 } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
235 // PHI nodes we can check just like select or GEP instructions, but we
236 // have to be careful about infinite recursion.
237 if (PHIUsers.insert(PN).second) // Not already visited.
238 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
239 GS.isNotSuitableForSRA = true;
240 } else if (isa<SetCondInst>(I)) {
241 GS.isNotSuitableForSRA = true;
242 } else if (isa<MemCpyInst>(I) || isa<MemMoveInst>(I)) {
243 if (I->getOperand(1) == V)
244 GS.StoredType = GlobalStatus::isStored;
245 if (I->getOperand(2) == V)
247 GS.isNotSuitableForSRA = true;
248 } else if (isa<MemSetInst>(I)) {
249 assert(I->getOperand(1) == V && "Memset only takes one pointer!");
250 GS.StoredType = GlobalStatus::isStored;
251 GS.isNotSuitableForSRA = true;
253 return true; // Any other non-load instruction might take address!
255 } else if (Constant *C = dyn_cast<Constant>(*UI)) {
256 GS.HasNonInstructionUser = true;
257 // We might have a dead and dangling constant hanging off of here.
258 if (!ConstantIsDead(C))
261 GS.HasNonInstructionUser = true;
262 // Otherwise must be some other user.
269 static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
270 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
272 unsigned IdxV = (unsigned)CI->getRawValue();
274 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
275 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
276 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
277 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
278 } else if (ConstantPacked *CP = dyn_cast<ConstantPacked>(Agg)) {
279 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
280 } else if (isa<ConstantAggregateZero>(Agg)) {
281 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
282 if (IdxV < STy->getNumElements())
283 return Constant::getNullValue(STy->getElementType(IdxV));
284 } else if (const SequentialType *STy =
285 dyn_cast<SequentialType>(Agg->getType())) {
286 return Constant::getNullValue(STy->getElementType());
288 } else if (isa<UndefValue>(Agg)) {
289 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
290 if (IdxV < STy->getNumElements())
291 return UndefValue::get(STy->getElementType(IdxV));
292 } else if (const SequentialType *STy =
293 dyn_cast<SequentialType>(Agg->getType())) {
294 return UndefValue::get(STy->getElementType());
301 /// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
302 /// users of the global, cleaning up the obvious ones. This is largely just a
303 /// quick scan over the use list to clean up the easy and obvious cruft. This
304 /// returns true if it made a change.
305 static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
306 bool Changed = false;
307 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
310 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
312 // Replace the load with the initializer.
313 LI->replaceAllUsesWith(Init);
314 LI->eraseFromParent();
317 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
318 // Store must be unreachable or storing Init into the global.
319 SI->eraseFromParent();
321 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
322 if (CE->getOpcode() == Instruction::GetElementPtr) {
323 Constant *SubInit = 0;
325 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
326 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
327 } else if (CE->getOpcode() == Instruction::Cast &&
328 isa<PointerType>(CE->getType())) {
329 // Pointer cast, delete any stores and memsets to the global.
330 Changed |= CleanupConstantGlobalUsers(CE, 0);
333 if (CE->use_empty()) {
334 CE->destroyConstant();
337 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
338 Constant *SubInit = 0;
340 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
341 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
342 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
343 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
345 if (GEP->use_empty()) {
346 GEP->eraseFromParent();
349 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
350 if (MI->getRawDest() == V) {
351 MI->eraseFromParent();
355 } else if (Constant *C = dyn_cast<Constant>(U)) {
356 // If we have a chain of dead constantexprs or other things dangling from
357 // us, and if they are all dead, nuke them without remorse.
358 if (ConstantIsDead(C)) {
359 C->destroyConstant();
360 // This could have invalidated UI, start over from scratch.
361 CleanupConstantGlobalUsers(V, Init);
369 /// SRAGlobal - Perform scalar replacement of aggregates on the specified global
370 /// variable. This opens the door for other optimizations by exposing the
371 /// behavior of the program in a more fine-grained way. We have determined that
372 /// this transformation is safe already. We return the first global variable we
373 /// insert so that the caller can reprocess it.
374 static GlobalVariable *SRAGlobal(GlobalVariable *GV) {
375 assert(GV->hasInternalLinkage() && !GV->isConstant());
376 Constant *Init = GV->getInitializer();
377 const Type *Ty = Init->getType();
379 std::vector<GlobalVariable*> NewGlobals;
380 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
382 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
383 NewGlobals.reserve(STy->getNumElements());
384 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
385 Constant *In = getAggregateConstantElement(Init,
386 ConstantUInt::get(Type::UIntTy, i));
387 assert(In && "Couldn't get element of initializer?");
388 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
389 GlobalVariable::InternalLinkage,
390 In, GV->getName()+"."+utostr(i));
391 Globals.insert(GV, NGV);
392 NewGlobals.push_back(NGV);
394 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
395 unsigned NumElements = 0;
396 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
397 NumElements = ATy->getNumElements();
398 else if (const PackedType *PTy = dyn_cast<PackedType>(STy))
399 NumElements = PTy->getNumElements();
401 assert(0 && "Unknown aggregate sequential type!");
403 if (NumElements > 16 && GV->hasNUsesOrMore(16))
404 return 0; // It's not worth it.
405 NewGlobals.reserve(NumElements);
406 for (unsigned i = 0, e = NumElements; i != e; ++i) {
407 Constant *In = getAggregateConstantElement(Init,
408 ConstantUInt::get(Type::UIntTy, i));
409 assert(In && "Couldn't get element of initializer?");
411 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
412 GlobalVariable::InternalLinkage,
413 In, GV->getName()+"."+utostr(i));
414 Globals.insert(GV, NGV);
415 NewGlobals.push_back(NGV);
419 if (NewGlobals.empty())
422 DEBUG(std::cerr << "PERFORMING GLOBAL SRA ON: " << *GV);
424 Constant *NullInt = Constant::getNullValue(Type::IntTy);
426 // Loop over all of the uses of the global, replacing the constantexpr geps,
427 // with smaller constantexpr geps or direct references.
428 while (!GV->use_empty()) {
429 User *GEP = GV->use_back();
430 assert(((isa<ConstantExpr>(GEP) &&
431 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
432 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
434 // Ignore the 1th operand, which has to be zero or else the program is quite
435 // broken (undefined). Get the 2nd operand, which is the structure or array
438 (unsigned)cast<ConstantInt>(GEP->getOperand(2))->getRawValue();
439 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
441 Value *NewPtr = NewGlobals[Val];
443 // Form a shorter GEP if needed.
444 if (GEP->getNumOperands() > 3)
445 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
446 std::vector<Constant*> Idxs;
447 Idxs.push_back(NullInt);
448 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
449 Idxs.push_back(CE->getOperand(i));
450 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs);
452 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
453 std::vector<Value*> Idxs;
454 Idxs.push_back(NullInt);
455 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
456 Idxs.push_back(GEPI->getOperand(i));
457 NewPtr = new GetElementPtrInst(NewPtr, Idxs,
458 GEPI->getName()+"."+utostr(Val), GEPI);
460 GEP->replaceAllUsesWith(NewPtr);
462 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
463 GEPI->eraseFromParent();
465 cast<ConstantExpr>(GEP)->destroyConstant();
468 // Delete the old global, now that it is dead.
472 // Loop over the new globals array deleting any globals that are obviously
473 // dead. This can arise due to scalarization of a structure or an array that
474 // has elements that are dead.
475 unsigned FirstGlobal = 0;
476 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
477 if (NewGlobals[i]->use_empty()) {
478 Globals.erase(NewGlobals[i]);
479 if (FirstGlobal == i) ++FirstGlobal;
482 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
485 /// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
486 /// value will trap if the value is dynamically null.
487 static bool AllUsesOfValueWillTrapIfNull(Value *V) {
488 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
489 if (isa<LoadInst>(*UI)) {
491 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
492 if (SI->getOperand(0) == V) {
493 //std::cerr << "NONTRAPPING USE: " << **UI;
494 return false; // Storing the value.
496 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
497 if (CI->getOperand(0) != V) {
498 //std::cerr << "NONTRAPPING USE: " << **UI;
499 return false; // Not calling the ptr
501 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
502 if (II->getOperand(0) != V) {
503 //std::cerr << "NONTRAPPING USE: " << **UI;
504 return false; // Not calling the ptr
506 } else if (CastInst *CI = dyn_cast<CastInst>(*UI)) {
507 if (!AllUsesOfValueWillTrapIfNull(CI)) return false;
508 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
509 if (!AllUsesOfValueWillTrapIfNull(GEPI)) return false;
510 } else if (isa<SetCondInst>(*UI) &&
511 isa<ConstantPointerNull>(UI->getOperand(1))) {
512 // Ignore setcc X, null
514 //std::cerr << "NONTRAPPING USE: " << **UI;
520 /// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
521 /// from GV will trap if the loaded value is null. Note that this also permits
522 /// comparisons of the loaded value against null, as a special case.
523 static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
524 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
525 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
526 if (!AllUsesOfValueWillTrapIfNull(LI))
528 } else if (isa<StoreInst>(*UI)) {
529 // Ignore stores to the global.
531 // We don't know or understand this user, bail out.
532 //std::cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
539 static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
540 bool Changed = false;
541 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
542 Instruction *I = cast<Instruction>(*UI++);
543 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
544 LI->setOperand(0, NewV);
546 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
547 if (SI->getOperand(1) == V) {
548 SI->setOperand(1, NewV);
551 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
552 if (I->getOperand(0) == V) {
553 // Calling through the pointer! Turn into a direct call, but be careful
554 // that the pointer is not also being passed as an argument.
555 I->setOperand(0, NewV);
557 bool PassedAsArg = false;
558 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
559 if (I->getOperand(i) == V) {
561 I->setOperand(i, NewV);
565 // Being passed as an argument also. Be careful to not invalidate UI!
569 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
570 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
571 ConstantExpr::getCast(NewV, CI->getType()));
572 if (CI->use_empty()) {
574 CI->eraseFromParent();
576 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
577 // Should handle GEP here.
578 std::vector<Constant*> Indices;
579 Indices.reserve(GEPI->getNumOperands()-1);
580 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
581 if (Constant *C = dyn_cast<Constant>(GEPI->getOperand(i)))
582 Indices.push_back(C);
585 if (Indices.size() == GEPI->getNumOperands()-1)
586 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
587 ConstantExpr::getGetElementPtr(NewV, Indices));
588 if (GEPI->use_empty()) {
590 GEPI->eraseFromParent();
599 /// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
600 /// value stored into it. If there are uses of the loaded value that would trap
601 /// if the loaded value is dynamically null, then we know that they cannot be
602 /// reachable with a null optimize away the load.
603 static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
604 std::vector<LoadInst*> Loads;
605 bool Changed = false;
607 // Replace all uses of loads with uses of uses of the stored value.
608 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end();
610 if (LoadInst *LI = dyn_cast<LoadInst>(*GUI)) {
612 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
614 assert(isa<StoreInst>(*GUI) && "Only expect load and stores!");
618 DEBUG(std::cerr << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
622 // Delete all of the loads we can, keeping track of whether we nuked them all!
623 bool AllLoadsGone = true;
624 while (!Loads.empty()) {
625 LoadInst *L = Loads.back();
626 if (L->use_empty()) {
627 L->eraseFromParent();
630 AllLoadsGone = false;
635 // If we nuked all of the loads, then none of the stores are needed either,
636 // nor is the global.
638 DEBUG(std::cerr << " *** GLOBAL NOW DEAD!\n");
639 CleanupConstantGlobalUsers(GV, 0);
640 if (GV->use_empty()) {
641 GV->eraseFromParent();
649 /// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
650 /// instructions that are foldable.
651 static void ConstantPropUsersOf(Value *V) {
652 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
653 if (Instruction *I = dyn_cast<Instruction>(*UI++))
654 if (Constant *NewC = ConstantFoldInstruction(I)) {
655 I->replaceAllUsesWith(NewC);
657 // Advance UI to the next non-I use to avoid invalidating it!
658 // Instructions could multiply use V.
659 while (UI != E && *UI == I)
661 I->eraseFromParent();
665 /// OptimizeGlobalAddressOfMalloc - This function takes the specified global
666 /// variable, and transforms the program as if it always contained the result of
667 /// the specified malloc. Because it is always the result of the specified
668 /// malloc, there is no reason to actually DO the malloc. Instead, turn the
669 /// malloc into a global, and any laods of GV as uses of the new global.
670 static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
672 DEBUG(std::cerr << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " <<*MI);
673 ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
675 if (NElements->getRawValue() != 1) {
676 // If we have an array allocation, transform it to a single element
677 // allocation to make the code below simpler.
678 Type *NewTy = ArrayType::get(MI->getAllocatedType(),
679 (unsigned)NElements->getRawValue());
681 new MallocInst(NewTy, Constant::getNullValue(Type::UIntTy),
682 MI->getAlignment(), MI->getName(), MI);
683 std::vector<Value*> Indices;
684 Indices.push_back(Constant::getNullValue(Type::IntTy));
685 Indices.push_back(Indices[0]);
686 Value *NewGEP = new GetElementPtrInst(NewMI, Indices,
687 NewMI->getName()+".el0", MI);
688 MI->replaceAllUsesWith(NewGEP);
689 MI->eraseFromParent();
693 // Create the new global variable. The contents of the malloc'd memory is
694 // undefined, so initialize with an undef value.
695 Constant *Init = UndefValue::get(MI->getAllocatedType());
696 GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false,
697 GlobalValue::InternalLinkage, Init,
698 GV->getName()+".body");
699 GV->getParent()->getGlobalList().insert(GV, NewGV);
701 // Anything that used the malloc now uses the global directly.
702 MI->replaceAllUsesWith(NewGV);
704 Constant *RepValue = NewGV;
705 if (NewGV->getType() != GV->getType()->getElementType())
706 RepValue = ConstantExpr::getCast(RepValue, GV->getType()->getElementType());
708 // If there is a comparison against null, we will insert a global bool to
709 // keep track of whether the global was initialized yet or not.
710 GlobalVariable *InitBool =
711 new GlobalVariable(Type::BoolTy, false, GlobalValue::InternalLinkage,
712 ConstantBool::False, GV->getName()+".init");
713 bool InitBoolUsed = false;
715 // Loop over all uses of GV, processing them in turn.
716 std::vector<StoreInst*> Stores;
717 while (!GV->use_empty())
718 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
719 while (!LI->use_empty()) {
720 Use &LoadUse = LI->use_begin().getUse();
721 if (!isa<SetCondInst>(LoadUse.getUser()))
724 // Replace the setcc X, 0 with a use of the bool value.
725 SetCondInst *SCI = cast<SetCondInst>(LoadUse.getUser());
726 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", SCI);
728 switch (SCI->getOpcode()) {
729 default: assert(0 && "Unknown opcode!");
730 case Instruction::SetLT:
731 LV = ConstantBool::False; // X < null -> always false
733 case Instruction::SetEQ:
734 case Instruction::SetLE:
735 LV = BinaryOperator::createNot(LV, "notinit", SCI);
737 case Instruction::SetNE:
738 case Instruction::SetGE:
739 case Instruction::SetGT:
742 SCI->replaceAllUsesWith(LV);
743 SCI->eraseFromParent();
746 LI->eraseFromParent();
748 StoreInst *SI = cast<StoreInst>(GV->use_back());
749 // The global is initialized when the store to it occurs.
750 new StoreInst(ConstantBool::True, InitBool, SI);
751 SI->eraseFromParent();
754 // If the initialization boolean was used, insert it, otherwise delete it.
756 while (!InitBool->use_empty()) // Delete initializations
757 cast<Instruction>(InitBool->use_back())->eraseFromParent();
760 GV->getParent()->getGlobalList().insert(GV, InitBool);
763 // Now the GV is dead, nuke it and the malloc.
764 GV->eraseFromParent();
765 MI->eraseFromParent();
767 // To further other optimizations, loop over all users of NewGV and try to
768 // constant prop them. This will promote GEP instructions with constant
769 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
770 ConstantPropUsersOf(NewGV);
771 if (RepValue != NewGV)
772 ConstantPropUsersOf(RepValue);
777 /// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
778 /// to make sure that there are no complex uses of V. We permit simple things
779 /// like dereferencing the pointer, but not storing through the address, unless
780 /// it is to the specified global.
781 static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
782 GlobalVariable *GV) {
783 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI)
784 if (isa<LoadInst>(*UI) || isa<SetCondInst>(*UI)) {
786 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
787 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
788 return false; // Storing the pointer itself... bad.
789 // Otherwise, storing through it, or storing into GV... fine.
790 } else if (isa<GetElementPtrInst>(*UI) || isa<SelectInst>(*UI)) {
791 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(cast<Instruction>(*UI),GV))
800 // OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
801 // that only one value (besides its initializer) is ever stored to the global.
802 static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
803 Module::global_iterator &GVI,
805 if (CastInst *CI = dyn_cast<CastInst>(StoredOnceVal))
806 StoredOnceVal = CI->getOperand(0);
807 else if (GetElementPtrInst *GEPI =dyn_cast<GetElementPtrInst>(StoredOnceVal)){
808 // "getelementptr Ptr, 0, 0, 0" is really just a cast.
809 bool IsJustACast = true;
810 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
811 if (!isa<Constant>(GEPI->getOperand(i)) ||
812 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
817 StoredOnceVal = GEPI->getOperand(0);
820 // If we are dealing with a pointer global that is initialized to null and
821 // only has one (non-null) value stored into it, then we can optimize any
822 // users of the loaded value (often calls and loads) that would trap if the
824 if (isa<PointerType>(GV->getInitializer()->getType()) &&
825 GV->getInitializer()->isNullValue()) {
826 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
827 if (GV->getInitializer()->getType() != SOVC->getType())
828 SOVC = ConstantExpr::getCast(SOVC, GV->getInitializer()->getType());
830 // Optimize away any trapping uses of the loaded value.
831 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
833 } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
834 // If we have a global that is only initialized with a fixed size malloc,
835 // and if all users of the malloc trap, and if the malloc'd address is not
836 // put anywhere else, transform the program to use global memory instead
837 // of malloc'd memory. This eliminates dynamic allocation (good) and
838 // exposes the resultant global to further GlobalOpt (even better). Note
839 // that we restrict this transformation to only working on small
840 // allocations (2048 bytes currently), as we don't want to introduce a 16M
841 // global or something.
842 if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize()))
843 if (MI->getAllocatedType()->isSized() &&
844 NElements->getRawValue()*
845 TD.getTypeSize(MI->getAllocatedType()) < 2048 &&
846 AllUsesOfLoadedValueWillTrapIfNull(GV) &&
847 ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV)) {
848 GVI = OptimizeGlobalAddressOfMalloc(GV, MI);
857 /// ShrinkGlobalToBoolean - At this point, we have learned that the only two
858 /// values ever stored into GV are its initializer and OtherVal.
859 static void ShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
860 // Create the new global, initializing it to false.
861 GlobalVariable *NewGV = new GlobalVariable(Type::BoolTy, false,
862 GlobalValue::InternalLinkage, ConstantBool::False, GV->getName()+".b");
863 GV->getParent()->getGlobalList().insert(GV, NewGV);
865 Constant *InitVal = GV->getInitializer();
866 assert(InitVal->getType() != Type::BoolTy && "No reason to shrink to bool!");
868 // If initialized to zero and storing one into the global, we can use a cast
869 // instead of a select to synthesize the desired value.
870 bool IsOneZero = false;
871 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
872 IsOneZero = InitVal->isNullValue() && CI->equalsInt(1);
874 while (!GV->use_empty()) {
875 Instruction *UI = cast<Instruction>(GV->use_back());
876 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
877 // Change the store into a boolean store.
878 bool StoringOther = SI->getOperand(0) == OtherVal;
879 // Only do this if we weren't storing a loaded value.
881 if (StoringOther || SI->getOperand(0) == InitVal)
882 StoreVal = ConstantBool::get(StoringOther);
884 // Otherwise, we are storing a previously loaded copy. To do this,
885 // change the copy from copying the original value to just copying the
887 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
889 // If we're already replaced the input, StoredVal will be a cast or
890 // select instruction. If not, it will be a load of the original
892 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
893 assert(LI->getOperand(0) == GV && "Not a copy!");
894 // Insert a new load, to preserve the saved value.
895 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
897 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
898 "This is not a form that we understand!");
899 StoreVal = StoredVal->getOperand(0);
900 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
903 new StoreInst(StoreVal, NewGV, SI);
904 } else if (!UI->use_empty()) {
905 // Change the load into a load of bool then a select.
906 LoadInst *LI = cast<LoadInst>(UI);
908 std::string Name = LI->getName(); LI->setName("");
909 LoadInst *NLI = new LoadInst(NewGV, Name+".b", LI);
912 NSI = new CastInst(NLI, LI->getType(), Name, LI);
914 NSI = new SelectInst(NLI, OtherVal, InitVal, Name, LI);
915 LI->replaceAllUsesWith(NSI);
917 UI->eraseFromParent();
920 GV->eraseFromParent();
924 /// ProcessInternalGlobal - Analyze the specified global variable and optimize
925 /// it if possible. If we make a change, return true.
926 bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
927 Module::global_iterator &GVI) {
928 std::set<PHINode*> PHIUsers;
930 GV->removeDeadConstantUsers();
932 if (GV->use_empty()) {
933 DEBUG(std::cerr << "GLOBAL DEAD: " << *GV);
934 GV->eraseFromParent();
939 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
940 // If this is a first class global and has only one accessing function
941 // and this function is main (which we know is not recursive we can make
942 // this global a local variable) we replace the global with a local alloca
945 // NOTE: It doesn't make sense to promote non first class types since we
946 // are just replacing static memory to stack memory.
947 if (!GS.HasMultipleAccessingFunctions &&
948 GS.AccessingFunction && !GS.HasNonInstructionUser &&
949 GV->getType()->getElementType()->isFirstClassType() &&
950 GS.AccessingFunction->getName() == "main" &&
951 GS.AccessingFunction->hasExternalLinkage()) {
952 DEBUG(std::cerr << "LOCALIZING GLOBAL: " << *GV);
953 Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
954 const Type* ElemTy = GV->getType()->getElementType();
955 // FIXME: Pass Global's alignment when globals have alignment
956 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
957 if (!isa<UndefValue>(GV->getInitializer()))
958 new StoreInst(GV->getInitializer(), Alloca, FirstI);
960 GV->replaceAllUsesWith(Alloca);
961 GV->eraseFromParent();
965 // If the global is never loaded (but may be stored to), it is dead.
968 DEBUG(std::cerr << "GLOBAL NEVER LOADED: " << *GV);
970 // Delete any stores we can find to the global. We may not be able to
971 // make it completely dead though.
972 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
974 // If the global is dead now, delete it.
975 if (GV->use_empty()) {
976 GV->eraseFromParent();
982 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
983 DEBUG(std::cerr << "MARKING CONSTANT: " << *GV);
984 GV->setConstant(true);
986 // Clean up any obviously simplifiable users now.
987 CleanupConstantGlobalUsers(GV, GV->getInitializer());
989 // If the global is dead now, just nuke it.
990 if (GV->use_empty()) {
991 DEBUG(std::cerr << " *** Marking constant allowed us to simplify "
992 "all users and delete global!\n");
993 GV->eraseFromParent();
999 } else if (!GS.isNotSuitableForSRA &&
1000 !GV->getInitializer()->getType()->isFirstClassType()) {
1001 if (GlobalVariable *FirstNewGV = SRAGlobal(GV)) {
1002 GVI = FirstNewGV; // Don't skip the newly produced globals!
1005 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
1006 // If the initial value for the global was an undef value, and if only
1007 // one other value was stored into it, we can just change the
1008 // initializer to be an undef value, then delete all stores to the
1009 // global. This allows us to mark it constant.
1010 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1011 if (isa<UndefValue>(GV->getInitializer())) {
1012 // Change the initial value here.
1013 GV->setInitializer(SOVConstant);
1015 // Clean up any obviously simplifiable users now.
1016 CleanupConstantGlobalUsers(GV, GV->getInitializer());
1018 if (GV->use_empty()) {
1019 DEBUG(std::cerr << " *** Substituting initializer allowed us to "
1020 "simplify all users and delete global!\n");
1021 GV->eraseFromParent();
1030 // Try to optimize globals based on the knowledge that only one value
1031 // (besides its initializer) is ever stored to the global.
1032 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1033 getAnalysis<TargetData>()))
1036 // Otherwise, if the global was not a boolean, we can shrink it to be a
1038 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1039 if (GV->getType()->getElementType() != Type::BoolTy &&
1040 !GV->getType()->getElementType()->isFloatingPoint()) {
1041 DEBUG(std::cerr << " *** SHRINKING TO BOOL: " << *GV);
1042 ShrinkGlobalToBoolean(GV, SOVConstant);
1051 /// OnlyCalledDirectly - Return true if the specified function is only called
1052 /// directly. In other words, its address is never taken.
1053 static bool OnlyCalledDirectly(Function *F) {
1054 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1055 Instruction *User = dyn_cast<Instruction>(*UI);
1056 if (!User) return false;
1057 if (!isa<CallInst>(User) && !isa<InvokeInst>(User)) return false;
1059 // See if the function address is passed as an argument.
1060 for (unsigned i = 1, e = User->getNumOperands(); i != e; ++i)
1061 if (User->getOperand(i) == F) return false;
1066 /// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1067 /// function, changing them to FastCC.
1068 static void ChangeCalleesToFastCall(Function *F) {
1069 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1070 Instruction *User = cast<Instruction>(*UI);
1071 if (CallInst *CI = dyn_cast<CallInst>(User))
1072 CI->setCallingConv(CallingConv::Fast);
1074 cast<InvokeInst>(User)->setCallingConv(CallingConv::Fast);
1078 bool GlobalOpt::OptimizeFunctions(Module &M) {
1079 bool Changed = false;
1080 // Optimize functions.
1081 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1083 F->removeDeadConstantUsers();
1084 if (F->use_empty() && (F->hasInternalLinkage() ||
1085 F->hasLinkOnceLinkage())) {
1086 M.getFunctionList().erase(F);
1089 } else if (F->hasInternalLinkage() &&
1090 F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
1091 OnlyCalledDirectly(F)) {
1092 // If this function has C calling conventions, is not a varargs
1093 // function, and is only called directly, promote it to use the Fast
1094 // calling convention.
1095 F->setCallingConv(CallingConv::Fast);
1096 ChangeCalleesToFastCall(F);
1104 bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1105 bool Changed = false;
1106 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1108 GlobalVariable *GV = GVI++;
1109 if (!GV->isConstant() && GV->hasInternalLinkage() &&
1110 GV->hasInitializer())
1111 Changed |= ProcessInternalGlobal(GV, GVI);
1116 /// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1117 /// initializers have an init priority of 65535.
1118 GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
1119 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1121 if (I->getName() == "llvm.global_ctors") {
1122 // Found it, verify it's an array of { int, void()* }.
1123 const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1125 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1126 if (!STy || STy->getNumElements() != 2 ||
1127 STy->getElementType(0) != Type::IntTy) return 0;
1128 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1129 if (!PFTy) return 0;
1130 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
1131 if (!FTy || FTy->getReturnType() != Type::VoidTy || FTy->isVarArg() ||
1132 FTy->getNumParams() != 0)
1135 // Verify that the initializer is simple enough for us to handle.
1136 if (!I->hasInitializer()) return 0;
1137 ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1139 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1140 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(CA->getOperand(i))) {
1141 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1144 // Must have a function or null ptr.
1145 if (!isa<Function>(CS->getOperand(1)))
1148 // Init priority must be standard.
1149 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
1150 if (!CI || CI->getRawValue() != 65535)
1161 /// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1162 /// return a list of the functions and null terminator as a vector.
1163 static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1164 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1165 std::vector<Function*> Result;
1166 Result.reserve(CA->getNumOperands());
1167 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
1168 ConstantStruct *CS = cast<ConstantStruct>(CA->getOperand(i));
1169 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1174 /// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1175 /// specified array, returning the new global to use.
1176 static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
1177 const std::vector<Function*> &Ctors) {
1178 // If we made a change, reassemble the initializer list.
1179 std::vector<Constant*> CSVals;
1180 CSVals.push_back(ConstantSInt::get(Type::IntTy, 65535));
1181 CSVals.push_back(0);
1183 // Create the new init list.
1184 std::vector<Constant*> CAList;
1185 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
1187 CSVals[1] = Ctors[i];
1189 const Type *FTy = FunctionType::get(Type::VoidTy,
1190 std::vector<const Type*>(), false);
1191 const PointerType *PFTy = PointerType::get(FTy);
1192 CSVals[1] = Constant::getNullValue(PFTy);
1193 CSVals[0] = ConstantSInt::get(Type::IntTy, 2147483647);
1195 CAList.push_back(ConstantStruct::get(CSVals));
1198 // Create the array initializer.
1199 const Type *StructTy =
1200 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
1201 Constant *CA = ConstantArray::get(ArrayType::get(StructTy, CAList.size()),
1204 // If we didn't change the number of elements, don't create a new GV.
1205 if (CA->getType() == GCL->getInitializer()->getType()) {
1206 GCL->setInitializer(CA);
1210 // Create the new global and insert it next to the existing list.
1211 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
1212 GCL->getLinkage(), CA,
1215 GCL->getParent()->getGlobalList().insert(GCL, NGV);
1217 // Nuke the old list, replacing any uses with the new one.
1218 if (!GCL->use_empty()) {
1220 if (V->getType() != GCL->getType())
1221 V = ConstantExpr::getCast(V, GCL->getType());
1222 GCL->replaceAllUsesWith(V);
1224 GCL->eraseFromParent();
1233 static Constant *getVal(std::map<Value*, Constant*> &ComputedValues,
1235 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
1236 Constant *R = ComputedValues[V];
1237 assert(R && "Reference to an uncomputed value!");
1241 /// isSimpleEnoughPointerToCommit - Return true if this constant is simple
1242 /// enough for us to understand. In particular, if it is a cast of something,
1243 /// we punt. We basically just support direct accesses to globals and GEP's of
1244 /// globals. This should be kept up to date with CommitValueTo.
1245 static bool isSimpleEnoughPointerToCommit(Constant *C) {
1246 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
1247 if (!GV->hasExternalLinkage() && !GV->hasInternalLinkage())
1248 return false; // do not allow weak/linkonce linkage.
1249 return !GV->isExternal(); // reject external globals.
1251 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
1252 // Handle a constantexpr gep.
1253 if (CE->getOpcode() == Instruction::GetElementPtr &&
1254 isa<GlobalVariable>(CE->getOperand(0))) {
1255 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1256 if (!GV->hasExternalLinkage() && !GV->hasInternalLinkage())
1257 return false; // do not allow weak/linkonce linkage.
1258 return GV->hasInitializer() &&
1259 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
1264 /// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
1265 /// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
1266 /// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
1267 static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
1268 ConstantExpr *Addr, unsigned OpNo) {
1269 // Base case of the recursion.
1270 if (OpNo == Addr->getNumOperands()) {
1271 assert(Val->getType() == Init->getType() && "Type mismatch!");
1275 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1276 std::vector<Constant*> Elts;
1278 // Break up the constant into its elements.
1279 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1280 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1281 Elts.push_back(CS->getOperand(i));
1282 } else if (isa<ConstantAggregateZero>(Init)) {
1283 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1284 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
1285 } else if (isa<UndefValue>(Init)) {
1286 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1287 Elts.push_back(UndefValue::get(STy->getElementType(i)));
1289 assert(0 && "This code is out of sync with "
1290 " ConstantFoldLoadThroughGEPConstantExpr");
1293 // Replace the element that we are supposed to.
1294 ConstantUInt *CU = cast<ConstantUInt>(Addr->getOperand(OpNo));
1295 assert(CU->getValue() < STy->getNumElements() &&
1296 "Struct index out of range!");
1297 unsigned Idx = (unsigned)CU->getValue();
1298 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
1300 // Return the modified struct.
1301 return ConstantStruct::get(Elts);
1303 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
1304 const ArrayType *ATy = cast<ArrayType>(Init->getType());
1306 // Break up the array into elements.
1307 std::vector<Constant*> Elts;
1308 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1309 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1310 Elts.push_back(CA->getOperand(i));
1311 } else if (isa<ConstantAggregateZero>(Init)) {
1312 Constant *Elt = Constant::getNullValue(ATy->getElementType());
1313 Elts.assign(ATy->getNumElements(), Elt);
1314 } else if (isa<UndefValue>(Init)) {
1315 Constant *Elt = UndefValue::get(ATy->getElementType());
1316 Elts.assign(ATy->getNumElements(), Elt);
1318 assert(0 && "This code is out of sync with "
1319 " ConstantFoldLoadThroughGEPConstantExpr");
1322 assert((uint64_t)CI->getRawValue() < ATy->getNumElements());
1323 Elts[(uint64_t)CI->getRawValue()] =
1324 EvaluateStoreInto(Elts[(uint64_t)CI->getRawValue()], Val, Addr, OpNo+1);
1325 return ConstantArray::get(ATy, Elts);
1329 /// CommitValueTo - We have decided that Addr (which satisfies the predicate
1330 /// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
1331 static void CommitValueTo(Constant *Val, Constant *Addr) {
1332 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
1333 assert(GV->hasInitializer());
1334 GV->setInitializer(Val);
1338 ConstantExpr *CE = cast<ConstantExpr>(Addr);
1339 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1341 Constant *Init = GV->getInitializer();
1342 Init = EvaluateStoreInto(Init, Val, CE, 2);
1343 GV->setInitializer(Init);
1346 /// ComputeLoadResult - Return the value that would be computed by a load from
1347 /// P after the stores reflected by 'memory' have been performed. If we can't
1348 /// decide, return null.
1349 static Constant *ComputeLoadResult(Constant *P,
1350 const std::map<Constant*, Constant*> &Memory) {
1351 // If this memory location has been recently stored, use the stored value: it
1352 // is the most up-to-date.
1353 std::map<Constant*, Constant*>::const_iterator I = Memory.find(P);
1354 if (I != Memory.end()) return I->second;
1357 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
1358 if (GV->hasInitializer())
1359 return GV->getInitializer();
1363 // Handle a constantexpr getelementptr.
1364 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
1365 if (CE->getOpcode() == Instruction::GetElementPtr &&
1366 isa<GlobalVariable>(CE->getOperand(0))) {
1367 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1368 if (GV->hasInitializer())
1369 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
1372 return 0; // don't know how to evaluate.
1375 /// EvaluateFunction - Evaluate a call to function F, returning true if
1376 /// successful, false if we can't evaluate it. ActualArgs contains the formal
1377 /// arguments for the function.
1378 static bool EvaluateFunction(Function *F, Constant *&RetVal,
1379 const std::vector<Constant*> &ActualArgs,
1380 std::vector<Function*> &CallStack,
1381 std::map<Constant*, Constant*> &MutatedMemory,
1382 std::vector<GlobalVariable*> &AllocaTmps) {
1383 // Check to see if this function is already executing (recursion). If so,
1384 // bail out. TODO: we might want to accept limited recursion.
1385 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
1388 CallStack.push_back(F);
1390 /// Values - As we compute SSA register values, we store their contents here.
1391 std::map<Value*, Constant*> Values;
1393 // Initialize arguments to the incoming values specified.
1395 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
1397 Values[AI] = ActualArgs[ArgNo];
1399 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
1400 /// we can only evaluate any one basic block at most once. This set keeps
1401 /// track of what we have executed so we can detect recursive cases etc.
1402 std::set<BasicBlock*> ExecutedBlocks;
1404 // CurInst - The current instruction we're evaluating.
1405 BasicBlock::iterator CurInst = F->begin()->begin();
1407 // This is the main evaluation loop.
1409 Constant *InstResult = 0;
1411 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
1412 if (SI->isVolatile()) return false; // no volatile accesses.
1413 Constant *Ptr = getVal(Values, SI->getOperand(1));
1414 if (!isSimpleEnoughPointerToCommit(Ptr))
1415 // If this is too complex for us to commit, reject it.
1417 Constant *Val = getVal(Values, SI->getOperand(0));
1418 MutatedMemory[Ptr] = Val;
1419 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
1420 InstResult = ConstantExpr::get(BO->getOpcode(),
1421 getVal(Values, BO->getOperand(0)),
1422 getVal(Values, BO->getOperand(1)));
1423 } else if (ShiftInst *SI = dyn_cast<ShiftInst>(CurInst)) {
1424 InstResult = ConstantExpr::get(SI->getOpcode(),
1425 getVal(Values, SI->getOperand(0)),
1426 getVal(Values, SI->getOperand(1)));
1427 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
1428 InstResult = ConstantExpr::getCast(getVal(Values, CI->getOperand(0)),
1430 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
1431 InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
1432 getVal(Values, SI->getOperand(1)),
1433 getVal(Values, SI->getOperand(2)));
1434 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
1435 Constant *P = getVal(Values, GEP->getOperand(0));
1436 std::vector<Constant*> GEPOps;
1437 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
1438 GEPOps.push_back(getVal(Values, GEP->getOperand(i)));
1439 InstResult = ConstantExpr::getGetElementPtr(P, GEPOps);
1440 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
1441 if (LI->isVolatile()) return false; // no volatile accesses.
1442 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
1444 if (InstResult == 0) return false; // Could not evaluate load.
1445 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
1446 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
1447 const Type *Ty = AI->getType()->getElementType();
1448 AllocaTmps.push_back(new GlobalVariable(Ty, false,
1449 GlobalValue::InternalLinkage,
1450 UndefValue::get(Ty),
1452 InstResult = AllocaTmps.back();
1453 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
1454 // Cannot handle inline asm.
1455 if (isa<InlineAsm>(CI->getOperand(0))) return false;
1457 // Resolve function pointers.
1458 Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
1459 if (!Callee) return false; // Cannot resolve.
1461 std::vector<Constant*> Formals;
1462 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
1463 Formals.push_back(getVal(Values, CI->getOperand(i)));
1465 if (Callee->isExternal()) {
1466 // If this is a function we can constant fold, do it.
1467 if (Constant *C = ConstantFoldCall(Callee, Formals)) {
1473 if (Callee->getFunctionType()->isVarArg())
1478 // Execute the call, if successful, use the return value.
1479 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
1480 MutatedMemory, AllocaTmps))
1482 InstResult = RetVal;
1484 } else if (TerminatorInst *TI = dyn_cast<TerminatorInst>(CurInst)) {
1485 BasicBlock *NewBB = 0;
1486 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
1487 if (BI->isUnconditional()) {
1488 NewBB = BI->getSuccessor(0);
1490 ConstantBool *Cond =
1491 dyn_cast<ConstantBool>(getVal(Values, BI->getCondition()));
1492 if (!Cond) return false; // Cannot determine.
1493 NewBB = BI->getSuccessor(!Cond->getValue());
1495 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
1497 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
1498 if (!Val) return false; // Cannot determine.
1499 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
1500 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
1501 if (RI->getNumOperands())
1502 RetVal = getVal(Values, RI->getOperand(0));
1504 CallStack.pop_back(); // return from fn.
1505 return true; // We succeeded at evaluating this ctor!
1507 // invoke, unwind, unreachable.
1508 return false; // Cannot handle this terminator.
1511 // Okay, we succeeded in evaluating this control flow. See if we have
1512 // executed the new block before. If so, we have a looping function,
1513 // which we cannot evaluate in reasonable time.
1514 if (!ExecutedBlocks.insert(NewBB).second)
1515 return false; // looped!
1517 // Okay, we have never been in this block before. Check to see if there
1518 // are any PHI nodes. If so, evaluate them with information about where
1520 BasicBlock *OldBB = CurInst->getParent();
1521 CurInst = NewBB->begin();
1523 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
1524 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
1526 // Do NOT increment CurInst. We know that the terminator had no value.
1529 // Did not know how to evaluate this!
1533 if (!CurInst->use_empty())
1534 Values[CurInst] = InstResult;
1536 // Advance program counter.
1541 /// EvaluateStaticConstructor - Evaluate static constructors in the function, if
1542 /// we can. Return true if we can, false otherwise.
1543 static bool EvaluateStaticConstructor(Function *F) {
1544 /// MutatedMemory - For each store we execute, we update this map. Loads
1545 /// check this to get the most up-to-date value. If evaluation is successful,
1546 /// this state is committed to the process.
1547 std::map<Constant*, Constant*> MutatedMemory;
1549 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
1550 /// to represent its body. This vector is needed so we can delete the
1551 /// temporary globals when we are done.
1552 std::vector<GlobalVariable*> AllocaTmps;
1554 /// CallStack - This is used to detect recursion. In pathological situations
1555 /// we could hit exponential behavior, but at least there is nothing
1557 std::vector<Function*> CallStack;
1559 // Call the function.
1560 Constant *RetValDummy;
1561 bool EvalSuccess = EvaluateFunction(F, RetValDummy, std::vector<Constant*>(),
1562 CallStack, MutatedMemory, AllocaTmps);
1564 // We succeeded at evaluation: commit the result.
1565 DEBUG(std::cerr << "FULLY EVALUATED GLOBAL CTOR FUNCTION '" <<
1566 F->getName() << "' to " << MutatedMemory.size() << " stores.\n");
1567 for (std::map<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
1568 E = MutatedMemory.end(); I != E; ++I)
1569 CommitValueTo(I->second, I->first);
1572 // At this point, we are done interpreting. If we created any 'alloca'
1573 // temporaries, release them now.
1574 while (!AllocaTmps.empty()) {
1575 GlobalVariable *Tmp = AllocaTmps.back();
1576 AllocaTmps.pop_back();
1578 // If there are still users of the alloca, the program is doing something
1579 // silly, e.g. storing the address of the alloca somewhere and using it
1580 // later. Since this is undefined, we'll just make it be null.
1581 if (!Tmp->use_empty())
1582 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
1592 /// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
1593 /// Return true if anything changed.
1594 bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
1595 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
1596 bool MadeChange = false;
1597 if (Ctors.empty()) return false;
1599 // Loop over global ctors, optimizing them when we can.
1600 for (unsigned i = 0; i != Ctors.size(); ++i) {
1601 Function *F = Ctors[i];
1602 // Found a null terminator in the middle of the list, prune off the rest of
1605 if (i != Ctors.size()-1) {
1612 // We cannot simplify external ctor functions.
1613 if (F->empty()) continue;
1615 // If we can evaluate the ctor at compile time, do.
1616 if (EvaluateStaticConstructor(F)) {
1617 Ctors.erase(Ctors.begin()+i);
1620 ++NumCtorsEvaluated;
1625 if (!MadeChange) return false;
1627 GCL = InstallGlobalCtors(GCL, Ctors);
1632 bool GlobalOpt::runOnModule(Module &M) {
1633 bool Changed = false;
1635 // Try to find the llvm.globalctors list.
1636 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
1638 bool LocalChange = true;
1639 while (LocalChange) {
1640 LocalChange = false;
1642 // Delete functions that are trivially dead, ccc -> fastcc
1643 LocalChange |= OptimizeFunctions(M);
1645 // Optimize global_ctors list.
1647 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
1649 // Optimize non-address-taken globals.
1650 LocalChange |= OptimizeGlobalVars(M);
1651 Changed |= LocalChange;
1654 // TODO: Move all global ctors functions to the end of the module for code