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