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/SetVector.h" 21 #include "llvm/ADT/Statistic.h" 22 #include "llvm/ADT/Twine.h" 23 #include "llvm/ADT/iterator_range.h" 24 #include "llvm/Analysis/BlockFrequencyInfo.h" 25 #include "llvm/Analysis/ConstantFolding.h" 26 #include "llvm/Analysis/MemoryBuiltins.h" 27 #include "llvm/Analysis/TargetLibraryInfo.h" 28 #include "llvm/Analysis/TargetTransformInfo.h" 29 #include "llvm/Analysis/ValueTracking.h" 30 #include "llvm/BinaryFormat/Dwarf.h" 31 #include "llvm/IR/Attributes.h" 32 #include "llvm/IR/BasicBlock.h" 33 #include "llvm/IR/CallingConv.h" 34 #include "llvm/IR/Constant.h" 35 #include "llvm/IR/Constants.h" 36 #include "llvm/IR/DataLayout.h" 37 #include "llvm/IR/DebugInfoMetadata.h" 38 #include "llvm/IR/DerivedTypes.h" 39 #include "llvm/IR/Dominators.h" 40 #include "llvm/IR/Function.h" 41 #include "llvm/IR/GlobalAlias.h" 42 #include "llvm/IR/GlobalValue.h" 43 #include "llvm/IR/GlobalVariable.h" 44 #include "llvm/IR/IRBuilder.h" 45 #include "llvm/IR/InstrTypes.h" 46 #include "llvm/IR/Instruction.h" 47 #include "llvm/IR/Instructions.h" 48 #include "llvm/IR/IntrinsicInst.h" 49 #include "llvm/IR/Module.h" 50 #include "llvm/IR/Operator.h" 51 #include "llvm/IR/Type.h" 52 #include "llvm/IR/Use.h" 53 #include "llvm/IR/User.h" 54 #include "llvm/IR/Value.h" 55 #include "llvm/IR/ValueHandle.h" 56 #include "llvm/InitializePasses.h" 57 #include "llvm/Pass.h" 58 #include "llvm/Support/AtomicOrdering.h" 59 #include "llvm/Support/Casting.h" 60 #include "llvm/Support/CommandLine.h" 61 #include "llvm/Support/Debug.h" 62 #include "llvm/Support/ErrorHandling.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(NumSubstitute,"Number of globals with initializers stored into them"); 82 STATISTIC(NumDeleted , "Number of globals deleted"); 83 STATISTIC(NumGlobUses , "Number of global uses devirtualized"); 84 STATISTIC(NumLocalized , "Number of globals localized"); 85 STATISTIC(NumShrunkToBool , "Number of global vars shrunk to booleans"); 86 STATISTIC(NumFastCallFns , "Number of functions converted to fastcc"); 87 STATISTIC(NumCtorsEvaluated, "Number of static ctors evaluated"); 88 STATISTIC(NumNestRemoved , "Number of nest attributes removed"); 89 STATISTIC(NumAliasesResolved, "Number of global aliases resolved"); 90 STATISTIC(NumAliasesRemoved, "Number of global aliases eliminated"); 91 STATISTIC(NumCXXDtorsRemoved, "Number of global C++ destructors removed"); 92 STATISTIC(NumInternalFunc, "Number of internal functions"); 93 STATISTIC(NumColdCC, "Number of functions marked coldcc"); 94 95 static cl::opt<bool> 96 EnableColdCCStressTest("enable-coldcc-stress-test", 97 cl::desc("Enable stress test of coldcc by adding " 98 "calling conv to all internal functions."), 99 cl::init(false), cl::Hidden); 100 101 static cl::opt<int> ColdCCRelFreq( 102 "coldcc-rel-freq", cl::Hidden, cl::init(2), 103 cl::desc( 104 "Maximum block frequency, expressed as a percentage of caller's " 105 "entry frequency, for a call site to be considered cold for enabling" 106 "coldcc")); 107 108 /// Is this global variable possibly used by a leak checker as a root? If so, 109 /// we might not really want to eliminate the stores to it. 110 static bool isLeakCheckerRoot(GlobalVariable *GV) { 111 // A global variable is a root if it is a pointer, or could plausibly contain 112 // a pointer. There are two challenges; one is that we could have a struct 113 // the has an inner member which is a pointer. We recurse through the type to 114 // detect these (up to a point). The other is that we may actually be a union 115 // of a pointer and another type, and so our LLVM type is an integer which 116 // gets converted into a pointer, or our type is an [i8 x #] with a pointer 117 // potentially contained here. 118 119 if (GV->hasPrivateLinkage()) 120 return false; 121 122 SmallVector<Type *, 4> Types; 123 Types.push_back(GV->getValueType()); 124 125 unsigned Limit = 20; 126 do { 127 Type *Ty = Types.pop_back_val(); 128 switch (Ty->getTypeID()) { 129 default: break; 130 case Type::PointerTyID: 131 return true; 132 case Type::FixedVectorTyID: 133 case Type::ScalableVectorTyID: 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 explicitly 198 // allow the memory pointed to by globals at exit. This is popular because it 199 // also solves another problem where the main thread of a C++ program may shut 200 // down 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 (User *U : llvm::make_early_inc_range(GV->users())) { 212 if (StoreInst *SI = dyn_cast<StoreInst>(U)) { 213 Value *V = SI->getValueOperand(); 214 if (isa<Constant>(V)) { 215 Changed = true; 216 SI->eraseFromParent(); 217 } else if (Instruction *I = dyn_cast<Instruction>(V)) { 218 if (I->hasOneUse()) 219 Dead.push_back(std::make_pair(I, SI)); 220 } 221 } else if (MemSetInst *MSI = dyn_cast<MemSetInst>(U)) { 222 if (isa<Constant>(MSI->getValue())) { 223 Changed = true; 224 MSI->eraseFromParent(); 225 } else if (Instruction *I = dyn_cast<Instruction>(MSI->getValue())) { 226 if (I->hasOneUse()) 227 Dead.push_back(std::make_pair(I, MSI)); 228 } 229 } else if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(U)) { 230 GlobalVariable *MemSrc = dyn_cast<GlobalVariable>(MTI->getSource()); 231 if (MemSrc && MemSrc->isConstant()) { 232 Changed = true; 233 MTI->eraseFromParent(); 234 } else if (Instruction *I = dyn_cast<Instruction>(MTI->getSource())) { 235 if (I->hasOneUse()) 236 Dead.push_back(std::make_pair(I, MTI)); 237 } 238 } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(U)) { 239 if (CE->use_empty()) { 240 CE->destroyConstant(); 241 Changed = true; 242 } 243 } else if (Constant *C = dyn_cast<Constant>(U)) { 244 if (isSafeToDestroyConstant(C)) { 245 C->destroyConstant(); 246 // This could have invalidated UI, start over from scratch. 247 Dead.clear(); 248 CleanupPointerRootUsers(GV, GetTLI); 249 return true; 250 } 251 } 252 } 253 254 for (int i = 0, e = Dead.size(); i != e; ++i) { 255 if (IsSafeComputationToRemove(Dead[i].first, GetTLI)) { 256 Dead[i].second->eraseFromParent(); 257 Instruction *I = Dead[i].first; 258 do { 259 if (isAllocationFn(I, GetTLI)) 260 break; 261 Instruction *J = dyn_cast<Instruction>(I->getOperand(0)); 262 if (!J) 263 break; 264 I->eraseFromParent(); 265 I = J; 266 } while (true); 267 I->eraseFromParent(); 268 Changed = true; 269 } 270 } 271 272 return Changed; 273 } 274 275 /// We just marked GV constant. Loop over all users of the global, cleaning up 276 /// the obvious ones. This is largely just a quick scan over the use list to 277 /// clean up the easy and obvious cruft. This returns true if it made a change. 278 static bool CleanupConstantGlobalUsers(GlobalVariable *GV, 279 const DataLayout &DL) { 280 Constant *Init = GV->getInitializer(); 281 SmallVector<User *, 8> WorkList(GV->users()); 282 SmallPtrSet<User *, 8> Visited; 283 bool Changed = false; 284 285 SmallVector<WeakTrackingVH> MaybeDeadInsts; 286 auto EraseFromParent = [&](Instruction *I) { 287 for (Value *Op : I->operands()) 288 if (auto *OpI = dyn_cast<Instruction>(Op)) 289 MaybeDeadInsts.push_back(OpI); 290 I->eraseFromParent(); 291 Changed = true; 292 }; 293 while (!WorkList.empty()) { 294 User *U = WorkList.pop_back_val(); 295 if (!Visited.insert(U).second) 296 continue; 297 298 if (auto *BO = dyn_cast<BitCastOperator>(U)) 299 append_range(WorkList, BO->users()); 300 if (auto *ASC = dyn_cast<AddrSpaceCastOperator>(U)) 301 append_range(WorkList, ASC->users()); 302 else if (auto *GEP = dyn_cast<GEPOperator>(U)) 303 append_range(WorkList, GEP->users()); 304 else if (auto *LI = dyn_cast<LoadInst>(U)) { 305 // A load from a uniform value is always the same, regardless of any 306 // applied offset. 307 Type *Ty = LI->getType(); 308 if (Constant *Res = ConstantFoldLoadFromUniformValue(Init, Ty)) { 309 LI->replaceAllUsesWith(Res); 310 EraseFromParent(LI); 311 continue; 312 } 313 314 Value *PtrOp = LI->getPointerOperand(); 315 APInt Offset(DL.getIndexTypeSizeInBits(PtrOp->getType()), 0); 316 PtrOp = PtrOp->stripAndAccumulateConstantOffsets( 317 DL, Offset, /* AllowNonInbounds */ true); 318 if (PtrOp == GV) { 319 if (auto *Value = ConstantFoldLoadFromConst(Init, Ty, Offset, DL)) { 320 LI->replaceAllUsesWith(Value); 321 EraseFromParent(LI); 322 } 323 } 324 } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) { 325 // Store must be unreachable or storing Init into the global. 326 EraseFromParent(SI); 327 } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(U)) { // memset/cpy/mv 328 if (getUnderlyingObject(MI->getRawDest()) == GV) 329 EraseFromParent(MI); 330 } 331 } 332 333 Changed |= 334 RecursivelyDeleteTriviallyDeadInstructionsPermissive(MaybeDeadInsts); 335 GV->removeDeadConstantUsers(); 336 return Changed; 337 } 338 339 /// Look at all uses of the global and determine which (offset, type) pairs it 340 /// can be split into. 341 static bool collectSRATypes(DenseMap<uint64_t, Type *> &Types, GlobalValue *GV, 342 const DataLayout &DL) { 343 SmallVector<Use *, 16> Worklist; 344 SmallPtrSet<Use *, 16> Visited; 345 auto AppendUses = [&](Value *V) { 346 for (Use &U : V->uses()) 347 if (Visited.insert(&U).second) 348 Worklist.push_back(&U); 349 }; 350 AppendUses(GV); 351 while (!Worklist.empty()) { 352 Use *U = Worklist.pop_back_val(); 353 User *V = U->getUser(); 354 355 auto *GEP = dyn_cast<GEPOperator>(V); 356 if (isa<BitCastOperator>(V) || isa<AddrSpaceCastOperator>(V) || 357 (GEP && GEP->hasAllConstantIndices())) { 358 AppendUses(V); 359 continue; 360 } 361 362 if (Value *Ptr = getLoadStorePointerOperand(V)) { 363 // This is storing the global address into somewhere, not storing into 364 // the global. 365 if (isa<StoreInst>(V) && U->getOperandNo() == 0) 366 return false; 367 368 APInt Offset(DL.getIndexTypeSizeInBits(Ptr->getType()), 0); 369 Ptr = Ptr->stripAndAccumulateConstantOffsets(DL, Offset, 370 /* AllowNonInbounds */ true); 371 if (Ptr != GV || Offset.getActiveBits() >= 64) 372 return false; 373 374 // TODO: We currently require that all accesses at a given offset must 375 // use the same type. This could be relaxed. 376 Type *Ty = getLoadStoreType(V); 377 auto It = Types.try_emplace(Offset.getZExtValue(), Ty).first; 378 if (Ty != It->second) 379 return false; 380 continue; 381 } 382 383 // Ignore dead constant users. 384 if (auto *C = dyn_cast<Constant>(V)) { 385 if (!isSafeToDestroyConstant(C)) 386 return false; 387 continue; 388 } 389 390 // Unknown user. 391 return false; 392 } 393 394 return true; 395 } 396 397 /// Copy over the debug info for a variable to its SRA replacements. 398 static void transferSRADebugInfo(GlobalVariable *GV, GlobalVariable *NGV, 399 uint64_t FragmentOffsetInBits, 400 uint64_t FragmentSizeInBits, 401 uint64_t VarSize) { 402 SmallVector<DIGlobalVariableExpression *, 1> GVs; 403 GV->getDebugInfo(GVs); 404 for (auto *GVE : GVs) { 405 DIVariable *Var = GVE->getVariable(); 406 DIExpression *Expr = GVE->getExpression(); 407 int64_t CurVarOffsetInBytes = 0; 408 uint64_t CurVarOffsetInBits = 0; 409 410 // Calculate the offset (Bytes), Continue if unknown. 411 if (!Expr->extractIfOffset(CurVarOffsetInBytes)) 412 continue; 413 414 // Ignore negative offset. 415 if (CurVarOffsetInBytes < 0) 416 continue; 417 418 // Convert offset to bits. 419 CurVarOffsetInBits = CHAR_BIT * (uint64_t)CurVarOffsetInBytes; 420 421 // Current var starts after the fragment, ignore. 422 if (CurVarOffsetInBits >= (FragmentOffsetInBits + FragmentSizeInBits)) 423 continue; 424 425 uint64_t CurVarSize = Var->getType()->getSizeInBits(); 426 // Current variable ends before start of fragment, ignore. 427 if (CurVarSize != 0 && 428 (CurVarOffsetInBits + CurVarSize) <= FragmentOffsetInBits) 429 continue; 430 431 // Current variable fits in the fragment. 432 if (CurVarOffsetInBits == FragmentOffsetInBits && 433 CurVarSize == FragmentSizeInBits) 434 Expr = DIExpression::get(Expr->getContext(), {}); 435 // If the FragmentSize is smaller than the variable, 436 // emit a fragment expression. 437 else if (FragmentSizeInBits < VarSize) { 438 if (auto E = DIExpression::createFragmentExpression( 439 Expr, FragmentOffsetInBits, FragmentSizeInBits)) 440 Expr = *E; 441 else 442 return; 443 } 444 auto *NGVE = DIGlobalVariableExpression::get(GVE->getContext(), Var, Expr); 445 NGV->addDebugInfo(NGVE); 446 } 447 } 448 449 /// Perform scalar replacement of aggregates on the specified global variable. 450 /// This opens the door for other optimizations by exposing the behavior of the 451 /// program in a more fine-grained way. We have determined that this 452 /// transformation is safe already. We return the first global variable we 453 /// insert so that the caller can reprocess it. 454 static GlobalVariable *SRAGlobal(GlobalVariable *GV, const DataLayout &DL) { 455 assert(GV->hasLocalLinkage()); 456 457 // Collect types to split into. 458 DenseMap<uint64_t, Type *> Types; 459 if (!collectSRATypes(Types, GV, DL) || Types.empty()) 460 return nullptr; 461 462 // Make sure we don't SRA back to the same type. 463 if (Types.size() == 1 && Types.begin()->second == GV->getValueType()) 464 return nullptr; 465 466 // Don't perform SRA if we would have to split into many globals. 467 if (Types.size() > 16) 468 return nullptr; 469 470 // Sort by offset. 471 SmallVector<std::pair<uint64_t, Type *>, 16> TypesVector; 472 append_range(TypesVector, Types); 473 sort(TypesVector, 474 [](const auto &A, const auto &B) { return A.first < B.first; }); 475 476 // Check that the types are non-overlapping. 477 uint64_t Offset = 0; 478 for (const auto &Pair : TypesVector) { 479 // Overlaps with previous type. 480 if (Pair.first < Offset) 481 return nullptr; 482 483 Offset = Pair.first + DL.getTypeAllocSize(Pair.second); 484 } 485 486 // Some accesses go beyond the end of the global, don't bother. 487 if (Offset > DL.getTypeAllocSize(GV->getValueType())) 488 return nullptr; 489 490 // Collect initializers for new globals. 491 Constant *OrigInit = GV->getInitializer(); 492 DenseMap<uint64_t, Constant *> Initializers; 493 for (const auto &Pair : Types) { 494 Constant *NewInit = ConstantFoldLoadFromConst(OrigInit, Pair.second, 495 APInt(64, Pair.first), DL); 496 if (!NewInit) { 497 LLVM_DEBUG(dbgs() << "Global SRA: Failed to evaluate initializer of " 498 << *GV << " with type " << *Pair.second << " at offset " 499 << Pair.first << "\n"); 500 return nullptr; 501 } 502 Initializers.insert({Pair.first, NewInit}); 503 } 504 505 LLVM_DEBUG(dbgs() << "PERFORMING GLOBAL SRA ON: " << *GV << "\n"); 506 507 // Get the alignment of the global, either explicit or target-specific. 508 Align StartAlignment = 509 DL.getValueOrABITypeAlignment(GV->getAlign(), GV->getValueType()); 510 uint64_t VarSize = DL.getTypeSizeInBits(GV->getValueType()); 511 512 // Create replacement globals. 513 DenseMap<uint64_t, GlobalVariable *> NewGlobals; 514 unsigned NameSuffix = 0; 515 for (auto &Pair : TypesVector) { 516 uint64_t Offset = Pair.first; 517 Type *Ty = Pair.second; 518 GlobalVariable *NGV = new GlobalVariable( 519 *GV->getParent(), Ty, false, GlobalVariable::InternalLinkage, 520 Initializers[Offset], GV->getName() + "." + Twine(NameSuffix++), GV, 521 GV->getThreadLocalMode(), GV->getAddressSpace()); 522 NGV->copyAttributesFrom(GV); 523 NewGlobals.insert({Offset, NGV}); 524 525 // Calculate the known alignment of the field. If the original aggregate 526 // had 256 byte alignment for example, something might depend on that: 527 // propagate info to each field. 528 Align NewAlign = commonAlignment(StartAlignment, Offset); 529 if (NewAlign > DL.getABITypeAlign(Ty)) 530 NGV->setAlignment(NewAlign); 531 532 // Copy over the debug info for the variable. 533 transferSRADebugInfo(GV, NGV, Offset * 8, DL.getTypeAllocSizeInBits(Ty), 534 VarSize); 535 } 536 537 // Replace uses of the original global with uses of the new global. 538 SmallVector<Value *, 16> Worklist; 539 SmallPtrSet<Value *, 16> Visited; 540 SmallVector<WeakTrackingVH, 16> DeadInsts; 541 auto AppendUsers = [&](Value *V) { 542 for (User *U : V->users()) 543 if (Visited.insert(U).second) 544 Worklist.push_back(U); 545 }; 546 AppendUsers(GV); 547 while (!Worklist.empty()) { 548 Value *V = Worklist.pop_back_val(); 549 if (isa<BitCastOperator>(V) || isa<AddrSpaceCastOperator>(V) || 550 isa<GEPOperator>(V)) { 551 AppendUsers(V); 552 if (isa<Instruction>(V)) 553 DeadInsts.push_back(V); 554 continue; 555 } 556 557 if (Value *Ptr = getLoadStorePointerOperand(V)) { 558 APInt Offset(DL.getIndexTypeSizeInBits(Ptr->getType()), 0); 559 Ptr = Ptr->stripAndAccumulateConstantOffsets(DL, Offset, 560 /* AllowNonInbounds */ true); 561 assert(Ptr == GV && "Load/store must be from/to global"); 562 GlobalVariable *NGV = NewGlobals[Offset.getZExtValue()]; 563 assert(NGV && "Must have replacement global for this offset"); 564 565 // Update the pointer operand and recalculate alignment. 566 Align PrefAlign = DL.getPrefTypeAlign(getLoadStoreType(V)); 567 Align NewAlign = 568 getOrEnforceKnownAlignment(NGV, PrefAlign, DL, cast<Instruction>(V)); 569 570 if (auto *LI = dyn_cast<LoadInst>(V)) { 571 LI->setOperand(0, NGV); 572 LI->setAlignment(NewAlign); 573 } else { 574 auto *SI = cast<StoreInst>(V); 575 SI->setOperand(1, NGV); 576 SI->setAlignment(NewAlign); 577 } 578 continue; 579 } 580 581 assert(isa<Constant>(V) && isSafeToDestroyConstant(cast<Constant>(V)) && 582 "Other users can only be dead constants"); 583 } 584 585 // Delete old instructions and global. 586 RecursivelyDeleteTriviallyDeadInstructions(DeadInsts); 587 GV->removeDeadConstantUsers(); 588 GV->eraseFromParent(); 589 ++NumSRA; 590 591 assert(NewGlobals.size() > 0); 592 return NewGlobals.begin()->second; 593 } 594 595 /// Return true if all users of the specified value will trap if the value is 596 /// dynamically null. PHIs keeps track of any phi nodes we've seen to avoid 597 /// reprocessing them. 598 static bool AllUsesOfValueWillTrapIfNull(const Value *V, 599 SmallPtrSetImpl<const PHINode*> &PHIs) { 600 for (const User *U : V->users()) { 601 if (const Instruction *I = dyn_cast<Instruction>(U)) { 602 // If null pointer is considered valid, then all uses are non-trapping. 603 // Non address-space 0 globals have already been pruned by the caller. 604 if (NullPointerIsDefined(I->getFunction())) 605 return false; 606 } 607 if (isa<LoadInst>(U)) { 608 // Will trap. 609 } else if (const StoreInst *SI = dyn_cast<StoreInst>(U)) { 610 if (SI->getOperand(0) == V) { 611 return false; // Storing the value. 612 } 613 } else if (const CallInst *CI = dyn_cast<CallInst>(U)) { 614 if (CI->getCalledOperand() != V) { 615 return false; // Not calling the ptr 616 } 617 } else if (const InvokeInst *II = dyn_cast<InvokeInst>(U)) { 618 if (II->getCalledOperand() != V) { 619 return false; // Not calling the ptr 620 } 621 } else if (const BitCastInst *CI = dyn_cast<BitCastInst>(U)) { 622 if (!AllUsesOfValueWillTrapIfNull(CI, PHIs)) return false; 623 } else if (const GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(U)) { 624 if (!AllUsesOfValueWillTrapIfNull(GEPI, PHIs)) return false; 625 } else if (const PHINode *PN = dyn_cast<PHINode>(U)) { 626 // If we've already seen this phi node, ignore it, it has already been 627 // checked. 628 if (PHIs.insert(PN).second && !AllUsesOfValueWillTrapIfNull(PN, PHIs)) 629 return false; 630 } else if (isa<ICmpInst>(U) && 631 !ICmpInst::isSigned(cast<ICmpInst>(U)->getPredicate()) && 632 isa<LoadInst>(U->getOperand(0)) && 633 isa<ConstantPointerNull>(U->getOperand(1))) { 634 assert(isa<GlobalValue>(cast<LoadInst>(U->getOperand(0)) 635 ->getPointerOperand() 636 ->stripPointerCasts()) && 637 "Should be GlobalVariable"); 638 // This and only this kind of non-signed ICmpInst is to be replaced with 639 // the comparing of the value of the created global init bool later in 640 // optimizeGlobalAddressOfAllocation for the global variable. 641 } else { 642 return false; 643 } 644 } 645 return true; 646 } 647 648 /// Return true if all uses of any loads from GV will trap if the loaded value 649 /// is null. Note that this also permits comparisons of the loaded value 650 /// against null, as a special case. 651 static bool allUsesOfLoadedValueWillTrapIfNull(const GlobalVariable *GV) { 652 SmallVector<const Value *, 4> Worklist; 653 Worklist.push_back(GV); 654 while (!Worklist.empty()) { 655 const Value *P = Worklist.pop_back_val(); 656 for (auto *U : P->users()) { 657 if (auto *LI = dyn_cast<LoadInst>(U)) { 658 SmallPtrSet<const PHINode *, 8> PHIs; 659 if (!AllUsesOfValueWillTrapIfNull(LI, PHIs)) 660 return false; 661 } else if (auto *SI = dyn_cast<StoreInst>(U)) { 662 // Ignore stores to the global. 663 if (SI->getPointerOperand() != P) 664 return false; 665 } else if (auto *CE = dyn_cast<ConstantExpr>(U)) { 666 if (CE->stripPointerCasts() != GV) 667 return false; 668 // Check further the ConstantExpr. 669 Worklist.push_back(CE); 670 } else { 671 // We don't know or understand this user, bail out. 672 return false; 673 } 674 } 675 } 676 677 return true; 678 } 679 680 /// Get all the loads/store uses for global variable \p GV. 681 static void allUsesOfLoadAndStores(GlobalVariable *GV, 682 SmallVector<Value *, 4> &Uses) { 683 SmallVector<Value *, 4> Worklist; 684 Worklist.push_back(GV); 685 while (!Worklist.empty()) { 686 auto *P = Worklist.pop_back_val(); 687 for (auto *U : P->users()) { 688 if (auto *CE = dyn_cast<ConstantExpr>(U)) { 689 Worklist.push_back(CE); 690 continue; 691 } 692 693 assert((isa<LoadInst>(U) || isa<StoreInst>(U)) && 694 "Expect only load or store instructions"); 695 Uses.push_back(U); 696 } 697 } 698 } 699 700 static bool OptimizeAwayTrappingUsesOfValue(Value *V, Constant *NewV) { 701 bool Changed = false; 702 for (auto UI = V->user_begin(), E = V->user_end(); UI != E; ) { 703 Instruction *I = cast<Instruction>(*UI++); 704 // Uses are non-trapping if null pointer is considered valid. 705 // Non address-space 0 globals are already pruned by the caller. 706 if (NullPointerIsDefined(I->getFunction())) 707 return false; 708 if (LoadInst *LI = dyn_cast<LoadInst>(I)) { 709 LI->setOperand(0, NewV); 710 Changed = true; 711 } else if (StoreInst *SI = dyn_cast<StoreInst>(I)) { 712 if (SI->getOperand(1) == V) { 713 SI->setOperand(1, NewV); 714 Changed = true; 715 } 716 } else if (isa<CallInst>(I) || isa<InvokeInst>(I)) { 717 CallBase *CB = cast<CallBase>(I); 718 if (CB->getCalledOperand() == V) { 719 // Calling through the pointer! Turn into a direct call, but be careful 720 // that the pointer is not also being passed as an argument. 721 CB->setCalledOperand(NewV); 722 Changed = true; 723 bool PassedAsArg = false; 724 for (unsigned i = 0, e = CB->arg_size(); i != e; ++i) 725 if (CB->getArgOperand(i) == V) { 726 PassedAsArg = true; 727 CB->setArgOperand(i, NewV); 728 } 729 730 if (PassedAsArg) { 731 // Being passed as an argument also. Be careful to not invalidate UI! 732 UI = V->user_begin(); 733 } 734 } 735 } else if (CastInst *CI = dyn_cast<CastInst>(I)) { 736 Changed |= OptimizeAwayTrappingUsesOfValue(CI, 737 ConstantExpr::getCast(CI->getOpcode(), 738 NewV, CI->getType())); 739 if (CI->use_empty()) { 740 Changed = true; 741 CI->eraseFromParent(); 742 } 743 } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) { 744 // Should handle GEP here. 745 SmallVector<Constant*, 8> Idxs; 746 Idxs.reserve(GEPI->getNumOperands()-1); 747 for (User::op_iterator i = GEPI->op_begin() + 1, e = GEPI->op_end(); 748 i != e; ++i) 749 if (Constant *C = dyn_cast<Constant>(*i)) 750 Idxs.push_back(C); 751 else 752 break; 753 if (Idxs.size() == GEPI->getNumOperands()-1) 754 Changed |= OptimizeAwayTrappingUsesOfValue( 755 GEPI, ConstantExpr::getGetElementPtr(GEPI->getSourceElementType(), 756 NewV, Idxs)); 757 if (GEPI->use_empty()) { 758 Changed = true; 759 GEPI->eraseFromParent(); 760 } 761 } 762 } 763 764 return Changed; 765 } 766 767 /// The specified global has only one non-null value stored into it. If there 768 /// are uses of the loaded value that would trap if the loaded value is 769 /// dynamically null, then we know that they cannot be reachable with a null 770 /// optimize away the load. 771 static bool OptimizeAwayTrappingUsesOfLoads( 772 GlobalVariable *GV, Constant *LV, const DataLayout &DL, 773 function_ref<TargetLibraryInfo &(Function &)> GetTLI) { 774 bool Changed = false; 775 776 // Keep track of whether we are able to remove all the uses of the global 777 // other than the store that defines it. 778 bool AllNonStoreUsesGone = true; 779 780 // Replace all uses of loads with uses of uses of the stored value. 781 for (User *GlobalUser : llvm::make_early_inc_range(GV->users())) { 782 if (LoadInst *LI = dyn_cast<LoadInst>(GlobalUser)) { 783 Changed |= OptimizeAwayTrappingUsesOfValue(LI, LV); 784 // If we were able to delete all uses of the loads 785 if (LI->use_empty()) { 786 LI->eraseFromParent(); 787 Changed = true; 788 } else { 789 AllNonStoreUsesGone = false; 790 } 791 } else if (isa<StoreInst>(GlobalUser)) { 792 // Ignore the store that stores "LV" to the global. 793 assert(GlobalUser->getOperand(1) == GV && 794 "Must be storing *to* the global"); 795 } else { 796 AllNonStoreUsesGone = false; 797 798 // If we get here we could have other crazy uses that are transitively 799 // loaded. 800 assert((isa<PHINode>(GlobalUser) || isa<SelectInst>(GlobalUser) || 801 isa<ConstantExpr>(GlobalUser) || isa<CmpInst>(GlobalUser) || 802 isa<BitCastInst>(GlobalUser) || 803 isa<GetElementPtrInst>(GlobalUser)) && 804 "Only expect load and stores!"); 805 } 806 } 807 808 if (Changed) { 809 LLVM_DEBUG(dbgs() << "OPTIMIZED LOADS FROM STORED ONCE POINTER: " << *GV 810 << "\n"); 811 ++NumGlobUses; 812 } 813 814 // If we nuked all of the loads, then none of the stores are needed either, 815 // nor is the global. 816 if (AllNonStoreUsesGone) { 817 if (isLeakCheckerRoot(GV)) { 818 Changed |= CleanupPointerRootUsers(GV, GetTLI); 819 } else { 820 Changed = true; 821 CleanupConstantGlobalUsers(GV, DL); 822 } 823 if (GV->use_empty()) { 824 LLVM_DEBUG(dbgs() << " *** GLOBAL NOW DEAD!\n"); 825 Changed = true; 826 GV->eraseFromParent(); 827 ++NumDeleted; 828 } 829 } 830 return Changed; 831 } 832 833 /// Walk the use list of V, constant folding all of the instructions that are 834 /// foldable. 835 static void ConstantPropUsersOf(Value *V, const DataLayout &DL, 836 TargetLibraryInfo *TLI) { 837 for (Value::user_iterator UI = V->user_begin(), E = V->user_end(); UI != E; ) 838 if (Instruction *I = dyn_cast<Instruction>(*UI++)) 839 if (Constant *NewC = ConstantFoldInstruction(I, DL, TLI)) { 840 I->replaceAllUsesWith(NewC); 841 842 // Advance UI to the next non-I use to avoid invalidating it! 843 // Instructions could multiply use V. 844 while (UI != E && *UI == I) 845 ++UI; 846 if (isInstructionTriviallyDead(I, TLI)) 847 I->eraseFromParent(); 848 } 849 } 850 851 /// This function takes the specified global variable, and transforms the 852 /// program as if it always contained the result of the specified malloc. 853 /// Because it is always the result of the specified malloc, there is no reason 854 /// to actually DO the malloc. Instead, turn the malloc into a global, and any 855 /// loads of GV as uses of the new global. 856 static GlobalVariable * 857 OptimizeGlobalAddressOfAllocation(GlobalVariable *GV, CallInst *CI, 858 uint64_t AllocSize, Constant *InitVal, 859 const DataLayout &DL, 860 TargetLibraryInfo *TLI) { 861 LLVM_DEBUG(errs() << "PROMOTING GLOBAL: " << *GV << " CALL = " << *CI 862 << '\n'); 863 864 // Create global of type [AllocSize x i8]. 865 Type *GlobalType = ArrayType::get(Type::getInt8Ty(GV->getContext()), 866 AllocSize); 867 868 // Create the new global variable. The contents of the allocated memory is 869 // undefined initially, so initialize with an undef value. 870 GlobalVariable *NewGV = new GlobalVariable( 871 *GV->getParent(), GlobalType, false, GlobalValue::InternalLinkage, 872 UndefValue::get(GlobalType), GV->getName() + ".body", nullptr, 873 GV->getThreadLocalMode()); 874 875 // Initialize the global at the point of the original call. Note that this 876 // is a different point from the initialization referred to below for the 877 // nullability handling. Sublety: We have not proven the original global was 878 // only initialized once. As such, we can not fold this into the initializer 879 // of the new global as may need to re-init the storage multiple times. 880 if (!isa<UndefValue>(InitVal)) { 881 IRBuilder<> Builder(CI->getNextNode()); 882 // TODO: Use alignment above if align!=1 883 Builder.CreateMemSet(NewGV, InitVal, AllocSize, None); 884 } 885 886 // Update users of the allocation to use the new global instead. 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 SmallSetVector<Constant *, 1> RepValues; 905 RepValues.insert(NewGV); 906 907 // If there is a comparison against null, we will insert a global bool to 908 // keep track of whether the global was initialized yet or not. 909 GlobalVariable *InitBool = 910 new GlobalVariable(Type::getInt1Ty(GV->getContext()), false, 911 GlobalValue::InternalLinkage, 912 ConstantInt::getFalse(GV->getContext()), 913 GV->getName()+".init", GV->getThreadLocalMode()); 914 bool InitBoolUsed = false; 915 916 // Loop over all instruction uses of GV, processing them in turn. 917 SmallVector<Value *, 4> Guses; 918 allUsesOfLoadAndStores(GV, Guses); 919 for (auto *U : Guses) { 920 if (StoreInst *SI = dyn_cast<StoreInst>(U)) { 921 // The global is initialized when the store to it occurs. If the stored 922 // value is null value, the global bool is set to false, otherwise true. 923 new StoreInst(ConstantInt::getBool( 924 GV->getContext(), 925 !isa<ConstantPointerNull>(SI->getValueOperand())), 926 InitBool, false, Align(1), SI->getOrdering(), 927 SI->getSyncScopeID(), SI); 928 SI->eraseFromParent(); 929 continue; 930 } 931 932 LoadInst *LI = cast<LoadInst>(U); 933 while (!LI->use_empty()) { 934 Use &LoadUse = *LI->use_begin(); 935 ICmpInst *ICI = dyn_cast<ICmpInst>(LoadUse.getUser()); 936 if (!ICI) { 937 auto *CE = ConstantExpr::getBitCast(NewGV, LI->getType()); 938 RepValues.insert(CE); 939 LoadUse.set(CE); 940 continue; 941 } 942 943 // Replace the cmp X, 0 with a use of the bool value. 944 Value *LV = new LoadInst(InitBool->getValueType(), InitBool, 945 InitBool->getName() + ".val", false, Align(1), 946 LI->getOrdering(), LI->getSyncScopeID(), LI); 947 InitBoolUsed = true; 948 switch (ICI->getPredicate()) { 949 default: llvm_unreachable("Unknown ICmp Predicate!"); 950 case ICmpInst::ICMP_ULT: // X < null -> always false 951 LV = ConstantInt::getFalse(GV->getContext()); 952 break; 953 case ICmpInst::ICMP_UGE: // X >= null -> always true 954 LV = ConstantInt::getTrue(GV->getContext()); 955 break; 956 case ICmpInst::ICMP_ULE: 957 case ICmpInst::ICMP_EQ: 958 LV = BinaryOperator::CreateNot(LV, "notinit", ICI); 959 break; 960 case ICmpInst::ICMP_NE: 961 case ICmpInst::ICMP_UGT: 962 break; // no change. 963 } 964 ICI->replaceAllUsesWith(LV); 965 ICI->eraseFromParent(); 966 } 967 LI->eraseFromParent(); 968 } 969 970 // If the initialization boolean was used, insert it, otherwise delete it. 971 if (!InitBoolUsed) { 972 while (!InitBool->use_empty()) // Delete initializations 973 cast<StoreInst>(InitBool->user_back())->eraseFromParent(); 974 delete InitBool; 975 } else 976 GV->getParent()->getGlobalList().insert(GV->getIterator(), InitBool); 977 978 // Now the GV is dead, nuke it and the allocation.. 979 GV->eraseFromParent(); 980 CI->eraseFromParent(); 981 982 // To further other optimizations, loop over all users of NewGV and try to 983 // constant prop them. This will promote GEP instructions with constant 984 // indices into GEP constant-exprs, which will allow global-opt to hack on it. 985 for (auto *CE : RepValues) 986 ConstantPropUsersOf(CE, DL, TLI); 987 988 return NewGV; 989 } 990 991 /// Scan the use-list of GV checking to make sure that there are no complex uses 992 /// of GV. We permit simple things like dereferencing the pointer, but not 993 /// storing through the address, unless it is to the specified global. 994 static bool 995 valueIsOnlyUsedLocallyOrStoredToOneGlobal(const CallInst *CI, 996 const GlobalVariable *GV) { 997 SmallPtrSet<const Value *, 4> Visited; 998 SmallVector<const Value *, 4> Worklist; 999 Worklist.push_back(CI); 1000 1001 while (!Worklist.empty()) { 1002 const Value *V = Worklist.pop_back_val(); 1003 if (!Visited.insert(V).second) 1004 continue; 1005 1006 for (const Use &VUse : V->uses()) { 1007 const User *U = VUse.getUser(); 1008 if (isa<LoadInst>(U) || isa<CmpInst>(U)) 1009 continue; // Fine, ignore. 1010 1011 if (auto *SI = dyn_cast<StoreInst>(U)) { 1012 if (SI->getValueOperand() == V && 1013 SI->getPointerOperand()->stripPointerCasts() != GV) 1014 return false; // Storing the pointer not into GV... bad. 1015 continue; // Otherwise, storing through it, or storing into GV... fine. 1016 } 1017 1018 if (auto *BCI = dyn_cast<BitCastInst>(U)) { 1019 Worklist.push_back(BCI); 1020 continue; 1021 } 1022 1023 if (auto *GEPI = dyn_cast<GetElementPtrInst>(U)) { 1024 Worklist.push_back(GEPI); 1025 continue; 1026 } 1027 1028 return false; 1029 } 1030 } 1031 1032 return true; 1033 } 1034 1035 /// If we have a global that is only initialized with a fixed size allocation 1036 /// try to transform the program to use global memory instead of heap 1037 /// allocated memory. This eliminates dynamic allocation, avoids an indirection 1038 /// accessing the data, and exposes the resultant global to further GlobalOpt. 1039 static bool tryToOptimizeStoreOfAllocationToGlobal(GlobalVariable *GV, 1040 CallInst *CI, 1041 const DataLayout &DL, 1042 TargetLibraryInfo *TLI) { 1043 if (!isAllocRemovable(CI, TLI)) 1044 // Must be able to remove the call when we get done.. 1045 return false; 1046 1047 Type *Int8Ty = Type::getInt8Ty(CI->getFunction()->getContext()); 1048 Constant *InitVal = getInitialValueOfAllocation(CI, TLI, Int8Ty); 1049 if (!InitVal) 1050 // Must be able to emit a memset for initialization 1051 return false; 1052 1053 uint64_t AllocSize; 1054 if (!getObjectSize(CI, AllocSize, DL, TLI, ObjectSizeOpts())) 1055 return false; 1056 1057 // Restrict this transformation to only working on small allocations 1058 // (2048 bytes currently), as we don't want to introduce a 16M global or 1059 // something. 1060 if (AllocSize >= 2048) 1061 return false; 1062 1063 // We can't optimize this global unless all uses of it are *known* to be 1064 // of the malloc value, not of the null initializer value (consider a use 1065 // that compares the global's value against zero to see if the malloc has 1066 // been reached). To do this, we check to see if all uses of the global 1067 // would trap if the global were null: this proves that they must all 1068 // happen after the malloc. 1069 if (!allUsesOfLoadedValueWillTrapIfNull(GV)) 1070 return false; 1071 1072 // We can't optimize this if the malloc itself is used in a complex way, 1073 // for example, being stored into multiple globals. This allows the 1074 // malloc to be stored into the specified global, loaded, gep, icmp'd. 1075 // These are all things we could transform to using the global for. 1076 if (!valueIsOnlyUsedLocallyOrStoredToOneGlobal(CI, GV)) 1077 return false; 1078 1079 OptimizeGlobalAddressOfAllocation(GV, CI, AllocSize, InitVal, DL, TLI); 1080 return true; 1081 } 1082 1083 // Try to optimize globals based on the knowledge that only one value (besides 1084 // its initializer) is ever stored to the global. 1085 static bool 1086 optimizeOnceStoredGlobal(GlobalVariable *GV, Value *StoredOnceVal, 1087 const DataLayout &DL, 1088 function_ref<TargetLibraryInfo &(Function &)> GetTLI) { 1089 // Ignore no-op GEPs and bitcasts. 1090 StoredOnceVal = StoredOnceVal->stripPointerCasts(); 1091 1092 // If we are dealing with a pointer global that is initialized to null and 1093 // only has one (non-null) value stored into it, then we can optimize any 1094 // users of the loaded value (often calls and loads) that would trap if the 1095 // value was null. 1096 if (GV->getInitializer()->getType()->isPointerTy() && 1097 GV->getInitializer()->isNullValue() && 1098 StoredOnceVal->getType()->isPointerTy() && 1099 !NullPointerIsDefined( 1100 nullptr /* F */, 1101 GV->getInitializer()->getType()->getPointerAddressSpace())) { 1102 if (Constant *SOVC = dyn_cast<Constant>(StoredOnceVal)) { 1103 if (GV->getInitializer()->getType() != SOVC->getType()) 1104 SOVC = ConstantExpr::getBitCast(SOVC, GV->getInitializer()->getType()); 1105 1106 // Optimize away any trapping uses of the loaded value. 1107 if (OptimizeAwayTrappingUsesOfLoads(GV, SOVC, DL, GetTLI)) 1108 return true; 1109 } else if (isAllocationFn(StoredOnceVal, GetTLI)) { 1110 if (auto *CI = dyn_cast<CallInst>(StoredOnceVal)) { 1111 auto *TLI = &GetTLI(*CI->getFunction()); 1112 if (tryToOptimizeStoreOfAllocationToGlobal(GV, CI, DL, TLI)) 1113 return true; 1114 } 1115 } 1116 } 1117 1118 return false; 1119 } 1120 1121 /// At this point, we have learned that the only two values ever stored into GV 1122 /// are its initializer and OtherVal. See if we can shrink the global into a 1123 /// boolean and select between the two values whenever it is used. This exposes 1124 /// the values to other scalar optimizations. 1125 static bool TryToShrinkGlobalToBoolean(GlobalVariable *GV, Constant *OtherVal) { 1126 Type *GVElType = GV->getValueType(); 1127 1128 // If GVElType is already i1, it is already shrunk. If the type of the GV is 1129 // an FP value, pointer or vector, don't do this optimization because a select 1130 // between them is very expensive and unlikely to lead to later 1131 // simplification. In these cases, we typically end up with "cond ? v1 : v2" 1132 // where v1 and v2 both require constant pool loads, a big loss. 1133 if (GVElType == Type::getInt1Ty(GV->getContext()) || 1134 GVElType->isFloatingPointTy() || 1135 GVElType->isPointerTy() || GVElType->isVectorTy()) 1136 return false; 1137 1138 // Walk the use list of the global seeing if all the uses are load or store. 1139 // If there is anything else, bail out. 1140 for (User *U : GV->users()) { 1141 if (!isa<LoadInst>(U) && !isa<StoreInst>(U)) 1142 return false; 1143 if (getLoadStoreType(U) != GVElType) 1144 return false; 1145 } 1146 1147 LLVM_DEBUG(dbgs() << " *** SHRINKING TO BOOL: " << *GV << "\n"); 1148 1149 // Create the new global, initializing it to false. 1150 GlobalVariable *NewGV = new GlobalVariable(Type::getInt1Ty(GV->getContext()), 1151 false, 1152 GlobalValue::InternalLinkage, 1153 ConstantInt::getFalse(GV->getContext()), 1154 GV->getName()+".b", 1155 GV->getThreadLocalMode(), 1156 GV->getType()->getAddressSpace()); 1157 NewGV->copyAttributesFrom(GV); 1158 GV->getParent()->getGlobalList().insert(GV->getIterator(), NewGV); 1159 1160 Constant *InitVal = GV->getInitializer(); 1161 assert(InitVal->getType() != Type::getInt1Ty(GV->getContext()) && 1162 "No reason to shrink to bool!"); 1163 1164 SmallVector<DIGlobalVariableExpression *, 1> GVs; 1165 GV->getDebugInfo(GVs); 1166 1167 // If initialized to zero and storing one into the global, we can use a cast 1168 // instead of a select to synthesize the desired value. 1169 bool IsOneZero = false; 1170 bool EmitOneOrZero = true; 1171 auto *CI = dyn_cast<ConstantInt>(OtherVal); 1172 if (CI && CI->getValue().getActiveBits() <= 64) { 1173 IsOneZero = InitVal->isNullValue() && CI->isOne(); 1174 1175 auto *CIInit = dyn_cast<ConstantInt>(GV->getInitializer()); 1176 if (CIInit && CIInit->getValue().getActiveBits() <= 64) { 1177 uint64_t ValInit = CIInit->getZExtValue(); 1178 uint64_t ValOther = CI->getZExtValue(); 1179 uint64_t ValMinus = ValOther - ValInit; 1180 1181 for(auto *GVe : GVs){ 1182 DIGlobalVariable *DGV = GVe->getVariable(); 1183 DIExpression *E = GVe->getExpression(); 1184 const DataLayout &DL = GV->getParent()->getDataLayout(); 1185 unsigned SizeInOctets = 1186 DL.getTypeAllocSizeInBits(NewGV->getValueType()) / 8; 1187 1188 // It is expected that the address of global optimized variable is on 1189 // top of the stack. After optimization, value of that variable will 1190 // be ether 0 for initial value or 1 for other value. The following 1191 // expression should return constant integer value depending on the 1192 // value at global object address: 1193 // val * (ValOther - ValInit) + ValInit: 1194 // DW_OP_deref DW_OP_constu <ValMinus> 1195 // DW_OP_mul DW_OP_constu <ValInit> DW_OP_plus DW_OP_stack_value 1196 SmallVector<uint64_t, 12> Ops = { 1197 dwarf::DW_OP_deref_size, SizeInOctets, 1198 dwarf::DW_OP_constu, ValMinus, 1199 dwarf::DW_OP_mul, dwarf::DW_OP_constu, ValInit, 1200 dwarf::DW_OP_plus}; 1201 bool WithStackValue = true; 1202 E = DIExpression::prependOpcodes(E, Ops, WithStackValue); 1203 DIGlobalVariableExpression *DGVE = 1204 DIGlobalVariableExpression::get(NewGV->getContext(), DGV, E); 1205 NewGV->addDebugInfo(DGVE); 1206 } 1207 EmitOneOrZero = false; 1208 } 1209 } 1210 1211 if (EmitOneOrZero) { 1212 // FIXME: This will only emit address for debugger on which will 1213 // be written only 0 or 1. 1214 for(auto *GV : GVs) 1215 NewGV->addDebugInfo(GV); 1216 } 1217 1218 while (!GV->use_empty()) { 1219 Instruction *UI = cast<Instruction>(GV->user_back()); 1220 if (StoreInst *SI = dyn_cast<StoreInst>(UI)) { 1221 // Change the store into a boolean store. 1222 bool StoringOther = SI->getOperand(0) == OtherVal; 1223 // Only do this if we weren't storing a loaded value. 1224 Value *StoreVal; 1225 if (StoringOther || SI->getOperand(0) == InitVal) { 1226 StoreVal = ConstantInt::get(Type::getInt1Ty(GV->getContext()), 1227 StoringOther); 1228 } else { 1229 // Otherwise, we are storing a previously loaded copy. To do this, 1230 // change the copy from copying the original value to just copying the 1231 // bool. 1232 Instruction *StoredVal = cast<Instruction>(SI->getOperand(0)); 1233 1234 // If we've already replaced the input, StoredVal will be a cast or 1235 // select instruction. If not, it will be a load of the original 1236 // global. 1237 if (LoadInst *LI = dyn_cast<LoadInst>(StoredVal)) { 1238 assert(LI->getOperand(0) == GV && "Not a copy!"); 1239 // Insert a new load, to preserve the saved value. 1240 StoreVal = new LoadInst(NewGV->getValueType(), NewGV, 1241 LI->getName() + ".b", false, Align(1), 1242 LI->getOrdering(), LI->getSyncScopeID(), LI); 1243 } else { 1244 assert((isa<CastInst>(StoredVal) || isa<SelectInst>(StoredVal)) && 1245 "This is not a form that we understand!"); 1246 StoreVal = StoredVal->getOperand(0); 1247 assert(isa<LoadInst>(StoreVal) && "Not a load of NewGV!"); 1248 } 1249 } 1250 StoreInst *NSI = 1251 new StoreInst(StoreVal, NewGV, false, Align(1), SI->getOrdering(), 1252 SI->getSyncScopeID(), SI); 1253 NSI->setDebugLoc(SI->getDebugLoc()); 1254 } else { 1255 // Change the load into a load of bool then a select. 1256 LoadInst *LI = cast<LoadInst>(UI); 1257 LoadInst *NLI = new LoadInst(NewGV->getValueType(), NewGV, 1258 LI->getName() + ".b", false, Align(1), 1259 LI->getOrdering(), LI->getSyncScopeID(), LI); 1260 Instruction *NSI; 1261 if (IsOneZero) 1262 NSI = new ZExtInst(NLI, LI->getType(), "", LI); 1263 else 1264 NSI = SelectInst::Create(NLI, OtherVal, InitVal, "", LI); 1265 NSI->takeName(LI); 1266 // Since LI is split into two instructions, NLI and NSI both inherit the 1267 // same DebugLoc 1268 NLI->setDebugLoc(LI->getDebugLoc()); 1269 NSI->setDebugLoc(LI->getDebugLoc()); 1270 LI->replaceAllUsesWith(NSI); 1271 } 1272 UI->eraseFromParent(); 1273 } 1274 1275 // Retain the name of the old global variable. People who are debugging their 1276 // programs may expect these variables to be named the same. 1277 NewGV->takeName(GV); 1278 GV->eraseFromParent(); 1279 return true; 1280 } 1281 1282 static bool deleteIfDead( 1283 GlobalValue &GV, SmallPtrSetImpl<const Comdat *> &NotDiscardableComdats) { 1284 GV.removeDeadConstantUsers(); 1285 1286 if (!GV.isDiscardableIfUnused() && !GV.isDeclaration()) 1287 return false; 1288 1289 if (const Comdat *C = GV.getComdat()) 1290 if (!GV.hasLocalLinkage() && NotDiscardableComdats.count(C)) 1291 return false; 1292 1293 bool Dead; 1294 if (auto *F = dyn_cast<Function>(&GV)) 1295 Dead = (F->isDeclaration() && F->use_empty()) || F->isDefTriviallyDead(); 1296 else 1297 Dead = GV.use_empty(); 1298 if (!Dead) 1299 return false; 1300 1301 LLVM_DEBUG(dbgs() << "GLOBAL DEAD: " << GV << "\n"); 1302 GV.eraseFromParent(); 1303 ++NumDeleted; 1304 return true; 1305 } 1306 1307 static bool isPointerValueDeadOnEntryToFunction( 1308 const Function *F, GlobalValue *GV, 1309 function_ref<DominatorTree &(Function &)> LookupDomTree) { 1310 // Find all uses of GV. We expect them all to be in F, and if we can't 1311 // identify any of the uses we bail out. 1312 // 1313 // On each of these uses, identify if the memory that GV points to is 1314 // used/required/live at the start of the function. If it is not, for example 1315 // if the first thing the function does is store to the GV, the GV can 1316 // possibly be demoted. 1317 // 1318 // We don't do an exhaustive search for memory operations - simply look 1319 // through bitcasts as they're quite common and benign. 1320 const DataLayout &DL = GV->getParent()->getDataLayout(); 1321 SmallVector<LoadInst *, 4> Loads; 1322 SmallVector<StoreInst *, 4> Stores; 1323 for (auto *U : GV->users()) { 1324 if (Operator::getOpcode(U) == Instruction::BitCast) { 1325 for (auto *UU : U->users()) { 1326 if (auto *LI = dyn_cast<LoadInst>(UU)) 1327 Loads.push_back(LI); 1328 else if (auto *SI = dyn_cast<StoreInst>(UU)) 1329 Stores.push_back(SI); 1330 else 1331 return false; 1332 } 1333 continue; 1334 } 1335 1336 Instruction *I = dyn_cast<Instruction>(U); 1337 if (!I) 1338 return false; 1339 assert(I->getParent()->getParent() == F); 1340 1341 if (auto *LI = dyn_cast<LoadInst>(I)) 1342 Loads.push_back(LI); 1343 else if (auto *SI = dyn_cast<StoreInst>(I)) 1344 Stores.push_back(SI); 1345 else 1346 return false; 1347 } 1348 1349 // We have identified all uses of GV into loads and stores. Now check if all 1350 // of them are known not to depend on the value of the global at the function 1351 // entry point. We do this by ensuring that every load is dominated by at 1352 // least one store. 1353 auto &DT = LookupDomTree(*const_cast<Function *>(F)); 1354 1355 // The below check is quadratic. Check we're not going to do too many tests. 1356 // FIXME: Even though this will always have worst-case quadratic time, we 1357 // could put effort into minimizing the average time by putting stores that 1358 // have been shown to dominate at least one load at the beginning of the 1359 // Stores array, making subsequent dominance checks more likely to succeed 1360 // early. 1361 // 1362 // The threshold here is fairly large because global->local demotion is a 1363 // very powerful optimization should it fire. 1364 const unsigned Threshold = 100; 1365 if (Loads.size() * Stores.size() > Threshold) 1366 return false; 1367 1368 for (auto *L : Loads) { 1369 auto *LTy = L->getType(); 1370 if (none_of(Stores, [&](const StoreInst *S) { 1371 auto *STy = S->getValueOperand()->getType(); 1372 // The load is only dominated by the store if DomTree says so 1373 // and the number of bits loaded in L is less than or equal to 1374 // the number of bits stored in S. 1375 return DT.dominates(S, L) && 1376 DL.getTypeStoreSize(LTy).getFixedSize() <= 1377 DL.getTypeStoreSize(STy).getFixedSize(); 1378 })) 1379 return false; 1380 } 1381 // All loads have known dependences inside F, so the global can be localized. 1382 return true; 1383 } 1384 1385 /// C may have non-instruction users. Can all of those users be turned into 1386 /// instructions? 1387 static bool allNonInstructionUsersCanBeMadeInstructions(Constant *C) { 1388 // We don't do this exhaustively. The most common pattern that we really need 1389 // to care about is a constant GEP or constant bitcast - so just looking 1390 // through one single ConstantExpr. 1391 // 1392 // The set of constants that this function returns true for must be able to be 1393 // handled by makeAllConstantUsesInstructions. 1394 for (auto *U : C->users()) { 1395 if (isa<Instruction>(U)) 1396 continue; 1397 if (!isa<ConstantExpr>(U)) 1398 // Non instruction, non-constantexpr user; cannot convert this. 1399 return false; 1400 for (auto *UU : U->users()) 1401 if (!isa<Instruction>(UU)) 1402 // A constantexpr used by another constant. We don't try and recurse any 1403 // further but just bail out at this point. 1404 return false; 1405 } 1406 1407 return true; 1408 } 1409 1410 /// C may have non-instruction users, and 1411 /// allNonInstructionUsersCanBeMadeInstructions has returned true. Convert the 1412 /// non-instruction users to instructions. 1413 static void makeAllConstantUsesInstructions(Constant *C) { 1414 SmallVector<ConstantExpr*,4> Users; 1415 for (auto *U : C->users()) { 1416 if (isa<ConstantExpr>(U)) 1417 Users.push_back(cast<ConstantExpr>(U)); 1418 else 1419 // We should never get here; allNonInstructionUsersCanBeMadeInstructions 1420 // should not have returned true for C. 1421 assert( 1422 isa<Instruction>(U) && 1423 "Can't transform non-constantexpr non-instruction to instruction!"); 1424 } 1425 1426 SmallVector<Value*,4> UUsers; 1427 for (auto *U : Users) { 1428 UUsers.clear(); 1429 append_range(UUsers, U->users()); 1430 for (auto *UU : UUsers) { 1431 Instruction *UI = cast<Instruction>(UU); 1432 Instruction *NewU = U->getAsInstruction(UI); 1433 UI->replaceUsesOfWith(U, NewU); 1434 } 1435 // We've replaced all the uses, so destroy the constant. (destroyConstant 1436 // will update value handles and metadata.) 1437 U->destroyConstant(); 1438 } 1439 } 1440 1441 // For a global variable with one store, if the store dominates any loads, 1442 // those loads will always load the stored value (as opposed to the 1443 // initializer), even in the presence of recursion. 1444 static bool forwardStoredOnceStore( 1445 GlobalVariable *GV, const StoreInst *StoredOnceStore, 1446 function_ref<DominatorTree &(Function &)> LookupDomTree) { 1447 const Value *StoredOnceValue = StoredOnceStore->getValueOperand(); 1448 SmallVector<LoadInst *> Loads; 1449 const Function *F = StoredOnceStore->getFunction(); 1450 for (User *U : GV->users()) { 1451 if (auto *LI = dyn_cast<LoadInst>(U)) { 1452 if (LI->getFunction() == F && 1453 LI->getType() == StoredOnceValue->getType() && LI->isSimple()) 1454 Loads.push_back(LI); 1455 } 1456 } 1457 // Only compute DT if we have any loads to examine. 1458 bool MadeChange = false; 1459 if (!Loads.empty()) { 1460 auto &DT = LookupDomTree(*const_cast<Function *>(F)); 1461 for (auto *LI : Loads) { 1462 if (DT.dominates(StoredOnceStore, LI)) { 1463 LI->replaceAllUsesWith(const_cast<Value *>(StoredOnceValue)); 1464 LI->eraseFromParent(); 1465 MadeChange = true; 1466 } 1467 } 1468 } 1469 return MadeChange; 1470 } 1471 1472 /// Analyze the specified global variable and optimize 1473 /// it if possible. If we make a change, return true. 1474 static bool 1475 processInternalGlobal(GlobalVariable *GV, const GlobalStatus &GS, 1476 function_ref<TargetTransformInfo &(Function &)> GetTTI, 1477 function_ref<TargetLibraryInfo &(Function &)> GetTLI, 1478 function_ref<DominatorTree &(Function &)> LookupDomTree) { 1479 auto &DL = GV->getParent()->getDataLayout(); 1480 // If this is a first class global and has only one accessing function and 1481 // this function is non-recursive, we replace the global with a local alloca 1482 // in this function. 1483 // 1484 // NOTE: It doesn't make sense to promote non-single-value types since we 1485 // are just replacing static memory to stack memory. 1486 // 1487 // If the global is in different address space, don't bring it to stack. 1488 if (!GS.HasMultipleAccessingFunctions && 1489 GS.AccessingFunction && 1490 GV->getValueType()->isSingleValueType() && 1491 GV->getType()->getAddressSpace() == 0 && 1492 !GV->isExternallyInitialized() && 1493 allNonInstructionUsersCanBeMadeInstructions(GV) && 1494 GS.AccessingFunction->doesNotRecurse() && 1495 isPointerValueDeadOnEntryToFunction(GS.AccessingFunction, GV, 1496 LookupDomTree)) { 1497 const DataLayout &DL = GV->getParent()->getDataLayout(); 1498 1499 LLVM_DEBUG(dbgs() << "LOCALIZING GLOBAL: " << *GV << "\n"); 1500 Instruction &FirstI = const_cast<Instruction&>(*GS.AccessingFunction 1501 ->getEntryBlock().begin()); 1502 Type *ElemTy = GV->getValueType(); 1503 // FIXME: Pass Global's alignment when globals have alignment 1504 AllocaInst *Alloca = new AllocaInst(ElemTy, DL.getAllocaAddrSpace(), nullptr, 1505 GV->getName(), &FirstI); 1506 if (!isa<UndefValue>(GV->getInitializer())) 1507 new StoreInst(GV->getInitializer(), Alloca, &FirstI); 1508 1509 makeAllConstantUsesInstructions(GV); 1510 1511 GV->replaceAllUsesWith(Alloca); 1512 GV->eraseFromParent(); 1513 ++NumLocalized; 1514 return true; 1515 } 1516 1517 bool Changed = false; 1518 1519 // If the global is never loaded (but may be stored to), it is dead. 1520 // Delete it now. 1521 if (!GS.IsLoaded) { 1522 LLVM_DEBUG(dbgs() << "GLOBAL NEVER LOADED: " << *GV << "\n"); 1523 1524 if (isLeakCheckerRoot(GV)) { 1525 // Delete any constant stores to the global. 1526 Changed = CleanupPointerRootUsers(GV, GetTLI); 1527 } else { 1528 // Delete any stores we can find to the global. We may not be able to 1529 // make it completely dead though. 1530 Changed = CleanupConstantGlobalUsers(GV, DL); 1531 } 1532 1533 // If the global is dead now, delete it. 1534 if (GV->use_empty()) { 1535 GV->eraseFromParent(); 1536 ++NumDeleted; 1537 Changed = true; 1538 } 1539 return Changed; 1540 1541 } 1542 if (GS.StoredType <= GlobalStatus::InitializerStored) { 1543 LLVM_DEBUG(dbgs() << "MARKING CONSTANT: " << *GV << "\n"); 1544 1545 // Don't actually mark a global constant if it's atomic because atomic loads 1546 // are implemented by a trivial cmpxchg in some edge-cases and that usually 1547 // requires write access to the variable even if it's not actually changed. 1548 if (GS.Ordering == AtomicOrdering::NotAtomic) { 1549 assert(!GV->isConstant() && "Expected a non-constant global"); 1550 GV->setConstant(true); 1551 Changed = true; 1552 } 1553 1554 // Clean up any obviously simplifiable users now. 1555 Changed |= CleanupConstantGlobalUsers(GV, DL); 1556 1557 // If the global is dead now, just nuke it. 1558 if (GV->use_empty()) { 1559 LLVM_DEBUG(dbgs() << " *** Marking constant allowed us to simplify " 1560 << "all users and delete global!\n"); 1561 GV->eraseFromParent(); 1562 ++NumDeleted; 1563 return true; 1564 } 1565 1566 // Fall through to the next check; see if we can optimize further. 1567 ++NumMarked; 1568 } 1569 if (!GV->getInitializer()->getType()->isSingleValueType()) { 1570 const DataLayout &DL = GV->getParent()->getDataLayout(); 1571 if (SRAGlobal(GV, DL)) 1572 return true; 1573 } 1574 Value *StoredOnceValue = GS.getStoredOnceValue(); 1575 if (GS.StoredType == GlobalStatus::StoredOnce && StoredOnceValue) { 1576 // Avoid speculating constant expressions that might trap (div/rem). 1577 auto *SOVConstant = dyn_cast<Constant>(StoredOnceValue); 1578 if (SOVConstant && SOVConstant->canTrap()) 1579 return Changed; 1580 1581 Function &StoreFn = 1582 const_cast<Function &>(*GS.StoredOnceStore->getFunction()); 1583 bool CanHaveNonUndefGlobalInitializer = 1584 GetTTI(StoreFn).canHaveNonUndefGlobalInitializerInAddressSpace( 1585 GV->getType()->getAddressSpace()); 1586 // If the initial value for the global was an undef value, and if only 1587 // one other value was stored into it, we can just change the 1588 // initializer to be the stored value, then delete all stores to the 1589 // global. This allows us to mark it constant. 1590 // This is restricted to address spaces that allow globals to have 1591 // initializers. NVPTX, for example, does not support initializers for 1592 // shared memory (AS 3). 1593 if (SOVConstant && isa<UndefValue>(GV->getInitializer()) && 1594 DL.getTypeAllocSize(SOVConstant->getType()) == 1595 DL.getTypeAllocSize(GV->getValueType()) && 1596 CanHaveNonUndefGlobalInitializer) { 1597 if (SOVConstant->getType() == GV->getValueType()) { 1598 // Change the initializer in place. 1599 GV->setInitializer(SOVConstant); 1600 } else { 1601 // Create a new global with adjusted type. 1602 auto *NGV = new GlobalVariable( 1603 *GV->getParent(), SOVConstant->getType(), GV->isConstant(), 1604 GV->getLinkage(), SOVConstant, "", GV, GV->getThreadLocalMode(), 1605 GV->getAddressSpace()); 1606 NGV->takeName(GV); 1607 NGV->copyAttributesFrom(GV); 1608 GV->replaceAllUsesWith(ConstantExpr::getBitCast(NGV, GV->getType())); 1609 GV->eraseFromParent(); 1610 GV = NGV; 1611 } 1612 1613 // Clean up any obviously simplifiable users now. 1614 CleanupConstantGlobalUsers(GV, DL); 1615 1616 if (GV->use_empty()) { 1617 LLVM_DEBUG(dbgs() << " *** Substituting initializer allowed us to " 1618 << "simplify all users and delete global!\n"); 1619 GV->eraseFromParent(); 1620 ++NumDeleted; 1621 } 1622 ++NumSubstitute; 1623 return true; 1624 } 1625 1626 // Try to optimize globals based on the knowledge that only one value 1627 // (besides its initializer) is ever stored to the global. 1628 if (optimizeOnceStoredGlobal(GV, StoredOnceValue, DL, GetTLI)) 1629 return true; 1630 1631 // Try to forward the store to any loads. 1632 if (forwardStoredOnceStore(GV, GS.StoredOnceStore, LookupDomTree)) 1633 return true; 1634 1635 // Otherwise, if the global was not a boolean, we can shrink it to be a 1636 // boolean. Skip this optimization for AS that doesn't allow an initializer. 1637 if (SOVConstant && GS.Ordering == AtomicOrdering::NotAtomic && 1638 (!isa<UndefValue>(GV->getInitializer()) || 1639 CanHaveNonUndefGlobalInitializer)) { 1640 if (TryToShrinkGlobalToBoolean(GV, SOVConstant)) { 1641 ++NumShrunkToBool; 1642 return true; 1643 } 1644 } 1645 } 1646 1647 return Changed; 1648 } 1649 1650 /// Analyze the specified global variable and optimize it if possible. If we 1651 /// make a change, return true. 1652 static bool 1653 processGlobal(GlobalValue &GV, 1654 function_ref<TargetTransformInfo &(Function &)> GetTTI, 1655 function_ref<TargetLibraryInfo &(Function &)> GetTLI, 1656 function_ref<DominatorTree &(Function &)> LookupDomTree) { 1657 if (GV.getName().startswith("llvm.")) 1658 return false; 1659 1660 GlobalStatus GS; 1661 1662 if (GlobalStatus::analyzeGlobal(&GV, GS)) 1663 return false; 1664 1665 bool Changed = false; 1666 if (!GS.IsCompared && !GV.hasGlobalUnnamedAddr()) { 1667 auto NewUnnamedAddr = GV.hasLocalLinkage() ? GlobalValue::UnnamedAddr::Global 1668 : GlobalValue::UnnamedAddr::Local; 1669 if (NewUnnamedAddr != GV.getUnnamedAddr()) { 1670 GV.setUnnamedAddr(NewUnnamedAddr); 1671 NumUnnamed++; 1672 Changed = true; 1673 } 1674 } 1675 1676 // Do more involved optimizations if the global is internal. 1677 if (!GV.hasLocalLinkage()) 1678 return Changed; 1679 1680 auto *GVar = dyn_cast<GlobalVariable>(&GV); 1681 if (!GVar) 1682 return Changed; 1683 1684 if (GVar->isConstant() || !GVar->hasInitializer()) 1685 return Changed; 1686 1687 return processInternalGlobal(GVar, GS, GetTTI, GetTLI, LookupDomTree) || 1688 Changed; 1689 } 1690 1691 /// Walk all of the direct calls of the specified function, changing them to 1692 /// FastCC. 1693 static void ChangeCalleesToFastCall(Function *F) { 1694 for (User *U : F->users()) { 1695 if (isa<BlockAddress>(U)) 1696 continue; 1697 cast<CallBase>(U)->setCallingConv(CallingConv::Fast); 1698 } 1699 } 1700 1701 static AttributeList StripAttr(LLVMContext &C, AttributeList Attrs, 1702 Attribute::AttrKind A) { 1703 unsigned AttrIndex; 1704 if (Attrs.hasAttrSomewhere(A, &AttrIndex)) 1705 return Attrs.removeAttributeAtIndex(C, AttrIndex, A); 1706 return Attrs; 1707 } 1708 1709 static void RemoveAttribute(Function *F, Attribute::AttrKind A) { 1710 F->setAttributes(StripAttr(F->getContext(), F->getAttributes(), A)); 1711 for (User *U : F->users()) { 1712 if (isa<BlockAddress>(U)) 1713 continue; 1714 CallBase *CB = cast<CallBase>(U); 1715 CB->setAttributes(StripAttr(F->getContext(), CB->getAttributes(), A)); 1716 } 1717 } 1718 1719 /// Return true if this is a calling convention that we'd like to change. The 1720 /// idea here is that we don't want to mess with the convention if the user 1721 /// explicitly requested something with performance implications like coldcc, 1722 /// GHC, or anyregcc. 1723 static bool hasChangeableCC(Function *F) { 1724 CallingConv::ID CC = F->getCallingConv(); 1725 1726 // FIXME: Is it worth transforming x86_stdcallcc and x86_fastcallcc? 1727 if (CC != CallingConv::C && CC != CallingConv::X86_ThisCall) 1728 return false; 1729 1730 // FIXME: Change CC for the whole chain of musttail calls when possible. 1731 // 1732 // Can't change CC of the function that either has musttail calls, or is a 1733 // musttail callee itself 1734 for (User *U : F->users()) { 1735 if (isa<BlockAddress>(U)) 1736 continue; 1737 CallInst* CI = dyn_cast<CallInst>(U); 1738 if (!CI) 1739 continue; 1740 1741 if (CI->isMustTailCall()) 1742 return false; 1743 } 1744 1745 for (BasicBlock &BB : *F) 1746 if (BB.getTerminatingMustTailCall()) 1747 return false; 1748 1749 return true; 1750 } 1751 1752 /// Return true if the block containing the call site has a BlockFrequency of 1753 /// less than ColdCCRelFreq% of the entry block. 1754 static bool isColdCallSite(CallBase &CB, BlockFrequencyInfo &CallerBFI) { 1755 const BranchProbability ColdProb(ColdCCRelFreq, 100); 1756 auto *CallSiteBB = CB.getParent(); 1757 auto CallSiteFreq = CallerBFI.getBlockFreq(CallSiteBB); 1758 auto CallerEntryFreq = 1759 CallerBFI.getBlockFreq(&(CB.getCaller()->getEntryBlock())); 1760 return CallSiteFreq < CallerEntryFreq * ColdProb; 1761 } 1762 1763 // This function checks if the input function F is cold at all call sites. It 1764 // also looks each call site's containing function, returning false if the 1765 // caller function contains other non cold calls. The input vector AllCallsCold 1766 // contains a list of functions that only have call sites in cold blocks. 1767 static bool 1768 isValidCandidateForColdCC(Function &F, 1769 function_ref<BlockFrequencyInfo &(Function &)> GetBFI, 1770 const std::vector<Function *> &AllCallsCold) { 1771 1772 if (F.user_empty()) 1773 return false; 1774 1775 for (User *U : F.users()) { 1776 if (isa<BlockAddress>(U)) 1777 continue; 1778 1779 CallBase &CB = cast<CallBase>(*U); 1780 Function *CallerFunc = CB.getParent()->getParent(); 1781 BlockFrequencyInfo &CallerBFI = GetBFI(*CallerFunc); 1782 if (!isColdCallSite(CB, CallerBFI)) 1783 return false; 1784 if (!llvm::is_contained(AllCallsCold, CallerFunc)) 1785 return false; 1786 } 1787 return true; 1788 } 1789 1790 static void changeCallSitesToColdCC(Function *F) { 1791 for (User *U : F->users()) { 1792 if (isa<BlockAddress>(U)) 1793 continue; 1794 cast<CallBase>(U)->setCallingConv(CallingConv::Cold); 1795 } 1796 } 1797 1798 // This function iterates over all the call instructions in the input Function 1799 // and checks that all call sites are in cold blocks and are allowed to use the 1800 // coldcc calling convention. 1801 static bool 1802 hasOnlyColdCalls(Function &F, 1803 function_ref<BlockFrequencyInfo &(Function &)> GetBFI) { 1804 for (BasicBlock &BB : F) { 1805 for (Instruction &I : BB) { 1806 if (CallInst *CI = dyn_cast<CallInst>(&I)) { 1807 // Skip over isline asm instructions since they aren't function calls. 1808 if (CI->isInlineAsm()) 1809 continue; 1810 Function *CalledFn = CI->getCalledFunction(); 1811 if (!CalledFn) 1812 return false; 1813 if (!CalledFn->hasLocalLinkage()) 1814 return false; 1815 // Skip over intrinsics since they won't remain as function calls. 1816 if (CalledFn->getIntrinsicID() != Intrinsic::not_intrinsic) 1817 continue; 1818 // Check if it's valid to use coldcc calling convention. 1819 if (!hasChangeableCC(CalledFn) || CalledFn->isVarArg() || 1820 CalledFn->hasAddressTaken()) 1821 return false; 1822 BlockFrequencyInfo &CallerBFI = GetBFI(F); 1823 if (!isColdCallSite(*CI, CallerBFI)) 1824 return false; 1825 } 1826 } 1827 } 1828 return true; 1829 } 1830 1831 static bool hasMustTailCallers(Function *F) { 1832 for (User *U : F->users()) { 1833 CallBase *CB = dyn_cast<CallBase>(U); 1834 if (!CB) { 1835 assert(isa<BlockAddress>(U) && 1836 "Expected either CallBase or BlockAddress"); 1837 continue; 1838 } 1839 if (CB->isMustTailCall()) 1840 return true; 1841 } 1842 return false; 1843 } 1844 1845 static bool hasInvokeCallers(Function *F) { 1846 for (User *U : F->users()) 1847 if (isa<InvokeInst>(U)) 1848 return true; 1849 return false; 1850 } 1851 1852 static void RemovePreallocated(Function *F) { 1853 RemoveAttribute(F, Attribute::Preallocated); 1854 1855 auto *M = F->getParent(); 1856 1857 IRBuilder<> Builder(M->getContext()); 1858 1859 // Cannot modify users() while iterating over it, so make a copy. 1860 SmallVector<User *, 4> PreallocatedCalls(F->users()); 1861 for (User *U : PreallocatedCalls) { 1862 CallBase *CB = dyn_cast<CallBase>(U); 1863 if (!CB) 1864 continue; 1865 1866 assert( 1867 !CB->isMustTailCall() && 1868 "Shouldn't call RemotePreallocated() on a musttail preallocated call"); 1869 // Create copy of call without "preallocated" operand bundle. 1870 SmallVector<OperandBundleDef, 1> OpBundles; 1871 CB->getOperandBundlesAsDefs(OpBundles); 1872 CallBase *PreallocatedSetup = nullptr; 1873 for (auto *It = OpBundles.begin(); It != OpBundles.end(); ++It) { 1874 if (It->getTag() == "preallocated") { 1875 PreallocatedSetup = cast<CallBase>(*It->input_begin()); 1876 OpBundles.erase(It); 1877 break; 1878 } 1879 } 1880 assert(PreallocatedSetup && "Did not find preallocated bundle"); 1881 uint64_t ArgCount = 1882 cast<ConstantInt>(PreallocatedSetup->getArgOperand(0))->getZExtValue(); 1883 1884 assert((isa<CallInst>(CB) || isa<InvokeInst>(CB)) && 1885 "Unknown indirect call type"); 1886 CallBase *NewCB = CallBase::Create(CB, OpBundles, CB); 1887 CB->replaceAllUsesWith(NewCB); 1888 NewCB->takeName(CB); 1889 CB->eraseFromParent(); 1890 1891 Builder.SetInsertPoint(PreallocatedSetup); 1892 auto *StackSave = 1893 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stacksave)); 1894 1895 Builder.SetInsertPoint(NewCB->getNextNonDebugInstruction()); 1896 Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::stackrestore), 1897 StackSave); 1898 1899 // Replace @llvm.call.preallocated.arg() with alloca. 1900 // Cannot modify users() while iterating over it, so make a copy. 1901 // @llvm.call.preallocated.arg() can be called with the same index multiple 1902 // times. So for each @llvm.call.preallocated.arg(), we see if we have 1903 // already created a Value* for the index, and if not, create an alloca and 1904 // bitcast right after the @llvm.call.preallocated.setup() so that it 1905 // dominates all uses. 1906 SmallVector<Value *, 2> ArgAllocas(ArgCount); 1907 SmallVector<User *, 2> PreallocatedArgs(PreallocatedSetup->users()); 1908 for (auto *User : PreallocatedArgs) { 1909 auto *UseCall = cast<CallBase>(User); 1910 assert(UseCall->getCalledFunction()->getIntrinsicID() == 1911 Intrinsic::call_preallocated_arg && 1912 "preallocated token use was not a llvm.call.preallocated.arg"); 1913 uint64_t AllocArgIndex = 1914 cast<ConstantInt>(UseCall->getArgOperand(1))->getZExtValue(); 1915 Value *AllocaReplacement = ArgAllocas[AllocArgIndex]; 1916 if (!AllocaReplacement) { 1917 auto AddressSpace = UseCall->getType()->getPointerAddressSpace(); 1918 auto *ArgType = 1919 UseCall->getFnAttr(Attribute::Preallocated).getValueAsType(); 1920 auto *InsertBefore = PreallocatedSetup->getNextNonDebugInstruction(); 1921 Builder.SetInsertPoint(InsertBefore); 1922 auto *Alloca = 1923 Builder.CreateAlloca(ArgType, AddressSpace, nullptr, "paarg"); 1924 auto *BitCast = Builder.CreateBitCast( 1925 Alloca, Type::getInt8PtrTy(M->getContext()), UseCall->getName()); 1926 ArgAllocas[AllocArgIndex] = BitCast; 1927 AllocaReplacement = BitCast; 1928 } 1929 1930 UseCall->replaceAllUsesWith(AllocaReplacement); 1931 UseCall->eraseFromParent(); 1932 } 1933 // Remove @llvm.call.preallocated.setup(). 1934 cast<Instruction>(PreallocatedSetup)->eraseFromParent(); 1935 } 1936 } 1937 1938 static bool 1939 OptimizeFunctions(Module &M, 1940 function_ref<TargetLibraryInfo &(Function &)> GetTLI, 1941 function_ref<TargetTransformInfo &(Function &)> GetTTI, 1942 function_ref<BlockFrequencyInfo &(Function &)> GetBFI, 1943 function_ref<DominatorTree &(Function &)> LookupDomTree, 1944 SmallPtrSetImpl<const Comdat *> &NotDiscardableComdats, 1945 function_ref<void(Function &F)> ChangedCFGCallback) { 1946 1947 bool Changed = false; 1948 1949 std::vector<Function *> AllCallsCold; 1950 for (Function &F : llvm::make_early_inc_range(M)) 1951 if (hasOnlyColdCalls(F, GetBFI)) 1952 AllCallsCold.push_back(&F); 1953 1954 // Optimize functions. 1955 for (Function &F : llvm::make_early_inc_range(M)) { 1956 // Don't perform global opt pass on naked functions; we don't want fast 1957 // calling conventions for naked functions. 1958 if (F.hasFnAttribute(Attribute::Naked)) 1959 continue; 1960 1961 // Functions without names cannot be referenced outside this module. 1962 if (!F.hasName() && !F.isDeclaration() && !F.hasLocalLinkage()) 1963 F.setLinkage(GlobalValue::InternalLinkage); 1964 1965 if (deleteIfDead(F, NotDiscardableComdats)) { 1966 Changed = true; 1967 continue; 1968 } 1969 1970 // LLVM's definition of dominance allows instructions that are cyclic 1971 // in unreachable blocks, e.g.: 1972 // %pat = select i1 %condition, @global, i16* %pat 1973 // because any instruction dominates an instruction in a block that's 1974 // not reachable from entry. 1975 // So, remove unreachable blocks from the function, because a) there's 1976 // no point in analyzing them and b) GlobalOpt should otherwise grow 1977 // some more complicated logic to break these cycles. 1978 // Notify the analysis manager that we've modified the function's CFG. 1979 if (!F.isDeclaration()) { 1980 if (removeUnreachableBlocks(F)) { 1981 Changed = true; 1982 ChangedCFGCallback(F); 1983 } 1984 } 1985 1986 Changed |= processGlobal(F, GetTTI, GetTLI, LookupDomTree); 1987 1988 if (!F.hasLocalLinkage()) 1989 continue; 1990 1991 // If we have an inalloca parameter that we can safely remove the 1992 // inalloca attribute from, do so. This unlocks optimizations that 1993 // wouldn't be safe in the presence of inalloca. 1994 // FIXME: We should also hoist alloca affected by this to the entry 1995 // block if possible. 1996 if (F.getAttributes().hasAttrSomewhere(Attribute::InAlloca) && 1997 !F.hasAddressTaken() && !hasMustTailCallers(&F)) { 1998 RemoveAttribute(&F, Attribute::InAlloca); 1999 Changed = true; 2000 } 2001 2002 // FIXME: handle invokes 2003 // FIXME: handle musttail 2004 if (F.getAttributes().hasAttrSomewhere(Attribute::Preallocated)) { 2005 if (!F.hasAddressTaken() && !hasMustTailCallers(&F) && 2006 !hasInvokeCallers(&F)) { 2007 RemovePreallocated(&F); 2008 Changed = true; 2009 } 2010 continue; 2011 } 2012 2013 if (hasChangeableCC(&F) && !F.isVarArg() && !F.hasAddressTaken()) { 2014 NumInternalFunc++; 2015 TargetTransformInfo &TTI = GetTTI(F); 2016 // Change the calling convention to coldcc if either stress testing is 2017 // enabled or the target would like to use coldcc on functions which are 2018 // cold at all call sites and the callers contain no other non coldcc 2019 // calls. 2020 if (EnableColdCCStressTest || 2021 (TTI.useColdCCForColdCall(F) && 2022 isValidCandidateForColdCC(F, GetBFI, AllCallsCold))) { 2023 F.setCallingConv(CallingConv::Cold); 2024 changeCallSitesToColdCC(&F); 2025 Changed = true; 2026 NumColdCC++; 2027 } 2028 } 2029 2030 if (hasChangeableCC(&F) && !F.isVarArg() && !F.hasAddressTaken()) { 2031 // If this function has a calling convention worth changing, is not a 2032 // varargs function, and is only called directly, promote it to use the 2033 // Fast calling convention. 2034 F.setCallingConv(CallingConv::Fast); 2035 ChangeCalleesToFastCall(&F); 2036 ++NumFastCallFns; 2037 Changed = true; 2038 } 2039 2040 if (F.getAttributes().hasAttrSomewhere(Attribute::Nest) && 2041 !F.hasAddressTaken()) { 2042 // The function is not used by a trampoline intrinsic, so it is safe 2043 // to remove the 'nest' attribute. 2044 RemoveAttribute(&F, Attribute::Nest); 2045 ++NumNestRemoved; 2046 Changed = true; 2047 } 2048 } 2049 return Changed; 2050 } 2051 2052 static bool 2053 OptimizeGlobalVars(Module &M, 2054 function_ref<TargetTransformInfo &(Function &)> GetTTI, 2055 function_ref<TargetLibraryInfo &(Function &)> GetTLI, 2056 function_ref<DominatorTree &(Function &)> LookupDomTree, 2057 SmallPtrSetImpl<const Comdat *> &NotDiscardableComdats) { 2058 bool Changed = false; 2059 2060 for (GlobalVariable &GV : llvm::make_early_inc_range(M.globals())) { 2061 // Global variables without names cannot be referenced outside this module. 2062 if (!GV.hasName() && !GV.isDeclaration() && !GV.hasLocalLinkage()) 2063 GV.setLinkage(GlobalValue::InternalLinkage); 2064 // Simplify the initializer. 2065 if (GV.hasInitializer()) 2066 if (auto *C = dyn_cast<Constant>(GV.getInitializer())) { 2067 auto &DL = M.getDataLayout(); 2068 // TLI is not used in the case of a Constant, so use default nullptr 2069 // for that optional parameter, since we don't have a Function to 2070 // provide GetTLI anyway. 2071 Constant *New = ConstantFoldConstant(C, DL, /*TLI*/ nullptr); 2072 if (New != C) 2073 GV.setInitializer(New); 2074 } 2075 2076 if (deleteIfDead(GV, NotDiscardableComdats)) { 2077 Changed = true; 2078 continue; 2079 } 2080 2081 Changed |= processGlobal(GV, GetTTI, GetTLI, LookupDomTree); 2082 } 2083 return Changed; 2084 } 2085 2086 /// Evaluate static constructors in the function, if we can. Return true if we 2087 /// can, false otherwise. 2088 static bool EvaluateStaticConstructor(Function *F, const DataLayout &DL, 2089 TargetLibraryInfo *TLI) { 2090 // Skip external functions. 2091 if (F->isDeclaration()) 2092 return false; 2093 // Call the function. 2094 Evaluator Eval(DL, TLI); 2095 Constant *RetValDummy; 2096 bool EvalSuccess = Eval.EvaluateFunction(F, RetValDummy, 2097 SmallVector<Constant*, 0>()); 2098 2099 if (EvalSuccess) { 2100 ++NumCtorsEvaluated; 2101 2102 // We succeeded at evaluation: commit the result. 2103 auto NewInitializers = Eval.getMutatedInitializers(); 2104 LLVM_DEBUG(dbgs() << "FULLY EVALUATED GLOBAL CTOR FUNCTION '" 2105 << F->getName() << "' to " << NewInitializers.size() 2106 << " stores.\n"); 2107 for (const auto &Pair : NewInitializers) 2108 Pair.first->setInitializer(Pair.second); 2109 for (GlobalVariable *GV : Eval.getInvariants()) 2110 GV->setConstant(true); 2111 } 2112 2113 return EvalSuccess; 2114 } 2115 2116 static int compareNames(Constant *const *A, Constant *const *B) { 2117 Value *AStripped = (*A)->stripPointerCasts(); 2118 Value *BStripped = (*B)->stripPointerCasts(); 2119 return AStripped->getName().compare(BStripped->getName()); 2120 } 2121 2122 static void setUsedInitializer(GlobalVariable &V, 2123 const SmallPtrSetImpl<GlobalValue *> &Init) { 2124 if (Init.empty()) { 2125 V.eraseFromParent(); 2126 return; 2127 } 2128 2129 // Type of pointer to the array of pointers. 2130 PointerType *Int8PtrTy = Type::getInt8PtrTy(V.getContext(), 0); 2131 2132 SmallVector<Constant *, 8> UsedArray; 2133 for (GlobalValue *GV : Init) { 2134 Constant *Cast 2135 = ConstantExpr::getPointerBitCastOrAddrSpaceCast(GV, Int8PtrTy); 2136 UsedArray.push_back(Cast); 2137 } 2138 // Sort to get deterministic order. 2139 array_pod_sort(UsedArray.begin(), UsedArray.end(), compareNames); 2140 ArrayType *ATy = ArrayType::get(Int8PtrTy, UsedArray.size()); 2141 2142 Module *M = V.getParent(); 2143 V.removeFromParent(); 2144 GlobalVariable *NV = 2145 new GlobalVariable(*M, ATy, false, GlobalValue::AppendingLinkage, 2146 ConstantArray::get(ATy, UsedArray), ""); 2147 NV->takeName(&V); 2148 NV->setSection("llvm.metadata"); 2149 delete &V; 2150 } 2151 2152 namespace { 2153 2154 /// An easy to access representation of llvm.used and llvm.compiler.used. 2155 class LLVMUsed { 2156 SmallPtrSet<GlobalValue *, 4> Used; 2157 SmallPtrSet<GlobalValue *, 4> CompilerUsed; 2158 GlobalVariable *UsedV; 2159 GlobalVariable *CompilerUsedV; 2160 2161 public: 2162 LLVMUsed(Module &M) { 2163 SmallVector<GlobalValue *, 4> Vec; 2164 UsedV = collectUsedGlobalVariables(M, Vec, false); 2165 Used = {Vec.begin(), Vec.end()}; 2166 Vec.clear(); 2167 CompilerUsedV = collectUsedGlobalVariables(M, Vec, true); 2168 CompilerUsed = {Vec.begin(), Vec.end()}; 2169 } 2170 2171 using iterator = SmallPtrSet<GlobalValue *, 4>::iterator; 2172 using used_iterator_range = iterator_range<iterator>; 2173 2174 iterator usedBegin() { return Used.begin(); } 2175 iterator usedEnd() { return Used.end(); } 2176 2177 used_iterator_range used() { 2178 return used_iterator_range(usedBegin(), usedEnd()); 2179 } 2180 2181 iterator compilerUsedBegin() { return CompilerUsed.begin(); } 2182 iterator compilerUsedEnd() { return CompilerUsed.end(); } 2183 2184 used_iterator_range compilerUsed() { 2185 return used_iterator_range(compilerUsedBegin(), compilerUsedEnd()); 2186 } 2187 2188 bool usedCount(GlobalValue *GV) const { return Used.count(GV); } 2189 2190 bool compilerUsedCount(GlobalValue *GV) const { 2191 return CompilerUsed.count(GV); 2192 } 2193 2194 bool usedErase(GlobalValue *GV) { return Used.erase(GV); } 2195 bool compilerUsedErase(GlobalValue *GV) { return CompilerUsed.erase(GV); } 2196 bool usedInsert(GlobalValue *GV) { return Used.insert(GV).second; } 2197 2198 bool compilerUsedInsert(GlobalValue *GV) { 2199 return CompilerUsed.insert(GV).second; 2200 } 2201 2202 void syncVariablesAndSets() { 2203 if (UsedV) 2204 setUsedInitializer(*UsedV, Used); 2205 if (CompilerUsedV) 2206 setUsedInitializer(*CompilerUsedV, CompilerUsed); 2207 } 2208 }; 2209 2210 } // end anonymous namespace 2211 2212 static bool hasUseOtherThanLLVMUsed(GlobalAlias &GA, const LLVMUsed &U) { 2213 if (GA.use_empty()) // No use at all. 2214 return false; 2215 2216 assert((!U.usedCount(&GA) || !U.compilerUsedCount(&GA)) && 2217 "We should have removed the duplicated " 2218 "element from llvm.compiler.used"); 2219 if (!GA.hasOneUse()) 2220 // Strictly more than one use. So at least one is not in llvm.used and 2221 // llvm.compiler.used. 2222 return true; 2223 2224 // Exactly one use. Check if it is in llvm.used or llvm.compiler.used. 2225 return !U.usedCount(&GA) && !U.compilerUsedCount(&GA); 2226 } 2227 2228 static bool hasMoreThanOneUseOtherThanLLVMUsed(GlobalValue &V, 2229 const LLVMUsed &U) { 2230 unsigned N = 2; 2231 assert((!U.usedCount(&V) || !U.compilerUsedCount(&V)) && 2232 "We should have removed the duplicated " 2233 "element from llvm.compiler.used"); 2234 if (U.usedCount(&V) || U.compilerUsedCount(&V)) 2235 ++N; 2236 return V.hasNUsesOrMore(N); 2237 } 2238 2239 static bool mayHaveOtherReferences(GlobalAlias &GA, const LLVMUsed &U) { 2240 if (!GA.hasLocalLinkage()) 2241 return true; 2242 2243 return U.usedCount(&GA) || U.compilerUsedCount(&GA); 2244 } 2245 2246 static bool hasUsesToReplace(GlobalAlias &GA, const LLVMUsed &U, 2247 bool &RenameTarget) { 2248 RenameTarget = false; 2249 bool Ret = false; 2250 if (hasUseOtherThanLLVMUsed(GA, U)) 2251 Ret = true; 2252 2253 // If the alias is externally visible, we may still be able to simplify it. 2254 if (!mayHaveOtherReferences(GA, U)) 2255 return Ret; 2256 2257 // If the aliasee has internal linkage, give it the name and linkage 2258 // of the alias, and delete the alias. This turns: 2259 // define internal ... @f(...) 2260 // @a = alias ... @f 2261 // into: 2262 // define ... @a(...) 2263 Constant *Aliasee = GA.getAliasee(); 2264 GlobalValue *Target = cast<GlobalValue>(Aliasee->stripPointerCasts()); 2265 if (!Target->hasLocalLinkage()) 2266 return Ret; 2267 2268 // Do not perform the transform if multiple aliases potentially target the 2269 // aliasee. This check also ensures that it is safe to replace the section 2270 // and other attributes of the aliasee with those of the alias. 2271 if (hasMoreThanOneUseOtherThanLLVMUsed(*Target, U)) 2272 return Ret; 2273 2274 RenameTarget = true; 2275 return true; 2276 } 2277 2278 static bool 2279 OptimizeGlobalAliases(Module &M, 2280 SmallPtrSetImpl<const Comdat *> &NotDiscardableComdats) { 2281 bool Changed = false; 2282 LLVMUsed Used(M); 2283 2284 for (GlobalValue *GV : Used.used()) 2285 Used.compilerUsedErase(GV); 2286 2287 // Return whether GV is explicitly or implicitly dso_local and not replaceable 2288 // by another definition in the current linkage unit. 2289 auto IsModuleLocal = [](GlobalValue &GV) { 2290 return !GlobalValue::isInterposableLinkage(GV.getLinkage()) && 2291 (GV.isDSOLocal() || GV.isImplicitDSOLocal()); 2292 }; 2293 2294 for (GlobalAlias &J : llvm::make_early_inc_range(M.aliases())) { 2295 // Aliases without names cannot be referenced outside this module. 2296 if (!J.hasName() && !J.isDeclaration() && !J.hasLocalLinkage()) 2297 J.setLinkage(GlobalValue::InternalLinkage); 2298 2299 if (deleteIfDead(J, NotDiscardableComdats)) { 2300 Changed = true; 2301 continue; 2302 } 2303 2304 // If the alias can change at link time, nothing can be done - bail out. 2305 if (!IsModuleLocal(J)) 2306 continue; 2307 2308 Constant *Aliasee = J.getAliasee(); 2309 GlobalValue *Target = dyn_cast<GlobalValue>(Aliasee->stripPointerCasts()); 2310 // We can't trivially replace the alias with the aliasee if the aliasee is 2311 // non-trivial in some way. We also can't replace the alias with the aliasee 2312 // if the aliasee may be preemptible at runtime. On ELF, a non-preemptible 2313 // alias can be used to access the definition as if preemption did not 2314 // happen. 2315 // TODO: Try to handle non-zero GEPs of local aliasees. 2316 if (!Target || !IsModuleLocal(*Target)) 2317 continue; 2318 2319 Target->removeDeadConstantUsers(); 2320 2321 // Make all users of the alias use the aliasee instead. 2322 bool RenameTarget; 2323 if (!hasUsesToReplace(J, Used, RenameTarget)) 2324 continue; 2325 2326 J.replaceAllUsesWith(ConstantExpr::getBitCast(Aliasee, J.getType())); 2327 ++NumAliasesResolved; 2328 Changed = true; 2329 2330 if (RenameTarget) { 2331 // Give the aliasee the name, linkage and other attributes of the alias. 2332 Target->takeName(&J); 2333 Target->setLinkage(J.getLinkage()); 2334 Target->setDSOLocal(J.isDSOLocal()); 2335 Target->setVisibility(J.getVisibility()); 2336 Target->setDLLStorageClass(J.getDLLStorageClass()); 2337 2338 if (Used.usedErase(&J)) 2339 Used.usedInsert(Target); 2340 2341 if (Used.compilerUsedErase(&J)) 2342 Used.compilerUsedInsert(Target); 2343 } else if (mayHaveOtherReferences(J, Used)) 2344 continue; 2345 2346 // Delete the alias. 2347 M.getAliasList().erase(&J); 2348 ++NumAliasesRemoved; 2349 Changed = true; 2350 } 2351 2352 Used.syncVariablesAndSets(); 2353 2354 return Changed; 2355 } 2356 2357 static Function * 2358 FindCXAAtExit(Module &M, function_ref<TargetLibraryInfo &(Function &)> GetTLI) { 2359 // Hack to get a default TLI before we have actual Function. 2360 auto FuncIter = M.begin(); 2361 if (FuncIter == M.end()) 2362 return nullptr; 2363 auto *TLI = &GetTLI(*FuncIter); 2364 2365 LibFunc F = LibFunc_cxa_atexit; 2366 if (!TLI->has(F)) 2367 return nullptr; 2368 2369 Function *Fn = M.getFunction(TLI->getName(F)); 2370 if (!Fn) 2371 return nullptr; 2372 2373 // Now get the actual TLI for Fn. 2374 TLI = &GetTLI(*Fn); 2375 2376 // Make sure that the function has the correct prototype. 2377 if (!TLI->getLibFunc(*Fn, F) || F != LibFunc_cxa_atexit) 2378 return nullptr; 2379 2380 return Fn; 2381 } 2382 2383 /// Returns whether the given function is an empty C++ destructor and can 2384 /// therefore be eliminated. 2385 /// Note that we assume that other optimization passes have already simplified 2386 /// the code so we simply check for 'ret'. 2387 static bool cxxDtorIsEmpty(const Function &Fn) { 2388 // FIXME: We could eliminate C++ destructors if they're readonly/readnone and 2389 // nounwind, but that doesn't seem worth doing. 2390 if (Fn.isDeclaration()) 2391 return false; 2392 2393 for (auto &I : Fn.getEntryBlock()) { 2394 if (I.isDebugOrPseudoInst()) 2395 continue; 2396 if (isa<ReturnInst>(I)) 2397 return true; 2398 break; 2399 } 2400 return false; 2401 } 2402 2403 static bool OptimizeEmptyGlobalCXXDtors(Function *CXAAtExitFn) { 2404 /// Itanium C++ ABI p3.3.5: 2405 /// 2406 /// After constructing a global (or local static) object, that will require 2407 /// destruction on exit, a termination function is registered as follows: 2408 /// 2409 /// extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d ); 2410 /// 2411 /// This registration, e.g. __cxa_atexit(f,p,d), is intended to cause the 2412 /// call f(p) when DSO d is unloaded, before all such termination calls 2413 /// registered before this one. It returns zero if registration is 2414 /// successful, nonzero on failure. 2415 2416 // This pass will look for calls to __cxa_atexit where the function is trivial 2417 // and remove them. 2418 bool Changed = false; 2419 2420 for (User *U : llvm::make_early_inc_range(CXAAtExitFn->users())) { 2421 // We're only interested in calls. Theoretically, we could handle invoke 2422 // instructions as well, but neither llvm-gcc nor clang generate invokes 2423 // to __cxa_atexit. 2424 CallInst *CI = dyn_cast<CallInst>(U); 2425 if (!CI) 2426 continue; 2427 2428 Function *DtorFn = 2429 dyn_cast<Function>(CI->getArgOperand(0)->stripPointerCasts()); 2430 if (!DtorFn || !cxxDtorIsEmpty(*DtorFn)) 2431 continue; 2432 2433 // Just remove the call. 2434 CI->replaceAllUsesWith(Constant::getNullValue(CI->getType())); 2435 CI->eraseFromParent(); 2436 2437 ++NumCXXDtorsRemoved; 2438 2439 Changed |= true; 2440 } 2441 2442 return Changed; 2443 } 2444 2445 static bool 2446 optimizeGlobalsInModule(Module &M, const DataLayout &DL, 2447 function_ref<TargetLibraryInfo &(Function &)> GetTLI, 2448 function_ref<TargetTransformInfo &(Function &)> GetTTI, 2449 function_ref<BlockFrequencyInfo &(Function &)> GetBFI, 2450 function_ref<DominatorTree &(Function &)> LookupDomTree, 2451 function_ref<void(Function &F)> ChangedCFGCallback) { 2452 SmallPtrSet<const Comdat *, 8> NotDiscardableComdats; 2453 bool Changed = false; 2454 bool LocalChange = true; 2455 Optional<uint32_t> FirstNotFullyEvaluatedPriority; 2456 2457 while (LocalChange) { 2458 LocalChange = false; 2459 2460 NotDiscardableComdats.clear(); 2461 for (const GlobalVariable &GV : M.globals()) 2462 if (const Comdat *C = GV.getComdat()) 2463 if (!GV.isDiscardableIfUnused() || !GV.use_empty()) 2464 NotDiscardableComdats.insert(C); 2465 for (Function &F : M) 2466 if (const Comdat *C = F.getComdat()) 2467 if (!F.isDefTriviallyDead()) 2468 NotDiscardableComdats.insert(C); 2469 for (GlobalAlias &GA : M.aliases()) 2470 if (const Comdat *C = GA.getComdat()) 2471 if (!GA.isDiscardableIfUnused() || !GA.use_empty()) 2472 NotDiscardableComdats.insert(C); 2473 2474 // Delete functions that are trivially dead, ccc -> fastcc 2475 LocalChange |= OptimizeFunctions(M, GetTLI, GetTTI, GetBFI, LookupDomTree, 2476 NotDiscardableComdats, ChangedCFGCallback); 2477 2478 // Optimize global_ctors list. 2479 LocalChange |= 2480 optimizeGlobalCtorsList(M, [&](uint32_t Priority, Function *F) { 2481 if (FirstNotFullyEvaluatedPriority && 2482 *FirstNotFullyEvaluatedPriority != Priority) 2483 return false; 2484 bool Evaluated = EvaluateStaticConstructor(F, DL, &GetTLI(*F)); 2485 if (!Evaluated) 2486 FirstNotFullyEvaluatedPriority = Priority; 2487 return Evaluated; 2488 }); 2489 2490 // Optimize non-address-taken globals. 2491 LocalChange |= OptimizeGlobalVars(M, GetTTI, GetTLI, LookupDomTree, 2492 NotDiscardableComdats); 2493 2494 // Resolve aliases, when possible. 2495 LocalChange |= OptimizeGlobalAliases(M, NotDiscardableComdats); 2496 2497 // Try to remove trivial global destructors if they are not removed 2498 // already. 2499 Function *CXAAtExitFn = FindCXAAtExit(M, GetTLI); 2500 if (CXAAtExitFn) 2501 LocalChange |= OptimizeEmptyGlobalCXXDtors(CXAAtExitFn); 2502 2503 Changed |= LocalChange; 2504 } 2505 2506 // TODO: Move all global ctors functions to the end of the module for code 2507 // layout. 2508 2509 return Changed; 2510 } 2511 2512 PreservedAnalyses GlobalOptPass::run(Module &M, ModuleAnalysisManager &AM) { 2513 auto &DL = M.getDataLayout(); 2514 auto &FAM = 2515 AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 2516 auto LookupDomTree = [&FAM](Function &F) -> DominatorTree &{ 2517 return FAM.getResult<DominatorTreeAnalysis>(F); 2518 }; 2519 auto GetTLI = [&FAM](Function &F) -> TargetLibraryInfo & { 2520 return FAM.getResult<TargetLibraryAnalysis>(F); 2521 }; 2522 auto GetTTI = [&FAM](Function &F) -> TargetTransformInfo & { 2523 return FAM.getResult<TargetIRAnalysis>(F); 2524 }; 2525 2526 auto GetBFI = [&FAM](Function &F) -> BlockFrequencyInfo & { 2527 return FAM.getResult<BlockFrequencyAnalysis>(F); 2528 }; 2529 auto ChangedCFGCallback = [&FAM](Function &F) { 2530 FAM.invalidate(F, PreservedAnalyses::none()); 2531 }; 2532 2533 if (!optimizeGlobalsInModule(M, DL, GetTLI, GetTTI, GetBFI, LookupDomTree, 2534 ChangedCFGCallback)) 2535 return PreservedAnalyses::all(); 2536 2537 PreservedAnalyses PA = PreservedAnalyses::none(); 2538 // We have not removed or replaced any functions. 2539 PA.preserve<FunctionAnalysisManagerModuleProxy>(); 2540 // The only place we modify the CFG is when calling 2541 // removeUnreachableBlocks(), but there we make sure to invalidate analyses 2542 // for modified functions. 2543 PA.preserveSet<CFGAnalyses>(); 2544 return PA; 2545 } 2546 2547 namespace { 2548 2549 struct GlobalOptLegacyPass : public ModulePass { 2550 static char ID; // Pass identification, replacement for typeid 2551 2552 GlobalOptLegacyPass() : ModulePass(ID) { 2553 initializeGlobalOptLegacyPassPass(*PassRegistry::getPassRegistry()); 2554 } 2555 2556 bool runOnModule(Module &M) override { 2557 if (skipModule(M)) 2558 return false; 2559 2560 auto &DL = M.getDataLayout(); 2561 auto LookupDomTree = [this](Function &F) -> DominatorTree & { 2562 return this->getAnalysis<DominatorTreeWrapperPass>(F).getDomTree(); 2563 }; 2564 auto GetTLI = [this](Function &F) -> TargetLibraryInfo & { 2565 return this->getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F); 2566 }; 2567 auto GetTTI = [this](Function &F) -> TargetTransformInfo & { 2568 return this->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 2569 }; 2570 2571 auto GetBFI = [this](Function &F) -> BlockFrequencyInfo & { 2572 return this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI(); 2573 }; 2574 2575 auto ChangedCFGCallback = [&LookupDomTree](Function &F) { 2576 auto &DT = LookupDomTree(F); 2577 DT.recalculate(F); 2578 }; 2579 2580 return optimizeGlobalsInModule(M, DL, GetTLI, GetTTI, GetBFI, LookupDomTree, 2581 ChangedCFGCallback); 2582 } 2583 2584 void getAnalysisUsage(AnalysisUsage &AU) const override { 2585 AU.addRequired<TargetLibraryInfoWrapperPass>(); 2586 AU.addRequired<TargetTransformInfoWrapperPass>(); 2587 AU.addRequired<DominatorTreeWrapperPass>(); 2588 AU.addRequired<BlockFrequencyInfoWrapperPass>(); 2589 } 2590 }; 2591 2592 } // end anonymous namespace 2593 2594 char GlobalOptLegacyPass::ID = 0; 2595 2596 INITIALIZE_PASS_BEGIN(GlobalOptLegacyPass, "globalopt", 2597 "Global Variable Optimizer", false, false) 2598 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 2599 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass) 2600 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass) 2601 INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass) 2602 INITIALIZE_PASS_END(GlobalOptLegacyPass, "globalopt", 2603 "Global Variable Optimizer", false, false) 2604 2605 ModulePass *llvm::createGlobalOptimizerPass() { 2606 return new GlobalOptLegacyPass(); 2607 } 2608