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