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