1 //===- GlobalOpt.cpp - Optimize Global Variables --------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 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. 13 // 14 //===----------------------------------------------------------------------===// 15 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/Operator.h" 25 #include "llvm/Pass.h" 26 #include "llvm/Analysis/ConstantFolding.h" 27 #include "llvm/Analysis/MemoryBuiltins.h" 28 #include "llvm/Target/TargetData.h" 29 #include "llvm/Target/TargetLibraryInfo.h" 30 #include "llvm/Support/CallSite.h" 31 #include "llvm/Support/Debug.h" 32 #include "llvm/Support/ErrorHandling.h" 33 #include "llvm/Support/GetElementPtrTypeIterator.h" 34 #include "llvm/Support/MathExtras.h" 35 #include "llvm/Support/raw_ostream.h" 36 #include "llvm/ADT/DenseMap.h" 37 #include "llvm/ADT/SmallPtrSet.h" 38 #include "llvm/ADT/SmallVector.h" 39 #include "llvm/ADT/Statistic.h" 40 #include "llvm/ADT/STLExtras.h" 41 #include <algorithm> 42 using namespace llvm; 43 44 STATISTIC(NumMarked , "Number of globals marked constant"); 45 STATISTIC(NumUnnamed , "Number of globals marked unnamed_addr"); 46 STATISTIC(NumSRA , "Number of aggregate globals broken into scalars"); 47 STATISTIC(NumHeapSRA , "Number of heap objects SRA'd"); 48 STATISTIC(NumSubstitute,"Number of globals with initializers stored into them"); 49 STATISTIC(NumDeleted , "Number of globals deleted"); 50 STATISTIC(NumFnDeleted , "Number of functions deleted"); 51 STATISTIC(NumGlobUses , "Number of global uses devirtualized"); 52 STATISTIC(NumLocalized , "Number of globals localized"); 53 STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans"); 54 STATISTIC(NumFastCallFns , "Number of functions converted to fastcc"); 55 STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated"); 56 STATISTIC(NumNestRemoved , "Number of nest attributes removed"); 57 STATISTIC(NumAliasesResolved, "Number of global aliases resolved"); 58 STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated"); 59 STATISTIC(NumCXXDtorsRemoved, "Number of global C++ destructors removed"); 60 61 namespace { 62 struct GlobalStatus; 63 struct GlobalOpt : public ModulePass { 64 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 65 AU.addRequired<TargetLibraryInfo>(); 66 } 67 static char ID; // Pass identification, replacement for typeid 68 GlobalOpt() : ModulePass(ID) { 69 initializeGlobalOptPass(*PassRegistry::getPassRegistry()); 70 } 71 72 bool runOnModule(Module &M); 73 74 private: 75 GlobalVariable *FindGlobalCtors(Module &M); 76 bool OptimizeFunctions(Module &M); 77 bool OptimizeGlobalVars(Module &M); 78 bool OptimizeGlobalAliases(Module &M); 79 bool OptimizeGlobalCtorsList(GlobalVariable *&GCL); 80 bool ProcessGlobal(GlobalVariable *GV,Module::global_iterator &GVI); 81 bool ProcessInternalGlobal(GlobalVariable *GV,Module::global_iterator &GVI, 82 const SmallPtrSet<const PHINode*, 16> &PHIUsers, 83 const GlobalStatus &GS); 84 bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn); 85 86 TargetData *TD; 87 TargetLibraryInfo *TLI; 88 }; 89 } 90 91 char GlobalOpt::ID = 0; 92 INITIALIZE_PASS_BEGIN(GlobalOpt, "globalopt", 93 "Global Variable Optimizer", false, false) 94 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfo) 95 INITIALIZE_PASS_END(GlobalOpt, "globalopt", 96 "Global Variable Optimizer", false, false) 97 98 ModulePass *llvm::createGlobalOptimizerPass() { return new GlobalOpt(); } 99 100 namespace { 101 102 /// GlobalStatus - As we analyze each global, keep track of some information 103 /// about it. If we find out that the address of the global is taken, none of 104 /// this info will be accurate. 105 struct GlobalStatus { 106 /// isCompared - True if the global's address is used in a comparison. 107 bool isCompared; 108 109 /// isLoaded - True if the global is ever loaded. If the global isn't ever 110 /// loaded it can be deleted. 111 bool isLoaded; 112 113 /// StoredType - Keep track of what stores to the global look like. 114 /// 115 enum StoredType { 116 /// NotStored - There is no store to this global. It can thus be marked 117 /// constant. 118 NotStored, 119 120 /// isInitializerStored - This global is stored to, but the only thing 121 /// stored is the constant it was initialized with. This is only tracked 122 /// for scalar globals. 123 isInitializerStored, 124 125 /// isStoredOnce - This global is stored to, but only its initializer and 126 /// one other value is ever stored to it. If this global isStoredOnce, we 127 /// track the value stored to it in StoredOnceValue below. This is only 128 /// tracked for scalar globals. 129 isStoredOnce, 130 131 /// isStored - This global is stored to by multiple values or something else 132 /// that we cannot track. 133 isStored 134 } StoredType; 135 136 /// StoredOnceValue - If only one value (besides the initializer constant) is 137 /// ever stored to this global, keep track of what value it is. 138 Value *StoredOnceValue; 139 140 /// AccessingFunction/HasMultipleAccessingFunctions - These start out 141 /// null/false. When the first accessing function is noticed, it is recorded. 142 /// When a second different accessing function is noticed, 143 /// HasMultipleAccessingFunctions is set to true. 144 const Function *AccessingFunction; 145 bool HasMultipleAccessingFunctions; 146 147 /// HasNonInstructionUser - Set to true if this global has a user that is not 148 /// an instruction (e.g. a constant expr or GV initializer). 149 bool HasNonInstructionUser; 150 151 /// HasPHIUser - Set to true if this global has a user that is a PHI node. 152 bool HasPHIUser; 153 154 /// AtomicOrdering - Set to the strongest atomic ordering requirement. 155 AtomicOrdering Ordering; 156 157 GlobalStatus() : isCompared(false), isLoaded(false), StoredType(NotStored), 158 StoredOnceValue(0), AccessingFunction(0), 159 HasMultipleAccessingFunctions(false), 160 HasNonInstructionUser(false), HasPHIUser(false), 161 Ordering(NotAtomic) {} 162 }; 163 164 } 165 166 /// StrongerOrdering - Return the stronger of the two ordering. If the two 167 /// orderings are acquire and release, then return AcquireRelease. 168 /// 169 static AtomicOrdering StrongerOrdering(AtomicOrdering X, AtomicOrdering Y) { 170 if (X == Acquire && Y == Release) return AcquireRelease; 171 if (Y == Acquire && X == Release) return AcquireRelease; 172 return (AtomicOrdering)std::max(X, Y); 173 } 174 175 /// SafeToDestroyConstant - It is safe to destroy a constant iff it is only used 176 /// by constants itself. Note that constants cannot be cyclic, so this test is 177 /// pretty easy to implement recursively. 178 /// 179 static bool SafeToDestroyConstant(const Constant *C) { 180 if (isa<GlobalValue>(C)) return false; 181 182 for (Value::const_use_iterator UI = C->use_begin(), E = C->use_end(); UI != E; 183 ++UI) 184 if (const Constant *CU = dyn_cast<Constant>(*UI)) { 185 if (!SafeToDestroyConstant(CU)) return false; 186 } else 187 return false; 188 return true; 189 } 190 191 192 /// AnalyzeGlobal - Look at all uses of the global and fill in the GlobalStatus 193 /// structure. If the global has its address taken, return true to indicate we 194 /// can't do anything with it. 195 /// 196 static bool AnalyzeGlobal(const Value *V, GlobalStatus &GS, 197 SmallPtrSet<const PHINode*, 16> &PHIUsers) { 198 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; 199 ++UI) { 200 const User *U = *UI; 201 if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) { 202 GS.HasNonInstructionUser = true; 203 204 // If the result of the constantexpr isn't pointer type, then we won't 205 // know to expect it in various places. Just reject early. 206 if (!isa<PointerType>(CE->getType())) return true; 207 208 if (AnalyzeGlobal(CE, GS, PHIUsers)) return true; 209 } else if (const Instruction *I = dyn_cast<Instruction>(U)) { 210 if (!GS.HasMultipleAccessingFunctions) { 211 const Function *F = I->getParent()->getParent(); 212 if (GS.AccessingFunction == 0) 213 GS.AccessingFunction = F; 214 else if (GS.AccessingFunction != F) 215 GS.HasMultipleAccessingFunctions = true; 216 } 217 if (const LoadInst *LI = dyn_cast<LoadInst>(I)) { 218 GS.isLoaded = true; 219 // Don't hack on volatile loads. 220 if (LI->isVolatile()) return true; 221 GS.Ordering = StrongerOrdering(GS.Ordering, LI->getOrdering()); 222 } else if (const StoreInst *SI = dyn_cast<StoreInst>(I)) { 223 // Don't allow a store OF the address, only stores TO the address. 224 if (SI->getOperand(0) == V) return true; 225 226 // Don't hack on volatile stores. 227 if (SI->isVolatile()) return true; 228 GS.Ordering = StrongerOrdering(GS.Ordering, SI->getOrdering()); 229 230 // If this is a direct store to the global (i.e., the global is a scalar 231 // value, not an aggregate), keep more specific information about 232 // stores. 233 if (GS.StoredType != GlobalStatus::isStored) { 234 if (const GlobalVariable *GV = dyn_cast<GlobalVariable>( 235 SI->getOperand(1))) { 236 Value *StoredVal = SI->getOperand(0); 237 if (StoredVal == GV->getInitializer()) { 238 if (GS.StoredType < GlobalStatus::isInitializerStored) 239 GS.StoredType = GlobalStatus::isInitializerStored; 240 } else if (isa<LoadInst>(StoredVal) && 241 cast<LoadInst>(StoredVal)->getOperand(0) == GV) { 242 if (GS.StoredType < GlobalStatus::isInitializerStored) 243 GS.StoredType = GlobalStatus::isInitializerStored; 244 } else if (GS.StoredType < GlobalStatus::isStoredOnce) { 245 GS.StoredType = GlobalStatus::isStoredOnce; 246 GS.StoredOnceValue = StoredVal; 247 } else if (GS.StoredType == GlobalStatus::isStoredOnce && 248 GS.StoredOnceValue == StoredVal) { 249 // noop. 250 } else { 251 GS.StoredType = GlobalStatus::isStored; 252 } 253 } else { 254 GS.StoredType = GlobalStatus::isStored; 255 } 256 } 257 } else if (isa<GetElementPtrInst>(I)) { 258 if (AnalyzeGlobal(I, GS, PHIUsers)) return true; 259 } else if (isa<SelectInst>(I)) { 260 if (AnalyzeGlobal(I, GS, PHIUsers)) return true; 261 } else if (const PHINode *PN = dyn_cast<PHINode>(I)) { 262 // PHI nodes we can check just like select or GEP instructions, but we 263 // have to be careful about infinite recursion. 264 if (PHIUsers.insert(PN)) // Not already visited. 265 if (AnalyzeGlobal(I, GS, PHIUsers)) return true; 266 GS.HasPHIUser = true; 267 } else if (isa<CmpInst>(I)) { 268 GS.isCompared = true; 269 } else if (const MemTransferInst *MTI = dyn_cast<MemTransferInst>(I)) { 270 if (MTI->isVolatile()) return true; 271 if (MTI->getArgOperand(0) == V) 272 GS.StoredType = GlobalStatus::isStored; 273 if (MTI->getArgOperand(1) == V) 274 GS.isLoaded = true; 275 } else if (const MemSetInst *MSI = dyn_cast<MemSetInst>(I)) { 276 assert(MSI->getArgOperand(0) == V && "Memset only takes one pointer!"); 277 if (MSI->isVolatile()) return true; 278 GS.StoredType = GlobalStatus::isStored; 279 } else { 280 return true; // Any other non-load instruction might take address! 281 } 282 } else if (const Constant *C = dyn_cast<Constant>(U)) { 283 GS.HasNonInstructionUser = true; 284 // We might have a dead and dangling constant hanging off of here. 285 if (!SafeToDestroyConstant(C)) 286 return true; 287 } else { 288 GS.HasNonInstructionUser = true; 289 // Otherwise must be some other user. 290 return true; 291 } 292 } 293 294 return false; 295 } 296 297 /// CleanupConstantGlobalUsers - We just marked GV constant. Loop over all 298 /// users of the global, cleaning up the obvious ones. This is largely just a 299 /// quick scan over the use list to clean up the easy and obvious cruft. This 300 /// returns true if it made a change. 301 static bool CleanupConstantGlobalUsers(Value *V, Constant *Init, 302 TargetData *TD, TargetLibraryInfo *TLI) { 303 bool Changed = false; 304 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E;) { 305 User *U = *UI++; 306 307 if (LoadInst *LI = dyn_cast<LoadInst>(U)) { 308 if (Init) { 309 // Replace the load with the initializer. 310 LI->replaceAllUsesWith(Init); 311 LI->eraseFromParent(); 312 Changed = true; 313 } 314 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) { 315 // Store must be unreachable or storing Init into the global. 316 SI->eraseFromParent(); 317 Changed = true; 318 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) { 319 if (CE->getOpcode() == Instruction::GetElementPtr) { 320 Constant *SubInit = 0; 321 if (Init) 322 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE); 323 Changed |= CleanupConstantGlobalUsers(CE, SubInit, TD, TLI); 324 } else if (CE->getOpcode() == Instruction::BitCast && 325 CE->getType()->isPointerTy()) { 326 // Pointer cast, delete any stores and memsets to the global. 327 Changed |= CleanupConstantGlobalUsers(CE, 0, TD, TLI); 328 } 329 330 if (CE->use_empty()) { 331 CE->destroyConstant(); 332 Changed = true; 333 } 334 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) { 335 // Do not transform "gepinst (gep constexpr (GV))" here, because forming 336 // "gepconstexpr (gep constexpr (GV))" will cause the two gep's to fold 337 // and will invalidate our notion of what Init is. 338 Constant *SubInit = 0; 339 if (!isa<ConstantExpr>(GEP->getOperand(0))) { 340 ConstantExpr *CE = 341 dyn_cast_or_null<ConstantExpr>(ConstantFoldInstruction(GEP, TD, TLI)); 342 if (Init && CE && CE->getOpcode() == Instruction::GetElementPtr) 343 SubInit = ConstantFoldLoadThroughGEPConstantExpr(Init, CE); 344 } 345 Changed |= CleanupConstantGlobalUsers(GEP, SubInit, TD, TLI); 346 347 if (GEP->use_empty()) { 348 GEP->eraseFromParent(); 349 Changed = true; 350 } 351 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv 352 if (MI->getRawDest() == V) { 353 MI->eraseFromParent(); 354 Changed = true; 355 } 356 357 } else if (Constant *C = dyn_cast<Constant>(U)) { 358 // If we have a chain of dead constantexprs or other things dangling from 359 // us, and if they are all dead, nuke them without remorse. 360 if (SafeToDestroyConstant(C)) { 361 C->destroyConstant(); 362 // This could have invalidated UI, start over from scratch. 363 CleanupConstantGlobalUsers(V, Init, TD, TLI); 364 return true; 365 } 366 } 367 } 368 return Changed; 369 } 370 371 /// isSafeSROAElementUse - Return true if the specified instruction is a safe 372 /// user of a derived expression from a global that we want to SROA. 373 static bool isSafeSROAElementUse(Value *V) { 374 // We might have a dead and dangling constant hanging off of here. 375 if (Constant *C = dyn_cast<Constant>(V)) 376 return SafeToDestroyConstant(C); 377 378 Instruction *I = dyn_cast<Instruction>(V); 379 if (!I) return false; 380 381 // Loads are ok. 382 if (isa<LoadInst>(I)) return true; 383 384 // Stores *to* the pointer are ok. 385 if (StoreInst *SI = dyn_cast<StoreInst>(I)) 386 return SI->getOperand(0) != V; 387 388 // Otherwise, it must be a GEP. 389 GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I); 390 if (GEPI == 0) return false; 391 392 if (GEPI->getNumOperands() < 3 || !isa<Constant>(GEPI->getOperand(1)) || 393 !cast<Constant>(GEPI->getOperand(1))->isNullValue()) 394 return false; 395 396 for (Value::use_iterator I = GEPI->use_begin(), E = GEPI->use_end(); 397 I != E; ++I) 398 if (!isSafeSROAElementUse(*I)) 399 return false; 400 return true; 401 } 402 403 404 /// IsUserOfGlobalSafeForSRA - U is a direct user of the specified global value. 405 /// Look at it and its uses and decide whether it is safe to SROA this global. 406 /// 407 static bool IsUserOfGlobalSafeForSRA(User *U, GlobalValue *GV) { 408 // The user of the global must be a GEP Inst or a ConstantExpr GEP. 409 if (!isa<GetElementPtrInst>(U) && 410 (!isa<ConstantExpr>(U) || 411 cast<ConstantExpr>(U)->getOpcode() != Instruction::GetElementPtr)) 412 return false; 413 414 // Check to see if this ConstantExpr GEP is SRA'able. In particular, we 415 // don't like < 3 operand CE's, and we don't like non-constant integer 416 // indices. This enforces that all uses are 'gep GV, 0, C, ...' for some 417 // value of C. 418 if (U->getNumOperands() < 3 || !isa<Constant>(U->getOperand(1)) || 419 !cast<Constant>(U->getOperand(1))->isNullValue() || 420 !isa<ConstantInt>(U->getOperand(2))) 421 return false; 422 423 gep_type_iterator GEPI = gep_type_begin(U), E = gep_type_end(U); 424 ++GEPI; // Skip over the pointer index. 425 426 // If this is a use of an array allocation, do a bit more checking for sanity. 427 if (ArrayType *AT = dyn_cast<ArrayType>(*GEPI)) { 428 uint64_t NumElements = AT->getNumElements(); 429 ConstantInt *Idx = cast<ConstantInt>(U->getOperand(2)); 430 431 // Check to make sure that index falls within the array. If not, 432 // something funny is going on, so we won't do the optimization. 433 // 434 if (Idx->getZExtValue() >= NumElements) 435 return false; 436 437 // We cannot scalar repl this level of the array unless any array 438 // sub-indices are in-range constants. In particular, consider: 439 // A[0][i]. We cannot know that the user isn't doing invalid things like 440 // allowing i to index an out-of-range subscript that accesses A[1]. 441 // 442 // Scalar replacing *just* the outer index of the array is probably not 443 // going to be a win anyway, so just give up. 444 for (++GEPI; // Skip array index. 445 GEPI != E; 446 ++GEPI) { 447 uint64_t NumElements; 448 if (ArrayType *SubArrayTy = dyn_cast<ArrayType>(*GEPI)) 449 NumElements = SubArrayTy->getNumElements(); 450 else if (VectorType *SubVectorTy = dyn_cast<VectorType>(*GEPI)) 451 NumElements = SubVectorTy->getNumElements(); 452 else { 453 assert((*GEPI)->isStructTy() && 454 "Indexed GEP type is not array, vector, or struct!"); 455 continue; 456 } 457 458 ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPI.getOperand()); 459 if (!IdxVal || IdxVal->getZExtValue() >= NumElements) 460 return false; 461 } 462 } 463 464 for (Value::use_iterator I = U->use_begin(), E = U->use_end(); I != E; ++I) 465 if (!isSafeSROAElementUse(*I)) 466 return false; 467 return true; 468 } 469 470 /// GlobalUsersSafeToSRA - Look at all uses of the global and decide whether it 471 /// is safe for us to perform this transformation. 472 /// 473 static bool GlobalUsersSafeToSRA(GlobalValue *GV) { 474 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); 475 UI != E; ++UI) { 476 if (!IsUserOfGlobalSafeForSRA(*UI, GV)) 477 return false; 478 } 479 return true; 480 } 481 482 483 /// SRAGlobal - Perform scalar replacement of aggregates on the specified global 484 /// variable. This opens the door for other optimizations by exposing the 485 /// behavior of the program in a more fine-grained way. We have determined that 486 /// this transformation is safe already. We return the first global variable we 487 /// insert so that the caller can reprocess it. 488 static GlobalVariable *SRAGlobal(GlobalVariable *GV, const TargetData &TD) { 489 // Make sure this global only has simple uses that we can SRA. 490 if (!GlobalUsersSafeToSRA(GV)) 491 return 0; 492 493 assert(GV->hasLocalLinkage() && !GV->isConstant()); 494 Constant *Init = GV->getInitializer(); 495 Type *Ty = Init->getType(); 496 497 std::vector<GlobalVariable*> NewGlobals; 498 Module::GlobalListType &Globals = GV->getParent()->getGlobalList(); 499 500 // Get the alignment of the global, either explicit or target-specific. 501 unsigned StartAlignment = GV->getAlignment(); 502 if (StartAlignment == 0) 503 StartAlignment = TD.getABITypeAlignment(GV->getType()); 504 505 if (StructType *STy = dyn_cast<StructType>(Ty)) { 506 NewGlobals.reserve(STy->getNumElements()); 507 const StructLayout &Layout = *TD.getStructLayout(STy); 508 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) { 509 Constant *In = Init->getAggregateElement(i); 510 assert(In && "Couldn't get element of initializer?"); 511 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(i), false, 512 GlobalVariable::InternalLinkage, 513 In, GV->getName()+"."+Twine(i), 514 GV->isThreadLocal(), 515 GV->getType()->getAddressSpace()); 516 Globals.insert(GV, NGV); 517 NewGlobals.push_back(NGV); 518 519 // Calculate the known alignment of the field. If the original aggregate 520 // had 256 byte alignment for example, something might depend on that: 521 // propagate info to each field. 522 uint64_t FieldOffset = Layout.getElementOffset(i); 523 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, FieldOffset); 524 if (NewAlign > TD.getABITypeAlignment(STy->getElementType(i))) 525 NGV->setAlignment(NewAlign); 526 } 527 } else if (SequentialType *STy = dyn_cast<SequentialType>(Ty)) { 528 unsigned NumElements = 0; 529 if (ArrayType *ATy = dyn_cast<ArrayType>(STy)) 530 NumElements = ATy->getNumElements(); 531 else 532 NumElements = cast<VectorType>(STy)->getNumElements(); 533 534 if (NumElements > 16 && GV->hasNUsesOrMore(16)) 535 return 0; // It's not worth it. 536 NewGlobals.reserve(NumElements); 537 538 uint64_t EltSize = TD.getTypeAllocSize(STy->getElementType()); 539 unsigned EltAlign = TD.getABITypeAlignment(STy->getElementType()); 540 for (unsigned i = 0, e = NumElements; i != e; ++i) { 541 Constant *In = Init->getAggregateElement(i); 542 assert(In && "Couldn't get element of initializer?"); 543 544 GlobalVariable *NGV = new GlobalVariable(STy->getElementType(), false, 545 GlobalVariable::InternalLinkage, 546 In, GV->getName()+"."+Twine(i), 547 GV->isThreadLocal(), 548 GV->getType()->getAddressSpace()); 549 Globals.insert(GV, NGV); 550 NewGlobals.push_back(NGV); 551 552 // Calculate the known alignment of the field. If the original aggregate 553 // had 256 byte alignment for example, something might depend on that: 554 // propagate info to each field. 555 unsigned NewAlign = (unsigned)MinAlign(StartAlignment, EltSize*i); 556 if (NewAlign > EltAlign) 557 NGV->setAlignment(NewAlign); 558 } 559 } 560 561 if (NewGlobals.empty()) 562 return 0; 563 564 DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV); 565 566 Constant *NullInt =Constant::getNullValue(Type::getInt32Ty(GV->getContext())); 567 568 // Loop over all of the uses of the global, replacing the constantexpr geps, 569 // with smaller constantexpr geps or direct references. 570 while (!GV->use_empty()) { 571 User *GEP = GV->use_back(); 572 assert(((isa<ConstantExpr>(GEP) && 573 cast<ConstantExpr>(GEP)->getOpcode()==Instruction::GetElementPtr)|| 574 isa<GetElementPtrInst>(GEP)) && "NonGEP CE's are not SRAable!"); 575 576 // Ignore the 1th operand, which has to be zero or else the program is quite 577 // broken (undefined). Get the 2nd operand, which is the structure or array 578 // index. 579 unsigned Val = cast<ConstantInt>(GEP->getOperand(2))->getZExtValue(); 580 if (Val >= NewGlobals.size()) Val = 0; // Out of bound array access. 581 582 Value *NewPtr = NewGlobals[Val]; 583 584 // Form a shorter GEP if needed. 585 if (GEP->getNumOperands() > 3) { 586 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GEP)) { 587 SmallVector<Constant*, 8> Idxs; 588 Idxs.push_back(NullInt); 589 for (unsigned i = 3, e = CE->getNumOperands(); i != e; ++i) 590 Idxs.push_back(CE->getOperand(i)); 591 NewPtr = ConstantExpr::getGetElementPtr(cast<Constant>(NewPtr), Idxs); 592 } else { 593 GetElementPtrInst *GEPI = cast<GetElementPtrInst>(GEP); 594 SmallVector<Value*, 8> Idxs; 595 Idxs.push_back(NullInt); 596 for (unsigned i = 3, e = GEPI->getNumOperands(); i != e; ++i) 597 Idxs.push_back(GEPI->getOperand(i)); 598 NewPtr = GetElementPtrInst::Create(NewPtr, Idxs, 599 GEPI->getName()+"."+Twine(Val),GEPI); 600 } 601 } 602 GEP->replaceAllUsesWith(NewPtr); 603 604 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(GEP)) 605 GEPI->eraseFromParent(); 606 else 607 cast<ConstantExpr>(GEP)->destroyConstant(); 608 } 609 610 // Delete the old global, now that it is dead. 611 Globals.erase(GV); 612 ++NumSRA; 613 614 // Loop over the new globals array deleting any globals that are obviously 615 // dead. This can arise due to scalarization of a structure or an array that 616 // has elements that are dead. 617 unsigned FirstGlobal = 0; 618 for (unsigned i = 0, e = NewGlobals.size(); i != e; ++i) 619 if (NewGlobals[i]->use_empty()) { 620 Globals.erase(NewGlobals[i]); 621 if (FirstGlobal == i) ++FirstGlobal; 622 } 623 624 return FirstGlobal != NewGlobals.size() ? NewGlobals[FirstGlobal] : 0; 625 } 626 627 /// AllUsesOfValueWillTrapIfNull - Return true if all users of the specified 628 /// value will trap if the value is dynamically null. PHIs keeps track of any 629 /// phi nodes we've seen to avoid reprocessing them. 630 static bool AllUsesOfValueWillTrapIfNull(const Value *V, 631 SmallPtrSet<const PHINode*, 8> &PHIs) { 632 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; 633 ++UI) { 634 const User *U = *UI; 635 636 if (isa<LoadInst>(U)) { 637 // Will trap. 638 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) { 639 if (SI->getOperand(0) == V) { 640 //cerr << "NONTRAPPING USE: " << *U; 641 return false; // Storing the value. 642 } 643 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) { 644 if (CI->getCalledValue() != V) { 645 //cerr << "NONTRAPPING USE: " << *U; 646 return false; // Not calling the ptr 647 } 648 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) { 649 if (II->getCalledValue() != V) { 650 //cerr << "NONTRAPPING USE: " << *U; 651 return false; // Not calling the ptr 652 } 653 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) { 654 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false; 655 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) { 656 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false; 657 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) { 658 // If we've already seen this phi node, ignore it, it has already been 659 // checked. 660 if (PHIs.insert(PN) && !AllUsesOfValueWillTrapIfNull(PN, PHIs)) 661 return false; 662 } else if (isa<ICmpInst>(U) && 663 isa<ConstantPointerNull>(UI->getOperand(1))) { 664 // Ignore icmp X, null 665 } else { 666 //cerr << "NONTRAPPING USE: " << *U; 667 return false; 668 } 669 } 670 return true; 671 } 672 673 /// AllUsesOfLoadedValueWillTrapIfNull - Return true if all uses of any loads 674 /// from GV will trap if the loaded value is null. Note that this also permits 675 /// comparisons of the loaded value against null, as a special case. 676 static bool AllUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) { 677 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end(); 678 UI != E; ++UI) { 679 const User *U = *UI; 680 681 if (const LoadInst *LI = dyn_cast<LoadInst>(U)) { 682 SmallPtrSet<const PHINode*, 8> PHIs; 683 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs)) 684 return false; 685 } else if (isa<StoreInst>(U)) { 686 // Ignore stores to the global. 687 } else { 688 // We don't know or understand this user, bail out. 689 //cerr << "UNKNOWN USER OF GLOBAL!: " << *U; 690 return false; 691 } 692 } 693 return true; 694 } 695 696 static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) { 697 bool Changed = false; 698 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) { 699 Instruction *I = cast<Instruction>(*UI++); 700 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 701 LI->setOperand(0, NewV); 702 Changed = true; 703 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) { 704 if (SI->getOperand(1) == V) { 705 SI->setOperand(1, NewV); 706 Changed = true; 707 } 708 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) { 709 CallSite CS(I); 710 if (CS.getCalledValue() == V) { 711 // Calling through the pointer! Turn into a direct call, but be careful 712 // that the pointer is not also being passed as an argument. 713 CS.setCalledFunction(NewV); 714 Changed = true; 715 bool PassedAsArg = false; 716 for (unsigned i = 0, e = CS.arg_size(); i != e; ++i) 717 if (CS.getArgument(i) == V) { 718 PassedAsArg = true; 719 CS.setArgument(i, NewV); 720 } 721 722 if (PassedAsArg) { 723 // Being passed as an argument also. Be careful to not invalidate UI! 724 UI = V->use_begin(); 725 } 726 } 727 } else if (CastInst *CI = dyn_cast<CastInst>(I)) { 728 Changed |= OptimizeAwayTrappingUsesOfValue(CI, 729 ConstantExpr::getCast(CI->getOpcode(), 730 NewV, CI->getType())); 731 if (CI->use_empty()) { 732 Changed = true; 733 CI->eraseFromParent(); 734 } 735 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) { 736 // Should handle GEP here. 737 SmallVector<Constant*, 8> Idxs; 738 Idxs.reserve(GEPI->getNumOperands()-1); 739 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end(); 740 i != e; ++i) 741 if (Constant *C = dyn_cast<Constant>(*i)) 742 Idxs.push_back(C); 743 else 744 break; 745 if (Idxs.size() == GEPI->getNumOperands()-1) 746 Changed |= OptimizeAwayTrappingUsesOfValue(GEPI, 747 ConstantExpr::getGetElementPtr(NewV, Idxs)); 748 if (GEPI->use_empty()) { 749 Changed = true; 750 GEPI->eraseFromParent(); 751 } 752 } 753 } 754 755 return Changed; 756 } 757 758 759 /// OptimizeAwayTrappingUsesOfLoads - The specified global has only one non-null 760 /// value stored into it. If there are uses of the loaded value that would trap 761 /// if the loaded value is dynamically null, then we know that they cannot be 762 /// reachable with a null optimize away the load. 763 static bool OptimizeAwayTrappingUsesOfLoads(GlobalVariable *GV, Constant *LV, 764 TargetData *TD, 765 TargetLibraryInfo *TLI) { 766 bool Changed = false; 767 768 // Keep track of whether we are able to remove all the uses of the global 769 // other than the store that defines it. 770 bool AllNonStoreUsesGone = true; 771 772 // Replace all uses of loads with uses of uses of the stored value. 773 for (Value::use_iterator GUI = GV->use_begin(), E = GV->use_end(); GUI != E;){ 774 User *GlobalUser = *GUI++; 775 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) { 776 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV); 777 // If we were able to delete all uses of the loads 778 if (LI->use_empty()) { 779 LI->eraseFromParent(); 780 Changed = true; 781 } else { 782 AllNonStoreUsesGone = false; 783 } 784 } else if (isa<StoreInst>(GlobalUser)) { 785 // Ignore the store that stores "LV" to the global. 786 assert(GlobalUser->getOperand(1) == GV && 787 "Must be storing *to* the global"); 788 } else { 789 AllNonStoreUsesGone = false; 790 791 // If we get here we could have other crazy uses that are transitively 792 // loaded. 793 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) || 794 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser)) && 795 "Only expect load and stores!"); 796 } 797 } 798 799 if (Changed) { 800 DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV); 801 ++NumGlobUses; 802 } 803 804 // If we nuked all of the loads, then none of the stores are needed either, 805 // nor is the global. 806 if (AllNonStoreUsesGone) { 807 DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n"); 808 CleanupConstantGlobalUsers(GV, 0, TD, TLI); 809 if (GV->use_empty()) { 810 GV->eraseFromParent(); 811 ++NumDeleted; 812 } 813 Changed = true; 814 } 815 return Changed; 816 } 817 818 /// ConstantPropUsersOf - Walk the use list of V, constant folding all of the 819 /// instructions that are foldable. 820 static void ConstantPropUsersOf(Value *V, 821 TargetData *TD, TargetLibraryInfo *TLI) { 822 for (Value::use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; ) 823 if (Instruction *I = dyn_cast<Instruction>(*UI++)) 824 if (Constant *NewC = ConstantFoldInstruction(I, TD, TLI)) { 825 I->replaceAllUsesWith(NewC); 826 827 // Advance UI to the next non-I use to avoid invalidating it! 828 // Instructions could multiply use V. 829 while (UI != E && *UI == I) 830 ++UI; 831 I->eraseFromParent(); 832 } 833 } 834 835 /// OptimizeGlobalAddressOfMalloc - This function takes the specified global 836 /// variable, and transforms the program as if it always contained the result of 837 /// the specified malloc. Because it is always the result of the specified 838 /// malloc, there is no reason to actually DO the malloc. Instead, turn the 839 /// malloc into a global, and any loads of GV as uses of the new global. 840 static GlobalVariable *OptimizeGlobalAddressOfMalloc(GlobalVariable *GV, 841 CallInst *CI, 842 Type *AllocTy, 843 ConstantInt *NElements, 844 TargetData *TD, 845 TargetLibraryInfo *TLI) { 846 DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI << '\n'); 847 848 Type *GlobalType; 849 if (NElements->getZExtValue() == 1) 850 GlobalType = AllocTy; 851 else 852 // If we have an array allocation, the global variable is of an array. 853 GlobalType = ArrayType::get(AllocTy, NElements->getZExtValue()); 854 855 // Create the new global variable. The contents of the malloc'd memory is 856 // undefined, so initialize with an undef value. 857 GlobalVariable *NewGV = new GlobalVariable(*GV->getParent(), 858 GlobalType, false, 859 GlobalValue::InternalLinkage, 860 UndefValue::get(GlobalType), 861 GV->getName()+".body", 862 GV, 863 GV->isThreadLocal()); 864 865 // If there are bitcast users of the malloc (which is typical, usually we have 866 // a malloc + bitcast) then replace them with uses of the new global. Update 867 // other users to use the global as well. 868 BitCastInst *TheBC = 0; 869 while (!CI->use_empty()) { 870 Instruction *User = cast<Instruction>(CI->use_back()); 871 if (BitCastInst *BCI = dyn_cast<BitCastInst>(User)) { 872 if (BCI->getType() == NewGV->getType()) { 873 BCI->replaceAllUsesWith(NewGV); 874 BCI->eraseFromParent(); 875 } else { 876 BCI->setOperand(0, NewGV); 877 } 878 } else { 879 if (TheBC == 0) 880 TheBC = new BitCastInst(NewGV, CI->getType(), "newgv", CI); 881 User->replaceUsesOfWith(CI, TheBC); 882 } 883 } 884 885 Constant *RepValue = NewGV; 886 if (NewGV->getType() != GV->getType()->getElementType()) 887 RepValue = ConstantExpr::getBitCast(RepValue, 888 GV->getType()->getElementType()); 889 890 // If there is a comparison against null, we will insert a global bool to 891 // keep track of whether the global was initialized yet or not. 892 GlobalVariable *InitBool = 893 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false, 894 GlobalValue::InternalLinkage, 895 ConstantInt::getFalse(GV->getContext()), 896 GV->getName()+".init", GV->isThreadLocal()); 897 bool InitBoolUsed = false; 898 899 // Loop over all uses of GV, processing them in turn. 900 while (!GV->use_empty()) { 901 if (StoreInst *SI = dyn_cast<StoreInst>(GV->use_back())) { 902 // The global is initialized when the store to it occurs. 903 new StoreInst(ConstantInt::getTrue(GV->getContext()), InitBool, false, 0, 904 SI->getOrdering(), SI->getSynchScope(), SI); 905 SI->eraseFromParent(); 906 continue; 907 } 908 909 LoadInst *LI = cast<LoadInst>(GV->use_back()); 910 while (!LI->use_empty()) { 911 Use &LoadUse = LI->use_begin().getUse(); 912 if (!isa<ICmpInst>(LoadUse.getUser())) { 913 LoadUse = RepValue; 914 continue; 915 } 916 917 ICmpInst *ICI = cast<ICmpInst>(LoadUse.getUser()); 918 // Replace the cmp X, 0 with a use of the bool value. 919 // Sink the load to where the compare was, if atomic rules allow us to. 920 Value *LV = new LoadInst(InitBool, InitBool->getName()+".val", false, 0, 921 LI->getOrdering(), LI->getSynchScope(), 922 LI->isUnordered() ? (Instruction*)ICI : LI); 923 InitBoolUsed = true; 924 switch (ICI->getPredicate()) { 925 default: llvm_unreachable("Unknown ICmp Predicate!"); 926 case ICmpInst::ICMP_ULT: 927 case ICmpInst::ICMP_SLT: // X < null -> always false 928 LV = ConstantInt::getFalse(GV->getContext()); 929 break; 930 case ICmpInst::ICMP_ULE: 931 case ICmpInst::ICMP_SLE: 932 case ICmpInst::ICMP_EQ: 933 LV = BinaryOperator::CreateNot(LV, "notinit", ICI); 934 break; 935 case ICmpInst::ICMP_NE: 936 case ICmpInst::ICMP_UGE: 937 case ICmpInst::ICMP_SGE: 938 case ICmpInst::ICMP_UGT: 939 case ICmpInst::ICMP_SGT: 940 break; // no change. 941 } 942 ICI->replaceAllUsesWith(LV); 943 ICI->eraseFromParent(); 944 } 945 LI->eraseFromParent(); 946 } 947 948 // If the initialization boolean was used, insert it, otherwise delete it. 949 if (!InitBoolUsed) { 950 while (!InitBool->use_empty()) // Delete initializations 951 cast<StoreInst>(InitBool->use_back())->eraseFromParent(); 952 delete InitBool; 953 } else 954 GV->getParent()->getGlobalList().insert(GV, InitBool); 955 956 // Now the GV is dead, nuke it and the malloc.. 957 GV->eraseFromParent(); 958 CI->eraseFromParent(); 959 960 // To further other optimizations, loop over all users of NewGV and try to 961 // constant prop them. This will promote GEP instructions with constant 962 // indices into GEP constant-exprs, which will allow global-opt to hack on it. 963 ConstantPropUsersOf(NewGV, TD, TLI); 964 if (RepValue != NewGV) 965 ConstantPropUsersOf(RepValue, TD, TLI); 966 967 return NewGV; 968 } 969 970 /// ValueIsOnlyUsedLocallyOrStoredToOneGlobal - Scan the use-list of V checking 971 /// to make sure that there are no complex uses of V. We permit simple things 972 /// like dereferencing the pointer, but not storing through the address, unless 973 /// it is to the specified global. 974 static bool ValueIsOnlyUsedLocallyOrStoredToOneGlobal(const Instruction *V, 975 const GlobalVariable *GV, 976 SmallPtrSet<const PHINode*, 8> &PHIs) { 977 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); 978 UI != E; ++UI) { 979 const Instruction *Inst = cast<Instruction>(*UI); 980 981 if (isa<LoadInst>(Inst) || isa<CmpInst>(Inst)) { 982 continue; // Fine, ignore. 983 } 984 985 if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) { 986 if (SI->getOperand(0) == V && SI->getOperand(1) != GV) 987 return false; // Storing the pointer itself... bad. 988 continue; // Otherwise, storing through it, or storing into GV... fine. 989 } 990 991 // Must index into the array and into the struct. 992 if (isa<GetElementPtrInst>(Inst) && Inst->getNumOperands() >= 3) { 993 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(Inst, GV, PHIs)) 994 return false; 995 continue; 996 } 997 998 if (const PHINode *PN = dyn_cast<PHINode>(Inst)) { 999 // PHIs are ok if all uses are ok. Don't infinitely recurse through PHI 1000 // cycles. 1001 if (PHIs.insert(PN)) 1002 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(PN, GV, PHIs)) 1003 return false; 1004 continue; 1005 } 1006 1007 if (const BitCastInst *BCI = dyn_cast<BitCastInst>(Inst)) { 1008 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(BCI, GV, PHIs)) 1009 return false; 1010 continue; 1011 } 1012 1013 return false; 1014 } 1015 return true; 1016 } 1017 1018 /// ReplaceUsesOfMallocWithGlobal - The Alloc pointer is stored into GV 1019 /// somewhere. Transform all uses of the allocation into loads from the 1020 /// global and uses of the resultant pointer. Further, delete the store into 1021 /// GV. This assumes that these value pass the 1022 /// 'ValueIsOnlyUsedLocallyOrStoredToOneGlobal' predicate. 1023 static void ReplaceUsesOfMallocWithGlobal(Instruction *Alloc, 1024 GlobalVariable *GV) { 1025 while (!Alloc->use_empty()) { 1026 Instruction *U = cast<Instruction>(*Alloc->use_begin()); 1027 Instruction *InsertPt = U; 1028 if (StoreInst *SI = dyn_cast<StoreInst>(U)) { 1029 // If this is the store of the allocation into the global, remove it. 1030 if (SI->getOperand(1) == GV) { 1031 SI->eraseFromParent(); 1032 continue; 1033 } 1034 } else if (PHINode *PN = dyn_cast<PHINode>(U)) { 1035 // Insert the load in the corresponding predecessor, not right before the 1036 // PHI. 1037 InsertPt = PN->getIncomingBlock(Alloc->use_begin())->getTerminator(); 1038 } else if (isa<BitCastInst>(U)) { 1039 // Must be bitcast between the malloc and store to initialize the global. 1040 ReplaceUsesOfMallocWithGlobal(U, GV); 1041 U->eraseFromParent(); 1042 continue; 1043 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) { 1044 // If this is a "GEP bitcast" and the user is a store to the global, then 1045 // just process it as a bitcast. 1046 if (GEPI->hasAllZeroIndices() && GEPI->hasOneUse()) 1047 if (StoreInst *SI = dyn_cast<StoreInst>(GEPI->use_back())) 1048 if (SI->getOperand(1) == GV) { 1049 // Must be bitcast GEP between the malloc and store to initialize 1050 // the global. 1051 ReplaceUsesOfMallocWithGlobal(GEPI, GV); 1052 GEPI->eraseFromParent(); 1053 continue; 1054 } 1055 } 1056 1057 // Insert a load from the global, and use it instead of the malloc. 1058 Value *NL = new LoadInst(GV, GV->getName()+".val", InsertPt); 1059 U->replaceUsesOfWith(Alloc, NL); 1060 } 1061 } 1062 1063 /// LoadUsesSimpleEnoughForHeapSRA - Verify that all uses of V (a load, or a phi 1064 /// of a load) are simple enough to perform heap SRA on. This permits GEP's 1065 /// that index through the array and struct field, icmps of null, and PHIs. 1066 static bool LoadUsesSimpleEnoughForHeapSRA(const Value *V, 1067 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIs, 1068 SmallPtrSet<const PHINode*, 32> &LoadUsingPHIsPerLoad) { 1069 // We permit two users of the load: setcc comparing against the null 1070 // pointer, and a getelementptr of a specific form. 1071 for (Value::const_use_iterator UI = V->use_begin(), E = V->use_end(); UI != E; 1072 ++UI) { 1073 const Instruction *User = cast<Instruction>(*UI); 1074 1075 // Comparison against null is ok. 1076 if (const ICmpInst *ICI = dyn_cast<ICmpInst>(User)) { 1077 if (!isa<ConstantPointerNull>(ICI->getOperand(1))) 1078 return false; 1079 continue; 1080 } 1081 1082 // getelementptr is also ok, but only a simple form. 1083 if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) { 1084 // Must index into the array and into the struct. 1085 if (GEPI->getNumOperands() < 3) 1086 return false; 1087 1088 // Otherwise the GEP is ok. 1089 continue; 1090 } 1091 1092 if (const PHINode *PN = dyn_cast<PHINode>(User)) { 1093 if (!LoadUsingPHIsPerLoad.insert(PN)) 1094 // This means some phi nodes are dependent on each other. 1095 // Avoid infinite looping! 1096 return false; 1097 if (!LoadUsingPHIs.insert(PN)) 1098 // If we have already analyzed this PHI, then it is safe. 1099 continue; 1100 1101 // Make sure all uses of the PHI are simple enough to transform. 1102 if (!LoadUsesSimpleEnoughForHeapSRA(PN, 1103 LoadUsingPHIs, LoadUsingPHIsPerLoad)) 1104 return false; 1105 1106 continue; 1107 } 1108 1109 // Otherwise we don't know what this is, not ok. 1110 return false; 1111 } 1112 1113 return true; 1114 } 1115 1116 1117 /// AllGlobalLoadUsesSimpleEnoughForHeapSRA - If all users of values loaded from 1118 /// GV are simple enough to perform HeapSRA, return true. 1119 static bool AllGlobalLoadUsesSimpleEnoughForHeapSRA(const GlobalVariable *GV, 1120 Instruction *StoredVal) { 1121 SmallPtrSet<const PHINode*, 32> LoadUsingPHIs; 1122 SmallPtrSet<const PHINode*, 32> LoadUsingPHIsPerLoad; 1123 for (Value::const_use_iterator UI = GV->use_begin(), E = GV->use_end(); 1124 UI != E; ++UI) 1125 if (const LoadInst *LI = dyn_cast<LoadInst>(*UI)) { 1126 if (!LoadUsesSimpleEnoughForHeapSRA(LI, LoadUsingPHIs, 1127 LoadUsingPHIsPerLoad)) 1128 return false; 1129 LoadUsingPHIsPerLoad.clear(); 1130 } 1131 1132 // If we reach here, we know that all uses of the loads and transitive uses 1133 // (through PHI nodes) are simple enough to transform. However, we don't know 1134 // that all inputs the to the PHI nodes are in the same equivalence sets. 1135 // Check to verify that all operands of the PHIs are either PHIS that can be 1136 // transformed, loads from GV, or MI itself. 1137 for (SmallPtrSet<const PHINode*, 32>::const_iterator I = LoadUsingPHIs.begin() 1138 , E = LoadUsingPHIs.end(); I != E; ++I) { 1139 const PHINode *PN = *I; 1140 for (unsigned op = 0, e = PN->getNumIncomingValues(); op != e; ++op) { 1141 Value *InVal = PN->getIncomingValue(op); 1142 1143 // PHI of the stored value itself is ok. 1144 if (InVal == StoredVal) continue; 1145 1146 if (const PHINode *InPN = dyn_cast<PHINode>(InVal)) { 1147 // One of the PHIs in our set is (optimistically) ok. 1148 if (LoadUsingPHIs.count(InPN)) 1149 continue; 1150 return false; 1151 } 1152 1153 // Load from GV is ok. 1154 if (const LoadInst *LI = dyn_cast<LoadInst>(InVal)) 1155 if (LI->getOperand(0) == GV) 1156 continue; 1157 1158 // UNDEF? NULL? 1159 1160 // Anything else is rejected. 1161 return false; 1162 } 1163 } 1164 1165 return true; 1166 } 1167 1168 static Value *GetHeapSROAValue(Value *V, unsigned FieldNo, 1169 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues, 1170 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) { 1171 std::vector<Value*> &FieldVals = InsertedScalarizedValues[V]; 1172 1173 if (FieldNo >= FieldVals.size()) 1174 FieldVals.resize(FieldNo+1); 1175 1176 // If we already have this value, just reuse the previously scalarized 1177 // version. 1178 if (Value *FieldVal = FieldVals[FieldNo]) 1179 return FieldVal; 1180 1181 // Depending on what instruction this is, we have several cases. 1182 Value *Result; 1183 if (LoadInst *LI = dyn_cast<LoadInst>(V)) { 1184 // This is a scalarized version of the load from the global. Just create 1185 // a new Load of the scalarized global. 1186 Result = new LoadInst(GetHeapSROAValue(LI->getOperand(0), FieldNo, 1187 InsertedScalarizedValues, 1188 PHIsToRewrite), 1189 LI->getName()+".f"+Twine(FieldNo), LI); 1190 } else if (PHINode *PN = dyn_cast<PHINode>(V)) { 1191 // PN's type is pointer to struct. Make a new PHI of pointer to struct 1192 // field. 1193 StructType *ST = 1194 cast<StructType>(cast<PointerType>(PN->getType())->getElementType()); 1195 1196 PHINode *NewPN = 1197 PHINode::Create(PointerType::getUnqual(ST->getElementType(FieldNo)), 1198 PN->getNumIncomingValues(), 1199 PN->getName()+".f"+Twine(FieldNo), PN); 1200 Result = NewPN; 1201 PHIsToRewrite.push_back(std::make_pair(PN, FieldNo)); 1202 } else { 1203 llvm_unreachable("Unknown usable value"); 1204 } 1205 1206 return FieldVals[FieldNo] = Result; 1207 } 1208 1209 /// RewriteHeapSROALoadUser - Given a load instruction and a value derived from 1210 /// the load, rewrite the derived value to use the HeapSRoA'd load. 1211 static void RewriteHeapSROALoadUser(Instruction *LoadUser, 1212 DenseMap<Value*, std::vector<Value*> > &InsertedScalarizedValues, 1213 std::vector<std::pair<PHINode*, unsigned> > &PHIsToRewrite) { 1214 // If this is a comparison against null, handle it. 1215 if (ICmpInst *SCI = dyn_cast<ICmpInst>(LoadUser)) { 1216 assert(isa<ConstantPointerNull>(SCI->getOperand(1))); 1217 // If we have a setcc of the loaded pointer, we can use a setcc of any 1218 // field. 1219 Value *NPtr = GetHeapSROAValue(SCI->getOperand(0), 0, 1220 InsertedScalarizedValues, PHIsToRewrite); 1221 1222 Value *New = new ICmpInst(SCI, SCI->getPredicate(), NPtr, 1223 Constant::getNullValue(NPtr->getType()), 1224 SCI->getName()); 1225 SCI->replaceAllUsesWith(New); 1226 SCI->eraseFromParent(); 1227 return; 1228 } 1229 1230 // Handle 'getelementptr Ptr, Idx, i32 FieldNo ...' 1231 if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(LoadUser)) { 1232 assert(GEPI->getNumOperands() >= 3 && isa<ConstantInt>(GEPI->getOperand(2)) 1233 && "Unexpected GEPI!"); 1234 1235 // Load the pointer for this field. 1236 unsigned FieldNo = cast<ConstantInt>(GEPI->getOperand(2))->getZExtValue(); 1237 Value *NewPtr = GetHeapSROAValue(GEPI->getOperand(0), FieldNo, 1238 InsertedScalarizedValues, PHIsToRewrite); 1239 1240 // Create the new GEP idx vector. 1241 SmallVector<Value*, 8> GEPIdx; 1242 GEPIdx.push_back(GEPI->getOperand(1)); 1243 GEPIdx.append(GEPI->op_begin()+3, GEPI->op_end()); 1244 1245 Value *NGEPI = GetElementPtrInst::Create(NewPtr, GEPIdx, 1246 GEPI->getName(), GEPI); 1247 GEPI->replaceAllUsesWith(NGEPI); 1248 GEPI->eraseFromParent(); 1249 return; 1250 } 1251 1252 // Recursively transform the users of PHI nodes. This will lazily create the 1253 // PHIs that are needed for individual elements. Keep track of what PHIs we 1254 // see in InsertedScalarizedValues so that we don't get infinite loops (very 1255 // antisocial). If the PHI is already in InsertedScalarizedValues, it has 1256 // already been seen first by another load, so its uses have already been 1257 // processed. 1258 PHINode *PN = cast<PHINode>(LoadUser); 1259 if (!InsertedScalarizedValues.insert(std::make_pair(PN, 1260 std::vector<Value*>())).second) 1261 return; 1262 1263 // If this is the first time we've seen this PHI, recursively process all 1264 // users. 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); 1268 } 1269 } 1270 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(); 1279 UI != E; ) { 1280 Instruction *User = cast<Instruction>(*UI++); 1281 RewriteHeapSROALoadUser(User, InsertedScalarizedValues, PHIsToRewrite); 1282 } 1283 1284 if (Load->use_empty()) { 1285 Load->eraseFromParent(); 1286 InsertedScalarizedValues.erase(Load); 1287 } 1288 } 1289 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 Type *MAT = getMallocAllocatedType(CI); 1296 StructType *STy = cast<StructType>(MAT); 1297 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 1301 // into GV. 1302 ReplaceUsesOfMallocWithGlobal(CI, GV); 1303 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; 1308 1309 for (unsigned FieldNo = 0, e = STy->getNumElements(); FieldNo != e;++FieldNo){ 1310 Type *FieldTy = STy->getElementType(FieldNo); 1311 PointerType *PFieldTy = PointerType::getUnqual(FieldTy); 1312 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); 1320 1321 unsigned TypeSize = TD->getTypeAllocSize(FieldTy); 1322 if (StructType *ST = dyn_cast<StructType>(FieldTy)) 1323 TypeSize = TD->getStructLayout(ST)->getSizeInBytes(); 1324 Type *IntPtrTy = TD->getIntPtrType(CI->getContext()); 1325 Value *NMI = CallInst::CreateMalloc(CI, IntPtrTy, FieldTy, 1326 ConstantInt::get(IntPtrTy, TypeSize), 1327 NElems, 0, 1328 CI->getName() + ".f" + Twine(FieldNo)); 1329 FieldMallocs.push_back(NMI); 1330 new StoreInst(NMI, NGV, CI); 1331 } 1332 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; } 1344 // } 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()), 1352 "isnull"); 1353 RunningOr = BinaryOperator::CreateOr(RunningOr, Cond, "tmp", CI); 1354 } 1355 1356 // Split the basic block at the old malloc. 1357 BasicBlock *OrigBB = CI->getParent(); 1358 BasicBlock *ContBB = OrigBB->splitBasicBlock(CI, "malloc_cont"); 1359 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(), 1363 "malloc_ret_null", 1364 OrigBB->getParent()); 1365 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); 1370 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())); 1377 BasicBlock *FreeBlock = BasicBlock::Create(Cmp->getContext(), "free_it", 1378 OrigBB->getParent()); 1379 BasicBlock *NextBlock = BasicBlock::Create(Cmp->getContext(), "next", 1380 OrigBB->getParent()); 1381 Instruction *BI = BranchInst::Create(FreeBlock, NextBlock, 1382 Cmp, NullPtrBlock); 1383 1384 // Fill in FreeBlock. 1385 CallInst::CreateFree(GVVal, BI); 1386 new StoreInst(Constant::getNullValue(GVVal->getType()), FieldGlobals[i], 1387 FreeBlock); 1388 BranchInst::Create(NextBlock, FreeBlock); 1389 1390 NullPtrBlock = NextBlock; 1391 } 1392 1393 BranchInst::Create(ContBB, NullPtrBlock); 1394 1395 // CI is no longer needed, remove it. 1396 CI->eraseFromParent(); 1397 1398 /// InsertedScalarizedLoads - As we process loads, if we can't immediately 1399 /// update all uses of the load, keep track of what scalarized loads are 1400 /// inserted for a given load. 1401 DenseMap<Value*, std::vector<Value*> > InsertedScalarizedValues; 1402 InsertedScalarizedValues[GV] = FieldGlobals; 1403 1404 std::vector<std::pair<PHINode*, unsigned> > PHIsToRewrite; 1405 1406 // Okay, the malloc site is completely handled. All of the uses of GV are now 1407 // loads, and all uses of those loads are simple. Rewrite them to use loads 1408 // of the per-field globals instead. 1409 for (Value::use_iterator UI = GV->use_begin(), E = GV->use_end(); UI != E;) { 1410 Instruction *User = cast<Instruction>(*UI++); 1411 1412 if (LoadInst *LI = dyn_cast<LoadInst>(User)) { 1413 RewriteUsesOfLoadForHeapSRoA(LI, InsertedScalarizedValues, PHIsToRewrite); 1414 continue; 1415 } 1416 1417 // Must be a store of null. 1418 StoreInst *SI = cast<StoreInst>(User); 1419 assert(isa<ConstantPointerNull>(SI->getOperand(0)) && 1420 "Unexpected heap-sra user!"); 1421 1422 // Insert a store of null into each global. 1423 for (unsigned i = 0, e = FieldGlobals.size(); i != e; ++i) { 1424 PointerType *PT = cast<PointerType>(FieldGlobals[i]->getType()); 1425 Constant *Null = Constant::getNullValue(PT->getElementType()); 1426 new StoreInst(Null, FieldGlobals[i], SI); 1427 } 1428 // Erase the original store. 1429 SI->eraseFromParent(); 1430 } 1431 1432 // While we have PHIs that are interesting to rewrite, do it. 1433 while (!PHIsToRewrite.empty()) { 1434 PHINode *PN = PHIsToRewrite.back().first; 1435 unsigned FieldNo = PHIsToRewrite.back().second; 1436 PHIsToRewrite.pop_back(); 1437 PHINode *FieldPN = cast<PHINode>(InsertedScalarizedValues[PN][FieldNo]); 1438 assert(FieldPN->getNumIncomingValues() == 0 &&"Already processed this phi"); 1439 1440 // Add all the incoming values. This can materialize more phis. 1441 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) { 1442 Value *InVal = PN->getIncomingValue(i); 1443 InVal = GetHeapSROAValue(InVal, FieldNo, InsertedScalarizedValues, 1444 PHIsToRewrite); 1445 FieldPN->addIncoming(InVal, PN->getIncomingBlock(i)); 1446 } 1447 } 1448 1449 // Drop all inter-phi links and any loads that made it this far. 1450 for (DenseMap<Value*, std::vector<Value*> >::iterator 1451 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end(); 1452 I != E; ++I) { 1453 if (PHINode *PN = dyn_cast<PHINode>(I->first)) 1454 PN->dropAllReferences(); 1455 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first)) 1456 LI->dropAllReferences(); 1457 } 1458 1459 // Delete all the phis and loads now that inter-references are dead. 1460 for (DenseMap<Value*, std::vector<Value*> >::iterator 1461 I = InsertedScalarizedValues.begin(), E = InsertedScalarizedValues.end(); 1462 I != E; ++I) { 1463 if (PHINode *PN = dyn_cast<PHINode>(I->first)) 1464 PN->eraseFromParent(); 1465 else if (LoadInst *LI = dyn_cast<LoadInst>(I->first)) 1466 LI->eraseFromParent(); 1467 } 1468 1469 // The old global is now dead, remove it. 1470 GV->eraseFromParent(); 1471 1472 ++NumHeapSRA; 1473 return cast<GlobalVariable>(FieldGlobals[0]); 1474 } 1475 1476 /// TryToOptimizeStoreOfMallocToGlobal - This function is called when we see a 1477 /// pointer global variable with a single value stored it that is a malloc or 1478 /// cast of malloc. 1479 static bool TryToOptimizeStoreOfMallocToGlobal(GlobalVariable *GV, 1480 CallInst *CI, 1481 Type *AllocTy, 1482 AtomicOrdering Ordering, 1483 Module::global_iterator &GVI, 1484 TargetData *TD, 1485 TargetLibraryInfo *TLI) { 1486 if (!TD) 1487 return false; 1488 1489 // If this is a malloc of an abstract type, don't touch it. 1490 if (!AllocTy->isSized()) 1491 return false; 1492 1493 // We can't optimize this global unless all uses of it are *known* to be 1494 // of the malloc value, not of the null initializer value (consider a use 1495 // that compares the global's value against zero to see if the malloc has 1496 // been reached). To do this, we check to see if all uses of the global 1497 // would trap if the global were null: this proves that they must all 1498 // happen after the malloc. 1499 if (!AllUsesOfLoadedValueWillTrapIfNull(GV)) 1500 return false; 1501 1502 // We can't optimize this if the malloc itself is used in a complex way, 1503 // for example, being stored into multiple globals. This allows the 1504 // malloc to be stored into the specified global, loaded icmp'd, and 1505 // GEP'd. These are all things we could transform to using the global 1506 // for. 1507 SmallPtrSet<const PHINode*, 8> PHIs; 1508 if (!ValueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV, PHIs)) 1509 return false; 1510 1511 // If we have a global that is only initialized with a fixed size malloc, 1512 // transform the program to use global memory instead of malloc'd memory. 1513 // This eliminates dynamic allocation, avoids an indirection accessing the 1514 // data, and exposes the resultant global to further GlobalOpt. 1515 // We cannot optimize the malloc if we cannot determine malloc array size. 1516 Value *NElems = getMallocArraySize(CI, TD, true); 1517 if (!NElems) 1518 return false; 1519 1520 if (ConstantInt *NElements = dyn_cast<ConstantInt>(NElems)) 1521 // Restrict this transformation to only working on small allocations 1522 // (2048 bytes currently), as we don't want to introduce a 16M global or 1523 // something. 1524 if (NElements->getZExtValue() * TD->getTypeAllocSize(AllocTy) < 2048) { 1525 GVI = OptimizeGlobalAddressOfMalloc(GV, CI, AllocTy, NElements, TD, TLI); 1526 return true; 1527 } 1528 1529 // If the allocation is an array of structures, consider transforming this 1530 // into multiple malloc'd arrays, one for each field. This is basically 1531 // SRoA for malloc'd memory. 1532 1533 if (Ordering != NotAtomic) 1534 return false; 1535 1536 // If this is an allocation of a fixed size array of structs, analyze as a 1537 // variable size array. malloc [100 x struct],1 -> malloc struct, 100 1538 if (NElems == ConstantInt::get(CI->getArgOperand(0)->getType(), 1)) 1539 if (ArrayType *AT = dyn_cast<ArrayType>(AllocTy)) 1540 AllocTy = AT->getElementType(); 1541 1542 StructType *AllocSTy = dyn_cast<StructType>(AllocTy); 1543 if (!AllocSTy) 1544 return false; 1545 1546 // This the structure has an unreasonable number of fields, leave it 1547 // alone. 1548 if (AllocSTy->getNumElements() <= 16 && AllocSTy->getNumElements() != 0 && 1549 AllGlobalLoadUsesSimpleEnoughForHeapSRA(GV, CI)) { 1550 1551 // If this is a fixed size array, transform the Malloc to be an alloc of 1552 // structs. malloc [100 x struct],1 -> malloc struct, 100 1553 if (ArrayType *AT = dyn_cast<ArrayType>(getMallocAllocatedType(CI))) { 1554 Type *IntPtrTy = TD->getIntPtrType(CI->getContext()); 1555 unsigned TypeSize = TD->getStructLayout(AllocSTy)->getSizeInBytes(); 1556 Value *AllocSize = ConstantInt::get(IntPtrTy, TypeSize); 1557 Value *NumElements = ConstantInt::get(IntPtrTy, AT->getNumElements()); 1558 Instruction *Malloc = CallInst::CreateMalloc(CI, IntPtrTy, AllocSTy, 1559 AllocSize, NumElements, 1560 0, CI->getName()); 1561 Instruction *Cast = new BitCastInst(Malloc, CI->getType(), "tmp", CI); 1562 CI->replaceAllUsesWith(Cast); 1563 CI->eraseFromParent(); 1564 CI = dyn_cast<BitCastInst>(Malloc) ? 1565 extractMallocCallFromBitCast(Malloc) : cast<CallInst>(Malloc); 1566 } 1567 1568 GVI = PerformHeapAllocSRoA(GV, CI, getMallocArraySize(CI, TD, true), TD); 1569 return true; 1570 } 1571 1572 return false; 1573 } 1574 1575 // OptimizeOnceStoredGlobal - Try to optimize globals based on the knowledge 1576 // that only one value (besides its initializer) is ever stored to the global. 1577 static bool OptimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal, 1578 AtomicOrdering Ordering, 1579 Module::global_iterator &GVI, 1580 TargetData *TD, TargetLibraryInfo *TLI) { 1581 // Ignore no-op GEPs and bitcasts. 1582 StoredOnceVal = StoredOnceVal->stripPointerCasts(); 1583 1584 // If we are dealing with a pointer global that is initialized to null and 1585 // only has one (non-null) value stored into it, then we can optimize any 1586 // users of the loaded value (often calls and loads) that would trap if the 1587 // value was null. 1588 if (GV->getInitializer()->getType()->isPointerTy() && 1589 GV->getInitializer()->isNullValue()) { 1590 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) { 1591 if (GV->getInitializer()->getType() != SOVC->getType()) 1592 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType()); 1593 1594 // Optimize away any trapping uses of the loaded value. 1595 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, TD, TLI)) 1596 return true; 1597 } else if (CallInst *CI = extractMallocCall(StoredOnceVal)) { 1598 Type *MallocType = getMallocAllocatedType(CI); 1599 if (MallocType && 1600 TryToOptimizeStoreOfMallocToGlobal(GV, CI, MallocType, Ordering, GVI, 1601 TD, TLI)) 1602 return true; 1603 } 1604 } 1605 1606 return false; 1607 } 1608 1609 /// TryToShrinkGlobalToBoolean - At this point, we have learned that the only 1610 /// two values ever stored into GV are its initializer and OtherVal. See if we 1611 /// can shrink the global into a boolean and select between the two values 1612 /// whenever it is used. This exposes the values to other scalar optimizations. 1613 static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) { 1614 Type *GVElType = GV->getType()->getElementType(); 1615 1616 // If GVElType is already i1, it is already shrunk. If the type of the GV is 1617 // an FP value, pointer or vector, don't do this optimization because a select 1618 // between them is very expensive and unlikely to lead to later 1619 // simplification. In these cases, we typically end up with "cond ? v1 : v2" 1620 // where v1 and v2 both require constant pool loads, a big loss. 1621 if (GVElType == Type::getInt1Ty(GV->getContext()) || 1622 GVElType->isFloatingPointTy() || 1623 GVElType->isPointerTy() || GVElType->isVectorTy()) 1624 return false; 1625 1626 // Walk the use list of the global seeing if all the uses are load or store. 1627 // If there is anything else, bail out. 1628 for (Value::use_iterator I = GV->use_begin(), E = GV->use_end(); I != E; ++I){ 1629 User *U = *I; 1630 if (!isa<LoadInst>(U) && !isa<StoreInst>(U)) 1631 return false; 1632 } 1633 1634 DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV); 1635 1636 // Create the new global, initializing it to false. 1637 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()), 1638 false, 1639 GlobalValue::InternalLinkage, 1640 ConstantInt::getFalse(GV->getContext()), 1641 GV->getName()+".b", 1642 GV->isThreadLocal()); 1643 GV->getParent()->getGlobalList().insert(GV, NewGV); 1644 1645 Constant *InitVal = GV->getInitializer(); 1646 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) && 1647 "No reason to shrink to bool!"); 1648 1649 // If initialized to zero and storing one into the global, we can use a cast 1650 // instead of a select to synthesize the desired value. 1651 bool IsOneZero = false; 1652 if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) 1653 IsOneZero = InitVal->isNullValue() && CI->isOne(); 1654 1655 while (!GV->use_empty()) { 1656 Instruction *UI = cast<Instruction>(GV->use_back()); 1657 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) { 1658 // Change the store into a boolean store. 1659 bool StoringOther = SI->getOperand(0) == OtherVal; 1660 // Only do this if we weren't storing a loaded value. 1661 Value *StoreVal; 1662 if (StoringOther || SI->getOperand(0) == InitVal) 1663 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()), 1664 StoringOther); 1665 else { 1666 // Otherwise, we are storing a previously loaded copy. To do this, 1667 // change the copy from copying the original value to just copying the 1668 // bool. 1669 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0)); 1670 1671 // If we've already replaced the input, StoredVal will be a cast or 1672 // select instruction. If not, it will be a load of the original 1673 // global. 1674 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) { 1675 assert(LI->getOperand(0) == GV && "Not a copy!"); 1676 // Insert a new load, to preserve the saved value. 1677 StoreVal = new LoadInst(NewGV, LI->getName()+".b", false, 0, 1678 LI->getOrdering(), LI->getSynchScope(), LI); 1679 } else { 1680 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) && 1681 "This is not a form that we understand!"); 1682 StoreVal = StoredVal->getOperand(0); 1683 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!"); 1684 } 1685 } 1686 new StoreInst(StoreVal, NewGV, false, 0, 1687 SI->getOrdering(), SI->getSynchScope(), SI); 1688 } else { 1689 // Change the load into a load of bool then a select. 1690 LoadInst *LI = cast<LoadInst>(UI); 1691 LoadInst *NLI = new LoadInst(NewGV, LI->getName()+".b", false, 0, 1692 LI->getOrdering(), LI->getSynchScope(), LI); 1693 Value *NSI; 1694 if (IsOneZero) 1695 NSI = new ZExtInst(NLI, LI->getType(), "", LI); 1696 else 1697 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI); 1698 NSI->takeName(LI); 1699 LI->replaceAllUsesWith(NSI); 1700 } 1701 UI->eraseFromParent(); 1702 } 1703 1704 GV->eraseFromParent(); 1705 return true; 1706 } 1707 1708 1709 /// ProcessGlobal - Analyze the specified global variable and optimize it if 1710 /// possible. If we make a change, return true. 1711 bool GlobalOpt::ProcessGlobal(GlobalVariable *GV, 1712 Module::global_iterator &GVI) { 1713 if (!GV->hasLocalLinkage()) 1714 return false; 1715 1716 // Do more involved optimizations if the global is internal. 1717 GV->removeDeadConstantUsers(); 1718 1719 if (GV->use_empty()) { 1720 DEBUG(dbgs() << "GLOBAL DEAD: " << *GV); 1721 GV->eraseFromParent(); 1722 ++NumDeleted; 1723 return true; 1724 } 1725 1726 SmallPtrSet<const PHINode*, 16> PHIUsers; 1727 GlobalStatus GS; 1728 1729 if (AnalyzeGlobal(GV, GS, PHIUsers)) 1730 return false; 1731 1732 if (!GS.isCompared && !GV->hasUnnamedAddr()) { 1733 GV->setUnnamedAddr(true); 1734 NumUnnamed++; 1735 } 1736 1737 if (GV->isConstant() || !GV->hasInitializer()) 1738 return false; 1739 1740 return ProcessInternalGlobal(GV, GVI, PHIUsers, GS); 1741 } 1742 1743 /// ProcessInternalGlobal - Analyze the specified global variable and optimize 1744 /// it if possible. If we make a change, return true. 1745 bool GlobalOpt::ProcessInternalGlobal(GlobalVariable *GV, 1746 Module::global_iterator &GVI, 1747 const SmallPtrSet<const PHINode*, 16> &PHIUsers, 1748 const GlobalStatus &GS) { 1749 // If this is a first class global and has only one accessing function 1750 // and this function is main (which we know is not recursive we can make 1751 // this global a local variable) we replace the global with a local alloca 1752 // in this function. 1753 // 1754 // NOTE: It doesn't make sense to promote non single-value types since we 1755 // are just replacing static memory to stack memory. 1756 // 1757 // If the global is in different address space, don't bring it to stack. 1758 if (!GS.HasMultipleAccessingFunctions && 1759 GS.AccessingFunction && !GS.HasNonInstructionUser && 1760 GV->getType()->getElementType()->isSingleValueType() && 1761 GS.AccessingFunction->getName() == "main" && 1762 GS.AccessingFunction->hasExternalLinkage() && 1763 GV->getType()->getAddressSpace() == 0) { 1764 DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV); 1765 Instruction &FirstI = const_cast<Instruction&>(*GS.AccessingFunction 1766 ->getEntryBlock().begin()); 1767 Type *ElemTy = GV->getType()->getElementType(); 1768 // FIXME: Pass Global's alignment when globals have alignment 1769 AllocaInst *Alloca = new AllocaInst(ElemTy, NULL, GV->getName(), &FirstI); 1770 if (!isa<UndefValue>(GV->getInitializer())) 1771 new StoreInst(GV->getInitializer(), Alloca, &FirstI); 1772 1773 GV->replaceAllUsesWith(Alloca); 1774 GV->eraseFromParent(); 1775 ++NumLocalized; 1776 return true; 1777 } 1778 1779 // If the global is never loaded (but may be stored to), it is dead. 1780 // Delete it now. 1781 if (!GS.isLoaded) { 1782 DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV); 1783 1784 // Delete any stores we can find to the global. We may not be able to 1785 // make it completely dead though. 1786 bool Changed = CleanupConstantGlobalUsers(GV, GV->getInitializer(), 1787 TD, TLI); 1788 1789 // If the global is dead now, delete it. 1790 if (GV->use_empty()) { 1791 GV->eraseFromParent(); 1792 ++NumDeleted; 1793 Changed = true; 1794 } 1795 return Changed; 1796 1797 } else if (GS.StoredType <= GlobalStatus::isInitializerStored) { 1798 DEBUG(dbgs() << "MARKING CONSTANT: " << *GV); 1799 GV->setConstant(true); 1800 1801 // Clean up any obviously simplifiable users now. 1802 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI); 1803 1804 // If the global is dead now, just nuke it. 1805 if (GV->use_empty()) { 1806 DEBUG(dbgs() << " *** Marking constant allowed us to simplify " 1807 << "all users and delete global!\n"); 1808 GV->eraseFromParent(); 1809 ++NumDeleted; 1810 } 1811 1812 ++NumMarked; 1813 return true; 1814 } else if (!GV->getInitializer()->getType()->isSingleValueType()) { 1815 if (TargetData *TD = getAnalysisIfAvailable<TargetData>()) 1816 if (GlobalVariable *FirstNewGV = SRAGlobal(GV, *TD)) { 1817 GVI = FirstNewGV; // Don't skip the newly produced globals! 1818 return true; 1819 } 1820 } else if (GS.StoredType == GlobalStatus::isStoredOnce) { 1821 // If the initial value for the global was an undef value, and if only 1822 // one other value was stored into it, we can just change the 1823 // initializer to be the stored value, then delete all stores to the 1824 // global. This allows us to mark it constant. 1825 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue)) 1826 if (isa<UndefValue>(GV->getInitializer())) { 1827 // Change the initial value here. 1828 GV->setInitializer(SOVConstant); 1829 1830 // Clean up any obviously simplifiable users now. 1831 CleanupConstantGlobalUsers(GV, GV->getInitializer(), TD, TLI); 1832 1833 if (GV->use_empty()) { 1834 DEBUG(dbgs() << " *** Substituting initializer allowed us to " 1835 << "simplify all users and delete global!\n"); 1836 GV->eraseFromParent(); 1837 ++NumDeleted; 1838 } else { 1839 GVI = GV; 1840 } 1841 ++NumSubstitute; 1842 return true; 1843 } 1844 1845 // Try to optimize globals based on the knowledge that only one value 1846 // (besides its initializer) is ever stored to the global. 1847 if (OptimizeOnceStoredGlobal(GV, GS.StoredOnceValue, GS.Ordering, GVI, 1848 TD, TLI)) 1849 return true; 1850 1851 // Otherwise, if the global was not a boolean, we can shrink it to be a 1852 // boolean. 1853 if (Constant *SOVConstant = dyn_cast<Constant>(GS.StoredOnceValue)) 1854 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) { 1855 ++NumShrunkToBool; 1856 return true; 1857 } 1858 } 1859 1860 return false; 1861 } 1862 1863 /// ChangeCalleesToFastCall - Walk all of the direct calls of the specified 1864 /// function, changing them to FastCC. 1865 static void ChangeCalleesToFastCall(Function *F) { 1866 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){ 1867 CallSite User(cast<Instruction>(*UI)); 1868 User.setCallingConv(CallingConv::Fast); 1869 } 1870 } 1871 1872 static AttrListPtr StripNest(const AttrListPtr &Attrs) { 1873 for (unsigned i = 0, e = Attrs.getNumSlots(); i != e; ++i) { 1874 if ((Attrs.getSlot(i).Attrs & Attribute::Nest) == 0) 1875 continue; 1876 1877 // There can be only one. 1878 return Attrs.removeAttr(Attrs.getSlot(i).Index, Attribute::Nest); 1879 } 1880 1881 return Attrs; 1882 } 1883 1884 static void RemoveNestAttribute(Function *F) { 1885 F->setAttributes(StripNest(F->getAttributes())); 1886 for (Value::use_iterator UI = F->use_begin(), E = F->use_end(); UI != E;++UI){ 1887 CallSite User(cast<Instruction>(*UI)); 1888 User.setAttributes(StripNest(User.getAttributes())); 1889 } 1890 } 1891 1892 bool GlobalOpt::OptimizeFunctions(Module &M) { 1893 bool Changed = false; 1894 // Optimize functions. 1895 for (Module::iterator FI = M.begin(), E = M.end(); FI != E; ) { 1896 Function *F = FI++; 1897 // Functions without names cannot be referenced outside this module. 1898 if (!F->hasName() && !F->isDeclaration()) 1899 F->setLinkage(GlobalValue::InternalLinkage); 1900 F->removeDeadConstantUsers(); 1901 if (F->isDefTriviallyDead()) { 1902 F->eraseFromParent(); 1903 Changed = true; 1904 ++NumFnDeleted; 1905 } else if (F->hasLocalLinkage()) { 1906 if (F->getCallingConv() == CallingConv::C && !F->isVarArg() && 1907 !F->hasAddressTaken()) { 1908 // If this function has C calling conventions, is not a varargs 1909 // function, and is only called directly, promote it to use the Fast 1910 // calling convention. 1911 F->setCallingConv(CallingConv::Fast); 1912 ChangeCalleesToFastCall(F); 1913 ++NumFastCallFns; 1914 Changed = true; 1915 } 1916 1917 if (F->getAttributes().hasAttrSomewhere(Attribute::Nest) && 1918 !F->hasAddressTaken()) { 1919 // The function is not used by a trampoline intrinsic, so it is safe 1920 // to remove the 'nest' attribute. 1921 RemoveNestAttribute(F); 1922 ++NumNestRemoved; 1923 Changed = true; 1924 } 1925 } 1926 } 1927 return Changed; 1928 } 1929 1930 bool GlobalOpt::OptimizeGlobalVars(Module &M) { 1931 bool Changed = false; 1932 for (Module::global_iterator GVI = M.global_begin(), E = M.global_end(); 1933 GVI != E; ) { 1934 GlobalVariable *GV = GVI++; 1935 // Global variables without names cannot be referenced outside this module. 1936 if (!GV->hasName() && !GV->isDeclaration()) 1937 GV->setLinkage(GlobalValue::InternalLinkage); 1938 // Simplify the initializer. 1939 if (GV->hasInitializer()) 1940 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(GV->getInitializer())) { 1941 Constant *New = ConstantFoldConstantExpression(CE, TD, TLI); 1942 if (New && New != CE) 1943 GV->setInitializer(New); 1944 } 1945 1946 Changed |= ProcessGlobal(GV, GVI); 1947 } 1948 return Changed; 1949 } 1950 1951 /// FindGlobalCtors - Find the llvm.global_ctors list, verifying that all 1952 /// initializers have an init priority of 65535. 1953 GlobalVariable *GlobalOpt::FindGlobalCtors(Module &M) { 1954 GlobalVariable *GV = M.getGlobalVariable("llvm.global_ctors"); 1955 if (GV == 0) return 0; 1956 1957 // Verify that the initializer is simple enough for us to handle. We are 1958 // only allowed to optimize the initializer if it is unique. 1959 if (!GV->hasUniqueInitializer()) return 0; 1960 1961 if (isa<ConstantAggregateZero>(GV->getInitializer())) 1962 return GV; 1963 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer()); 1964 1965 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) { 1966 if (isa<ConstantAggregateZero>(*i)) 1967 continue; 1968 ConstantStruct *CS = cast<ConstantStruct>(*i); 1969 if (isa<ConstantPointerNull>(CS->getOperand(1))) 1970 continue; 1971 1972 // Must have a function or null ptr. 1973 if (!isa<Function>(CS->getOperand(1))) 1974 return 0; 1975 1976 // Init priority must be standard. 1977 ConstantInt *CI = cast<ConstantInt>(CS->getOperand(0)); 1978 if (CI->getZExtValue() != 65535) 1979 return 0; 1980 } 1981 1982 return GV; 1983 } 1984 1985 /// ParseGlobalCtors - Given a llvm.global_ctors list that we can understand, 1986 /// return a list of the functions and null terminator as a vector. 1987 static std::vector<Function*> ParseGlobalCtors(GlobalVariable *GV) { 1988 if (GV->getInitializer()->isNullValue()) 1989 return std::vector<Function*>(); 1990 ConstantArray *CA = cast<ConstantArray>(GV->getInitializer()); 1991 std::vector<Function*> Result; 1992 Result.reserve(CA->getNumOperands()); 1993 for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e; ++i) { 1994 ConstantStruct *CS = cast<ConstantStruct>(*i); 1995 Result.push_back(dyn_cast<Function>(CS->getOperand(1))); 1996 } 1997 return Result; 1998 } 1999 2000 /// InstallGlobalCtors - Given a specified llvm.global_ctors list, install the 2001 /// specified array, returning the new global to use. 2002 static GlobalVariable *InstallGlobalCtors(GlobalVariable *GCL, 2003 const std::vector<Function*> &Ctors) { 2004 // If we made a change, reassemble the initializer list. 2005 Constant *CSVals[2]; 2006 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()), 65535); 2007 CSVals[1] = 0; 2008 2009 StructType *StructTy = 2010 cast <StructType>( 2011 cast<ArrayType>(GCL->getType()->getElementType())->getElementType()); 2012 2013 // Create the new init list. 2014 std::vector<Constant*> CAList; 2015 for (unsigned i = 0, e = Ctors.size(); i != e; ++i) { 2016 if (Ctors[i]) { 2017 CSVals[1] = Ctors[i]; 2018 } else { 2019 Type *FTy = FunctionType::get(Type::getVoidTy(GCL->getContext()), 2020 false); 2021 PointerType *PFTy = PointerType::getUnqual(FTy); 2022 CSVals[1] = Constant::getNullValue(PFTy); 2023 CSVals[0] = ConstantInt::get(Type::getInt32Ty(GCL->getContext()), 2024 0x7fffffff); 2025 } 2026 CAList.push_back(ConstantStruct::get(StructTy, CSVals)); 2027 } 2028 2029 // Create the array initializer. 2030 Constant *CA = ConstantArray::get(ArrayType::get(StructTy, 2031 CAList.size()), CAList); 2032 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); 2036 return GCL; 2037 } 2038 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); 2044 NGV->takeName(GCL); 2045 2046 // Nuke the old list, replacing any uses with the new one. 2047 if (!GCL->use_empty()) { 2048 Constant *V = NGV; 2049 if (V->getType() != GCL->getType()) 2050 V = ConstantExpr::getBitCast(V, GCL->getType()); 2051 GCL->replaceAllUsesWith(V); 2052 } 2053 GCL->eraseFromParent(); 2054 2055 if (Ctors.size()) 2056 return NGV; 2057 else 2058 return 0; 2059 } 2060 2061 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!"); 2066 return R; 2067 } 2068 2069 static inline bool 2070 isSimpleEnoughValueToCommit(Constant *C, 2071 SmallPtrSet<Constant*, 8> &SimpleConstants, 2072 const TargetData *TD); 2073 2074 2075 /// isSimpleEnoughValueToCommit - Return true if the specified constant can be 2076 /// handled by the code generator. We don't want to generate something like: 2077 /// void *X = &X/42; 2078 /// because the code generator doesn't have a relocation that can handle that. 2079 /// 2080 /// This function should be called if C was not found (but just got inserted) 2081 /// in SimpleConstants to avoid having to rescan the same constants all the 2082 /// time. 2083 static bool isSimpleEnoughValueToCommitHelper(Constant *C, 2084 SmallPtrSet<Constant*, 8> &SimpleConstants, 2085 const TargetData *TD) { 2086 // Simple integer, undef, constant aggregate zero, global addresses, etc are 2087 // all supported. 2088 if (C->getNumOperands() == 0 || isa<BlockAddress>(C) || 2089 isa<GlobalValue>(C)) 2090 return true; 2091 2092 // Aggregate values are safe if all their elements are. 2093 if (isa<ConstantArray>(C) || isa<ConstantStruct>(C) || 2094 isa<ConstantVector>(C)) { 2095 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) { 2096 Constant *Op = cast<Constant>(C->getOperand(i)); 2097 if (!isSimpleEnoughValueToCommit(Op, SimpleConstants, TD)) 2098 return false; 2099 } 2100 return true; 2101 } 2102 2103 // We don't know exactly what relocations are allowed in constant expressions, 2104 // so we allow &global+constantoffset, which is safe and uniformly supported 2105 // across targets. 2106 ConstantExpr *CE = cast<ConstantExpr>(C); 2107 switch (CE->getOpcode()) { 2108 case Instruction::BitCast: 2109 // Bitcast is fine if the casted value is fine. 2110 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD); 2111 2112 case Instruction::IntToPtr: 2113 case Instruction::PtrToInt: 2114 // int <=> ptr is fine if the int type is the same size as the 2115 // pointer type. 2116 if (!TD || TD->getTypeSizeInBits(CE->getType()) != 2117 TD->getTypeSizeInBits(CE->getOperand(0)->getType())) 2118 return false; 2119 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD); 2120 2121 // GEP is fine if it is simple + constant offset. 2122 case Instruction::GetElementPtr: 2123 for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i) 2124 if (!isa<ConstantInt>(CE->getOperand(i))) 2125 return false; 2126 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD); 2127 2128 case Instruction::Add: 2129 // We allow simple+cst. 2130 if (!isa<ConstantInt>(CE->getOperand(1))) 2131 return false; 2132 return isSimpleEnoughValueToCommit(CE->getOperand(0), SimpleConstants, TD); 2133 } 2134 return false; 2135 } 2136 2137 static inline bool 2138 isSimpleEnoughValueToCommit(Constant *C, 2139 SmallPtrSet<Constant*, 8> &SimpleConstants, 2140 const TargetData *TD) { 2141 // If we already checked this constant, we win. 2142 if (!SimpleConstants.insert(C)) return true; 2143 // Check the constant. 2144 return isSimpleEnoughValueToCommitHelper(C, SimpleConstants, TD); 2145 } 2146 2147 2148 /// isSimpleEnoughPointerToCommit - Return true if this constant is simple 2149 /// enough for us to understand. In particular, if it is a cast to anything 2150 /// other than from one pointer type to another pointer type, we punt. 2151 /// We basically just support direct accesses to globals and GEP's of 2152 /// globals. This should be kept up to date with CommitValueTo. 2153 static bool isSimpleEnoughPointerToCommit(Constant *C) { 2154 // Conservatively, avoid aggregate types. This is because we don't 2155 // want to worry about them partially overlapping other stores. 2156 if (!cast<PointerType>(C->getType())->getElementType()->isSingleValueType()) 2157 return false; 2158 2159 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(C)) 2160 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or 2161 // external globals. 2162 return GV->hasUniqueInitializer(); 2163 2164 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) { 2165 // Handle a constantexpr gep. 2166 if (CE->getOpcode() == Instruction::GetElementPtr && 2167 isa<GlobalVariable>(CE->getOperand(0)) && 2168 cast<GEPOperator>(CE)->isInBounds()) { 2169 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0)); 2170 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or 2171 // external globals. 2172 if (!GV->hasUniqueInitializer()) 2173 return false; 2174 2175 // The first index must be zero. 2176 ConstantInt *CI = dyn_cast<ConstantInt>(*llvm::next(CE->op_begin())); 2177 if (!CI || !CI->isZero()) return false; 2178 2179 // The remaining indices must be compile-time known integers within the 2180 // notional bounds of the corresponding static array types. 2181 if (!CE->isGEPWithNoNotionalOverIndexing()) 2182 return false; 2183 2184 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE); 2185 2186 // A constantexpr bitcast from a pointer to another pointer is a no-op, 2187 // and we know how to evaluate it by moving the bitcast from the pointer 2188 // operand to the value operand. 2189 } else if (CE->getOpcode() == Instruction::BitCast && 2190 isa<GlobalVariable>(CE->getOperand(0))) { 2191 // Do not allow weak/*_odr/linkonce/dllimport/dllexport linkage or 2192 // external globals. 2193 return cast<GlobalVariable>(CE->getOperand(0))->hasUniqueInitializer(); 2194 } 2195 } 2196 2197 return false; 2198 } 2199 2200 /// EvaluateStoreInto - Evaluate a piece of a constantexpr store into a global 2201 /// initializer. This returns 'Init' modified to reflect 'Val' stored into it. 2202 /// At this point, the GEP operands of Addr [0, OpNo) have been stepped into. 2203 static Constant *EvaluateStoreInto(Constant *Init, Constant *Val, 2204 ConstantExpr *Addr, unsigned OpNo) { 2205 // Base case of the recursion. 2206 if (OpNo == Addr->getNumOperands()) { 2207 assert(Val->getType() == Init->getType() && "Type mismatch!"); 2208 return Val; 2209 } 2210 2211 SmallVector<Constant*, 32> Elts; 2212 if (StructType *STy = dyn_cast<StructType>(Init->getType())) { 2213 // Break up the constant into its elements. 2214 for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) 2215 Elts.push_back(Init->getAggregateElement(i)); 2216 2217 // Replace the element that we are supposed to. 2218 ConstantInt *CU = cast<ConstantInt>(Addr->getOperand(OpNo)); 2219 unsigned Idx = CU->getZExtValue(); 2220 assert(Idx < STy->getNumElements() && "Struct index out of range!"); 2221 Elts[Idx] = EvaluateStoreInto(Elts[Idx], Val, Addr, OpNo+1); 2222 2223 // Return the modified struct. 2224 return ConstantStruct::get(STy, Elts); 2225 } 2226 2227 ConstantInt *CI = cast<ConstantInt>(Addr->getOperand(OpNo)); 2228 SequentialType *InitTy = cast<SequentialType>(Init->getType()); 2229 2230 uint64_t NumElts; 2231 if (ArrayType *ATy = dyn_cast<ArrayType>(InitTy)) 2232 NumElts = ATy->getNumElements(); 2233 else 2234 NumElts = InitTy->getVectorNumElements(); 2235 2236 // Break up the array into elements. 2237 for (uint64_t i = 0, e = NumElts; i != e; ++i) 2238 Elts.push_back(Init->getAggregateElement(i)); 2239 2240 assert(CI->getZExtValue() < NumElts); 2241 Elts[CI->getZExtValue()] = 2242 EvaluateStoreInto(Elts[CI->getZExtValue()], Val, Addr, OpNo+1); 2243 2244 if (Init->getType()->isArrayTy()) 2245 return ConstantArray::get(cast<ArrayType>(InitTy), Elts); 2246 return ConstantVector::get(Elts); 2247 } 2248 2249 /// CommitValueTo - We have decided that Addr (which satisfies the predicate 2250 /// isSimpleEnoughPointerToCommit) should get Val as its value. Make it happen. 2251 static void CommitValueTo(Constant *Val, Constant *Addr) { 2252 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Addr)) { 2253 assert(GV->hasInitializer()); 2254 GV->setInitializer(Val); 2255 return; 2256 } 2257 2258 ConstantExpr *CE = cast<ConstantExpr>(Addr); 2259 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0)); 2260 GV->setInitializer(EvaluateStoreInto(GV->getInitializer(), Val, CE, 2)); 2261 } 2262 2263 /// ComputeLoadResult - Return the value that would be computed by a load from 2264 /// P after the stores reflected by 'memory' have been performed. If we can't 2265 /// decide, return null. 2266 static Constant *ComputeLoadResult(Constant *P, 2267 const DenseMap<Constant*, Constant*> &Memory) { 2268 // If this memory location has been recently stored, use the stored value: it 2269 // is the most up-to-date. 2270 DenseMap<Constant*, Constant*>::const_iterator I = Memory.find(P); 2271 if (I != Memory.end()) return I->second; 2272 2273 // Access it. 2274 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(P)) { 2275 if (GV->hasDefinitiveInitializer()) 2276 return GV->getInitializer(); 2277 return 0; 2278 } 2279 2280 // Handle a constantexpr getelementptr. 2281 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(P)) 2282 if (CE->getOpcode() == Instruction::GetElementPtr && 2283 isa<GlobalVariable>(CE->getOperand(0))) { 2284 GlobalVariable *GV = cast<GlobalVariable>(CE->getOperand(0)); 2285 if (GV->hasDefinitiveInitializer()) 2286 return ConstantFoldLoadThroughGEPConstantExpr(GV->getInitializer(), CE); 2287 } 2288 2289 return 0; // don't know how to evaluate. 2290 } 2291 2292 static bool EvaluateFunction(Function *F, Constant *&RetVal, 2293 const SmallVectorImpl<Constant*> &ActualArgs, 2294 std::vector<Function*> &CallStack, 2295 DenseMap<Constant*, Constant*> &MutatedMemory, 2296 std::vector<GlobalVariable*> &AllocaTmps, 2297 SmallPtrSet<Constant*, 8> &SimpleConstants, 2298 const TargetData *TD, 2299 const TargetLibraryInfo *TLI); 2300 2301 /// EvaluateBlock - Evaluate all instructions in block BB, returning true if 2302 /// successful, false if we can't evaluate it. NewBB returns the next BB that 2303 /// control flows into, or null upon return. 2304 static bool EvaluateBlock(BasicBlock::iterator CurInst, BasicBlock *&NextBB, 2305 std::vector<Function*> &CallStack, 2306 DenseMap<Value*, Constant*> &Values, 2307 DenseMap<Constant*, Constant*> &MutatedMemory, 2308 std::vector<GlobalVariable*> &AllocaTmps, 2309 SmallPtrSet<Constant*, 8> &SimpleConstants, 2310 const TargetData *TD, 2311 const TargetLibraryInfo *TLI) { 2312 // This is the main evaluation loop. 2313 while (1) { 2314 Constant *InstResult = 0; 2315 2316 if (StoreInst *SI = dyn_cast<StoreInst>(CurInst)) { 2317 if (!SI->isSimple()) return false; // no volatile/atomic accesses. 2318 Constant *Ptr = getVal(Values, SI->getOperand(1)); 2319 if (!isSimpleEnoughPointerToCommit(Ptr)) 2320 // If this is too complex for us to commit, reject it. 2321 return false; 2322 2323 Constant *Val = getVal(Values, SI->getOperand(0)); 2324 2325 // If this might be too difficult for the backend to handle (e.g. the addr 2326 // of one global variable divided by another) then we can't commit it. 2327 if (!isSimpleEnoughValueToCommit(Val, SimpleConstants, TD)) 2328 return false; 2329 2330 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) 2331 if (CE->getOpcode() == Instruction::BitCast) { 2332 // If we're evaluating a store through a bitcast, then we need 2333 // to pull the bitcast off the pointer type and push it onto the 2334 // stored value. 2335 Ptr = CE->getOperand(0); 2336 2337 Type *NewTy = cast<PointerType>(Ptr->getType())->getElementType(); 2338 2339 // In order to push the bitcast onto the stored value, a bitcast 2340 // from NewTy to Val's type must be legal. If it's not, we can try 2341 // introspecting NewTy to find a legal conversion. 2342 while (!Val->getType()->canLosslesslyBitCastTo(NewTy)) { 2343 // If NewTy is a struct, we can convert the pointer to the struct 2344 // into a pointer to its first member. 2345 // FIXME: This could be extended to support arrays as well. 2346 if (StructType *STy = dyn_cast<StructType>(NewTy)) { 2347 NewTy = STy->getTypeAtIndex(0U); 2348 2349 IntegerType *IdxTy = IntegerType::get(NewTy->getContext(), 32); 2350 Constant *IdxZero = ConstantInt::get(IdxTy, 0, false); 2351 Constant * const IdxList[] = {IdxZero, IdxZero}; 2352 2353 Ptr = ConstantExpr::getGetElementPtr(Ptr, IdxList); 2354 2355 // If we can't improve the situation by introspecting NewTy, 2356 // we have to give up. 2357 } else { 2358 return false; 2359 } 2360 } 2361 2362 // If we found compatible types, go ahead and push the bitcast 2363 // onto the stored value. 2364 Val = ConstantExpr::getBitCast(Val, NewTy); 2365 } 2366 2367 MutatedMemory[Ptr] = Val; 2368 } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(CurInst)) { 2369 InstResult = ConstantExpr::get(BO->getOpcode(), 2370 getVal(Values, BO->getOperand(0)), 2371 getVal(Values, BO->getOperand(1))); 2372 } else if (CmpInst *CI = dyn_cast<CmpInst>(CurInst)) { 2373 InstResult = ConstantExpr::getCompare(CI->getPredicate(), 2374 getVal(Values, CI->getOperand(0)), 2375 getVal(Values, CI->getOperand(1))); 2376 } else if (CastInst *CI = dyn_cast<CastInst>(CurInst)) { 2377 InstResult = ConstantExpr::getCast(CI->getOpcode(), 2378 getVal(Values, CI->getOperand(0)), 2379 CI->getType()); 2380 } else if (SelectInst *SI = dyn_cast<SelectInst>(CurInst)) { 2381 InstResult = ConstantExpr::getSelect(getVal(Values, SI->getOperand(0)), 2382 getVal(Values, SI->getOperand(1)), 2383 getVal(Values, SI->getOperand(2))); 2384 } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(CurInst)) { 2385 Constant *P = getVal(Values, GEP->getOperand(0)); 2386 SmallVector<Constant*, 8> GEPOps; 2387 for (User::op_iterator i = GEP->op_begin() + 1, e = GEP->op_end(); 2388 i != e; ++i) 2389 GEPOps.push_back(getVal(Values, *i)); 2390 InstResult = 2391 ConstantExpr::getGetElementPtr(P, GEPOps, 2392 cast<GEPOperator>(GEP)->isInBounds()); 2393 } else if (LoadInst *LI = dyn_cast<LoadInst>(CurInst)) { 2394 if (!LI->isSimple()) return false; // no volatile/atomic accesses. 2395 InstResult = ComputeLoadResult(getVal(Values, LI->getOperand(0)), 2396 MutatedMemory); 2397 if (InstResult == 0) return false; // Could not evaluate load. 2398 } else if (AllocaInst *AI = dyn_cast<AllocaInst>(CurInst)) { 2399 if (AI->isArrayAllocation()) return false; // Cannot handle array allocs. 2400 Type *Ty = AI->getType()->getElementType(); 2401 AllocaTmps.push_back(new GlobalVariable(Ty, false, 2402 GlobalValue::InternalLinkage, 2403 UndefValue::get(Ty), 2404 AI->getName())); 2405 InstResult = AllocaTmps.back(); 2406 } else if (isa<CallInst>(CurInst) || isa<InvokeInst>(CurInst)) { 2407 CallSite CS(CurInst); 2408 2409 // Debug info can safely be ignored here. 2410 if (isa<DbgInfoIntrinsic>(CS.getInstruction())) { 2411 ++CurInst; 2412 continue; 2413 } 2414 2415 // Cannot handle inline asm. 2416 if (isa<InlineAsm>(CS.getCalledValue())) return false; 2417 2418 if (MemSetInst *MSI = dyn_cast<MemSetInst>(CS.getInstruction())) { 2419 if (MSI->isVolatile()) return false; 2420 Constant *Ptr = getVal(Values, MSI->getDest()); 2421 Constant *Val = getVal(Values, MSI->getValue()); 2422 Constant *DestVal = ComputeLoadResult(getVal(Values, Ptr), 2423 MutatedMemory); 2424 if (Val->isNullValue() && DestVal && DestVal->isNullValue()) { 2425 // This memset is a no-op. 2426 ++CurInst; 2427 continue; 2428 } 2429 return false; 2430 } 2431 2432 // Resolve function pointers. 2433 Function *Callee = dyn_cast<Function>(getVal(Values, 2434 CS.getCalledValue())); 2435 if (!Callee || Callee->mayBeOverridden()) 2436 return false; // Cannot resolve. 2437 2438 SmallVector<Constant*, 8> Formals; 2439 for (User::op_iterator i = CS.arg_begin(), e = CS.arg_end(); i != e; ++i) 2440 Formals.push_back(getVal(Values, *i)); 2441 2442 if (Callee->isDeclaration()) { 2443 // If this is a function we can constant fold, do it. 2444 if (Constant *C = ConstantFoldCall(Callee, Formals, TLI)) { 2445 InstResult = C; 2446 } else { 2447 return false; 2448 } 2449 } else { 2450 if (Callee->getFunctionType()->isVarArg()) 2451 return false; 2452 2453 Constant *RetVal; 2454 // Execute the call, if successful, use the return value. 2455 if (!EvaluateFunction(Callee, RetVal, Formals, CallStack, 2456 MutatedMemory, AllocaTmps, SimpleConstants, TD, 2457 TLI)) 2458 return false; 2459 InstResult = RetVal; 2460 2461 if (InvokeInst *II = dyn_cast<InvokeInst>(CurInst)) { 2462 NextBB = II->getNormalDest(); 2463 return true; 2464 } 2465 } 2466 } else if (isa<TerminatorInst>(CurInst)) { 2467 if (BranchInst *BI = dyn_cast<BranchInst>(CurInst)) { 2468 if (BI->isUnconditional()) { 2469 NextBB = BI->getSuccessor(0); 2470 } else { 2471 ConstantInt *Cond = 2472 dyn_cast<ConstantInt>(getVal(Values, BI->getCondition())); 2473 if (!Cond) return false; // Cannot determine. 2474 2475 NextBB = BI->getSuccessor(!Cond->getZExtValue()); 2476 } 2477 } else if (SwitchInst *SI = dyn_cast<SwitchInst>(CurInst)) { 2478 ConstantInt *Val = 2479 dyn_cast<ConstantInt>(getVal(Values, SI->getCondition())); 2480 if (!Val) return false; // Cannot determine. 2481 unsigned ValTISucc = SI->resolveSuccessorIndex(SI->findCaseValue(Val)); 2482 NextBB = SI->getSuccessor(ValTISucc); 2483 } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(CurInst)) { 2484 Value *Val = getVal(Values, IBI->getAddress())->stripPointerCasts(); 2485 if (BlockAddress *BA = dyn_cast<BlockAddress>(Val)) 2486 NextBB = BA->getBasicBlock(); 2487 else 2488 return false; // Cannot determine. 2489 } else if (isa<ReturnInst>(CurInst)) { 2490 NextBB = 0; 2491 } else { 2492 // invoke, unwind, resume, unreachable. 2493 return false; // Cannot handle this terminator. 2494 } 2495 2496 // We succeeded at evaluating this block! 2497 return true; 2498 } else { 2499 // Did not know how to evaluate this! 2500 return false; 2501 } 2502 2503 if (!CurInst->use_empty()) { 2504 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(InstResult)) 2505 InstResult = ConstantFoldConstantExpression(CE, TD, TLI); 2506 2507 Values[CurInst] = InstResult; 2508 } 2509 2510 // Advance program counter. 2511 ++CurInst; 2512 } 2513 } 2514 2515 /// EvaluateFunction - Evaluate a call to function F, returning true if 2516 /// successful, false if we can't evaluate it. ActualArgs contains the formal 2517 /// arguments for the function. 2518 static bool EvaluateFunction(Function *F, Constant *&RetVal, 2519 const SmallVectorImpl<Constant*> &ActualArgs, 2520 std::vector<Function*> &CallStack, 2521 DenseMap<Constant*, Constant*> &MutatedMemory, 2522 std::vector<GlobalVariable*> &AllocaTmps, 2523 SmallPtrSet<Constant*, 8> &SimpleConstants, 2524 const TargetData *TD, 2525 const TargetLibraryInfo *TLI) { 2526 // Check to see if this function is already executing (recursion). If so, 2527 // bail out. TODO: we might want to accept limited recursion. 2528 if (std::find(CallStack.begin(), CallStack.end(), F) != CallStack.end()) 2529 return false; 2530 2531 CallStack.push_back(F); 2532 2533 // Values - As we compute SSA register values, we store their contents here. 2534 DenseMap<Value*, Constant*> Values; 2535 2536 // Initialize arguments to the incoming values specified. 2537 unsigned ArgNo = 0; 2538 for (Function::arg_iterator AI = F->arg_begin(), E = F->arg_end(); AI != E; 2539 ++AI, ++ArgNo) 2540 Values[AI] = ActualArgs[ArgNo]; 2541 2542 // ExecutedBlocks - We only handle non-looping, non-recursive code. As such, 2543 // we can only evaluate any one basic block at most once. This set keeps 2544 // track of what we have executed so we can detect recursive cases etc. 2545 SmallPtrSet<BasicBlock*, 32> ExecutedBlocks; 2546 2547 // CurBB - The current basic block we're evaluating. 2548 BasicBlock *CurBB = F->begin(); 2549 2550 BasicBlock::iterator CurInst = CurBB->begin(); 2551 2552 while (1) { 2553 BasicBlock *NextBB; 2554 if (!EvaluateBlock(CurInst, NextBB, CallStack, Values, MutatedMemory, 2555 AllocaTmps, SimpleConstants, TD, TLI)) 2556 return false; 2557 2558 if (NextBB == 0) { 2559 // Successfully running until there's no next block means that we found 2560 // the return. Fill it the return value and pop the call stack. 2561 ReturnInst *RI = cast<ReturnInst>(CurBB->getTerminator()); 2562 if (RI->getNumOperands()) 2563 RetVal = getVal(Values, RI->getOperand(0)); 2564 CallStack.pop_back(); 2565 return true; 2566 } 2567 2568 // Okay, we succeeded in evaluating this control flow. See if we have 2569 // executed the new block before. If so, we have a looping function, 2570 // which we cannot evaluate in reasonable time. 2571 if (!ExecutedBlocks.insert(NextBB)) 2572 return false; // looped! 2573 2574 // Okay, we have never been in this block before. Check to see if there 2575 // are any PHI nodes. If so, evaluate them with information about where 2576 // we came from. 2577 PHINode *PN = 0; 2578 for (CurInst = NextBB->begin(); 2579 (PN = dyn_cast<PHINode>(CurInst)); ++CurInst) 2580 Values[PN] = getVal(Values, PN->getIncomingValueForBlock(CurBB)); 2581 2582 // Advance to the next block. 2583 CurBB = NextBB; 2584 } 2585 } 2586 2587 /// EvaluateStaticConstructor - Evaluate static constructors in the function, if 2588 /// we can. Return true if we can, false otherwise. 2589 static bool EvaluateStaticConstructor(Function *F, const TargetData *TD, 2590 const TargetLibraryInfo *TLI) { 2591 // MutatedMemory - For each store we execute, we update this map. Loads 2592 // check this to get the most up-to-date value. If evaluation is successful, 2593 // this state is committed to the process. 2594 DenseMap<Constant*, Constant*> MutatedMemory; 2595 2596 // AllocaTmps - To 'execute' an alloca, we create a temporary global variable 2597 // to represent its body. This vector is needed so we can delete the 2598 // temporary globals when we are done. 2599 std::vector<GlobalVariable*> AllocaTmps; 2600 2601 // CallStack - This is used to detect recursion. In pathological situations 2602 // we could hit exponential behavior, but at least there is nothing 2603 // unbounded. 2604 std::vector<Function*> CallStack; 2605 2606 // SimpleConstants - These are constants we have checked and know to be 2607 // simple enough to live in a static initializer of a global. 2608 SmallPtrSet<Constant*, 8> SimpleConstants; 2609 2610 // Call the function. 2611 Constant *RetValDummy; 2612 bool EvalSuccess = EvaluateFunction(F, RetValDummy, 2613 SmallVector<Constant*, 0>(), CallStack, 2614 MutatedMemory, AllocaTmps, 2615 SimpleConstants, TD, TLI); 2616 2617 if (EvalSuccess) { 2618 // We succeeded at evaluation: commit the result. 2619 DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '" 2620 << F->getName() << "' to " << MutatedMemory.size() 2621 << " stores.\n"); 2622 for (DenseMap<Constant*, Constant*>::iterator I = MutatedMemory.begin(), 2623 E = MutatedMemory.end(); I != E; ++I) 2624 CommitValueTo(I->second, I->first); 2625 } 2626 2627 // At this point, we are done interpreting. If we created any 'alloca' 2628 // temporaries, release them now. 2629 while (!AllocaTmps.empty()) { 2630 GlobalVariable *Tmp = AllocaTmps.back(); 2631 AllocaTmps.pop_back(); 2632 2633 // If there are still users of the alloca, the program is doing something 2634 // silly, e.g. storing the address of the alloca somewhere and using it 2635 // later. Since this is undefined, we'll just make it be null. 2636 if (!Tmp->use_empty()) 2637 Tmp->replaceAllUsesWith(Constant::getNullValue(Tmp->getType())); 2638 delete Tmp; 2639 } 2640 2641 return EvalSuccess; 2642 } 2643 2644 /// OptimizeGlobalCtorsList - Simplify and evaluation global ctors if possible. 2645 /// Return true if anything changed. 2646 bool GlobalOpt::OptimizeGlobalCtorsList(GlobalVariable *&GCL) { 2647 std::vector<Function*> Ctors = ParseGlobalCtors(GCL); 2648 bool MadeChange = false; 2649 if (Ctors.empty()) return false; 2650 2651 // Loop over global ctors, optimizing them when we can. 2652 for (unsigned i = 0; i != Ctors.size(); ++i) { 2653 Function *F = Ctors[i]; 2654 // Found a null terminator in the middle of the list, prune off the rest of 2655 // the list. 2656 if (F == 0) { 2657 if (i != Ctors.size()-1) { 2658 Ctors.resize(i+1); 2659 MadeChange = true; 2660 } 2661 break; 2662 } 2663 2664 // We cannot simplify external ctor functions. 2665 if (F->empty()) continue; 2666 2667 // If we can evaluate the ctor at compile time, do. 2668 if (EvaluateStaticConstructor(F, TD, TLI)) { 2669 Ctors.erase(Ctors.begin()+i); 2670 MadeChange = true; 2671 --i; 2672 ++NumCtorsEvaluated; 2673 continue; 2674 } 2675 } 2676 2677 if (!MadeChange) return false; 2678 2679 GCL = InstallGlobalCtors(GCL, Ctors); 2680 return true; 2681 } 2682 2683 bool GlobalOpt::OptimizeGlobalAliases(Module &M) { 2684 bool Changed = false; 2685 2686 for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end(); 2687 I != E;) { 2688 Module::alias_iterator J = I++; 2689 // Aliases without names cannot be referenced outside this module. 2690 if (!J->hasName() && !J->isDeclaration()) 2691 J->setLinkage(GlobalValue::InternalLinkage); 2692 // If the aliasee may change at link time, nothing can be done - bail out. 2693 if (J->mayBeOverridden()) 2694 continue; 2695 2696 Constant *Aliasee = J->getAliasee(); 2697 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts()); 2698 Target->removeDeadConstantUsers(); 2699 bool hasOneUse = Target->hasOneUse() && Aliasee->hasOneUse(); 2700 2701 // Make all users of the alias use the aliasee instead. 2702 if (!J->use_empty()) { 2703 J->replaceAllUsesWith(Aliasee); 2704 ++NumAliasesResolved; 2705 Changed = true; 2706 } 2707 2708 // If the alias is externally visible, we may still be able to simplify it. 2709 if (!J->hasLocalLinkage()) { 2710 // If the aliasee has internal linkage, give it the name and linkage 2711 // of the alias, and delete the alias. This turns: 2712 // define internal ... @f(...) 2713 // @a = alias ... @f 2714 // into: 2715 // define ... @a(...) 2716 if (!Target->hasLocalLinkage()) 2717 continue; 2718 2719 // Do not perform the transform if multiple aliases potentially target the 2720 // aliasee. This check also ensures that it is safe to replace the section 2721 // and other attributes of the aliasee with those of the alias. 2722 if (!hasOneUse) 2723 continue; 2724 2725 // Give the aliasee the name, linkage and other attributes of the alias. 2726 Target->takeName(J); 2727 Target->setLinkage(J->getLinkage()); 2728 Target->GlobalValue::copyAttributesFrom(J); 2729 } 2730 2731 // Delete the alias. 2732 M.getAliasList().erase(J); 2733 ++NumAliasesRemoved; 2734 Changed = true; 2735 } 2736 2737 return Changed; 2738 } 2739 2740 static Function *FindCXAAtExit(Module &M, TargetLibraryInfo *TLI) { 2741 if (!TLI->has(LibFunc::cxa_atexit)) 2742 return 0; 2743 2744 Function *Fn = M.getFunction(TLI->getName(LibFunc::cxa_atexit)); 2745 2746 if (!Fn) 2747 return 0; 2748 2749 FunctionType *FTy = Fn->getFunctionType(); 2750 2751 // Checking that the function has the right return type, the right number of 2752 // parameters and that they all have pointer types should be enough. 2753 if (!FTy->getReturnType()->isIntegerTy() || 2754 FTy->getNumParams() != 3 || 2755 !FTy->getParamType(0)->isPointerTy() || 2756 !FTy->getParamType(1)->isPointerTy() || 2757 !FTy->getParamType(2)->isPointerTy()) 2758 return 0; 2759 2760 return Fn; 2761 } 2762 2763 /// cxxDtorIsEmpty - Returns whether the given function is an empty C++ 2764 /// destructor and can therefore be eliminated. 2765 /// Note that we assume that other optimization passes have already simplified 2766 /// the code so we only look for a function with a single basic block, where 2767 /// the only allowed instructions are 'ret', 'call' to an empty C++ dtor and 2768 /// other side-effect free instructions. 2769 static bool cxxDtorIsEmpty(const Function &Fn, 2770 SmallPtrSet<const Function *, 8> &CalledFunctions) { 2771 // FIXME: We could eliminate C++ destructors if they're readonly/readnone and 2772 // nounwind, but that doesn't seem worth doing. 2773 if (Fn.isDeclaration()) 2774 return false; 2775 2776 if (++Fn.begin() != Fn.end()) 2777 return false; 2778 2779 const BasicBlock &EntryBlock = Fn.getEntryBlock(); 2780 for (BasicBlock::const_iterator I = EntryBlock.begin(), E = EntryBlock.end(); 2781 I != E; ++I) { 2782 if (const CallInst *CI = dyn_cast<CallInst>(I)) { 2783 // Ignore debug intrinsics. 2784 if (isa<DbgInfoIntrinsic>(CI)) 2785 continue; 2786 2787 const Function *CalledFn = CI->getCalledFunction(); 2788 2789 if (!CalledFn) 2790 return false; 2791 2792 SmallPtrSet<const Function *, 8> NewCalledFunctions(CalledFunctions); 2793 2794 // Don't treat recursive functions as empty. 2795 if (!NewCalledFunctions.insert(CalledFn)) 2796 return false; 2797 2798 if (!cxxDtorIsEmpty(*CalledFn, NewCalledFunctions)) 2799 return false; 2800 } else if (isa<ReturnInst>(*I)) 2801 return true; // We're done. 2802 else if (I->mayHaveSideEffects()) 2803 return false; // Destructor with side effects, bail. 2804 } 2805 2806 return false; 2807 } 2808 2809 bool GlobalOpt::OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) { 2810 /// Itanium C++ ABI p3.3.5: 2811 /// 2812 /// After constructing a global (or local static) object, that will require 2813 /// destruction on exit, a termination function is registered as follows: 2814 /// 2815 /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d ); 2816 /// 2817 /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the 2818 /// call f(p) when DSO d is unloaded, before all such termination calls 2819 /// registered before this one. It returns zero if registration is 2820 /// successful, nonzero on failure. 2821 2822 // This pass will look for calls to __cxa_atexit where the function is trivial 2823 // and remove them. 2824 bool Changed = false; 2825 2826 for (Function::use_iterator I = CXAAtExitFn->use_begin(), 2827 E = CXAAtExitFn->use_end(); I != E;) { 2828 // We're only interested in calls. Theoretically, we could handle invoke 2829 // instructions as well, but neither llvm-gcc nor clang generate invokes 2830 // to __cxa_atexit. 2831 CallInst *CI = dyn_cast<CallInst>(*I++); 2832 if (!CI) 2833 continue; 2834 2835 Function *DtorFn = 2836 dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts()); 2837 if (!DtorFn) 2838 continue; 2839 2840 SmallPtrSet<const Function *, 8> CalledFunctions; 2841 if (!cxxDtorIsEmpty(*DtorFn, CalledFunctions)) 2842 continue; 2843 2844 // Just remove the call. 2845 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType())); 2846 CI->eraseFromParent(); 2847 2848 ++NumCXXDtorsRemoved; 2849 2850 Changed |= true; 2851 } 2852 2853 return Changed; 2854 } 2855 2856 bool GlobalOpt::runOnModule(Module &M) { 2857 bool Changed = false; 2858 2859 TD = getAnalysisIfAvailable<TargetData>(); 2860 TLI = &getAnalysis<TargetLibraryInfo>(); 2861 2862 // Try to find the llvm.globalctors list. 2863 GlobalVariable *GlobalCtors = FindGlobalCtors(M); 2864 2865 Function *CXAAtExitFn = FindCXAAtExit(M, TLI); 2866 2867 bool LocalChange = true; 2868 while (LocalChange) { 2869 LocalChange = false; 2870 2871 // Delete functions that are trivially dead, ccc -> fastcc 2872 LocalChange |= OptimizeFunctions(M); 2873 2874 // Optimize global_ctors list. 2875 if (GlobalCtors) 2876 LocalChange |= OptimizeGlobalCtorsList(GlobalCtors); 2877 2878 // Optimize non-address-taken globals. 2879 LocalChange |= OptimizeGlobalVars(M); 2880 2881 // Resolve aliases, when possible. 2882 LocalChange |= OptimizeGlobalAliases(M); 2883 2884 // Try to remove trivial global destructors. 2885 if (CXAAtExitFn) 2886 LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn); 2887 2888 Changed |= LocalChange; 2889 } 2890 2891 // TODO: Move all global ctors functions to the end of the module for code 2892 // layout. 2893 2894 return Changed; 2895 } 2896