1 //===- GlobalOpt.cpp - Optimize Global Variables --------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This pass transforms simple global variables that never have their address
11 // taken. If obviously true, it marks read/write globals as constant, deletes
12 // variables only stored to, etc.
14 //===----------------------------------------------------------------------===//
16 #define DEBUG_TYPE "globalopt"
17 #include "llvm/Transforms/IPO.h"
18 #include "llvm/CallingConv.h"
19 #include "llvm/Constants.h"
20 #include "llvm/DerivedTypes.h"
21 #include "llvm/Instructions.h"
22 #include "llvm/IntrinsicInst.h"
23 #include "llvm/Module.h"
24 #include "llvm/Pass.h"
25 #include "llvm/Analysis/ConstantFolding.h"
26 #include "llvm/Analysis/MemoryBuiltins.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Support/CallSite.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/GetElementPtrTypeIterator.h"
32 #include "llvm/Support/MathExtras.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/ADT/DenseMap.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/SmallVector.h"
37 #include "llvm/ADT/Statistic.h"
38 #include "llvm/ADT/STLExtras.h"
42 STATISTIC(NumMarked , "Number of globals marked constant");
43 STATISTIC(NumUnnamed , "Number of globals marked unnamed_addr");
44 STATISTIC(NumSRA , "Number of aggregate globals broken into scalars");
45 STATISTIC(NumHeapSRA , "Number of heap objects SRA'd");
46 STATISTIC(NumSubstitute,"Number of globals with initializers stored into them");
47 STATISTIC(NumDeleted , "Number of globals deleted");
48 STATISTIC(NumFnDeleted , "Number of functions deleted");
49 STATISTIC(NumGlobUses , "Number of global uses devirtualized");
50 STATISTIC(NumLocalized , "Number of globals localized");
51 STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans");
52 STATISTIC(NumFastCallFns , "Number of functions converted to fastcc");
53 STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated");
54 STATISTIC(NumNestRemoved , "Number of nest attributes removed");
55 STATISTIC(NumAliasesResolved, "Number of global aliases resolved");
56 STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated");
60 struct GlobalOpt : public ModulePass {
61 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
63 static char ID; // Pass identification, replacement for typeid
64 GlobalOpt() : ModulePass(ID) {
65 initializeGlobalOptPass(*PassRegistry::getPassRegistry());
68 bool runOnModule(Module &M);
71 GlobalVariable *FindGlobalCtors(Module &M);
72 bool OptimizeFunctions(Module &M);
73 bool OptimizeGlobalVars(Module &M);
74 bool OptimizeGlobalAliases(Module &M);
75 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL);
76 bool ProcessGlobal(GlobalVariable *GV,Module::global_iterator &GVI);
77 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI,
78 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
79 const GlobalStatus &GS);
83 char GlobalOpt::ID = 0;
84 INITIALIZE_PASS(GlobalOpt, "globalopt",
85 "Global Variable Optimizer", false, false)
87 ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); }
91 /// GlobalStatus - As we analyze each global, keep track of some information
92 /// about it. If we find out that the address of the global is taken, none of
93 /// this info will be accurate.
95 /// isCompared - True if the global's address is used in a comparison.
98 /// isLoaded - True if the global is ever loaded. If the global isn't ever
99 /// loaded it can be deleted.
102 /// StoredType - Keep track of what stores to the global look like.
105 /// NotStored - There is no store to this global. It can thus be marked
109 /// isInitializerStored - This global is stored to, but the only thing
110 /// stored is the constant it was initialized with. This is only tracked
111 /// for scalar globals.
114 /// isStoredOnce - This global is stored to, but only its initializer and
115 /// one other value is ever stored to it. If this global isStoredOnce, we
116 /// track the value stored to it in StoredOnceValue below. This is only
117 /// tracked for scalar globals.
120 /// isStored - This global is stored to by multiple values or something else
121 /// that we cannot track.
125 /// StoredOnceValue - If only one value (besides the initializer constant) is
126 /// ever stored to this global, keep track of what value it is.
127 Value *StoredOnceValue;
129 /// AccessingFunction/HasMultipleAccessingFunctions - These start out
130 /// null/false. When the first accessing function is noticed, it is recorded.
131 /// When a second different accessing function is noticed,
132 /// HasMultipleAccessingFunctions is set to true.
133 const Function *AccessingFunction;
134 bool HasMultipleAccessingFunctions;
136 /// HasNonInstructionUser - Set to true if this global has a user that is not
137 /// an instruction (e.g. a constant expr or GV initializer).
138 bool HasNonInstructionUser;
140 /// HasPHIUser - Set to true if this global has a user that is a PHI node.
143 GlobalStatus() : isCompared(false), isLoaded(false), StoredType(NotStored),
144 StoredOnceValue(0), AccessingFunction(0),
145 HasMultipleAccessingFunctions(false), HasNonInstructionUser(false),
151 // SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
152 // by constants itself. Note that constants cannot be cyclic, so this test is
153 // pretty easy to implement recursively.
155 static bool SafeToDestroyConstant(const Constant *C) {
156 if (isa<GlobalValue>(C)) return false;
158 for (Value::const_use_iterator UI = C->use_begin(), E = C->use_end(); UI != E;
160 if (const Constant *CU = dyn_cast<Constant>(*UI)) {
161 if (!SafeToDestroyConstant(CU)) return false;
168 /// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus
169 /// structure. If the global has its address taken, return true to indicate we
170 /// can't do anything with it.
172 static bool AnalyzeGlobal(const Value *V, GlobalStatus &GS,
173 SmallPtrSet<const PHINode*, 16> &PHIUsers) {
174 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
177 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) {
178 GS.HasNonInstructionUser = true;
180 // If the result of the constantexpr isn't pointer type, then we won't
181 // know to expect it in various places. Just reject early.
182 if (!isa<PointerType>(CE->getType())) return true;
184 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true;
185 } else if (const Instruction *I = dyn_cast<Instruction>(U)) {
186 if (!GS.HasMultipleAccessingFunctions) {
187 const Function *F = I->getParent()->getParent();
188 if (GS.AccessingFunction == 0)
189 GS.AccessingFunction = F;
190 else if (GS.AccessingFunction != F)
191 GS.HasMultipleAccessingFunctions = true;
193 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) {
195 if (LI->isVolatile()) return true; // Don't hack on volatile loads.
196 } else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) {
197 // Don't allow a store OF the address, only stores TO the address.
198 if (SI->getOperand(0) == V) return true;
200 if (SI->isVolatile()) return true; // Don't hack on volatile stores.
202 // If this is a direct store to the global (i.e., the global is a scalar
203 // value, not an aggregate), keep more specific information about
205 if (GS.StoredType != GlobalStatus::isStored) {
206 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>(
207 SI->getOperand(1))) {
208 Value *StoredVal = SI->getOperand(0);
209 if (StoredVal == GV->getInitializer()) {
210 if (GS.StoredType < GlobalStatus::isInitializerStored)
211 GS.StoredType = GlobalStatus::isInitializerStored;
212 } else if (isa<LoadInst>(StoredVal) &&
213 cast<LoadInst>(StoredVal)->getOperand(0) == GV) {
214 if (GS.StoredType < GlobalStatus::isInitializerStored)
215 GS.StoredType = GlobalStatus::isInitializerStored;
216 } else if (GS.StoredType < GlobalStatus::isStoredOnce) {
217 GS.StoredType = GlobalStatus::isStoredOnce;
218 GS.StoredOnceValue = StoredVal;
219 } else if (GS.StoredType == GlobalStatus::isStoredOnce &&
220 GS.StoredOnceValue == StoredVal) {
223 GS.StoredType = GlobalStatus::isStored;
226 GS.StoredType = GlobalStatus::isStored;
229 } else if (isa<GetElementPtrInst>(I)) {
230 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
231 } else if (isa<SelectInst>(I)) {
232 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
233 } else if (const PHINode *PN = dyn_cast<PHINode>(I)) {
234 // PHI nodes we can check just like select or GEP instructions, but we
235 // have to be careful about infinite recursion.
236 if (PHIUsers.insert(PN)) // Not already visited.
237 if (AnalyzeGlobal(I, GS, PHIUsers)) return true;
238 GS.HasPHIUser = true;
239 } else if (isa<CmpInst>(I)) {
240 GS.isCompared = true;
241 } else if (isa<MemTransferInst>(I)) {
242 const MemTransferInst *MTI = cast<MemTransferInst>(I);
243 if (MTI->getArgOperand(0) == V)
244 GS.StoredType = GlobalStatus::isStored;
245 if (MTI->getArgOperand(1) == V)
247 } else if (isa<MemSetInst>(I)) {
248 assert(cast<MemSetInst>(I)->getArgOperand(0) == V &&
249 "Memset only takes one pointer!");
250 GS.StoredType = GlobalStatus::isStored;
252 return true; // Any other non-load instruction might take address!
254 } else if (const Constant *C = dyn_cast<Constant>(U)) {
255 GS.HasNonInstructionUser = true;
256 // We might have a dead and dangling constant hanging off of here.
257 if (!SafeToDestroyConstant(C))
260 GS.HasNonInstructionUser = true;
261 // Otherwise must be some other user.
269 static Constant *getAggregateConstantElement(Constant *Agg, Constant *Idx) {
270 ConstantInt *CI = dyn_cast<ConstantInt>(Idx);
272 unsigned IdxV = CI->getZExtValue();
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 (ConstantVector *CP = dyn_cast<ConstantVector>(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::BitCast &&
328 CE->getType()->isPointerTy()) {
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 // Do not transform "gepinst (gep constexpr (GV))" here, because forming
339 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold
340 // and will invalidate our notion of what Init is.
341 Constant *SubInit = 0;
342 if (!isa<ConstantExpr>(GEP->getOperand(0))) {
344 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP));
345 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr)
346 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE);
348 Changed |= CleanupConstantGlobalUsers(GEP, SubInit);
350 if (GEP->use_empty()) {
351 GEP->eraseFromParent();
354 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv
355 if (MI->getRawDest() == V) {
356 MI->eraseFromParent();
360 } else if (Constant *C = dyn_cast<Constant>(U)) {
361 // If we have a chain of dead constantexprs or other things dangling from
362 // us, and if they are all dead, nuke them without remorse.
363 if (SafeToDestroyConstant(C)) {
364 C->destroyConstant();
365 // This could have invalidated UI, start over from scratch.
366 CleanupConstantGlobalUsers(V, Init);
374 /// isSafeSROAElementUse - Return true if the specified instruction is a safe
375 /// user of a derived expression from a global that we want to SROA.
376 static bool isSafeSROAElementUse(Value *V) {
377 // We might have a dead and dangling constant hanging off of here.
378 if (Constant *C = dyn_cast<Constant>(V))
379 return SafeToDestroyConstant(C);
381 Instruction *I = dyn_cast<Instruction>(V);
382 if (!I) return false;
385 if (isa<LoadInst>(I)) return true;
387 // Stores *to* the pointer are ok.
388 if (StoreInst *SI = dyn_cast<StoreInst>(I))
389 return SI->getOperand(0) != V;
391 // Otherwise, it must be a GEP.
392 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I);
393 if (GEPI == 0) return false;
395 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) ||
396 !cast<Constant>(GEPI->getOperand(1))->isNullValue())
399 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end();
401 if (!isSafeSROAElementUse(*I))
407 /// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value.
408 /// Look at it and its uses and decide whether it is safe to SROA this global.
410 static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) {
411 // The user of the global must be a GEP Inst or a ConstantExpr GEP.
412 if (!isa<GetElementPtrInst>(U) &&
413 (!isa<ConstantExpr>(U) ||
414 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr))
417 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we
418 // don't like < 3 operand CE's, and we don't like non-constant integer
419 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some
421 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) ||
422 !cast<Constant>(U->getOperand(1))->isNullValue() ||
423 !isa<ConstantInt>(U->getOperand(2)))
426 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U);
427 ++GEPI; // Skip over the pointer index.
429 // If this is a use of an array allocation, do a bit more checking for sanity.
430 if (const ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) {
431 uint64_t NumElements = AT->getNumElements();
432 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2));
434 // Check to make sure that index falls within the array. If not,
435 // something funny is going on, so we won't do the optimization.
437 if (Idx->getZExtValue() >= NumElements)
440 // We cannot scalar repl this level of the array unless any array
441 // sub-indices are in-range constants. In particular, consider:
442 // A[0][i]. We cannot know that the user isn't doing invalid things like
443 // allowing i to index an out-of-range subscript that accesses A[1].
445 // Scalar replacing *just* the outer index of the array is probably not
446 // going to be a win anyway, so just give up.
447 for (++GEPI; // Skip array index.
450 uint64_t NumElements;
451 if (const ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI))
452 NumElements = SubArrayTy->getNumElements();
453 else if (const VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI))
454 NumElements = SubVectorTy->getNumElements();
456 assert((*GEPI)->isStructTy() &&
457 "Indexed GEP type is not array, vector, or struct!");
461 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand());
462 if (!IdxVal || IdxVal->getZExtValue() >= NumElements)
467 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I)
468 if (!isSafeSROAElementUse(*I))
473 /// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it
474 /// is safe for us to perform this transformation.
476 static bool GlobalUsersSafeToSRA(GlobalValue *GV) {
477 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end();
479 if (!IsUserOfGlobalSafeForSRA(*UI, GV))
486 /// SRAGlobal - Perform scalar replacement of aggregates on the specified global
487 /// variable. This opens the door for other optimizations by exposing the
488 /// behavior of the program in a more fine-grained way. We have determined that
489 /// this transformation is safe already. We return the first global variable we
490 /// insert so that the caller can reprocess it.
491 static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD) {
492 // Make sure this global only has simple uses that we can SRA.
493 if (!GlobalUsersSafeToSRA(GV))
496 assert(GV->hasLocalLinkage() && !GV->isConstant());
497 Constant *Init = GV->getInitializer();
498 const Type *Ty = Init->getType();
500 std::vector<GlobalVariable*> NewGlobals;
501 Module::GlobalListType &Globals = GV->getParent()->getGlobalList();
503 // Get the alignment of the global, either explicit or target-specific.
504 unsigned StartAlignment = GV->getAlignment();
505 if (StartAlignment == 0)
506 StartAlignment = TD.getABITypeAlignment(GV->getType());
508 if (const StructType *STy = dyn_cast<StructType>(Ty)) {
509 NewGlobals.reserve(STy->getNumElements());
510 const StructLayout &Layout = *TD.getStructLayout(STy);
511 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
512 Constant *In = getAggregateConstantElement(Init,
513 ConstantInt::get(Type::getInt32Ty(STy->getContext()), i));
514 assert(In && "Couldn't get element of initializer?");
515 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false,
516 GlobalVariable::InternalLinkage,
517 In, GV->getName()+"."+Twine(i),
519 GV->getType()->getAddressSpace());
520 Globals.insert(GV, NGV);
521 NewGlobals.push_back(NGV);
523 // Calculate the known alignment of the field. If the original aggregate
524 // had 256 byte alignment for example, something might depend on that:
525 // propagate info to each field.
526 uint64_t FieldOffset = Layout.getElementOffset(i);
527 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset);
528 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i)))
529 NGV->setAlignment(NewAlign);
531 } else if (const SequentialType *STy = dyn_cast<SequentialType>(Ty)) {
532 unsigned NumElements = 0;
533 if (const ArrayType *ATy = dyn_cast<ArrayType>(STy))
534 NumElements = ATy->getNumElements();
536 NumElements = cast<VectorType>(STy)->getNumElements();
538 if (NumElements > 16 && GV->hasNUsesOrMore(16))
539 return 0; // It's not worth it.
540 NewGlobals.reserve(NumElements);
542 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType());
543 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType());
544 for (unsigned i = 0, e = NumElements; i != e; ++i) {
545 Constant *In = getAggregateConstantElement(Init,
546 ConstantInt::get(Type::getInt32Ty(Init->getContext()), i));
547 assert(In && "Couldn't get element of initializer?");
549 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false,
550 GlobalVariable::InternalLinkage,
551 In, GV->getName()+"."+Twine(i),
553 GV->getType()->getAddressSpace());
554 Globals.insert(GV, NGV);
555 NewGlobals.push_back(NGV);
557 // Calculate the known alignment of the field. If the original aggregate
558 // had 256 byte alignment for example, something might depend on that:
559 // propagate info to each field.
560 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i);
561 if (NewAlign > EltAlign)
562 NGV->setAlignment(NewAlign);
566 if (NewGlobals.empty())
569 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV);
571 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext()));
573 // Loop over all of the uses of the global, replacing the constantexpr geps,
574 // with smaller constantexpr geps or direct references.
575 while (!GV->use_empty()) {
576 User *GEP = GV->use_back();
577 assert(((isa<ConstantExpr>(GEP) &&
578 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)||
579 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!");
581 // Ignore the 1th operand, which has to be zero or else the program is quite
582 // broken (undefined). Get the 2nd operand, which is the structure or array
584 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue();
585 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access.
587 Value *NewPtr = NewGlobals[Val];
589 // Form a shorter GEP if needed.
590 if (GEP->getNumOperands() > 3) {
591 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) {
592 SmallVector<Constant*, 8> Idxs;
593 Idxs.push_back(NullInt);
594 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i)
595 Idxs.push_back(CE->getOperand(i));
596 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr),
597 &Idxs[0], Idxs.size());
599 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP);
600 SmallVector<Value*, 8> Idxs;
601 Idxs.push_back(NullInt);
602 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i)
603 Idxs.push_back(GEPI->getOperand(i));
604 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs.begin(), Idxs.end(),
605 GEPI->getName()+"."+Twine(Val),GEPI);
608 GEP->replaceAllUsesWith(NewPtr);
610 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP))
611 GEPI->eraseFromParent();
613 cast<ConstantExpr>(GEP)->destroyConstant();
616 // Delete the old global, now that it is dead.
620 // Loop over the new globals array deleting any globals that are obviously
621 // dead. This can arise due to scalarization of a structure or an array that
622 // has elements that are dead.
623 unsigned FirstGlobal = 0;
624 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i)
625 if (NewGlobals[i]->use_empty()) {
626 Globals.erase(NewGlobals[i]);
627 if (FirstGlobal == i) ++FirstGlobal;
630 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0;
633 /// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified
634 /// value will trap if the value is dynamically null. PHIs keeps track of any
635 /// phi nodes we've seen to avoid reprocessing them.
636 static bool AllUsesOfValueWillTrapIfNull(const Value *V,
637 SmallPtrSet<const PHINode*, 8> &PHIs) {
638 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
642 if (isa<LoadInst>(U)) {
644 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) {
645 if (SI->getOperand(0) == V) {
646 //cerr << "NONTRAPPING USE: " << *U;
647 return false; // Storing the value.
649 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) {
650 if (CI->getCalledValue() != V) {
651 //cerr << "NONTRAPPING USE: " << *U;
652 return false; // Not calling the ptr
654 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) {
655 if (II->getCalledValue() != V) {
656 //cerr << "NONTRAPPING USE: " << *U;
657 return false; // Not calling the ptr
659 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) {
660 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false;
661 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
662 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false;
663 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) {
664 // If we've already seen this phi node, ignore it, it has already been
666 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs))
668 } else if (isa<ICmpInst>(U) &&
669 isa<ConstantPointerNull>(UI->getOperand(1))) {
670 // Ignore icmp X, null
672 //cerr << "NONTRAPPING USE: " << *U;
679 /// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads
680 /// from GV will trap if the loaded value is null. Note that this also permits
681 /// comparisons of the loaded value against null, as a special case.
682 static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) {
683 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
687 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) {
688 SmallPtrSet<const PHINode*, 8> PHIs;
689 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs))
691 } else if (isa<StoreInst>(U)) {
692 // Ignore stores to the global.
694 // We don't know or understand this user, bail out.
695 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U;
702 static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) {
703 bool Changed = false;
704 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) {
705 Instruction *I = cast<Instruction>(*UI++);
706 if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
707 LI->setOperand(0, NewV);
709 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
710 if (SI->getOperand(1) == V) {
711 SI->setOperand(1, NewV);
714 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) {
716 if (CS.getCalledValue() == V) {
717 // Calling through the pointer! Turn into a direct call, but be careful
718 // that the pointer is not also being passed as an argument.
719 CS.setCalledFunction(NewV);
721 bool PassedAsArg = false;
722 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i)
723 if (CS.getArgument(i) == V) {
725 CS.setArgument(i, NewV);
729 // Being passed as an argument also. Be careful to not invalidate UI!
733 } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
734 Changed |= OptimizeAwayTrappingUsesOfValue(CI,
735 ConstantExpr::getCast(CI->getOpcode(),
736 NewV, CI->getType()));
737 if (CI->use_empty()) {
739 CI->eraseFromParent();
741 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
742 // Should handle GEP here.
743 SmallVector<Constant*, 8> Idxs;
744 Idxs.reserve(GEPI->getNumOperands()-1);
745 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end();
747 if (Constant *C = dyn_cast<Constant>(*i))
751 if (Idxs.size() == GEPI->getNumOperands()-1)
752 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI,
753 ConstantExpr::getGetElementPtr(NewV, &Idxs[0],
755 if (GEPI->use_empty()) {
757 GEPI->eraseFromParent();
766 /// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null
767 /// value stored into it. If there are uses of the loaded value that would trap
768 /// if the loaded value is dynamically null, then we know that they cannot be
769 /// reachable with a null optimize away the load.
770 static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV) {
771 bool Changed = false;
773 // Keep track of whether we are able to remove all the uses of the global
774 // other than the store that defines it.
775 bool AllNonStoreUsesGone = true;
777 // Replace all uses of loads with uses of uses of the stored value.
778 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){
779 User *GlobalUser = *GUI++;
780 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) {
781 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV);
782 // If we were able to delete all uses of the loads
783 if (LI->use_empty()) {
784 LI->eraseFromParent();
787 AllNonStoreUsesGone = false;
789 } else if (isa<StoreInst>(GlobalUser)) {
790 // Ignore the store that stores "LV" to the global.
791 assert(GlobalUser->getOperand(1) == GV &&
792 "Must be storing *to* the global");
794 AllNonStoreUsesGone = false;
796 // If we get here we could have other crazy uses that are transitively
798 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) ||
799 isa<ConstantExpr>(GlobalUser)) && "Only expect load and stores!");
804 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV);
808 // If we nuked all of the loads, then none of the stores are needed either,
809 // nor is the global.
810 if (AllNonStoreUsesGone) {
811 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n");
812 CleanupConstantGlobalUsers(GV, 0);
813 if (GV->use_empty()) {
814 GV->eraseFromParent();
822 /// ConstantPropUsersOf - Walk the use list of V, constant folding all of the
823 /// instructions that are foldable.
824 static void ConstantPropUsersOf(Value *V) {
825 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; )
826 if (Instruction *I = dyn_cast<Instruction>(*UI++))
827 if (Constant *NewC = ConstantFoldInstruction(I)) {
828 I->replaceAllUsesWith(NewC);
830 // Advance UI to the next non-I use to avoid invalidating it!
831 // Instructions could multiply use V.
832 while (UI != E && *UI == I)
834 I->eraseFromParent();
838 /// OptimizeGlobalAddressOfMalloc - This function takes the specified global
839 /// variable, and transforms the program as if it always contained the result of
840 /// the specified malloc. Because it is always the result of the specified
841 /// malloc, there is no reason to actually DO the malloc. Instead, turn the
842 /// malloc into a global, and any loads of GV as uses of the new global.
843 static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV,
846 ConstantInt *NElements,
848 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n');
850 const Type *GlobalType;
851 if (NElements->getZExtValue() == 1)
852 GlobalType = AllocTy;
854 // If we have an array allocation, the global variable is of an array.
855 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue());
857 // Create the new global variable. The contents of the malloc'd memory is
858 // undefined, so initialize with an undef value.
859 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(),
861 GlobalValue::InternalLinkage,
862 UndefValue::get(GlobalType),
863 GV->getName()+".body",
865 GV->isThreadLocal());
867 // If there are bitcast users of the malloc (which is typical, usually we have
868 // a malloc + bitcast) then replace them with uses of the new global. Update
869 // other users to use the global as well.
870 BitCastInst *TheBC = 0;
871 while (!CI->use_empty()) {
872 Instruction *User = cast<Instruction>(CI->use_back());
873 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) {
874 if (BCI->getType() == NewGV->getType()) {
875 BCI->replaceAllUsesWith(NewGV);
876 BCI->eraseFromParent();
878 BCI->setOperand(0, NewGV);
882 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI);
883 User->replaceUsesOfWith(CI, TheBC);
887 Constant *RepValue = NewGV;
888 if (NewGV->getType() != GV->getType()->getElementType())
889 RepValue = ConstantExpr::getBitCast(RepValue,
890 GV->getType()->getElementType());
892 // If there is a comparison against null, we will insert a global bool to
893 // keep track of whether the global was initialized yet or not.
894 GlobalVariable *InitBool =
895 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false,
896 GlobalValue::InternalLinkage,
897 ConstantInt::getFalse(GV->getContext()),
898 GV->getName()+".init", GV->isThreadLocal());
899 bool InitBoolUsed = false;
901 // Loop over all uses of GV, processing them in turn.
902 while (!GV->use_empty()) {
903 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) {
904 // The global is initialized when the store to it occurs.
905 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, SI);
906 SI->eraseFromParent();
910 LoadInst *LI = cast<LoadInst>(GV->use_back());
911 while (!LI->use_empty()) {
912 Use &LoadUse = LI->use_begin().getUse();
913 if (!isa<ICmpInst>(LoadUse.getUser())) {
918 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser());
919 // Replace the cmp X, 0 with a use of the bool value.
920 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", ICI);
922 switch (ICI->getPredicate()) {
923 default: llvm_unreachable("Unknown ICmp Predicate!");
924 case ICmpInst::ICMP_ULT:
925 case ICmpInst::ICMP_SLT: // X < null -> always false
926 LV = ConstantInt::getFalse(GV->getContext());
928 case ICmpInst::ICMP_ULE:
929 case ICmpInst::ICMP_SLE:
930 case ICmpInst::ICMP_EQ:
931 LV = BinaryOperator::CreateNot(LV, "notinit", ICI);
933 case ICmpInst::ICMP_NE:
934 case ICmpInst::ICMP_UGE:
935 case ICmpInst::ICMP_SGE:
936 case ICmpInst::ICMP_UGT:
937 case ICmpInst::ICMP_SGT:
940 ICI->replaceAllUsesWith(LV);
941 ICI->eraseFromParent();
943 LI->eraseFromParent();
946 // If the initialization boolean was used, insert it, otherwise delete it.
948 while (!InitBool->use_empty()) // Delete initializations
949 cast<StoreInst>(InitBool->use_back())->eraseFromParent();
952 GV->getParent()->getGlobalList().insert(GV, InitBool);
954 // Now the GV is dead, nuke it and the malloc..
955 GV->eraseFromParent();
956 CI->eraseFromParent();
958 // To further other optimizations, loop over all users of NewGV and try to
959 // constant prop them. This will promote GEP instructions with constant
960 // indices into GEP constant-exprs, which will allow global-opt to hack on it.
961 ConstantPropUsersOf(NewGV);
962 if (RepValue != NewGV)
963 ConstantPropUsersOf(RepValue);
968 /// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking
969 /// to make sure that there are no complex uses of V. We permit simple things
970 /// like dereferencing the pointer, but not storing through the address, unless
971 /// it is to the specified global.
972 static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V,
973 const GlobalVariable *GV,
974 SmallPtrSet<const PHINode*, 8> &PHIs) {
975 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end();
977 const Instruction *Inst = cast<Instruction>(*UI);
979 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) {
980 continue; // Fine, ignore.
983 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
984 if (SI->getOperand(0) == V && SI->getOperand(1) != GV)
985 return false; // Storing the pointer itself... bad.
986 continue; // Otherwise, storing through it, or storing into GV... fine.
989 // Must index into the array and into the struct.
990 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) {
991 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs))
996 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) {
997 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI
1000 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs))
1005 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) {
1006 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs))
1016 /// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV
1017 /// somewhere. Transform all uses of the allocation into loads from the
1018 /// global and uses of the resultant pointer. Further, delete the store into
1019 /// GV. This assumes that these value pass the
1020 /// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate.
1021 static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc,
1022 GlobalVariable *GV) {
1023 while (!Alloc->use_empty()) {
1024 Instruction *U = cast<Instruction>(*Alloc->use_begin());
1025 Instruction *InsertPt = U;
1026 if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
1027 // If this is the store of the allocation into the global, remove it.
1028 if (SI->getOperand(1) == GV) {
1029 SI->eraseFromParent();
1032 } else if (PHINode *PN = dyn_cast<PHINode>(U)) {
1033 // Insert the load in the corresponding predecessor, not right before the
1035 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator();
1036 } else if (isa<BitCastInst>(U)) {
1037 // Must be bitcast between the malloc and store to initialize the global.
1038 ReplaceUsesOfMallocWithGlobal(U, GV);
1039 U->eraseFromParent();
1041 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) {
1042 // If this is a "GEP bitcast" and the user is a store to the global, then
1043 // just process it as a bitcast.
1044 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse())
1045 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back()))
1046 if (SI->getOperand(1) == GV) {
1047 // Must be bitcast GEP between the malloc and store to initialize
1049 ReplaceUsesOfMallocWithGlobal(GEPI, GV);
1050 GEPI->eraseFromParent();
1055 // Insert a load from the global, and use it instead of the malloc.
1056 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt);
1057 U->replaceUsesOfWith(Alloc, NL);
1061 /// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi
1062 /// of a load) are simple enough to perform heap SRA on. This permits GEP's
1063 /// that index through the array and struct field, icmps of null, and PHIs.
1064 static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V,
1065 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs,
1066 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) {
1067 // We permit two users of the load: setcc comparing against the null
1068 // pointer, and a getelementptr of a specific form.
1069 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;
1071 const Instruction *User = cast<Instruction>(*UI);
1073 // Comparison against null is ok.
1074 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) {
1075 if (!isa<ConstantPointerNull>(ICI->getOperand(1)))
1080 // getelementptr is also ok, but only a simple form.
1081 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
1082 // Must index into the array and into the struct.
1083 if (GEPI->getNumOperands() < 3)
1086 // Otherwise the GEP is ok.
1090 if (const PHINode *PN = dyn_cast<PHINode>(User)) {
1091 if (!LoadUsingPHIsPerLoad.insert(PN))
1092 // This means some phi nodes are dependent on each other.
1093 // Avoid infinite looping!
1095 if (!LoadUsingPHIs.insert(PN))
1096 // If we have already analyzed this PHI, then it is safe.
1099 // Make sure all uses of the PHI are simple enough to transform.
1100 if (!LoadUsesSimpleEnoughForHeapSRA(PN,
1101 LoadUsingPHIs, LoadUsingPHIsPerLoad))
1107 // Otherwise we don't know what this is, not ok.
1115 /// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from
1116 /// GV are simple enough to perform HeapSRA, return true.
1117 static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV,
1118 Instruction *StoredVal) {
1119 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs;
1120 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad;
1121 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end();
1123 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) {
1124 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs,
1125 LoadUsingPHIsPerLoad))
1127 LoadUsingPHIsPerLoad.clear();
1130 // If we reach here, we know that all uses of the loads and transitive uses
1131 // (through PHI nodes) are simple enough to transform. However, we don't know
1132 // that all inputs the to the PHI nodes are in the same equivalence sets.
1133 // Check to verify that all operands of the PHIs are either PHIS that can be
1134 // transformed, loads from GV, or MI itself.
1135 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin()
1136 , E = LoadUsingPHIs.end(); I != E; ++I) {
1137 const PHINode *PN = *I;
1138 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) {
1139 Value *InVal = PN->getIncomingValue(op);
1141 // PHI of the stored value itself is ok.
1142 if (InVal == StoredVal) continue;
1144 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) {
1145 // One of the PHIs in our set is (optimistically) ok.
1146 if (LoadUsingPHIs.count(InPN))
1151 // Load from GV is ok.
1152 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal))
1153 if (LI->getOperand(0) == GV)
1158 // Anything else is rejected.
1166 static Value *GetHeapSROAValue(Value *V, unsigned FieldNo,
1167 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1168 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1169 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V];
1171 if (FieldNo >= FieldVals.size())
1172 FieldVals.resize(FieldNo+1);
1174 // If we already have this value, just reuse the previously scalarized
1176 if (Value *FieldVal = FieldVals[FieldNo])
1179 // Depending on what instruction this is, we have several cases.
1181 if (LoadInst *LI = dyn_cast<LoadInst>(V)) {
1182 // This is a scalarized version of the load from the global. Just create
1183 // a new Load of the scalarized global.
1184 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo,
1185 InsertedScalarizedValues,
1187 LI->getName()+".f"+Twine(FieldNo), LI);
1188 } else if (PHINode *PN = dyn_cast<PHINode>(V)) {
1189 // PN's type is pointer to struct. Make a new PHI of pointer to struct
1191 const StructType *ST =
1192 cast<StructType>(cast<PointerType>(PN->getType())->getElementType());
1195 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)),
1196 PN->getName()+".f"+Twine(FieldNo), PN);
1197 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo));
1199 llvm_unreachable("Unknown usable value");
1203 return FieldVals[FieldNo] = Result;
1206 /// RewriteHeapSROALoadUser - Given a load instruction and a value derived from
1207 /// the load, rewrite the derived value to use the HeapSRoA'd load.
1208 static void RewriteHeapSROALoadUser(Instruction *LoadUser,
1209 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1210 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1211 // If this is a comparison against null, handle it.
1212 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) {
1213 assert(isa<ConstantPointerNull>(SCI->getOperand(1)));
1214 // If we have a setcc of the loaded pointer, we can use a setcc of any
1216 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0,
1217 InsertedScalarizedValues, PHIsToRewrite);
1219 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr,
1220 Constant::getNullValue(NPtr->getType()),
1222 SCI->replaceAllUsesWith(New);
1223 SCI->eraseFromParent();
1227 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...'
1228 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) {
1229 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2))
1230 && "Unexpected GEPI!");
1232 // Load the pointer for this field.
1233 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue();
1234 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo,
1235 InsertedScalarizedValues, PHIsToRewrite);
1237 // Create the new GEP idx vector.
1238 SmallVector<Value*, 8> GEPIdx;
1239 GEPIdx.push_back(GEPI->getOperand(1));
1240 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end());
1242 Value *NGEPI = GetElementPtrInst::Create(NewPtr,
1243 GEPIdx.begin(), GEPIdx.end(),
1244 GEPI->getName(), GEPI);
1245 GEPI->replaceAllUsesWith(NGEPI);
1246 GEPI->eraseFromParent();
1250 // Recursively transform the users of PHI nodes. This will lazily create the
1251 // PHIs that are needed for individual elements. Keep track of what PHIs we
1252 // see in InsertedScalarizedValues so that we don't get infinite loops (very
1253 // antisocial). If the PHI is already in InsertedScalarizedValues, it has
1254 // already been seen first by another load, so its uses have already been
1256 PHINode *PN = cast<PHINode>(LoadUser);
1258 DenseMap<Value*, std::vector<Value*> >::iterator InsertPos;
1259 tie(InsertPos, Inserted) =
1260 InsertedScalarizedValues.insert(std::make_pair(PN, std::vector<Value*>()));
1261 if (!Inserted) return;
1263 // If this is the first time we've seen this PHI, recursively process all
1265 for (Value::use_iterator UI = PN->use_begin(), E = PN->use_end(); UI != E; ) {
1266 Instruction *User = cast<Instruction>(*UI++);
1267 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
1271 /// RewriteUsesOfLoadForHeapSRoA - We are performing Heap SRoA on a global. Ptr
1272 /// is a value loaded from the global. Eliminate all uses of Ptr, making them
1273 /// use FieldGlobals instead. All uses of loaded values satisfy
1274 /// AllGlobalLoadUsesSimpleEnoughForHeapSRA.
1275 static void RewriteUsesOfLoadForHeapSRoA(LoadInst *Load,
1276 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues,
1277 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) {
1278 for (Value::use_iterator UI = Load->use_begin(), E = Load->use_end();
1280 Instruction *User = cast<Instruction>(*UI++);
1281 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite);
1284 if (Load->use_empty()) {
1285 Load->eraseFromParent();
1286 InsertedScalarizedValues.erase(Load);
1290 /// PerformHeapAllocSRoA - CI is an allocation of an array of structures. Break
1291 /// it up into multiple allocations of arrays of the fields.
1292 static GlobalVariable *PerformHeapAllocSRoA(GlobalVariable *GV, CallInst *CI,
1293 Value* NElems, TargetData *TD) {
1294 DEBUG(dbgs() << "SROA HEAP ALLOC: " << *GV << " MALLOC = " << *CI << '\n');
1295 const Type* MAT = getMallocAllocatedType(CI);
1296 const StructType *STy = cast<StructType>(MAT);
1298 // There is guaranteed to be at least one use of the malloc (storing
1299 // it into GV). If there are other uses, change them to be uses of
1300 // the global to simplify later code. This also deletes the store
1302 ReplaceUsesOfMallocWithGlobal(CI, GV);
1304 // Okay, at this point, there are no users of the malloc. Insert N
1305 // new mallocs at the same place as CI, and N globals.
1306 std::vector<Value*> FieldGlobals;
1307 std::vector<Value*> FieldMallocs;
1309 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){
1310 const Type *FieldTy = STy->getElementType(FieldNo);
1311 const PointerType *PFieldTy = PointerType::getUnqual(FieldTy);
1313 GlobalVariable *NGV =
1314 new GlobalVariable(*GV->getParent(),
1315 PFieldTy, false, GlobalValue::InternalLinkage,
1316 Constant::getNullValue(PFieldTy),
1317 GV->getName() + ".f" + Twine(FieldNo), GV,
1318 GV->isThreadLocal());
1319 FieldGlobals.push_back(NGV);
1321 unsigned TypeSize = TD->getTypeAllocSize(FieldTy);
1322 if (const StructType *ST = dyn_cast<StructType>(FieldTy))
1323 TypeSize = TD->getStructLayout(ST)->getSizeInBytes();
1324 const Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
1325 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy,
1326 ConstantInt::get(IntPtrTy, TypeSize),
1328 CI->getName() + ".f" + Twine(FieldNo));
1329 FieldMallocs.push_back(NMI);
1330 new StoreInst(NMI, NGV, CI);
1333 // The tricky aspect of this transformation is handling the case when malloc
1334 // fails. In the original code, malloc failing would set the result pointer
1335 // of malloc to null. In this case, some mallocs could succeed and others
1336 // could fail. As such, we emit code that looks like this:
1337 // F0 = malloc(field0)
1338 // F1 = malloc(field1)
1339 // F2 = malloc(field2)
1340 // if (F0 == 0 || F1 == 0 || F2 == 0) {
1341 // if (F0) { free(F0); F0 = 0; }
1342 // if (F1) { free(F1); F1 = 0; }
1343 // if (F2) { free(F2); F2 = 0; }
1345 // The malloc can also fail if its argument is too large.
1346 Constant *ConstantZero = ConstantInt::get(CI->getArgOperand(0)->getType(), 0);
1347 Value *RunningOr = new ICmpInst(CI, ICmpInst::ICMP_SLT, CI->getArgOperand(0),
1348 ConstantZero, "isneg");
1349 for (unsigned i = 0, e = FieldMallocs.size(); i != e; ++i) {
1350 Value *Cond = new ICmpInst(CI, ICmpInst::ICMP_EQ, FieldMallocs[i],
1351 Constant::getNullValue(FieldMallocs[i]->getType()),
1353 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI);
1356 // Split the basic block at the old malloc.
1357 BasicBlock *OrigBB = CI->getParent();
1358 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont");
1360 // Create the block to check the first condition. Put all these blocks at the
1361 // end of the function as they are unlikely to be executed.
1362 BasicBlock *NullPtrBlock = BasicBlock::Create(OrigBB->getContext(),
1364 OrigBB->getParent());
1366 // Remove the uncond branch from OrigBB to ContBB, turning it into a cond
1367 // branch on RunningOr.
1368 OrigBB->getTerminator()->eraseFromParent();
1369 BranchInst::Create(NullPtrBlock, ContBB, RunningOr, OrigBB);
1371 // Within the NullPtrBlock, we need to emit a comparison and branch for each
1372 // pointer, because some may be null while others are not.
1373 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1374 Value *GVVal = new LoadInst(FieldGlobals[i], "tmp", NullPtrBlock);
1375 Value *Cmp = new ICmpInst(*NullPtrBlock, ICmpInst::ICMP_NE, GVVal,
1376 Constant::getNullValue(GVVal->getType()),
1378 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it",
1379 OrigBB->getParent());
1380 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next",
1381 OrigBB->getParent());
1382 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock,
1385 // Fill in FreeBlock.
1386 CallInst::CreateFree(GVVal, BI);
1387 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i],
1389 BranchInst::Create(NextBlock, FreeBlock);
1391 NullPtrBlock = NextBlock;
1394 BranchInst::Create(ContBB, NullPtrBlock);
1396 // CI is no longer needed, remove it.
1397 CI->eraseFromParent();
1399 /// InsertedScalarizedLoads - As we process loads, if we can't immediately
1400 /// update all uses of the load, keep track of what scalarized loads are
1401 /// inserted for a given load.
1402 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues;
1403 InsertedScalarizedValues[GV] = FieldGlobals;
1405 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite;
1407 // Okay, the malloc site is completely handled. All of the uses of GV are now
1408 // loads, and all uses of those loads are simple. Rewrite them to use loads
1409 // of the per-field globals instead.
1410 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) {
1411 Instruction *User = cast<Instruction>(*UI++);
1413 if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
1414 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite);
1418 // Must be a store of null.
1419 StoreInst *SI = cast<StoreInst>(User);
1420 assert(isa<ConstantPointerNull>(SI->getOperand(0)) &&
1421 "Unexpected heap-sra user!");
1423 // Insert a store of null into each global.
1424 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) {
1425 const PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType());
1426 Constant *Null = Constant::getNullValue(PT->getElementType());
1427 new StoreInst(Null, FieldGlobals[i], SI);
1429 // Erase the original store.
1430 SI->eraseFromParent();
1433 // While we have PHIs that are interesting to rewrite, do it.
1434 while (!PHIsToRewrite.empty()) {
1435 PHINode *PN = PHIsToRewrite.back().first;
1436 unsigned FieldNo = PHIsToRewrite.back().second;
1437 PHIsToRewrite.pop_back();
1438 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]);
1439 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi");
1441 // Add all the incoming values. This can materialize more phis.
1442 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
1443 Value *InVal = PN->getIncomingValue(i);
1444 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues,
1446 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i));
1450 // Drop all inter-phi links and any loads that made it this far.
1451 for (DenseMap<Value*, std::vector<Value*> >::iterator
1452 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1454 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1455 PN->dropAllReferences();
1456 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1457 LI->dropAllReferences();
1460 // Delete all the phis and loads now that inter-references are dead.
1461 for (DenseMap<Value*, std::vector<Value*> >::iterator
1462 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end();
1464 if (PHINode *PN = dyn_cast<PHINode>(I->first))
1465 PN->eraseFromParent();
1466 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first))
1467 LI->eraseFromParent();
1470 // The old global is now dead, remove it.
1471 GV->eraseFromParent();
1474 return cast<GlobalVariable>(FieldGlobals[0]);
1477 /// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a
1478 /// pointer global variable with a single value stored it that is a malloc or
1480 static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV,
1482 const Type *AllocTy,
1483 Module::global_iterator &GVI,
1488 // If this is a malloc of an abstract type, don't touch it.
1489 if (!AllocTy->isSized())
1492 // We can't optimize this global unless all uses of it are *known* to be
1493 // of the malloc value, not of the null initializer value (consider a use
1494 // that compares the global's value against zero to see if the malloc has
1495 // been reached). To do this, we check to see if all uses of the global
1496 // would trap if the global were null: this proves that they must all
1497 // happen after the malloc.
1498 if (!AllUsesOfLoadedValueWillTrapIfNull(GV))
1501 // We can't optimize this if the malloc itself is used in a complex way,
1502 // for example, being stored into multiple globals. This allows the
1503 // malloc to be stored into the specified global, loaded setcc'd, and
1504 // GEP'd. These are all things we could transform to using the global
1506 SmallPtrSet<const PHINode*, 8> PHIs;
1507 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs))
1510 // If we have a global that is only initialized with a fixed size malloc,
1511 // transform the program to use global memory instead of malloc'd memory.
1512 // This eliminates dynamic allocation, avoids an indirection accessing the
1513 // data, and exposes the resultant global to further GlobalOpt.
1514 // We cannot optimize the malloc if we cannot determine malloc array size.
1515 Value *NElems = getMallocArraySize(CI, TD, true);
1519 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems))
1520 // Restrict this transformation to only working on small allocations
1521 // (2048 bytes currently), as we don't want to introduce a 16M global or
1523 if (NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) {
1524 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD);
1528 // If the allocation is an array of structures, consider transforming this
1529 // into multiple malloc'd arrays, one for each field. This is basically
1530 // SRoA for malloc'd memory.
1532 // If this is an allocation of a fixed size array of structs, analyze as a
1533 // variable size array. malloc [100 x struct],1 -> malloc struct, 100
1534 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1))
1535 if (const ArrayType *AT = dyn_cast<ArrayType>(AllocTy))
1536 AllocTy = AT->getElementType();
1538 const StructType *AllocSTy = dyn_cast<StructType>(AllocTy);
1542 // This the structure has an unreasonable number of fields, leave it
1544 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 &&
1545 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) {
1547 // If this is a fixed size array, transform the Malloc to be an alloc of
1548 // structs. malloc [100 x struct],1 -> malloc struct, 100
1549 if (const ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI))) {
1550 const Type *IntPtrTy = TD->getIntPtrType(CI->getContext());
1551 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes();
1552 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize);
1553 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements());
1554 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy,
1555 AllocSize, NumElements,
1557 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI);
1558 CI->replaceAllUsesWith(Cast);
1559 CI->eraseFromParent();
1560 CI = dyn_cast<BitCastInst>(Malloc) ?
1561 extractMallocCallFromBitCast(Malloc) : cast<CallInst>(Malloc);
1564 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, true),TD);
1571 // OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge
1572 // that only one value (besides its initializer) is ever stored to the global.
1573 static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal,
1574 Module::global_iterator &GVI,
1576 // Ignore no-op GEPs and bitcasts.
1577 StoredOnceVal = StoredOnceVal->stripPointerCasts();
1579 // If we are dealing with a pointer global that is initialized to null and
1580 // only has one (non-null) value stored into it, then we can optimize any
1581 // users of the loaded value (often calls and loads) that would trap if the
1583 if (GV->getInitializer()->getType()->isPointerTy() &&
1584 GV->getInitializer()->isNullValue()) {
1585 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) {
1586 if (GV->getInitializer()->getType() != SOVC->getType())
1588 ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType());
1590 // Optimize away any trapping uses of the loaded value.
1591 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC))
1593 } else if (CallInst *CI = extractMallocCall(StoredOnceVal)) {
1594 const Type* MallocType = getMallocAllocatedType(CI);
1595 if (MallocType && TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType,
1604 /// TryToShrinkGlobalToBoolean - At this point, we have learned that the only
1605 /// two values ever stored into GV are its initializer and OtherVal. See if we
1606 /// can shrink the global into a boolean and select between the two values
1607 /// whenever it is used. This exposes the values to other scalar optimizations.
1608 static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) {
1609 const Type *GVElType = GV->getType()->getElementType();
1611 // If GVElType is already i1, it is already shrunk. If the type of the GV is
1612 // an FP value, pointer or vector, don't do this optimization because a select
1613 // between them is very expensive and unlikely to lead to later
1614 // simplification. In these cases, we typically end up with "cond ? v1 : v2"
1615 // where v1 and v2 both require constant pool loads, a big loss.
1616 if (GVElType == Type::getInt1Ty(GV->getContext()) ||
1617 GVElType->isFloatingPointTy() ||
1618 GVElType->isPointerTy() || GVElType->isVectorTy())
1621 // Walk the use list of the global seeing if all the uses are load or store.
1622 // If there is anything else, bail out.
1623 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){
1625 if (!isa<LoadInst>(U) && !isa<StoreInst>(U))
1629 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV);
1631 // Create the new global, initializing it to false.
1632 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()),
1634 GlobalValue::InternalLinkage,
1635 ConstantInt::getFalse(GV->getContext()),
1637 GV->isThreadLocal());
1638 GV->getParent()->getGlobalList().insert(GV, NewGV);
1640 Constant *InitVal = GV->getInitializer();
1641 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) &&
1642 "No reason to shrink to bool!");
1644 // If initialized to zero and storing one into the global, we can use a cast
1645 // instead of a select to synthesize the desired value.
1646 bool IsOneZero = false;
1647 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal))
1648 IsOneZero = InitVal->isNullValue() && CI->isOne();
1650 while (!GV->use_empty()) {
1651 Instruction *UI = cast<Instruction>(GV->use_back());
1652 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
1653 // Change the store into a boolean store.
1654 bool StoringOther = SI->getOperand(0) == OtherVal;
1655 // Only do this if we weren't storing a loaded value.
1657 if (StoringOther || SI->getOperand(0) == InitVal)
1658 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()),
1661 // Otherwise, we are storing a previously loaded copy. To do this,
1662 // change the copy from copying the original value to just copying the
1664 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0));
1666 // If we've already replaced the input, StoredVal will be a cast or
1667 // select instruction. If not, it will be a load of the original
1669 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) {
1670 assert(LI->getOperand(0) == GV && "Not a copy!");
1671 // Insert a new load, to preserve the saved value.
1672 StoreVal = new LoadInst(NewGV, LI->getName()+".b", LI);
1674 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) &&
1675 "This is not a form that we understand!");
1676 StoreVal = StoredVal->getOperand(0);
1677 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!");
1680 new StoreInst(StoreVal, NewGV, SI);
1682 // Change the load into a load of bool then a select.
1683 LoadInst *LI = cast<LoadInst>(UI);
1684 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", LI);
1687 NSI = new ZExtInst(NLI, LI->getType(), "", LI);
1689 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI);
1691 LI->replaceAllUsesWith(NSI);
1693 UI->eraseFromParent();
1696 GV->eraseFromParent();
1701 /// ProcessInternalGlobal - Analyze the specified global variable and optimize
1702 /// it if possible. If we make a change, return true.
1703 bool GlobalOpt::ProcessGlobal(GlobalVariable *GV,
1704 Module::global_iterator &GVI) {
1705 if (!GV->hasLocalLinkage())
1708 // Do more involved optimizations if the global is internal.
1709 GV->removeDeadConstantUsers();
1711 if (GV->use_empty()) {
1712 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV);
1713 GV->eraseFromParent();
1718 SmallPtrSet<const PHINode*, 16> PHIUsers;
1721 if (AnalyzeGlobal(GV, GS, PHIUsers))
1724 if (!GS.isCompared && !GV->hasUnnamedAddr()) {
1725 GV->setUnnamedAddr(true);
1729 if (GV->isConstant() || !GV->hasInitializer())
1732 return ProcessInternalGlobal(GV, GVI, PHIUsers, GS);
1735 /// ProcessInternalGlobal - Analyze the specified global variable and optimize
1736 /// it if possible. If we make a change, return true.
1737 bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV,
1738 Module::global_iterator &GVI,
1739 const SmallPtrSet<const PHINode*, 16> &PHIUsers,
1740 const GlobalStatus &GS) {
1741 // If this is a first class global and has only one accessing function
1742 // and this function is main (which we know is not recursive we can make
1743 // this global a local variable) we replace the global with a local alloca
1744 // in this function.
1746 // NOTE: It doesn't make sense to promote non single-value types since we
1747 // are just replacing static memory to stack memory.
1749 // If the global is in different address space, don't bring it to stack.
1750 if (!GS.HasMultipleAccessingFunctions &&
1751 GS.AccessingFunction && !GS.HasNonInstructionUser &&
1752 GV->getType()->getElementType()->isSingleValueType() &&
1753 GS.AccessingFunction->getName() == "main" &&
1754 GS.AccessingFunction->hasExternalLinkage() &&
1755 GV->getType()->getAddressSpace() == 0) {
1756 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV);
1757 Instruction& FirstI = const_cast<Instruction&>(*GS.AccessingFunction
1758 ->getEntryBlock().begin());
1759 const Type* ElemTy = GV->getType()->getElementType();
1760 // FIXME: Pass Global's alignment when globals have alignment
1761 AllocaInst* Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI);
1762 if (!isa<UndefValue>(GV->getInitializer()))
1763 new StoreInst(GV->getInitializer(), Alloca, &FirstI);
1765 GV->replaceAllUsesWith(Alloca);
1766 GV->eraseFromParent();
1771 // If the global is never loaded (but may be stored to), it is dead.
1774 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV);
1776 // Delete any stores we can find to the global. We may not be able to
1777 // make it completely dead though.
1778 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer());
1780 // If the global is dead now, delete it.
1781 if (GV->use_empty()) {
1782 GV->eraseFromParent();
1788 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) {
1789 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV);
1790 GV->setConstant(true);
1792 // Clean up any obviously simplifiable users now.
1793 CleanupConstantGlobalUsers(GV, GV->getInitializer());
1795 // If the global is dead now, just nuke it.
1796 if (GV->use_empty()) {
1797 DEBUG(dbgs() << " *** Marking constant allowed us to simplify "
1798 << "all users and delete global!\n");
1799 GV->eraseFromParent();
1805 } else if (!GV->getInitializer()->getType()->isSingleValueType()) {
1806 if (TargetData *TD = getAnalysisIfAvailable<TargetData>())
1807 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) {
1808 GVI = FirstNewGV; // Don't skip the newly produced globals!
1811 } else if (GS.StoredType == GlobalStatus::isStoredOnce) {
1812 // If the initial value for the global was an undef value, and if only
1813 // one other value was stored into it, we can just change the
1814 // initializer to be the stored value, then delete all stores to the
1815 // global. This allows us to mark it constant.
1816 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1817 if (isa<UndefValue>(GV->getInitializer())) {
1818 // Change the initial value here.
1819 GV->setInitializer(SOVConstant);
1821 // Clean up any obviously simplifiable users now.
1822 CleanupConstantGlobalUsers(GV, GV->getInitializer());
1824 if (GV->use_empty()) {
1825 DEBUG(dbgs() << " *** Substituting initializer allowed us to "
1826 << "simplify all users and delete global!\n");
1827 GV->eraseFromParent();
1836 // Try to optimize globals based on the knowledge that only one value
1837 // (besides its initializer) is ever stored to the global.
1838 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GVI,
1839 getAnalysisIfAvailable<TargetData>()))
1842 // Otherwise, if the global was not a boolean, we can shrink it to be a
1844 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue))
1845 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) {
1854 /// ChangeCalleesToFastCall - Walk all of the direct calls of the specified
1855 /// function, changing them to FastCC.
1856 static void ChangeCalleesToFastCall(Function *F) {
1857 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1858 CallSite User(cast<Instruction>(*UI));
1859 User.setCallingConv(CallingConv::Fast);
1863 static AttrListPtr StripNest(const AttrListPtr &Attrs) {
1864 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) {
1865 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0)
1868 // There can be only one.
1869 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest);
1875 static void RemoveNestAttribute(Function *F) {
1876 F->setAttributes(StripNest(F->getAttributes()));
1877 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){
1878 CallSite User(cast<Instruction>(*UI));
1879 User.setAttributes(StripNest(User.getAttributes()));
1883 bool GlobalOpt::OptimizeFunctions(Module &M) {
1884 bool Changed = false;
1885 // Optimize functions.
1886 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) {
1888 // Functions without names cannot be referenced outside this module.
1889 if (!F->hasName() && !F->isDeclaration())
1890 F->setLinkage(GlobalValue::InternalLinkage);
1891 F->removeDeadConstantUsers();
1892 if (F->use_empty() && (F->hasLocalLinkage() || F->hasLinkOnceLinkage())) {
1893 F->eraseFromParent();
1896 } else if (F->hasLocalLinkage()) {
1897 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() &&
1898 !F->hasAddressTaken()) {
1899 // If this function has C calling conventions, is not a varargs
1900 // function, and is only called directly, promote it to use the Fast
1901 // calling convention.
1902 F->setCallingConv(CallingConv::Fast);
1903 ChangeCalleesToFastCall(F);
1908 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) &&
1909 !F->hasAddressTaken()) {
1910 // The function is not used by a trampoline intrinsic, so it is safe
1911 // to remove the 'nest' attribute.
1912 RemoveNestAttribute(F);
1921 bool GlobalOpt::OptimizeGlobalVars(Module &M) {
1922 bool Changed = false;
1923 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end();
1925 GlobalVariable *GV = GVI++;
1926 // Global variables without names cannot be referenced outside this module.
1927 if (!GV->hasName() && !GV->isDeclaration())
1928 GV->setLinkage(GlobalValue::InternalLinkage);
1929 // Simplify the initializer.
1930 if (GV->hasInitializer())
1931 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) {
1932 TargetData *TD = getAnalysisIfAvailable<TargetData>();
1933 Constant *New = ConstantFoldConstantExpression(CE, TD);
1934 if (New && New != CE)
1935 GV->setInitializer(New);
1938 Changed |= ProcessGlobal(GV, GVI);
1943 /// FindGlobalCtors - Find the llvm.globalctors list, verifying that all
1944 /// initializers have an init priority of 65535.
1945 GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) {
1946 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors");
1947 if (GV == 0) return 0;
1949 // Found it, verify it's an array of { int, void()* }.
1950 const ArrayType *ATy =dyn_cast<ArrayType>(GV->getType()->getElementType());
1952 const StructType *STy = dyn_cast<StructType>(ATy->getElementType());
1953 if (!STy || STy->getNumElements() != 2 ||
1954 !STy->getElementType(0)->isIntegerTy(32)) return 0;
1955 const PointerType *PFTy = dyn_cast<PointerType>(STy->getElementType(1));
1956 if (!PFTy) return 0;
1957 const FunctionType *FTy = dyn_cast<FunctionType>(PFTy->getElementType());
1958 if (!FTy || !FTy->getReturnType()->isVoidTy() ||
1959 FTy->isVarArg() || FTy->getNumParams() != 0)
1962 // Verify that the initializer is simple enough for us to handle. We are
1963 // only allowed to optimize the initializer if it is unique.
1964 if (!GV->hasUniqueInitializer()) return 0;
1966 ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer());
1969 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1970 ConstantStruct *CS = dyn_cast<ConstantStruct>(*i);
1971 if (CS == 0) return 0;
1973 if (isa<ConstantPointerNull>(CS->getOperand(1)))
1976 // Must have a function or null ptr.
1977 if (!isa<Function>(CS->getOperand(1)))
1980 // Init priority must be standard.
1981 ConstantInt *CI = dyn_cast<ConstantInt>(CS->getOperand(0));
1982 if (!CI || CI->getZExtValue() != 65535)
1989 /// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand,
1990 /// return a list of the functions and null terminator as a vector.
1991 static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) {
1992 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer());
1993 std::vector<Function*> Result;
1994 Result.reserve(CA->getNumOperands());
1995 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) {
1996 ConstantStruct *CS = cast<ConstantStruct>(*i);
1997 Result.push_back(dyn_cast<Function>(CS->getOperand(1)));
2002 /// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the
2003 /// specified array, returning the new global to use.
2004 static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL,
2005 const std::vector<Function*> &Ctors) {
2006 // If we made a change, reassemble the initializer list.
2007 std::vector<Constant*> CSVals;
2008 CSVals.push_back(ConstantInt::get(Type::getInt32Ty(GCL->getContext()),65535));
2009 CSVals.push_back(0);
2011 // Create the new init list.
2012 std::vector<Constant*> CAList;
2013 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) {
2015 CSVals[1] = Ctors[i];
2017 const Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()),
2019 const PointerType *PFTy = PointerType::getUnqual(FTy);
2020 CSVals[1] = Constant::getNullValue(PFTy);
2021 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()),
2024 CAList.push_back(ConstantStruct::get(GCL->getContext(), CSVals, false));
2027 // Create the array initializer.
2028 const Type *StructTy =
2029 cast<ArrayType>(GCL->getType()->getElementType())->getElementType();
2030 Constant *CA = ConstantArray::get(ArrayType::get(StructTy,
2031 CAList.size()), CAList);
2033 // If we didn't change the number of elements, don't create a new GV.
2034 if (CA->getType() == GCL->getInitializer()->getType()) {
2035 GCL->setInitializer(CA);
2039 // Create the new global and insert it next to the existing list.
2040 GlobalVariable *NGV = new GlobalVariable(CA->getType(), GCL->isConstant(),
2041 GCL->getLinkage(), CA, "",
2042 GCL->isThreadLocal());
2043 GCL->getParent()->getGlobalList().insert(GCL, NGV);
2046 // Nuke the old list, replacing any uses with the new one.
2047 if (!GCL->use_empty()) {
2049 if (V->getType() != GCL->getType())
2050 V = ConstantExpr::getBitCast(V, GCL->getType());
2051 GCL->replaceAllUsesWith(V);
2053 GCL->eraseFromParent();
2062 static Constant *getVal(DenseMap<Value*, Constant*> &ComputedValues, Value *V) {
2063 if (Constant *CV = dyn_cast<Constant>(V)) return CV;
2064 Constant *R = ComputedValues[V];
2065 assert(R && "Reference to an uncomputed value!");
2070 isSimpleEnoughValueToCommit(Constant *C,
2071 SmallPtrSet<Constant*, 8> &SimpleConstants);
2074 /// isSimpleEnoughValueToCommit - Return true if the specified constant can be
2075 /// handled by the code generator. We don't want to generate something like:
2076 /// void *X = &X/42;
2077 /// because the code generator doesn't have a relocation that can handle that.
2079 /// This function should be called if C was not found (but just got inserted)
2080 /// in SimpleConstants to avoid having to rescan the same constants all the
2082 static bool isSimpleEnoughValueToCommitHelper(Constant *C,
2083 SmallPtrSet<Constant*, 8> &SimpleConstants) {
2084 // Simple integer, undef, constant aggregate zero, global addresses, etc are
2086 if (C->getNumOperands() == 0 || isa<BlockAddress>(C) ||
2087 isa<GlobalValue>(C))
2090 // Aggregate values are safe if all their elements are.
2091 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) ||
2092 isa<ConstantVector>(C)) {
2093 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
2094 Constant *Op = cast<Constant>(C->getOperand(i));
2095 if (!isSimpleEnoughValueToCommit(Op, SimpleConstants))
2101 // We don't know exactly what relocations are allowed in constant expressions,
2102 // so we allow &global+constantoffset, which is safe and uniformly supported
2104 ConstantExpr *CE = cast<ConstantExpr>(C);
2105 switch (CE->getOpcode()) {
2106 case Instruction::BitCast:
2107 case Instruction::IntToPtr:
2108 case Instruction::PtrToInt:
2109 // These casts are always fine if the casted value is.
2110 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants);
2112 // GEP is fine if it is simple + constant offset.
2113 case Instruction::GetElementPtr:
2114 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
2115 if (!isa<ConstantInt>(CE->getOperand(i)))
2117 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants);
2119 case Instruction::Add:
2120 // We allow simple+cst.
2121 if (!isa<ConstantInt>(CE->getOperand(1)))
2123 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants);
2129 isSimpleEnoughValueToCommit(Constant *C,
2130 SmallPtrSet<Constant*, 8> &SimpleConstants) {
2131 // If we already checked this constant, we win.
2132 if (!SimpleConstants.insert(C)) return true;
2133 // Check the constant.
2134 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants);
2138 /// isSimpleEnoughPointerToCommit - Return true if this constant is simple
2139 /// enough for us to understand. In particular, if it is a cast to anything
2140 /// other than from one pointer type to another pointer type, we punt.
2141 /// We basically just support direct accesses to globals and GEP's of
2142 /// globals. This should be kept up to date with CommitValueTo.
2143 static bool isSimpleEnoughPointerToCommit(Constant *C) {
2144 // Conservatively, avoid aggregate types. This is because we don't
2145 // want to worry about them partially overlapping other stores.
2146 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType())
2149 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C))
2150 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2151 // external globals.
2152 return GV->hasUniqueInitializer();
2154 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
2155 // Handle a constantexpr gep.
2156 if (CE->getOpcode() == Instruction::GetElementPtr &&
2157 isa<GlobalVariable>(CE->getOperand(0)) &&
2158 cast<GEPOperator>(CE)->isInBounds()) {
2159 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2160 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2161 // external globals.
2162 if (!GV->hasUniqueInitializer())
2165 // The first index must be zero.
2166 ConstantInt *CI = dyn_cast<ConstantInt>(*llvm::next(CE->op_begin()));
2167 if (!CI || !CI->isZero()) return false;
2169 // The remaining indices must be compile-time known integers within the
2170 // notional bounds of the corresponding static array types.
2171 if (!CE->isGEPWithNoNotionalOverIndexing())
2174 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
2176 // A constantexpr bitcast from a pointer to another pointer is a no-op,
2177 // and we know how to evaluate it by moving the bitcast from the pointer
2178 // operand to the value operand.
2179 } else if (CE->getOpcode() == Instruction::BitCast &&
2180 isa<GlobalVariable>(CE->getOperand(0))) {
2181 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or
2182 // external globals.
2183 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer();
2190 /// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global
2191 /// initializer. This returns 'Init' modified to reflect 'Val' stored into it.
2192 /// At this point, the GEP operands of Addr [0, OpNo) have been stepped into.
2193 static Constant *EvaluateStoreInto(Constant *Init, Constant *Val,
2194 ConstantExpr *Addr, unsigned OpNo) {
2195 // Base case of the recursion.
2196 if (OpNo == Addr->getNumOperands()) {
2197 assert(Val->getType() == Init->getType() && "Type mismatch!");
2201 std::vector<Constant*> Elts;
2202 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2204 // Break up the constant into its elements.
2205 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2206 for (User::op_iterator i = CS->op_begin(), e = CS->op_end(); i != e; ++i)
2207 Elts.push_back(cast<Constant>(*i));
2208 } else if (isa<ConstantAggregateZero>(Init)) {
2209 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2210 Elts.push_back(Constant::getNullValue(STy->getElementType(i)));
2211 } else if (isa<UndefValue>(Init)) {
2212 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i)
2213 Elts.push_back(UndefValue::get(STy->getElementType(i)));
2215 llvm_unreachable("This code is out of sync with "
2216 " ConstantFoldLoadThroughGEPConstantExpr");
2219 // Replace the element that we are supposed to.
2220 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo));
2221 unsigned Idx = CU->getZExtValue();
2222 assert(Idx < STy->getNumElements() && "Struct index out of range!");
2223 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1);
2225 // Return the modified struct.
2226 return ConstantStruct::get(Init->getContext(), &Elts[0], Elts.size(),
2229 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo));
2230 const SequentialType *InitTy = cast<SequentialType>(Init->getType());
2233 if (const ArrayType *ATy = dyn_cast<ArrayType>(InitTy))
2234 NumElts = ATy->getNumElements();
2236 NumElts = cast<VectorType>(InitTy)->getNumElements();
2239 // Break up the array into elements.
2240 if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2241 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i)
2242 Elts.push_back(cast<Constant>(*i));
2243 } else if (ConstantVector *CV = dyn_cast<ConstantVector>(Init)) {
2244 for (User::op_iterator i = CV->op_begin(), e = CV->op_end(); i != e; ++i)
2245 Elts.push_back(cast<Constant>(*i));
2246 } else if (isa<ConstantAggregateZero>(Init)) {
2247 Elts.assign(NumElts, Constant::getNullValue(InitTy->getElementType()));
2249 assert(isa<UndefValue>(Init) && "This code is out of sync with "
2250 " ConstantFoldLoadThroughGEPConstantExpr");
2251 Elts.assign(NumElts, UndefValue::get(InitTy->getElementType()));
2254 assert(CI->getZExtValue() < NumElts);
2255 Elts[CI->getZExtValue()] =
2256 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1);
2258 if (Init->getType()->isArrayTy())
2259 return ConstantArray::get(cast<ArrayType>(InitTy), Elts);
2260 return ConstantVector::get(Elts);
2264 /// CommitValueTo - We have decided that Addr (which satisfies the predicate
2265 /// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen.
2266 static void CommitValueTo(Constant *Val, Constant *Addr) {
2267 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) {
2268 assert(GV->hasInitializer());
2269 GV->setInitializer(Val);
2273 ConstantExpr *CE = cast<ConstantExpr>(Addr);
2274 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2275 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2));
2278 /// ComputeLoadResult - Return the value that would be computed by a load from
2279 /// P after the stores reflected by 'memory' have been performed. If we can't
2280 /// decide, return null.
2281 static Constant *ComputeLoadResult(Constant *P,
2282 const DenseMap<Constant*, Constant*> &Memory) {
2283 // If this memory location has been recently stored, use the stored value: it
2284 // is the most up-to-date.
2285 DenseMap<Constant*, Constant*>::const_iterator I = Memory.find(P);
2286 if (I != Memory.end()) return I->second;
2289 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) {
2290 if (GV->hasDefinitiveInitializer())
2291 return GV->getInitializer();
2295 // Handle a constantexpr getelementptr.
2296 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P))
2297 if (CE->getOpcode() == Instruction::GetElementPtr &&
2298 isa<GlobalVariable>(CE->getOperand(0))) {
2299 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0));
2300 if (GV->hasDefinitiveInitializer())
2301 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE);
2304 return 0; // don't know how to evaluate.
2307 /// EvaluateFunction - Evaluate a call to function F, returning true if
2308 /// successful, false if we can't evaluate it. ActualArgs contains the formal
2309 /// arguments for the function.
2310 static bool EvaluateFunction(Function *F, Constant *&RetVal,
2311 const SmallVectorImpl<Constant*> &ActualArgs,
2312 std::vector<Function*> &CallStack,
2313 DenseMap<Constant*, Constant*> &MutatedMemory,
2314 std::vector<GlobalVariable*> &AllocaTmps,
2315 SmallPtrSet<Constant*, 8> &SimpleConstants,
2316 const TargetData *TD) {
2317 // Check to see if this function is already executing (recursion). If so,
2318 // bail out. TODO: we might want to accept limited recursion.
2319 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end())
2322 CallStack.push_back(F);
2324 /// Values - As we compute SSA register values, we store their contents here.
2325 DenseMap<Value*, Constant*> Values;
2327 // Initialize arguments to the incoming values specified.
2329 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E;
2331 Values[AI] = ActualArgs[ArgNo];
2333 /// ExecutedBlocks - We only handle non-looping, non-recursive code. As such,
2334 /// we can only evaluate any one basic block at most once. This set keeps
2335 /// track of what we have executed so we can detect recursive cases etc.
2336 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks;
2338 // CurInst - The current instruction we're evaluating.
2339 BasicBlock::iterator CurInst = F->begin()->begin();
2341 // This is the main evaluation loop.
2343 Constant *InstResult = 0;
2345 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) {
2346 if (SI->isVolatile()) return false; // no volatile accesses.
2347 Constant *Ptr = getVal(Values, SI->getOperand(1));
2348 if (!isSimpleEnoughPointerToCommit(Ptr))
2349 // If this is too complex for us to commit, reject it.
2352 Constant *Val = getVal(Values, SI->getOperand(0));
2354 // If this might be too difficult for the backend to handle (e.g. the addr
2355 // of one global variable divided by another) then we can't commit it.
2356 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants))
2359 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr))
2360 if (CE->getOpcode() == Instruction::BitCast) {
2361 // If we're evaluating a store through a bitcast, then we need
2362 // to pull the bitcast off the pointer type and push it onto the
2364 Ptr = CE->getOperand(0);
2366 const Type *NewTy=cast<PointerType>(Ptr->getType())->getElementType();
2368 // In order to push the bitcast onto the stored value, a bitcast
2369 // from NewTy to Val's type must be legal. If it's not, we can try
2370 // introspecting NewTy to find a legal conversion.
2371 while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) {
2372 // If NewTy is a struct, we can convert the pointer to the struct
2373 // into a pointer to its first member.
2374 // FIXME: This could be extended to support arrays as well.
2375 if (const StructType *STy = dyn_cast<StructType>(NewTy)) {
2376 NewTy = STy->getTypeAtIndex(0U);
2378 const IntegerType *IdxTy =IntegerType::get(NewTy->getContext(), 32);
2379 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false);
2380 Constant * const IdxList[] = {IdxZero, IdxZero};
2382 Ptr = ConstantExpr::getGetElementPtr(Ptr, IdxList, 2);
2384 // If we can't improve the situation by introspecting NewTy,
2385 // we have to give up.
2391 // If we found compatible types, go ahead and push the bitcast
2392 // onto the stored value.
2393 Val = ConstantExpr::getBitCast(Val, NewTy);
2396 MutatedMemory[Ptr] = Val;
2397 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) {
2398 InstResult = ConstantExpr::get(BO->getOpcode(),
2399 getVal(Values, BO->getOperand(0)),
2400 getVal(Values, BO->getOperand(1)));
2401 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) {
2402 InstResult = ConstantExpr::getCompare(CI->getPredicate(),
2403 getVal(Values, CI->getOperand(0)),
2404 getVal(Values, CI->getOperand(1)));
2405 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) {
2406 InstResult = ConstantExpr::getCast(CI->getOpcode(),
2407 getVal(Values, CI->getOperand(0)),
2409 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) {
2410 InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)),
2411 getVal(Values, SI->getOperand(1)),
2412 getVal(Values, SI->getOperand(2)));
2413 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) {
2414 Constant *P = getVal(Values, GEP->getOperand(0));
2415 SmallVector<Constant*, 8> GEPOps;
2416 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end();
2418 GEPOps.push_back(getVal(Values, *i));
2419 InstResult = cast<GEPOperator>(GEP)->isInBounds() ?
2420 ConstantExpr::getInBoundsGetElementPtr(P, &GEPOps[0], GEPOps.size()) :
2421 ConstantExpr::getGetElementPtr(P, &GEPOps[0], GEPOps.size());
2422 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) {
2423 if (LI->isVolatile()) return false; // no volatile accesses.
2424 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)),
2426 if (InstResult == 0) return false; // Could not evaluate load.
2427 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) {
2428 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs.
2429 const Type *Ty = AI->getType()->getElementType();
2430 AllocaTmps.push_back(new GlobalVariable(Ty, false,
2431 GlobalValue::InternalLinkage,
2432 UndefValue::get(Ty),
2434 InstResult = AllocaTmps.back();
2435 } else if (CallInst *CI = dyn_cast<CallInst>(CurInst)) {
2437 // Debug info can safely be ignored here.
2438 if (isa<DbgInfoIntrinsic>(CI)) {
2443 // Cannot handle inline asm.
2444 if (isa<InlineAsm>(CI->getCalledValue())) return false;
2446 // Resolve function pointers.
2447 Function *Callee = dyn_cast<Function>(getVal(Values,
2448 CI->getCalledValue()));
2449 if (!Callee) return false; // Cannot resolve.
2451 SmallVector<Constant*, 8> Formals;
2453 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end();
2455 Formals.push_back(getVal(Values, *i));
2457 if (Callee->isDeclaration()) {
2458 // If this is a function we can constant fold, do it.
2459 if (Constant *C = ConstantFoldCall(Callee, Formals.data(),
2466 if (Callee->getFunctionType()->isVarArg())
2470 // Execute the call, if successful, use the return value.
2471 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack,
2472 MutatedMemory, AllocaTmps, SimpleConstants, TD))
2474 InstResult = RetVal;
2476 } else if (isa<TerminatorInst>(CurInst)) {
2477 BasicBlock *NewBB = 0;
2478 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) {
2479 if (BI->isUnconditional()) {
2480 NewBB = BI->getSuccessor(0);
2483 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition()));
2484 if (!Cond) return false; // Cannot determine.
2486 NewBB = BI->getSuccessor(!Cond->getZExtValue());
2488 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) {
2490 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition()));
2491 if (!Val) return false; // Cannot determine.
2492 NewBB = SI->getSuccessor(SI->findCaseValue(Val));
2493 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) {
2494 Value *Val = getVal(Values, IBI->getAddress())->stripPointerCasts();
2495 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val))
2496 NewBB = BA->getBasicBlock();
2498 return false; // Cannot determine.
2499 } else if (ReturnInst *RI = dyn_cast<ReturnInst>(CurInst)) {
2500 if (RI->getNumOperands())
2501 RetVal = getVal(Values, RI->getOperand(0));
2503 CallStack.pop_back(); // return from fn.
2504 return true; // We succeeded at evaluating this ctor!
2506 // invoke, unwind, unreachable.
2507 return false; // Cannot handle this terminator.
2510 // Okay, we succeeded in evaluating this control flow. See if we have
2511 // executed the new block before. If so, we have a looping function,
2512 // which we cannot evaluate in reasonable time.
2513 if (!ExecutedBlocks.insert(NewBB))
2514 return false; // looped!
2516 // Okay, we have never been in this block before. Check to see if there
2517 // are any PHI nodes. If so, evaluate them with information about where
2519 BasicBlock *OldBB = CurInst->getParent();
2520 CurInst = NewBB->begin();
2522 for (; (PN = dyn_cast<PHINode>(CurInst)); ++CurInst)
2523 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(OldBB));
2525 // Do NOT increment CurInst. We know that the terminator had no value.
2528 // Did not know how to evaluate this!
2532 if (!CurInst->use_empty()) {
2533 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult))
2534 InstResult = ConstantFoldConstantExpression(CE, TD);
2536 Values[CurInst] = InstResult;
2539 // Advance program counter.
2544 /// EvaluateStaticConstructor - Evaluate static constructors in the function, if
2545 /// we can. Return true if we can, false otherwise.
2546 static bool EvaluateStaticConstructor(Function *F, const TargetData *TD) {
2547 /// MutatedMemory - For each store we execute, we update this map. Loads
2548 /// check this to get the most up-to-date value. If evaluation is successful,
2549 /// this state is committed to the process.
2550 DenseMap<Constant*, Constant*> MutatedMemory;
2552 /// AllocaTmps - To 'execute' an alloca, we create a temporary global variable
2553 /// to represent its body. This vector is needed so we can delete the
2554 /// temporary globals when we are done.
2555 std::vector<GlobalVariable*> AllocaTmps;
2557 /// CallStack - This is used to detect recursion. In pathological situations
2558 /// we could hit exponential behavior, but at least there is nothing
2560 std::vector<Function*> CallStack;
2562 /// SimpleConstants - These are constants we have checked and know to be
2563 /// simple enough to live in a static initializer of a global.
2564 SmallPtrSet<Constant*, 8> SimpleConstants;
2566 // Call the function.
2567 Constant *RetValDummy;
2568 bool EvalSuccess = EvaluateFunction(F, RetValDummy,
2569 SmallVector<Constant*, 0>(), CallStack,
2570 MutatedMemory, AllocaTmps,
2571 SimpleConstants, TD);
2574 // We succeeded at evaluation: commit the result.
2575 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '"
2576 << F->getName() << "' to " << MutatedMemory.size()
2578 for (DenseMap<Constant*, Constant*>::iterator I = MutatedMemory.begin(),
2579 E = MutatedMemory.end(); I != E; ++I)
2580 CommitValueTo(I->second, I->first);
2583 // At this point, we are done interpreting. If we created any 'alloca'
2584 // temporaries, release them now.
2585 while (!AllocaTmps.empty()) {
2586 GlobalVariable *Tmp = AllocaTmps.back();
2587 AllocaTmps.pop_back();
2589 // If there are still users of the alloca, the program is doing something
2590 // silly, e.g. storing the address of the alloca somewhere and using it
2591 // later. Since this is undefined, we'll just make it be null.
2592 if (!Tmp->use_empty())
2593 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType()));
2602 /// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible.
2603 /// Return true if anything changed.
2604 bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) {
2605 std::vector<Function*> Ctors = ParseGlobalCtors(GCL);
2606 bool MadeChange = false;
2607 if (Ctors.empty()) return false;
2609 const TargetData *TD = getAnalysisIfAvailable<TargetData>();
2610 // Loop over global ctors, optimizing them when we can.
2611 for (unsigned i = 0; i != Ctors.size(); ++i) {
2612 Function *F = Ctors[i];
2613 // Found a null terminator in the middle of the list, prune off the rest of
2616 if (i != Ctors.size()-1) {
2623 // We cannot simplify external ctor functions.
2624 if (F->empty()) continue;
2626 // If we can evaluate the ctor at compile time, do.
2627 if (EvaluateStaticConstructor(F, TD)) {
2628 Ctors.erase(Ctors.begin()+i);
2631 ++NumCtorsEvaluated;
2636 if (!MadeChange) return false;
2638 GCL = InstallGlobalCtors(GCL, Ctors);
2642 bool GlobalOpt::OptimizeGlobalAliases(Module &M) {
2643 bool Changed = false;
2645 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
2647 Module::alias_iterator J = I++;
2648 // Aliases without names cannot be referenced outside this module.
2649 if (!J->hasName() && !J->isDeclaration())
2650 J->setLinkage(GlobalValue::InternalLinkage);
2651 // If the aliasee may change at link time, nothing can be done - bail out.
2652 if (J->mayBeOverridden())
2655 Constant *Aliasee = J->getAliasee();
2656 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts());
2657 Target->removeDeadConstantUsers();
2658 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse();
2660 // Make all users of the alias use the aliasee instead.
2661 if (!J->use_empty()) {
2662 J->replaceAllUsesWith(Aliasee);
2663 ++NumAliasesResolved;
2667 // If the alias is externally visible, we may still be able to simplify it.
2668 if (!J->hasLocalLinkage()) {
2669 // If the aliasee has internal linkage, give it the name and linkage
2670 // of the alias, and delete the alias. This turns:
2671 // define internal ... @f(...)
2672 // @a = alias ... @f
2674 // define ... @a(...)
2675 if (!Target->hasLocalLinkage())
2678 // Do not perform the transform if multiple aliases potentially target the
2679 // aliasee. This check also ensures that it is safe to replace the section
2680 // and other attributes of the aliasee with those of the alias.
2684 // Give the aliasee the name, linkage and other attributes of the alias.
2685 Target->takeName(J);
2686 Target->setLinkage(J->getLinkage());
2687 Target->GlobalValue::copyAttributesFrom(J);
2690 // Delete the alias.
2691 M.getAliasList().erase(J);
2692 ++NumAliasesRemoved;
2699 bool GlobalOpt::runOnModule(Module &M) {
2700 bool Changed = false;
2702 // Try to find the llvm.globalctors list.
2703 GlobalVariable *GlobalCtors = FindGlobalCtors(M);
2705 bool LocalChange = true;
2706 while (LocalChange) {
2707 LocalChange = false;
2709 // Delete functions that are trivially dead, ccc -> fastcc
2710 LocalChange |= OptimizeFunctions(M);
2712 // Optimize global_ctors list.
2714 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors);
2716 // Optimize non-address-taken globals.
2717 LocalChange |= OptimizeGlobalVars(M);
2719 // Resolve aliases, when possible.
2720 LocalChange |= OptimizeGlobalAliases(M);
2721 Changed |= LocalChange;
2724 // TODO: Move all global ctors functions to the end of the module for code