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/Analysis/ConstantFolding.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Support/Compiler.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/ADT/StringExtras.h"
36 STATISTIC(NumMarked , "Number of globals marked constant");
37 STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
38 STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
39 STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
40 STATISTIC(NumDeleted , "Number of globals deleted");
41 STATISTIC(NumFnDeleted , "Number of functions deleted");
42 STATISTIC(NumGlobUses , "Number of global uses devirtualized");
43 STATISTIC(NumLocalized , "Number of globals localized");
44 STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
45 STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
46 STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
49 struct VISIBILITY_HIDDEN GlobalOpt : public ModulePass {
50 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
51 AU.addRequired<TargetData>();
53 static char ID; // Pass identification, replacement for typeid
54 GlobalOpt() : ModulePass((intptr_t)&ID) {}
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 char GlobalOpt::ID = 0;
67 RegisterPass<GlobalOpt> X("globalopt", "Global Variable Optimizer");
70 ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
72 /// GlobalStatus - As we analyze each global, keep track of some information
73 /// about it. If we find out that the address of the global is taken, none of
74 /// this info will be accurate.
75 struct VISIBILITY_HIDDEN GlobalStatus {
76 /// isLoaded - True if the global is ever loaded. If the global isn't ever
77 /// loaded it can be deleted.
80 /// StoredType - Keep track of what stores to the global look like.
83 /// NotStored - There is no store to this global. It can thus be marked
87 /// isInitializerStored - This global is stored to, but the only thing
88 /// stored is the constant it was initialized with. This is only tracked
89 /// for scalar globals.
92 /// isStoredOnce - This global is stored to, but only its initializer and
93 /// one other value is ever stored to it. If this global isStoredOnce, we
94 /// track the value stored to it in StoredOnceValue below. This is only
95 /// tracked for scalar globals.
98 /// isStored - This global is stored to by multiple values or something else
99 /// that we cannot track.
103 /// StoredOnceValue - If only one value (besides the initializer constant) is
104 /// ever stored to this global, keep track of what value it is.
105 Value *StoredOnceValue;
107 /// AccessingFunction/HasMultipleAccessingFunctions - These start out
108 /// null/false. When the first accessing function is noticed, it is recorded.
109 /// When a second different accessing function is noticed,
110 /// HasMultipleAccessingFunctions is set to true.
111 Function *AccessingFunction;
112 bool HasMultipleAccessingFunctions;
114 /// HasNonInstructionUser - Set to true if this global has a user that is not
115 /// an instruction (e.g. a constant expr or GV initializer).
116 bool HasNonInstructionUser;
118 /// HasPHIUser - Set to true if this global has a user that is a PHI node.
121 /// isNotSuitableForSRA - Keep track of whether any SRA preventing users of
122 /// the global exist. Such users include GEP instruction with variable
123 /// indexes, and non-gep/load/store users like constant expr casts.
124 bool isNotSuitableForSRA;
126 GlobalStatus() : isLoaded(false), StoredType(NotStored), StoredOnceValue(0),
127 AccessingFunction(0), HasMultipleAccessingFunctions(false),
128 HasNonInstructionUser(false), HasPHIUser(false),
129 isNotSuitableForSRA(false) {}
134 /// ConstantIsDead - Return true if the specified constant is (transitively)
135 /// dead. The constant may be used by other constants (e.g. constant arrays and
136 /// constant exprs) as long as they are dead, but it cannot be used by anything
138 static bool ConstantIsDead(Constant *C) {
139 if (isa<GlobalValue>(C)) return false;
141 for (Value::use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; ++UI)
142 if (Constant *CU = dyn_cast<Constant>(*UI)) {
143 if (!ConstantIsDead(CU)) return false;
150 /// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
151 /// structure. If the global has its address taken, return true to indicate we
152 /// can't do anything with it.
154 static bool AnalyzeGlobal(Value *V, GlobalStatus &GS,
155 std::set<PHINode*> &PHIUsers) {
156 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
157 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(*UI)) {
158 GS.HasNonInstructionUser = true;
160 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
161 if (CE->getOpcode() != Instruction::GetElementPtr)
162 GS.isNotSuitableForSRA = true;
163 else if (!GS.isNotSuitableForSRA) {
164 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
165 // don't like < 3 operand CE's, and we don't like non-constant integer
167 if (CE->getNumOperands() < 3 || !CE->getOperand(1)->isNullValue())
168 GS.isNotSuitableForSRA = true;
170 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
171 if (!isa<ConstantInt>(CE->getOperand(i))) {
172 GS.isNotSuitableForSRA = true;
178 } else if (Instruction *I = dyn_cast<Instruction>(*UI)) {
179 if (!GS.HasMultipleAccessingFunctions) {
180 Function *F = I->getParent()->getParent();
181 if (GS.AccessingFunction == 0)
182 GS.AccessingFunction = F;
183 else if (GS.AccessingFunction != F)
184 GS.HasMultipleAccessingFunctions = true;
186 if (isa<LoadInst>(I)) {
188 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
189 // Don't allow a store OF the address, only stores TO the address.
190 if (SI->getOperand(0) == V) return true;
192 // If this is a direct store to the global (i.e., the global is a scalar
193 // value, not an aggregate), keep more specific information about
195 if (GS.StoredType != GlobalStatus::isStored)
196 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(SI->getOperand(1))){
197 Value *StoredVal = SI->getOperand(0);
198 if (StoredVal == GV->getInitializer()) {
199 if (GS.StoredType < GlobalStatus::isInitializerStored)
200 GS.StoredType = GlobalStatus::isInitializerStored;
201 } else if (isa<LoadInst>(StoredVal) &&
202 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
204 if (GS.StoredType < GlobalStatus::isInitializerStored)
205 GS.StoredType = GlobalStatus::isInitializerStored;
206 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
207 GS.StoredType = GlobalStatus::isStoredOnce;
208 GS.StoredOnceValue = StoredVal;
209 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
210 GS.StoredOnceValue == StoredVal) {
213 GS.StoredType = GlobalStatus::isStored;
216 GS.StoredType = GlobalStatus::isStored;
218 } else if (isa<GetElementPtrInst>(I)) {
219 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
221 // If the first two indices are constants, this can be SRA'd.
222 if (isa<GlobalVariable>(I->getOperand(0))) {
223 if (I->getNumOperands() < 3 || !isa<Constant>(I->getOperand(1)) ||
224 !cast<Constant>(I->getOperand(1))->isNullValue() ||
225 !isa<ConstantInt>(I->getOperand(2)))
226 GS.isNotSuitableForSRA = true;
227 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(I->getOperand(0))){
228 if (CE->getOpcode() != Instruction::GetElementPtr ||
229 CE->getNumOperands() < 3 || I->getNumOperands() < 2 ||
230 !isa<Constant>(I->getOperand(0)) ||
231 !cast<Constant>(I->getOperand(0))->isNullValue())
232 GS.isNotSuitableForSRA = true;
234 GS.isNotSuitableForSRA = true;
236 } else if (isa<SelectInst>(I)) {
237 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
238 GS.isNotSuitableForSRA = true;
239 } else if (PHINode *PN = dyn_cast<PHINode>(I)) {
240 // PHI nodes we can check just like select or GEP instructions, but we
241 // have to be careful about infinite recursion.
242 if (PHIUsers.insert(PN).second) // Not already visited.
243 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
244 GS.isNotSuitableForSRA = true;
245 GS.HasPHIUser = true;
246 } else if (isa<CmpInst>(I)) {
247 GS.isNotSuitableForSRA = true;
248 } else if (isa<MemCpyInst>(I) || isa<MemMoveInst>(I)) {
249 if (I->getOperand(1) == V)
250 GS.StoredType = GlobalStatus::isStored;
251 if (I->getOperand(2) == V)
253 GS.isNotSuitableForSRA = true;
254 } else if (isa<MemSetInst>(I)) {
255 assert(I->getOperand(1) == V && "Memset only takes one pointer!");
256 GS.StoredType = GlobalStatus::isStored;
257 GS.isNotSuitableForSRA = true;
259 return true; // Any other non-load instruction might take address!
261 } else if (Constant *C = dyn_cast<Constant>(*UI)) {
262 GS.HasNonInstructionUser = true;
263 // We might have a dead and dangling constant hanging off of here.
264 if (!ConstantIsDead(C))
267 GS.HasNonInstructionUser = true;
268 // Otherwise must be some other user.
275 static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
276 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
278 unsigned IdxV = CI->getZExtValue();
280 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Agg)) {
281 if (IdxV < CS->getNumOperands()) return CS->getOperand(IdxV);
282 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Agg)) {
283 if (IdxV < CA->getNumOperands()) return CA->getOperand(IdxV);
284 } else if (ConstantVector *CP = dyn_cast<ConstantVector>(Agg)) {
285 if (IdxV < CP->getNumOperands()) return CP->getOperand(IdxV);
286 } else if (isa<ConstantAggregateZero>(Agg)) {
287 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
288 if (IdxV < STy->getNumElements())
289 return Constant::getNullValue(STy->getElementType(IdxV));
290 } else if (const SequentialType *STy =
291 dyn_cast<SequentialType>(Agg->getType())) {
292 return Constant::getNullValue(STy->getElementType());
294 } else if (isa<UndefValue>(Agg)) {
295 if (const StructType *STy = dyn_cast<StructType>(Agg->getType())) {
296 if (IdxV < STy->getNumElements())
297 return UndefValue::get(STy->getElementType(IdxV));
298 } else if (const SequentialType *STy =
299 dyn_cast<SequentialType>(Agg->getType())) {
300 return UndefValue::get(STy->getElementType());
307 /// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all
308 /// users of the global, cleaning up the obvious ones. This is largely just a
309 /// quick scan over the use list to clean up the easy and obvious cruft. This
310 /// returns true if it made a change.
311 static bool CleanupConstantGlobalUsers(Value *V, Constant *Init) {
312 bool Changed = false;
313 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) {
316 if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
318 // Replace the load with the initializer.
319 LI->replaceAllUsesWith(Init);
320 LI->eraseFromParent();
323 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
324 // Store must be unreachable or storing Init into the global.
325 SI->eraseFromParent();
327 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
328 if (CE->getOpcode() == Instruction::GetElementPtr) {
329 Constant *SubInit = 0;
331 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
332 Changed |= CleanupConstantGlobalUsers(CE, SubInit);
333 } else if (CE->getOpcode() == Instruction::BitCast &&
334 isa<PointerType>(CE->getType())) {
335 // Pointer cast, delete any stores and memsets to the global.
336 Changed |= CleanupConstantGlobalUsers(CE, 0);
339 if (CE->use_empty()) {
340 CE->destroyConstant();
343 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
344 Constant *SubInit = 0;
346 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
347 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
348 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
349 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
351 if (GEP->use_empty()) {
352 GEP->eraseFromParent();
355 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
356 if (MI->getRawDest() == V) {
357 MI->eraseFromParent();
361 } else if (Constant *C = dyn_cast<Constant>(U)) {
362 // If we have a chain of dead constantexprs or other things dangling from
363 // us, and if they are all dead, nuke them without remorse.
364 if (ConstantIsDead(C)) {
365 C->destroyConstant();
366 // This could have invalidated UI, start over from scratch.
367 CleanupConstantGlobalUsers(V, Init);
375 /// SRAGlobal - Perform scalar replacement of aggregates on the specified global
376 /// variable. This opens the door for other optimizations by exposing the
377 /// behavior of the program in a more fine-grained way. We have determined that
378 /// this transformation is safe already. We return the first global variable we
379 /// insert so that the caller can reprocess it.
380 static GlobalVariable *SRAGlobal(GlobalVariable *GV) {
381 assert(GV->hasInternalLinkage() && !GV->isConstant());
382 Constant *Init = GV->getInitializer();
383 const Type *Ty = Init->getType();
385 std::vector<GlobalVariable*> NewGlobals;
386 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
388 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
389 NewGlobals.reserve(STy->getNumElements());
390 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
391 Constant *In = getAggregateConstantElement(Init,
392 ConstantInt::get(Type::Int32Ty, i));
393 assert(In && "Couldn't get element of initializer?");
394 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
395 GlobalVariable::InternalLinkage,
396 In, GV->getName()+"."+utostr(i),
398 GV->isThreadLocal());
399 Globals.insert(GV, NGV);
400 NewGlobals.push_back(NGV);
402 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
403 unsigned NumElements = 0;
404 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
405 NumElements = ATy->getNumElements();
406 else if (const VectorType *PTy = dyn_cast<VectorType>(STy))
407 NumElements = PTy->getNumElements();
409 assert(0 && "Unknown aggregate sequential type!");
411 if (NumElements > 16 && GV->hasNUsesOrMore(16))
412 return 0; // It's not worth it.
413 NewGlobals.reserve(NumElements);
414 for (unsigned i = 0, e = NumElements; i != e; ++i) {
415 Constant *In = getAggregateConstantElement(Init,
416 ConstantInt::get(Type::Int32Ty, i));
417 assert(In && "Couldn't get element of initializer?");
419 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
420 GlobalVariable::InternalLinkage,
421 In, GV->getName()+"."+utostr(i),
423 GV->isThreadLocal());
424 Globals.insert(GV, NGV);
425 NewGlobals.push_back(NGV);
429 if (NewGlobals.empty())
432 DOUT << "PERFORMING GLOBAL SRA ON: " << *GV;
434 Constant *NullInt = Constant::getNullValue(Type::Int32Ty);
436 // Loop over all of the uses of the global, replacing the constantexpr geps,
437 // with smaller constantexpr geps or direct references.
438 while (!GV->use_empty()) {
439 User *GEP = GV->use_back();
440 assert(((isa<ConstantExpr>(GEP) &&
441 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
442 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
444 // Ignore the 1th operand, which has to be zero or else the program is quite
445 // broken (undefined). Get the 2nd operand, which is the structure or array
447 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
448 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
450 Value *NewPtr = NewGlobals[Val];
452 // Form a shorter GEP if needed.
453 if (GEP->getNumOperands() > 3)
454 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
455 SmallVector<Constant*, 8> Idxs;
456 Idxs.push_back(NullInt);
457 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
458 Idxs.push_back(CE->getOperand(i));
459 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr),
460 &Idxs[0], Idxs.size());
462 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
463 SmallVector<Value*, 8> Idxs;
464 Idxs.push_back(NullInt);
465 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
466 Idxs.push_back(GEPI->getOperand(i));
467 NewPtr = new GetElementPtrInst(NewPtr, &Idxs[0], Idxs.size(),
468 GEPI->getName()+"."+utostr(Val), GEPI);
470 GEP->replaceAllUsesWith(NewPtr);
472 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
473 GEPI->eraseFromParent();
475 cast<ConstantExpr>(GEP)->destroyConstant();
478 // Delete the old global, now that it is dead.
482 // Loop over the new globals array deleting any globals that are obviously
483 // dead. This can arise due to scalarization of a structure or an array that
484 // has elements that are dead.
485 unsigned FirstGlobal = 0;
486 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
487 if (NewGlobals[i]->use_empty()) {
488 Globals.erase(NewGlobals[i]);
489 if (FirstGlobal == i) ++FirstGlobal;
492 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
495 /// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
496 /// value will trap if the value is dynamically null.
497 static bool AllUsesOfValueWillTrapIfNull(Value *V) {
498 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ++UI)
499 if (isa<LoadInst>(*UI)) {
501 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
502 if (SI->getOperand(0) == V) {
503 //cerr << "NONTRAPPING USE: " << **UI;
504 return false; // Storing the value.
506 } else if (CallInst *CI = dyn_cast<CallInst>(*UI)) {
507 if (CI->getOperand(0) != V) {
508 //cerr << "NONTRAPPING USE: " << **UI;
509 return false; // Not calling the ptr
511 } else if (InvokeInst *II = dyn_cast<InvokeInst>(*UI)) {
512 if (II->getOperand(0) != V) {
513 //cerr << "NONTRAPPING USE: " << **UI;
514 return false; // Not calling the ptr
516 } else if (CastInst *CI = dyn_cast<CastInst>(*UI)) {
517 if (!AllUsesOfValueWillTrapIfNull(CI)) return false;
518 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI)) {
519 if (!AllUsesOfValueWillTrapIfNull(GEPI)) return false;
520 } else if (isa<ICmpInst>(*UI) &&
521 isa<ConstantPointerNull>(UI->getOperand(1))) {
522 // Ignore setcc X, null
524 //cerr << "NONTRAPPING USE: " << **UI;
530 /// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
531 /// from GV will trap if the loaded value is null. Note that this also permits
532 /// comparisons of the loaded value against null, as a special case.
533 static bool AllUsesOfLoadedValueWillTrapIfNull(GlobalVariable *GV) {
534 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI!=E; ++UI)
535 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
536 if (!AllUsesOfValueWillTrapIfNull(LI))
538 } else if (isa<StoreInst>(*UI)) {
539 // Ignore stores to the global.
541 // We don't know or understand this user, bail out.
542 //cerr << "UNKNOWN USER OF GLOBAL!: " << **UI;
549 static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
550 bool Changed = false;
551 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
552 Instruction *I = cast<Instruction>(*UI++);
553 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
554 LI->setOperand(0, NewV);
556 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
557 if (SI->getOperand(1) == V) {
558 SI->setOperand(1, NewV);
561 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
562 if (I->getOperand(0) == V) {
563 // Calling through the pointer! Turn into a direct call, but be careful
564 // that the pointer is not also being passed as an argument.
565 I->setOperand(0, NewV);
567 bool PassedAsArg = false;
568 for (unsigned i = 1, e = I->getNumOperands(); i != e; ++i)
569 if (I->getOperand(i) == V) {
571 I->setOperand(i, NewV);
575 // Being passed as an argument also. Be careful to not invalidate UI!
579 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
580 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
581 ConstantExpr::getCast(CI->getOpcode(),
582 NewV, CI->getType()));
583 if (CI->use_empty()) {
585 CI->eraseFromParent();
587 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
588 // Should handle GEP here.
589 SmallVector<Constant*, 8> Idxs;
590 Idxs.reserve(GEPI->getNumOperands()-1);
591 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
592 if (Constant *C = dyn_cast<Constant>(GEPI->getOperand(i)))
596 if (Idxs.size() == GEPI->getNumOperands()-1)
597 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
598 ConstantExpr::getGetElementPtr(NewV, &Idxs[0],
600 if (GEPI->use_empty()) {
602 GEPI->eraseFromParent();
611 /// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
612 /// value stored into it. If there are uses of the loaded value that would trap
613 /// if the loaded value is dynamically null, then we know that they cannot be
614 /// reachable with a null optimize away the load.
615 static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
616 std::vector<LoadInst*> Loads;
617 bool Changed = false;
619 // Replace all uses of loads with uses of uses of the stored value.
620 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end();
622 if (LoadInst *LI = dyn_cast<LoadInst>(*GUI)) {
624 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
626 // If we get here we could have stores, loads, or phi nodes whose values
628 assert((isa<StoreInst>(*GUI) || isa<PHINode>(*GUI)) &&
629 "Only expect load and stores!");
633 DOUT << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV;
637 // Delete all of the loads we can, keeping track of whether we nuked them all!
638 bool AllLoadsGone = true;
639 while (!Loads.empty()) {
640 LoadInst *L = Loads.back();
641 if (L->use_empty()) {
642 L->eraseFromParent();
645 AllLoadsGone = false;
650 // If we nuked all of the loads, then none of the stores are needed either,
651 // nor is the global.
653 DOUT << " *** GLOBAL NOW DEAD!\n";
654 CleanupConstantGlobalUsers(GV, 0);
655 if (GV->use_empty()) {
656 GV->eraseFromParent();
664 /// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
665 /// instructions that are foldable.
666 static void ConstantPropUsersOf(Value *V) {
667 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
668 if (Instruction *I = dyn_cast<Instruction>(*UI++))
669 if (Constant *NewC = ConstantFoldInstruction(I)) {
670 I->replaceAllUsesWith(NewC);
672 // Advance UI to the next non-I use to avoid invalidating it!
673 // Instructions could multiply use V.
674 while (UI != E && *UI == I)
676 I->eraseFromParent();
680 /// OptimizeGlobalAddressOfMalloc - This function takes the specified global
681 /// variable, and transforms the program as if it always contained the result of
682 /// the specified malloc. Because it is always the result of the specified
683 /// malloc, there is no reason to actually DO the malloc. Instead, turn the
684 /// malloc into a global, and any loads of GV as uses of the new global.
685 static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
687 DOUT << "PROMOTING MALLOC GLOBAL: " << *GV << " MALLOC = " << *MI;
688 ConstantInt *NElements = cast<ConstantInt>(MI->getArraySize());
690 if (NElements->getZExtValue() != 1) {
691 // If we have an array allocation, transform it to a single element
692 // allocation to make the code below simpler.
693 Type *NewTy = ArrayType::get(MI->getAllocatedType(),
694 NElements->getZExtValue());
696 new MallocInst(NewTy, Constant::getNullValue(Type::Int32Ty),
697 MI->getAlignment(), MI->getName(), MI);
699 Indices[0] = Indices[1] = Constant::getNullValue(Type::Int32Ty);
700 Value *NewGEP = new GetElementPtrInst(NewMI, Indices, 2,
701 NewMI->getName()+".el0", MI);
702 MI->replaceAllUsesWith(NewGEP);
703 MI->eraseFromParent();
707 // Create the new global variable. The contents of the malloc'd memory is
708 // undefined, so initialize with an undef value.
709 Constant *Init = UndefValue::get(MI->getAllocatedType());
710 GlobalVariable *NewGV = new GlobalVariable(MI->getAllocatedType(), false,
711 GlobalValue::InternalLinkage, Init,
712 GV->getName()+".body",
714 GV->isThreadLocal());
715 GV->getParent()->getGlobalList().insert(GV, NewGV);
717 // Anything that used the malloc now uses the global directly.
718 MI->replaceAllUsesWith(NewGV);
720 Constant *RepValue = NewGV;
721 if (NewGV->getType() != GV->getType()->getElementType())
722 RepValue = ConstantExpr::getBitCast(RepValue,
723 GV->getType()->getElementType());
725 // If there is a comparison against null, we will insert a global bool to
726 // keep track of whether the global was initialized yet or not.
727 GlobalVariable *InitBool =
728 new GlobalVariable(Type::Int1Ty, false, GlobalValue::InternalLinkage,
729 ConstantInt::getFalse(), GV->getName()+".init",
730 (Module *)NULL, GV->isThreadLocal());
731 bool InitBoolUsed = false;
733 // Loop over all uses of GV, processing them in turn.
734 std::vector<StoreInst*> Stores;
735 while (!GV->use_empty())
736 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
737 while (!LI->use_empty()) {
738 Use &LoadUse = LI->use_begin().getUse();
739 if (!isa<ICmpInst>(LoadUse.getUser()))
742 ICmpInst *CI = cast<ICmpInst>(LoadUse.getUser());
743 // Replace the cmp X, 0 with a use of the bool value.
744 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", CI);
746 switch (CI->getPredicate()) {
747 default: assert(0 && "Unknown ICmp Predicate!");
748 case ICmpInst::ICMP_ULT:
749 case ICmpInst::ICMP_SLT:
750 LV = ConstantInt::getFalse(); // X < null -> always false
752 case ICmpInst::ICMP_ULE:
753 case ICmpInst::ICMP_SLE:
754 case ICmpInst::ICMP_EQ:
755 LV = BinaryOperator::createNot(LV, "notinit", CI);
757 case ICmpInst::ICMP_NE:
758 case ICmpInst::ICMP_UGE:
759 case ICmpInst::ICMP_SGE:
760 case ICmpInst::ICMP_UGT:
761 case ICmpInst::ICMP_SGT:
764 CI->replaceAllUsesWith(LV);
765 CI->eraseFromParent();
768 LI->eraseFromParent();
770 StoreInst *SI = cast<StoreInst>(GV->use_back());
771 // The global is initialized when the store to it occurs.
772 new StoreInst(ConstantInt::getTrue(), InitBool, SI);
773 SI->eraseFromParent();
776 // If the initialization boolean was used, insert it, otherwise delete it.
778 while (!InitBool->use_empty()) // Delete initializations
779 cast<Instruction>(InitBool->use_back())->eraseFromParent();
782 GV->getParent()->getGlobalList().insert(GV, InitBool);
785 // Now the GV is dead, nuke it and the malloc.
786 GV->eraseFromParent();
787 MI->eraseFromParent();
789 // To further other optimizations, loop over all users of NewGV and try to
790 // constant prop them. This will promote GEP instructions with constant
791 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
792 ConstantPropUsersOf(NewGV);
793 if (RepValue != NewGV)
794 ConstantPropUsersOf(RepValue);
799 /// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
800 /// to make sure that there are no complex uses of V. We permit simple things
801 /// like dereferencing the pointer, but not storing through the address, unless
802 /// it is to the specified global.
803 static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Instruction *V,
804 GlobalVariable *GV) {
805 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;++UI)
806 if (isa<LoadInst>(*UI) || isa<CmpInst>(*UI)) {
808 } else if (StoreInst *SI = dyn_cast<StoreInst>(*UI)) {
809 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
810 return false; // Storing the pointer itself... bad.
811 // Otherwise, storing through it, or storing into GV... fine.
812 } else if (isa<GetElementPtrInst>(*UI) || isa<SelectInst>(*UI)) {
813 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(cast<Instruction>(*UI),GV))
821 /// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
822 /// somewhere. Transform all uses of the allocation into loads from the
823 /// global and uses of the resultant pointer. Further, delete the store into
824 /// GV. This assumes that these value pass the
825 /// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
826 static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
827 GlobalVariable *GV) {
828 while (!Alloc->use_empty()) {
829 Instruction *U = Alloc->use_back();
830 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
831 // If this is the store of the allocation into the global, remove it.
832 if (SI->getOperand(1) == GV) {
833 SI->eraseFromParent();
838 // Insert a load from the global, and use it instead of the malloc.
839 Value *NL = new LoadInst(GV, GV->getName()+".val", U);
840 U->replaceUsesOfWith(Alloc, NL);
844 /// GlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
845 /// GV are simple enough to perform HeapSRA, return true.
846 static bool GlobalLoadUsesSimpleEnoughForHeapSRA(GlobalVariable *GV) {
847 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;
849 if (LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
850 // We permit two users of the load: setcc comparing against the null
851 // pointer, and a getelementptr of a specific form.
852 for (Value::use_iterator UI = LI->use_begin(), E = LI->use_end(); UI != E;
854 // Comparison against null is ok.
855 if (ICmpInst *ICI = dyn_cast<ICmpInst>(*UI)) {
856 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
861 // getelementptr is also ok, but only a simple form.
862 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(*UI);
863 if (!GEPI) return false;
865 // Must index into the array and into the struct.
866 if (GEPI->getNumOperands() < 3)
869 // Otherwise the GEP is ok.
876 /// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
877 /// is a value loaded from the global. Eliminate all uses of Ptr, making them
878 /// use FieldGlobals instead. All uses of loaded values satisfy
879 /// GlobalLoadUsesSimpleEnoughForHeapSRA.
880 static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Ptr,
881 const std::vector<GlobalVariable*> &FieldGlobals) {
882 std::vector<Value *> InsertedLoadsForPtr;
883 //InsertedLoadsForPtr.resize(FieldGlobals.size());
884 while (!Ptr->use_empty()) {
885 Instruction *User = Ptr->use_back();
887 // If this is a comparison against null, handle it.
888 if (ICmpInst *SCI = dyn_cast<ICmpInst>(User)) {
889 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
890 // If we have a setcc of the loaded pointer, we can use a setcc of any
893 if (InsertedLoadsForPtr.empty()) {
894 NPtr = new LoadInst(FieldGlobals[0], Ptr->getName()+".f0", Ptr);
895 InsertedLoadsForPtr.push_back(Ptr);
897 NPtr = InsertedLoadsForPtr.back();
900 Value *New = new ICmpInst(SCI->getPredicate(), NPtr,
901 Constant::getNullValue(NPtr->getType()),
902 SCI->getName(), SCI);
903 SCI->replaceAllUsesWith(New);
904 SCI->eraseFromParent();
908 // Otherwise, this should be: 'getelementptr Ptr, Idx, uint FieldNo ...'
909 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(User);
910 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
911 && "Unexpected GEPI!");
913 // Load the pointer for this field.
914 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
915 if (InsertedLoadsForPtr.size() <= FieldNo)
916 InsertedLoadsForPtr.resize(FieldNo+1);
917 if (InsertedLoadsForPtr[FieldNo] == 0)
918 InsertedLoadsForPtr[FieldNo] = new LoadInst(FieldGlobals[FieldNo],
919 Ptr->getName()+".f" +
920 utostr(FieldNo), Ptr);
921 Value *NewPtr = InsertedLoadsForPtr[FieldNo];
923 // Create the new GEP idx vector.
924 SmallVector<Value*, 8> GEPIdx;
925 GEPIdx.push_back(GEPI->getOperand(1));
926 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
928 Value *NGEPI = new GetElementPtrInst(NewPtr, &GEPIdx[0], GEPIdx.size(),
929 GEPI->getName(), GEPI);
930 GEPI->replaceAllUsesWith(NGEPI);
931 GEPI->eraseFromParent();
935 /// PerformHeapAllocSRoA - MI is an allocation of an array of structures. Break
936 /// it up into multiple allocations of arrays of the fields.
937 static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, MallocInst *MI){
938 DOUT << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *MI;
939 const StructType *STy = cast<StructType>(MI->getAllocatedType());
941 // There is guaranteed to be at least one use of the malloc (storing
942 // it into GV). If there are other uses, change them to be uses of
943 // the global to simplify later code. This also deletes the store
945 ReplaceUsesOfMallocWithGlobal(MI, GV);
947 // Okay, at this point, there are no users of the malloc. Insert N
948 // new mallocs at the same place as MI, and N globals.
949 std::vector<GlobalVariable*> FieldGlobals;
950 std::vector<MallocInst*> FieldMallocs;
952 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
953 const Type *FieldTy = STy->getElementType(FieldNo);
954 const Type *PFieldTy = PointerType::get(FieldTy);
956 GlobalVariable *NGV =
957 new GlobalVariable(PFieldTy, false, GlobalValue::InternalLinkage,
958 Constant::getNullValue(PFieldTy),
959 GV->getName() + ".f" + utostr(FieldNo), GV,
960 GV->isThreadLocal());
961 FieldGlobals.push_back(NGV);
963 MallocInst *NMI = new MallocInst(FieldTy, MI->getArraySize(),
964 MI->getName() + ".f" + utostr(FieldNo),MI);
965 FieldMallocs.push_back(NMI);
966 new StoreInst(NMI, NGV, MI);
969 // The tricky aspect of this transformation is handling the case when malloc
970 // fails. In the original code, malloc failing would set the result pointer
971 // of malloc to null. In this case, some mallocs could succeed and others
972 // could fail. As such, we emit code that looks like this:
973 // F0 = malloc(field0)
974 // F1 = malloc(field1)
975 // F2 = malloc(field2)
976 // if (F0 == 0 || F1 == 0 || F2 == 0) {
977 // if (F0) { free(F0); F0 = 0; }
978 // if (F1) { free(F1); F1 = 0; }
979 // if (F2) { free(F2); F2 = 0; }
981 Value *RunningOr = 0;
982 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
983 Value *Cond = new ICmpInst(ICmpInst::ICMP_EQ, FieldMallocs[i],
984 Constant::getNullValue(FieldMallocs[i]->getType()),
987 RunningOr = Cond; // First seteq
989 RunningOr = BinaryOperator::createOr(RunningOr, Cond, "tmp", MI);
992 // Split the basic block at the old malloc.
993 BasicBlock *OrigBB = MI->getParent();
994 BasicBlock *ContBB = OrigBB->splitBasicBlock(MI, "malloc_cont");
996 // Create the block to check the first condition. Put all these blocks at the
997 // end of the function as they are unlikely to be executed.
998 BasicBlock *NullPtrBlock = new BasicBlock("malloc_ret_null",
999 OrigBB->getParent());
1001 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1002 // branch on RunningOr.
1003 OrigBB->getTerminator()->eraseFromParent();
1004 new BranchInst(NullPtrBlock, ContBB, RunningOr, OrigBB);
1006 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1007 // pointer, because some may be null while others are not.
1008 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1009 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
1010 Value *Cmp = new ICmpInst(ICmpInst::ICMP_NE, GVVal,
1011 Constant::getNullValue(GVVal->getType()),
1012 "tmp", NullPtrBlock);
1013 BasicBlock *FreeBlock = new BasicBlock("free_it", OrigBB->getParent());
1014 BasicBlock *NextBlock = new BasicBlock("next", OrigBB->getParent());
1015 new BranchInst(FreeBlock, NextBlock, Cmp, NullPtrBlock);
1017 // Fill in FreeBlock.
1018 new FreeInst(GVVal, FreeBlock);
1019 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1021 new BranchInst(NextBlock, FreeBlock);
1023 NullPtrBlock = NextBlock;
1026 new BranchInst(ContBB, NullPtrBlock);
1029 // MI is no longer needed, remove it.
1030 MI->eraseFromParent();
1033 // Okay, the malloc site is completely handled. All of the uses of GV are now
1034 // loads, and all uses of those loads are simple. Rewrite them to use loads
1035 // of the per-field globals instead.
1036 while (!GV->use_empty()) {
1037 if (LoadInst *LI = dyn_cast<LoadInst>(GV->use_back())) {
1038 RewriteUsesOfLoadForHeapSRoA(LI, FieldGlobals);
1039 LI->eraseFromParent();
1041 // Must be a store of null.
1042 StoreInst *SI = cast<StoreInst>(GV->use_back());
1043 assert(isa<Constant>(SI->getOperand(0)) &&
1044 cast<Constant>(SI->getOperand(0))->isNullValue() &&
1045 "Unexpected heap-sra user!");
1047 // Insert a store of null into each global.
1048 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1050 Constant::getNullValue(FieldGlobals[i]->getType()->getElementType());
1051 new StoreInst(Null, FieldGlobals[i], SI);
1053 // Erase the original store.
1054 SI->eraseFromParent();
1058 // The old global is now dead, remove it.
1059 GV->eraseFromParent();
1062 return FieldGlobals[0];
1066 // OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1067 // that only one value (besides its initializer) is ever stored to the global.
1068 static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
1069 Module::global_iterator &GVI,
1071 if (CastInst *CI = dyn_cast<CastInst>(StoredOnceVal))
1072 StoredOnceVal = CI->getOperand(0);
1073 else if (GetElementPtrInst *GEPI =dyn_cast<GetElementPtrInst>(StoredOnceVal)){
1074 // "getelementptr Ptr, 0, 0, 0" is really just a cast.
1075 bool IsJustACast = true;
1076 for (unsigned i = 1, e = GEPI->getNumOperands(); i != e; ++i)
1077 if (!isa<Constant>(GEPI->getOperand(i)) ||
1078 !cast<Constant>(GEPI->getOperand(i))->isNullValue()) {
1079 IsJustACast = false;
1083 StoredOnceVal = GEPI->getOperand(0);
1086 // If we are dealing with a pointer global that is initialized to null and
1087 // only has one (non-null) value stored into it, then we can optimize any
1088 // users of the loaded value (often calls and loads) that would trap if the
1090 if (isa<PointerType>(GV->getInitializer()->getType()) &&
1091 GV->getInitializer()->isNullValue()) {
1092 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1093 if (GV->getInitializer()->getType() != SOVC->getType())
1094 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
1096 // Optimize away any trapping uses of the loaded value.
1097 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
1099 } else if (MallocInst *MI = dyn_cast<MallocInst>(StoredOnceVal)) {
1100 // If this is a malloc of an abstract type, don't touch it.
1101 if (!MI->getAllocatedType()->isSized())
1104 // We can't optimize this global unless all uses of it are *known* to be
1105 // of the malloc value, not of the null initializer value (consider a use
1106 // that compares the global's value against zero to see if the malloc has
1107 // been reached). To do this, we check to see if all uses of the global
1108 // would trap if the global were null: this proves that they must all
1109 // happen after the malloc.
1110 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1113 // We can't optimize this if the malloc itself is used in a complex way,
1114 // for example, being stored into multiple globals. This allows the
1115 // malloc to be stored into the specified global, loaded setcc'd, and
1116 // GEP'd. These are all things we could transform to using the global
1118 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(MI, GV))
1122 // If we have a global that is only initialized with a fixed size malloc,
1123 // transform the program to use global memory instead of malloc'd memory.
1124 // This eliminates dynamic allocation, avoids an indirection accessing the
1125 // data, and exposes the resultant global to further GlobalOpt.
1126 if (ConstantInt *NElements = dyn_cast<ConstantInt>(MI->getArraySize())) {
1127 // Restrict this transformation to only working on small allocations
1128 // (2048 bytes currently), as we don't want to introduce a 16M global or
1130 if (NElements->getZExtValue()*
1131 TD.getTypeSize(MI->getAllocatedType()) < 2048) {
1132 GVI = OptimizeGlobalAddressOfMalloc(GV, MI);
1137 // If the allocation is an array of structures, consider transforming this
1138 // into multiple malloc'd arrays, one for each field. This is basically
1139 // SRoA for malloc'd memory.
1140 if (const StructType *AllocTy =
1141 dyn_cast<StructType>(MI->getAllocatedType())) {
1142 // This the structure has an unreasonable number of fields, leave it
1144 if (AllocTy->getNumElements() <= 16 && AllocTy->getNumElements() > 0 &&
1145 GlobalLoadUsesSimpleEnoughForHeapSRA(GV)) {
1146 GVI = PerformHeapAllocSRoA(GV, MI);
1156 /// ShrinkGlobalToBoolean - At this point, we have learned that the only two
1157 /// values ever stored into GV are its initializer and OtherVal.
1158 static void ShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
1159 // Create the new global, initializing it to false.
1160 GlobalVariable *NewGV = new GlobalVariable(Type::Int1Ty, false,
1161 GlobalValue::InternalLinkage, ConstantInt::getFalse(),
1164 GV->isThreadLocal());
1165 GV->getParent()->getGlobalList().insert(GV, NewGV);
1167 Constant *InitVal = GV->getInitializer();
1168 assert(InitVal->getType() != Type::Int1Ty && "No reason to shrink to bool!");
1170 // If initialized to zero and storing one into the global, we can use a cast
1171 // instead of a select to synthesize the desired value.
1172 bool IsOneZero = false;
1173 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
1174 IsOneZero = InitVal->isNullValue() && CI->isOne();
1176 while (!GV->use_empty()) {
1177 Instruction *UI = cast<Instruction>(GV->use_back());
1178 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
1179 // Change the store into a boolean store.
1180 bool StoringOther = SI->getOperand(0) == OtherVal;
1181 // Only do this if we weren't storing a loaded value.
1183 if (StoringOther || SI->getOperand(0) == InitVal)
1184 StoreVal = ConstantInt::get(Type::Int1Ty, StoringOther);
1186 // Otherwise, we are storing a previously loaded copy. To do this,
1187 // change the copy from copying the original value to just copying the
1189 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1191 // If we're already replaced the input, StoredVal will be a cast or
1192 // select instruction. If not, it will be a load of the original
1194 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1195 assert(LI->getOperand(0) == GV && "Not a copy!");
1196 // Insert a new load, to preserve the saved value.
1197 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1199 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1200 "This is not a form that we understand!");
1201 StoreVal = StoredVal->getOperand(0);
1202 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1205 new StoreInst(StoreVal, NewGV, SI);
1206 } else if (!UI->use_empty()) {
1207 // Change the load into a load of bool then a select.
1208 LoadInst *LI = cast<LoadInst>(UI);
1209 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
1212 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
1214 NSI = new SelectInst(NLI, OtherVal, InitVal, "", LI);
1216 LI->replaceAllUsesWith(NSI);
1218 UI->eraseFromParent();
1221 GV->eraseFromParent();
1225 /// ProcessInternalGlobal - Analyze the specified global variable and optimize
1226 /// it if possible. If we make a change, return true.
1227 bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1228 Module::global_iterator &GVI) {
1229 std::set<PHINode*> PHIUsers;
1231 GV->removeDeadConstantUsers();
1233 if (GV->use_empty()) {
1234 DOUT << "GLOBAL DEAD: " << *GV;
1235 GV->eraseFromParent();
1240 if (!AnalyzeGlobal(GV, GS, PHIUsers)) {
1242 cerr << "Global: " << *GV;
1243 cerr << " isLoaded = " << GS.isLoaded << "\n";
1244 cerr << " StoredType = ";
1245 switch (GS.StoredType) {
1246 case GlobalStatus::NotStored: cerr << "NEVER STORED\n"; break;
1247 case GlobalStatus::isInitializerStored: cerr << "INIT STORED\n"; break;
1248 case GlobalStatus::isStoredOnce: cerr << "STORED ONCE\n"; break;
1249 case GlobalStatus::isStored: cerr << "stored\n"; break;
1251 if (GS.StoredType == GlobalStatus::isStoredOnce && GS.StoredOnceValue)
1252 cerr << " StoredOnceValue = " << *GS.StoredOnceValue << "\n";
1253 if (GS.AccessingFunction && !GS.HasMultipleAccessingFunctions)
1254 cerr << " AccessingFunction = " << GS.AccessingFunction->getName()
1256 cerr << " HasMultipleAccessingFunctions = "
1257 << GS.HasMultipleAccessingFunctions << "\n";
1258 cerr << " HasNonInstructionUser = " << GS.HasNonInstructionUser<<"\n";
1259 cerr << " isNotSuitableForSRA = " << GS.isNotSuitableForSRA << "\n";
1263 // If this is a first class global and has only one accessing function
1264 // and this function is main (which we know is not recursive we can make
1265 // this global a local variable) we replace the global with a local alloca
1266 // in this function.
1268 // NOTE: It doesn't make sense to promote non first class types since we
1269 // are just replacing static memory to stack memory.
1270 if (!GS.HasMultipleAccessingFunctions &&
1271 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1272 GV->getType()->getElementType()->isFirstClassType() &&
1273 GS.AccessingFunction->getName() == "main" &&
1274 GS.AccessingFunction->hasExternalLinkage()) {
1275 DOUT << "LOCALIZING GLOBAL: " << *GV;
1276 Instruction* FirstI = GS.AccessingFunction->getEntryBlock().begin();
1277 const Type* ElemTy = GV->getType()->getElementType();
1278 // FIXME: Pass Global's alignment when globals have alignment
1279 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), FirstI);
1280 if (!isa<UndefValue>(GV->getInitializer()))
1281 new StoreInst(GV->getInitializer(), Alloca, FirstI);
1283 GV->replaceAllUsesWith(Alloca);
1284 GV->eraseFromParent();
1289 // If the global is never loaded (but may be stored to), it is dead.
1292 DOUT << "GLOBAL NEVER LOADED: " << *GV;
1294 // Delete any stores we can find to the global. We may not be able to
1295 // make it completely dead though.
1296 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
1298 // If the global is dead now, delete it.
1299 if (GV->use_empty()) {
1300 GV->eraseFromParent();
1306 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1307 DOUT << "MARKING CONSTANT: " << *GV;
1308 GV->setConstant(true);
1310 // Clean up any obviously simplifiable users now.
1311 CleanupConstantGlobalUsers(GV, GV->getInitializer());
1313 // If the global is dead now, just nuke it.
1314 if (GV->use_empty()) {
1315 DOUT << " *** Marking constant allowed us to simplify "
1316 << "all users and delete global!\n";
1317 GV->eraseFromParent();
1323 } else if (!GS.isNotSuitableForSRA &&
1324 !GV->getInitializer()->getType()->isFirstClassType()) {
1325 if (GlobalVariable *FirstNewGV = SRAGlobal(GV)) {
1326 GVI = FirstNewGV; // Don't skip the newly produced globals!
1329 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
1330 // If the initial value for the global was an undef value, and if only
1331 // one other value was stored into it, we can just change the
1332 // initializer to be an undef value, then delete all stores to the
1333 // global. This allows us to mark it constant.
1334 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1335 if (isa<UndefValue>(GV->getInitializer())) {
1336 // Change the initial value here.
1337 GV->setInitializer(SOVConstant);
1339 // Clean up any obviously simplifiable users now.
1340 CleanupConstantGlobalUsers(GV, GV->getInitializer());
1342 if (GV->use_empty()) {
1343 DOUT << " *** Substituting initializer allowed us to "
1344 << "simplify all users and delete global!\n";
1345 GV->eraseFromParent();
1354 // Try to optimize globals based on the knowledge that only one value
1355 // (besides its initializer) is ever stored to the global.
1356 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1357 getAnalysis<TargetData>()))
1360 // Otherwise, if the global was not a boolean, we can shrink it to be a
1362 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1363 if (GV->getType()->getElementType() != Type::Int1Ty &&
1364 !GV->getType()->getElementType()->isFloatingPoint() &&
1365 !isa<VectorType>(GV->getType()->getElementType()) &&
1366 !GS.HasPHIUser && !GS.isNotSuitableForSRA) {
1367 DOUT << " *** SHRINKING TO BOOL: " << *GV;
1368 ShrinkGlobalToBoolean(GV, SOVConstant);
1377 /// OnlyCalledDirectly - Return true if the specified function is only called
1378 /// directly. In other words, its address is never taken.
1379 static bool OnlyCalledDirectly(Function *F) {
1380 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1381 Instruction *User = dyn_cast<Instruction>(*UI);
1382 if (!User) return false;
1383 if (!isa<CallInst>(User) && !isa<InvokeInst>(User)) return false;
1385 // See if the function address is passed as an argument.
1386 for (unsigned i = 1, e = User->getNumOperands(); i != e; ++i)
1387 if (User->getOperand(i) == F) return false;
1392 /// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1393 /// function, changing them to FastCC.
1394 static void ChangeCalleesToFastCall(Function *F) {
1395 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1396 Instruction *User = cast<Instruction>(*UI);
1397 if (CallInst *CI = dyn_cast<CallInst>(User))
1398 CI->setCallingConv(CallingConv::Fast);
1400 cast<InvokeInst>(User)->setCallingConv(CallingConv::Fast);
1404 bool GlobalOpt::OptimizeFunctions(Module &M) {
1405 bool Changed = false;
1406 // Optimize functions.
1407 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1409 F->removeDeadConstantUsers();
1410 if (F->use_empty() && (F->hasInternalLinkage() ||
1411 F->hasLinkOnceLinkage())) {
1412 M.getFunctionList().erase(F);
1415 } else if (F->hasInternalLinkage() &&
1416 F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
1417 OnlyCalledDirectly(F)) {
1418 // If this function has C calling conventions, is not a varargs
1419 // function, and is only called directly, promote it to use the Fast
1420 // calling convention.
1421 F->setCallingConv(CallingConv::Fast);
1422 ChangeCalleesToFastCall(F);
1430 bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1431 bool Changed = false;
1432 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1434 GlobalVariable *GV = GVI++;
1435 if (!GV->isConstant() && GV->hasInternalLinkage() &&
1436 GV->hasInitializer())
1437 Changed |= ProcessInternalGlobal(GV, GVI);
1442 /// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1443 /// initializers have an init priority of 65535.
1444 GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
1445 for (Module::global_iterator I = M.global_begin(), E = M.global_end();
1447 if (I->getName() == "llvm.global_ctors") {
1448 // Found it, verify it's an array of { int, void()* }.
1449 const ArrayType *ATy =dyn_cast<ArrayType>(I->getType()->getElementType());
1451 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1452 if (!STy || STy->getNumElements() != 2 ||
1453 STy->getElementType(0) != Type::Int32Ty) return 0;
1454 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1455 if (!PFTy) return 0;
1456 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
1457 if (!FTy || FTy->getReturnType() != Type::VoidTy || FTy->isVarArg() ||
1458 FTy->getNumParams() != 0)
1461 // Verify that the initializer is simple enough for us to handle.
1462 if (!I->hasInitializer()) return 0;
1463 ConstantArray *CA = dyn_cast<ConstantArray>(I->getInitializer());
1465 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1466 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(CA->getOperand(i))) {
1467 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1470 // Must have a function or null ptr.
1471 if (!isa<Function>(CS->getOperand(1)))
1474 // Init priority must be standard.
1475 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
1476 if (!CI || CI->getZExtValue() != 65535)
1487 /// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1488 /// return a list of the functions and null terminator as a vector.
1489 static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1490 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1491 std::vector<Function*> Result;
1492 Result.reserve(CA->getNumOperands());
1493 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i) {
1494 ConstantStruct *CS = cast<ConstantStruct>(CA->getOperand(i));
1495 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
1500 /// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
1501 /// specified array, returning the new global to use.
1502 static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
1503 const std::vector<Function*> &Ctors) {
1504 // If we made a change, reassemble the initializer list.
1505 std::vector<Constant*> CSVals;
1506 CSVals.push_back(ConstantInt::get(Type::Int32Ty, 65535));
1507 CSVals.push_back(0);
1509 // Create the new init list.
1510 std::vector<Constant*> CAList;
1511 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
1513 CSVals[1] = Ctors[i];
1515 const Type *FTy = FunctionType::get(Type::VoidTy,
1516 std::vector<const Type*>(), false);
1517 const PointerType *PFTy = PointerType::get(FTy);
1518 CSVals[1] = Constant::getNullValue(PFTy);
1519 CSVals[0] = ConstantInt::get(Type::Int32Ty, 2147483647);
1521 CAList.push_back(ConstantStruct::get(CSVals));
1524 // Create the array initializer.
1525 const Type *StructTy =
1526 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
1527 Constant *CA = ConstantArray::get(ArrayType::get(StructTy, CAList.size()),
1530 // If we didn't change the number of elements, don't create a new GV.
1531 if (CA->getType() == GCL->getInitializer()->getType()) {
1532 GCL->setInitializer(CA);
1536 // Create the new global and insert it next to the existing list.
1537 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
1538 GCL->getLinkage(), CA, "",
1540 GCL->isThreadLocal());
1541 GCL->getParent()->getGlobalList().insert(GCL, NGV);
1544 // Nuke the old list, replacing any uses with the new one.
1545 if (!GCL->use_empty()) {
1547 if (V->getType() != GCL->getType())
1548 V = ConstantExpr::getBitCast(V, GCL->getType());
1549 GCL->replaceAllUsesWith(V);
1551 GCL->eraseFromParent();
1560 static Constant *getVal(std::map<Value*, Constant*> &ComputedValues,
1562 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
1563 Constant *R = ComputedValues[V];
1564 assert(R && "Reference to an uncomputed value!");
1568 /// isSimpleEnoughPointerToCommit - Return true if this constant is simple
1569 /// enough for us to understand. In particular, if it is a cast of something,
1570 /// we punt. We basically just support direct accesses to globals and GEP's of
1571 /// globals. This should be kept up to date with CommitValueTo.
1572 static bool isSimpleEnoughPointerToCommit(Constant *C) {
1573 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) {
1574 if (!GV->hasExternalLinkage() && !GV->hasInternalLinkage())
1575 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
1576 return !GV->isDeclaration(); // reject external globals.
1578 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
1579 // Handle a constantexpr gep.
1580 if (CE->getOpcode() == Instruction::GetElementPtr &&
1581 isa<GlobalVariable>(CE->getOperand(0))) {
1582 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1583 if (!GV->hasExternalLinkage() && !GV->hasInternalLinkage())
1584 return false; // do not allow weak/linkonce/dllimport/dllexport linkage.
1585 return GV->hasInitializer() &&
1586 ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
1591 /// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
1592 /// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
1593 /// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
1594 static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
1595 ConstantExpr *Addr, unsigned OpNo) {
1596 // Base case of the recursion.
1597 if (OpNo == Addr->getNumOperands()) {
1598 assert(Val->getType() == Init->getType() && "Type mismatch!");
1602 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1603 std::vector<Constant*> Elts;
1605 // Break up the constant into its elements.
1606 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1607 for (unsigned i = 0, e = CS->getNumOperands(); i != e; ++i)
1608 Elts.push_back(CS->getOperand(i));
1609 } else if (isa<ConstantAggregateZero>(Init)) {
1610 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1611 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
1612 } else if (isa<UndefValue>(Init)) {
1613 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
1614 Elts.push_back(UndefValue::get(STy->getElementType(i)));
1616 assert(0 && "This code is out of sync with "
1617 " ConstantFoldLoadThroughGEPConstantExpr");
1620 // Replace the element that we are supposed to.
1621 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
1622 unsigned Idx = CU->getZExtValue();
1623 assert(Idx < STy->getNumElements() && "Struct index out of range!");
1624 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
1626 // Return the modified struct.
1627 return ConstantStruct::get(Elts);
1629 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
1630 const ArrayType *ATy = cast<ArrayType>(Init->getType());
1632 // Break up the array into elements.
1633 std::vector<Constant*> Elts;
1634 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1635 for (unsigned i = 0, e = CA->getNumOperands(); i != e; ++i)
1636 Elts.push_back(CA->getOperand(i));
1637 } else if (isa<ConstantAggregateZero>(Init)) {
1638 Constant *Elt = Constant::getNullValue(ATy->getElementType());
1639 Elts.assign(ATy->getNumElements(), Elt);
1640 } else if (isa<UndefValue>(Init)) {
1641 Constant *Elt = UndefValue::get(ATy->getElementType());
1642 Elts.assign(ATy->getNumElements(), Elt);
1644 assert(0 && "This code is out of sync with "
1645 " ConstantFoldLoadThroughGEPConstantExpr");
1648 assert(CI->getZExtValue() < ATy->getNumElements());
1649 Elts[CI->getZExtValue()] =
1650 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
1651 return ConstantArray::get(ATy, Elts);
1655 /// CommitValueTo - We have decided that Addr (which satisfies the predicate
1656 /// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
1657 static void CommitValueTo(Constant *Val, Constant *Addr) {
1658 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
1659 assert(GV->hasInitializer());
1660 GV->setInitializer(Val);
1664 ConstantExpr *CE = cast<ConstantExpr>(Addr);
1665 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1667 Constant *Init = GV->getInitializer();
1668 Init = EvaluateStoreInto(Init, Val, CE, 2);
1669 GV->setInitializer(Init);
1672 /// ComputeLoadResult - Return the value that would be computed by a load from
1673 /// P after the stores reflected by 'memory' have been performed. If we can't
1674 /// decide, return null.
1675 static Constant *ComputeLoadResult(Constant *P,
1676 const std::map<Constant*, Constant*> &Memory) {
1677 // If this memory location has been recently stored, use the stored value: it
1678 // is the most up-to-date.
1679 std::map<Constant*, Constant*>::const_iterator I = Memory.find(P);
1680 if (I != Memory.end()) return I->second;
1683 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
1684 if (GV->hasInitializer())
1685 return GV->getInitializer();
1689 // Handle a constantexpr getelementptr.
1690 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
1691 if (CE->getOpcode() == Instruction::GetElementPtr &&
1692 isa<GlobalVariable>(CE->getOperand(0))) {
1693 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
1694 if (GV->hasInitializer())
1695 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
1698 return 0; // don't know how to evaluate.
1701 /// EvaluateFunction - Evaluate a call to function F, returning true if
1702 /// successful, false if we can't evaluate it. ActualArgs contains the formal
1703 /// arguments for the function.
1704 static bool EvaluateFunction(Function *F, Constant *&RetVal,
1705 const std::vector<Constant*> &ActualArgs,
1706 std::vector<Function*> &CallStack,
1707 std::map<Constant*, Constant*> &MutatedMemory,
1708 std::vector<GlobalVariable*> &AllocaTmps) {
1709 // Check to see if this function is already executing (recursion). If so,
1710 // bail out. TODO: we might want to accept limited recursion.
1711 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
1714 CallStack.push_back(F);
1716 /// Values - As we compute SSA register values, we store their contents here.
1717 std::map<Value*, Constant*> Values;
1719 // Initialize arguments to the incoming values specified.
1721 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
1723 Values[AI] = ActualArgs[ArgNo];
1725 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
1726 /// we can only evaluate any one basic block at most once. This set keeps
1727 /// track of what we have executed so we can detect recursive cases etc.
1728 std::set<BasicBlock*> ExecutedBlocks;
1730 // CurInst - The current instruction we're evaluating.
1731 BasicBlock::iterator CurInst = F->begin()->begin();
1733 // This is the main evaluation loop.
1735 Constant *InstResult = 0;
1737 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
1738 if (SI->isVolatile()) return false; // no volatile accesses.
1739 Constant *Ptr = getVal(Values, SI->getOperand(1));
1740 if (!isSimpleEnoughPointerToCommit(Ptr))
1741 // If this is too complex for us to commit, reject it.
1743 Constant *Val = getVal(Values, SI->getOperand(0));
1744 MutatedMemory[Ptr] = Val;
1745 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
1746 InstResult = ConstantExpr::get(BO->getOpcode(),
1747 getVal(Values, BO->getOperand(0)),
1748 getVal(Values, BO->getOperand(1)));
1749 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
1750 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
1751 getVal(Values, CI->getOperand(0)),
1752 getVal(Values, CI->getOperand(1)));
1753 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
1754 InstResult = ConstantExpr::getCast(CI->getOpcode(),
1755 getVal(Values, CI->getOperand(0)),
1757 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
1758 InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
1759 getVal(Values, SI->getOperand(1)),
1760 getVal(Values, SI->getOperand(2)));
1761 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
1762 Constant *P = getVal(Values, GEP->getOperand(0));
1763 SmallVector<Constant*, 8> GEPOps;
1764 for (unsigned i = 1, e = GEP->getNumOperands(); i != e; ++i)
1765 GEPOps.push_back(getVal(Values, GEP->getOperand(i)));
1766 InstResult = ConstantExpr::getGetElementPtr(P, &GEPOps[0], GEPOps.size());
1767 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
1768 if (LI->isVolatile()) return false; // no volatile accesses.
1769 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
1771 if (InstResult == 0) return false; // Could not evaluate load.
1772 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
1773 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
1774 const Type *Ty = AI->getType()->getElementType();
1775 AllocaTmps.push_back(new GlobalVariable(Ty, false,
1776 GlobalValue::InternalLinkage,
1777 UndefValue::get(Ty),
1779 InstResult = AllocaTmps.back();
1780 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
1781 // Cannot handle inline asm.
1782 if (isa<InlineAsm>(CI->getOperand(0))) return false;
1784 // Resolve function pointers.
1785 Function *Callee = dyn_cast<Function>(getVal(Values, CI->getOperand(0)));
1786 if (!Callee) return false; // Cannot resolve.
1788 std::vector<Constant*> Formals;
1789 for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)
1790 Formals.push_back(getVal(Values, CI->getOperand(i)));
1792 if (Callee->isDeclaration()) {
1793 // If this is a function we can constant fold, do it.
1794 if (Constant *C = ConstantFoldCall(Callee, &Formals[0],
1801 if (Callee->getFunctionType()->isVarArg())
1806 // Execute the call, if successful, use the return value.
1807 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
1808 MutatedMemory, AllocaTmps))
1810 InstResult = RetVal;
1812 } else if (isa<TerminatorInst>(CurInst)) {
1813 BasicBlock *NewBB = 0;
1814 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
1815 if (BI->isUnconditional()) {
1816 NewBB = BI->getSuccessor(0);
1819 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
1820 if (!Cond) return false; // Cannot determine.
1822 NewBB = BI->getSuccessor(!Cond->getZExtValue());
1824 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
1826 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
1827 if (!Val) return false; // Cannot determine.
1828 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
1829 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
1830 if (RI->getNumOperands())
1831 RetVal = getVal(Values, RI->getOperand(0));
1833 CallStack.pop_back(); // return from fn.
1834 return true; // We succeeded at evaluating this ctor!
1836 // invoke, unwind, unreachable.
1837 return false; // Cannot handle this terminator.
1840 // Okay, we succeeded in evaluating this control flow. See if we have
1841 // executed the new block before. If so, we have a looping function,
1842 // which we cannot evaluate in reasonable time.
1843 if (!ExecutedBlocks.insert(NewBB).second)
1844 return false; // looped!
1846 // Okay, we have never been in this block before. Check to see if there
1847 // are any PHI nodes. If so, evaluate them with information about where
1849 BasicBlock *OldBB = CurInst->getParent();
1850 CurInst = NewBB->begin();
1852 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
1853 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
1855 // Do NOT increment CurInst. We know that the terminator had no value.
1858 // Did not know how to evaluate this!
1862 if (!CurInst->use_empty())
1863 Values[CurInst] = InstResult;
1865 // Advance program counter.
1870 /// EvaluateStaticConstructor - Evaluate static constructors in the function, if
1871 /// we can. Return true if we can, false otherwise.
1872 static bool EvaluateStaticConstructor(Function *F) {
1873 /// MutatedMemory - For each store we execute, we update this map. Loads
1874 /// check this to get the most up-to-date value. If evaluation is successful,
1875 /// this state is committed to the process.
1876 std::map<Constant*, Constant*> MutatedMemory;
1878 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
1879 /// to represent its body. This vector is needed so we can delete the
1880 /// temporary globals when we are done.
1881 std::vector<GlobalVariable*> AllocaTmps;
1883 /// CallStack - This is used to detect recursion. In pathological situations
1884 /// we could hit exponential behavior, but at least there is nothing
1886 std::vector<Function*> CallStack;
1888 // Call the function.
1889 Constant *RetValDummy;
1890 bool EvalSuccess = EvaluateFunction(F, RetValDummy, std::vector<Constant*>(),
1891 CallStack, MutatedMemory, AllocaTmps);
1893 // We succeeded at evaluation: commit the result.
1894 DOUT << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
1895 << F->getName() << "' to " << MutatedMemory.size()
1897 for (std::map<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
1898 E = MutatedMemory.end(); I != E; ++I)
1899 CommitValueTo(I->second, I->first);
1902 // At this point, we are done interpreting. If we created any 'alloca'
1903 // temporaries, release them now.
1904 while (!AllocaTmps.empty()) {
1905 GlobalVariable *Tmp = AllocaTmps.back();
1906 AllocaTmps.pop_back();
1908 // If there are still users of the alloca, the program is doing something
1909 // silly, e.g. storing the address of the alloca somewhere and using it
1910 // later. Since this is undefined, we'll just make it be null.
1911 if (!Tmp->use_empty())
1912 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
1921 /// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
1922 /// Return true if anything changed.
1923 bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
1924 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
1925 bool MadeChange = false;
1926 if (Ctors.empty()) return false;
1928 // Loop over global ctors, optimizing them when we can.
1929 for (unsigned i = 0; i != Ctors.size(); ++i) {
1930 Function *F = Ctors[i];
1931 // Found a null terminator in the middle of the list, prune off the rest of
1934 if (i != Ctors.size()-1) {
1941 // We cannot simplify external ctor functions.
1942 if (F->empty()) continue;
1944 // If we can evaluate the ctor at compile time, do.
1945 if (EvaluateStaticConstructor(F)) {
1946 Ctors.erase(Ctors.begin()+i);
1949 ++NumCtorsEvaluated;
1954 if (!MadeChange) return false;
1956 GCL = InstallGlobalCtors(GCL, Ctors);
1961 bool GlobalOpt::runOnModule(Module &M) {
1962 bool Changed = false;
1964 // Try to find the llvm.globalctors list.
1965 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
1967 bool LocalChange = true;
1968 while (LocalChange) {
1969 LocalChange = false;
1971 // Delete functions that are trivially dead, ccc -> fastcc
1972 LocalChange |= OptimizeFunctions(M);
1974 // Optimize global_ctors list.
1976 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
1978 // Optimize non-address-taken globals.
1979 LocalChange |= OptimizeGlobalVars(M);
1980 Changed |= LocalChange;
1983 // TODO: Move all global ctors functions to the end of the module for code