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