1 //===- ThinLTOBitcodeWriter.cpp - Bitcode writing pass for ThinLTO --------===// 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 #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h" 10 #include "llvm/Analysis/BasicAliasAnalysis.h" 11 #include "llvm/Analysis/ModuleSummaryAnalysis.h" 12 #include "llvm/Analysis/ProfileSummaryInfo.h" 13 #include "llvm/Analysis/TypeMetadataUtils.h" 14 #include "llvm/Bitcode/BitcodeWriter.h" 15 #include "llvm/IR/Constants.h" 16 #include "llvm/IR/DebugInfo.h" 17 #include "llvm/IR/Instructions.h" 18 #include "llvm/IR/Intrinsics.h" 19 #include "llvm/IR/Module.h" 20 #include "llvm/IR/PassManager.h" 21 #include "llvm/InitializePasses.h" 22 #include "llvm/Object/ModuleSymbolTable.h" 23 #include "llvm/Pass.h" 24 #include "llvm/Support/ScopedPrinter.h" 25 #include "llvm/Support/raw_ostream.h" 26 #include "llvm/Transforms/IPO.h" 27 #include "llvm/Transforms/IPO/FunctionAttrs.h" 28 #include "llvm/Transforms/IPO/FunctionImport.h" 29 #include "llvm/Transforms/IPO/LowerTypeTests.h" 30 #include "llvm/Transforms/Utils/Cloning.h" 31 #include "llvm/Transforms/Utils/ModuleUtils.h" 32 using namespace llvm; 33 34 namespace { 35 36 // Determine if a promotion alias should be created for a symbol name. 37 static bool allowPromotionAlias(const std::string &Name) { 38 // Promotion aliases are used only in inline assembly. It's safe to 39 // simply skip unusual names. Subset of MCAsmInfo::isAcceptableChar() 40 // and MCAsmInfoXCOFF::isAcceptableChar(). 41 for (const char &C : Name) { 42 if (isAlnum(C) || C == '_' || C == '.') 43 continue; 44 return false; 45 } 46 return true; 47 } 48 49 // Promote each local-linkage entity defined by ExportM and used by ImportM by 50 // changing visibility and appending the given ModuleId. 51 void promoteInternals(Module &ExportM, Module &ImportM, StringRef ModuleId, 52 SetVector<GlobalValue *> &PromoteExtra) { 53 DenseMap<const Comdat *, Comdat *> RenamedComdats; 54 for (auto &ExportGV : ExportM.global_values()) { 55 if (!ExportGV.hasLocalLinkage()) 56 continue; 57 58 auto Name = ExportGV.getName(); 59 GlobalValue *ImportGV = nullptr; 60 if (!PromoteExtra.count(&ExportGV)) { 61 ImportGV = ImportM.getNamedValue(Name); 62 if (!ImportGV) 63 continue; 64 ImportGV->removeDeadConstantUsers(); 65 if (ImportGV->use_empty()) { 66 ImportGV->eraseFromParent(); 67 continue; 68 } 69 } 70 71 std::string OldName = Name.str(); 72 std::string NewName = (Name + ModuleId).str(); 73 74 if (const auto *C = ExportGV.getComdat()) 75 if (C->getName() == Name) 76 RenamedComdats.try_emplace(C, ExportM.getOrInsertComdat(NewName)); 77 78 ExportGV.setName(NewName); 79 ExportGV.setLinkage(GlobalValue::ExternalLinkage); 80 ExportGV.setVisibility(GlobalValue::HiddenVisibility); 81 82 if (ImportGV) { 83 ImportGV->setName(NewName); 84 ImportGV->setVisibility(GlobalValue::HiddenVisibility); 85 } 86 87 if (isa<Function>(&ExportGV) && allowPromotionAlias(OldName)) { 88 // Create a local alias with the original name to avoid breaking 89 // references from inline assembly. 90 std::string Alias = 91 ".lto_set_conditional " + OldName + "," + NewName + "\n"; 92 ExportM.appendModuleInlineAsm(Alias); 93 } 94 } 95 96 if (!RenamedComdats.empty()) 97 for (auto &GO : ExportM.global_objects()) 98 if (auto *C = GO.getComdat()) { 99 auto Replacement = RenamedComdats.find(C); 100 if (Replacement != RenamedComdats.end()) 101 GO.setComdat(Replacement->second); 102 } 103 } 104 105 // Promote all internal (i.e. distinct) type ids used by the module by replacing 106 // them with external type ids formed using the module id. 107 // 108 // Note that this needs to be done before we clone the module because each clone 109 // will receive its own set of distinct metadata nodes. 110 void promoteTypeIds(Module &M, StringRef ModuleId) { 111 DenseMap<Metadata *, Metadata *> LocalToGlobal; 112 auto ExternalizeTypeId = [&](CallInst *CI, unsigned ArgNo) { 113 Metadata *MD = 114 cast<MetadataAsValue>(CI->getArgOperand(ArgNo))->getMetadata(); 115 116 if (isa<MDNode>(MD) && cast<MDNode>(MD)->isDistinct()) { 117 Metadata *&GlobalMD = LocalToGlobal[MD]; 118 if (!GlobalMD) { 119 std::string NewName = (Twine(LocalToGlobal.size()) + ModuleId).str(); 120 GlobalMD = MDString::get(M.getContext(), NewName); 121 } 122 123 CI->setArgOperand(ArgNo, 124 MetadataAsValue::get(M.getContext(), GlobalMD)); 125 } 126 }; 127 128 if (Function *TypeTestFunc = 129 M.getFunction(Intrinsic::getName(Intrinsic::type_test))) { 130 for (const Use &U : TypeTestFunc->uses()) { 131 auto CI = cast<CallInst>(U.getUser()); 132 ExternalizeTypeId(CI, 1); 133 } 134 } 135 136 if (Function *TypeCheckedLoadFunc = 137 M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load))) { 138 for (const Use &U : TypeCheckedLoadFunc->uses()) { 139 auto CI = cast<CallInst>(U.getUser()); 140 ExternalizeTypeId(CI, 2); 141 } 142 } 143 144 for (GlobalObject &GO : M.global_objects()) { 145 SmallVector<MDNode *, 1> MDs; 146 GO.getMetadata(LLVMContext::MD_type, MDs); 147 148 GO.eraseMetadata(LLVMContext::MD_type); 149 for (auto MD : MDs) { 150 auto I = LocalToGlobal.find(MD->getOperand(1)); 151 if (I == LocalToGlobal.end()) { 152 GO.addMetadata(LLVMContext::MD_type, *MD); 153 continue; 154 } 155 GO.addMetadata( 156 LLVMContext::MD_type, 157 *MDNode::get(M.getContext(), {MD->getOperand(0), I->second})); 158 } 159 } 160 } 161 162 // Drop unused globals, and drop type information from function declarations. 163 // FIXME: If we made functions typeless then there would be no need to do this. 164 void simplifyExternals(Module &M) { 165 FunctionType *EmptyFT = 166 FunctionType::get(Type::getVoidTy(M.getContext()), false); 167 168 for (Function &F : llvm::make_early_inc_range(M)) { 169 if (F.isDeclaration() && F.use_empty()) { 170 F.eraseFromParent(); 171 continue; 172 } 173 174 if (!F.isDeclaration() || F.getFunctionType() == EmptyFT || 175 // Changing the type of an intrinsic may invalidate the IR. 176 F.getName().startswith("llvm.")) 177 continue; 178 179 Function *NewF = 180 Function::Create(EmptyFT, GlobalValue::ExternalLinkage, 181 F.getAddressSpace(), "", &M); 182 NewF->copyAttributesFrom(&F); 183 // Only copy function attribtues. 184 NewF->setAttributes(AttributeList::get(M.getContext(), 185 AttributeList::FunctionIndex, 186 F.getAttributes().getFnAttrs())); 187 NewF->takeName(&F); 188 F.replaceAllUsesWith(ConstantExpr::getBitCast(NewF, F.getType())); 189 F.eraseFromParent(); 190 } 191 192 for (GlobalVariable &GV : llvm::make_early_inc_range(M.globals())) { 193 if (GV.isDeclaration() && GV.use_empty()) { 194 GV.eraseFromParent(); 195 continue; 196 } 197 } 198 } 199 200 static void 201 filterModule(Module *M, 202 function_ref<bool(const GlobalValue *)> ShouldKeepDefinition) { 203 std::vector<GlobalValue *> V; 204 for (GlobalValue &GV : M->global_values()) 205 if (!ShouldKeepDefinition(&GV)) 206 V.push_back(&GV); 207 208 for (GlobalValue *GV : V) 209 if (!convertToDeclaration(*GV)) 210 GV->eraseFromParent(); 211 } 212 213 void forEachVirtualFunction(Constant *C, function_ref<void(Function *)> Fn) { 214 if (auto *F = dyn_cast<Function>(C)) 215 return Fn(F); 216 if (isa<GlobalValue>(C)) 217 return; 218 for (Value *Op : C->operands()) 219 forEachVirtualFunction(cast<Constant>(Op), Fn); 220 } 221 222 // Clone any @llvm[.compiler].used over to the new module and append 223 // values whose defs were cloned into that module. 224 static void cloneUsedGlobalVariables(const Module &SrcM, Module &DestM, 225 bool CompilerUsed) { 226 SmallVector<GlobalValue *, 4> Used, NewUsed; 227 // First collect those in the llvm[.compiler].used set. 228 collectUsedGlobalVariables(SrcM, Used, CompilerUsed); 229 // Next build a set of the equivalent values defined in DestM. 230 for (auto *V : Used) { 231 auto *GV = DestM.getNamedValue(V->getName()); 232 if (GV && !GV->isDeclaration()) 233 NewUsed.push_back(GV); 234 } 235 // Finally, add them to a llvm[.compiler].used variable in DestM. 236 if (CompilerUsed) 237 appendToCompilerUsed(DestM, NewUsed); 238 else 239 appendToUsed(DestM, NewUsed); 240 } 241 242 // If it's possible to split M into regular and thin LTO parts, do so and write 243 // a multi-module bitcode file with the two parts to OS. Otherwise, write only a 244 // regular LTO bitcode file to OS. 245 void splitAndWriteThinLTOBitcode( 246 raw_ostream &OS, raw_ostream *ThinLinkOS, 247 function_ref<AAResults &(Function &)> AARGetter, Module &M) { 248 std::string ModuleId = getUniqueModuleId(&M); 249 if (ModuleId.empty()) { 250 // We couldn't generate a module ID for this module, write it out as a 251 // regular LTO module with an index for summary-based dead stripping. 252 ProfileSummaryInfo PSI(M); 253 M.addModuleFlag(Module::Error, "ThinLTO", uint32_t(0)); 254 ModuleSummaryIndex Index = buildModuleSummaryIndex(M, nullptr, &PSI); 255 WriteBitcodeToFile(M, OS, /*ShouldPreserveUseListOrder=*/false, &Index); 256 257 if (ThinLinkOS) 258 // We don't have a ThinLTO part, but still write the module to the 259 // ThinLinkOS if requested so that the expected output file is produced. 260 WriteBitcodeToFile(M, *ThinLinkOS, /*ShouldPreserveUseListOrder=*/false, 261 &Index); 262 263 return; 264 } 265 266 promoteTypeIds(M, ModuleId); 267 268 // Returns whether a global or its associated global has attached type 269 // metadata. The former may participate in CFI or whole-program 270 // devirtualization, so they need to appear in the merged module instead of 271 // the thin LTO module. Similarly, globals that are associated with globals 272 // with type metadata need to appear in the merged module because they will 273 // reference the global's section directly. 274 auto HasTypeMetadata = [](const GlobalObject *GO) { 275 if (MDNode *MD = GO->getMetadata(LLVMContext::MD_associated)) 276 if (auto *AssocVM = dyn_cast_or_null<ValueAsMetadata>(MD->getOperand(0))) 277 if (auto *AssocGO = dyn_cast<GlobalObject>(AssocVM->getValue())) 278 if (AssocGO->hasMetadata(LLVMContext::MD_type)) 279 return true; 280 return GO->hasMetadata(LLVMContext::MD_type); 281 }; 282 283 // Collect the set of virtual functions that are eligible for virtual constant 284 // propagation. Each eligible function must not access memory, must return 285 // an integer of width <=64 bits, must take at least one argument, must not 286 // use its first argument (assumed to be "this") and all arguments other than 287 // the first one must be of <=64 bit integer type. 288 // 289 // Note that we test whether this copy of the function is readnone, rather 290 // than testing function attributes, which must hold for any copy of the 291 // function, even a less optimized version substituted at link time. This is 292 // sound because the virtual constant propagation optimizations effectively 293 // inline all implementations of the virtual function into each call site, 294 // rather than using function attributes to perform local optimization. 295 DenseSet<const Function *> EligibleVirtualFns; 296 // If any member of a comdat lives in MergedM, put all members of that 297 // comdat in MergedM to keep the comdat together. 298 DenseSet<const Comdat *> MergedMComdats; 299 for (GlobalVariable &GV : M.globals()) 300 if (HasTypeMetadata(&GV)) { 301 if (const auto *C = GV.getComdat()) 302 MergedMComdats.insert(C); 303 forEachVirtualFunction(GV.getInitializer(), [&](Function *F) { 304 auto *RT = dyn_cast<IntegerType>(F->getReturnType()); 305 if (!RT || RT->getBitWidth() > 64 || F->arg_empty() || 306 !F->arg_begin()->use_empty()) 307 return; 308 for (auto &Arg : drop_begin(F->args())) { 309 auto *ArgT = dyn_cast<IntegerType>(Arg.getType()); 310 if (!ArgT || ArgT->getBitWidth() > 64) 311 return; 312 } 313 if (!F->isDeclaration() && 314 computeFunctionBodyMemoryAccess(*F, AARGetter(*F)) == 315 FMRB_DoesNotAccessMemory) 316 EligibleVirtualFns.insert(F); 317 }); 318 } 319 320 ValueToValueMapTy VMap; 321 std::unique_ptr<Module> MergedM( 322 CloneModule(M, VMap, [&](const GlobalValue *GV) -> bool { 323 if (const auto *C = GV->getComdat()) 324 if (MergedMComdats.count(C)) 325 return true; 326 if (auto *F = dyn_cast<Function>(GV)) 327 return EligibleVirtualFns.count(F); 328 if (auto *GVar = 329 dyn_cast_or_null<GlobalVariable>(GV->getAliaseeObject())) 330 return HasTypeMetadata(GVar); 331 return false; 332 })); 333 StripDebugInfo(*MergedM); 334 MergedM->setModuleInlineAsm(""); 335 336 // Clone any llvm.*used globals to ensure the included values are 337 // not deleted. 338 cloneUsedGlobalVariables(M, *MergedM, /*CompilerUsed*/ false); 339 cloneUsedGlobalVariables(M, *MergedM, /*CompilerUsed*/ true); 340 341 for (Function &F : *MergedM) 342 if (!F.isDeclaration()) { 343 // Reset the linkage of all functions eligible for virtual constant 344 // propagation. The canonical definitions live in the thin LTO module so 345 // that they can be imported. 346 F.setLinkage(GlobalValue::AvailableExternallyLinkage); 347 F.setComdat(nullptr); 348 } 349 350 SetVector<GlobalValue *> CfiFunctions; 351 for (auto &F : M) 352 if ((!F.hasLocalLinkage() || F.hasAddressTaken()) && HasTypeMetadata(&F)) 353 CfiFunctions.insert(&F); 354 355 // Remove all globals with type metadata, globals with comdats that live in 356 // MergedM, and aliases pointing to such globals from the thin LTO module. 357 filterModule(&M, [&](const GlobalValue *GV) { 358 if (auto *GVar = dyn_cast_or_null<GlobalVariable>(GV->getAliaseeObject())) 359 if (HasTypeMetadata(GVar)) 360 return false; 361 if (const auto *C = GV->getComdat()) 362 if (MergedMComdats.count(C)) 363 return false; 364 return true; 365 }); 366 367 promoteInternals(*MergedM, M, ModuleId, CfiFunctions); 368 promoteInternals(M, *MergedM, ModuleId, CfiFunctions); 369 370 auto &Ctx = MergedM->getContext(); 371 SmallVector<MDNode *, 8> CfiFunctionMDs; 372 for (auto V : CfiFunctions) { 373 Function &F = *cast<Function>(V); 374 SmallVector<MDNode *, 2> Types; 375 F.getMetadata(LLVMContext::MD_type, Types); 376 377 SmallVector<Metadata *, 4> Elts; 378 Elts.push_back(MDString::get(Ctx, F.getName())); 379 CfiFunctionLinkage Linkage; 380 if (lowertypetests::isJumpTableCanonical(&F)) 381 Linkage = CFL_Definition; 382 else if (F.hasExternalWeakLinkage()) 383 Linkage = CFL_WeakDeclaration; 384 else 385 Linkage = CFL_Declaration; 386 Elts.push_back(ConstantAsMetadata::get( 387 llvm::ConstantInt::get(Type::getInt8Ty(Ctx), Linkage))); 388 append_range(Elts, Types); 389 CfiFunctionMDs.push_back(MDTuple::get(Ctx, Elts)); 390 } 391 392 if(!CfiFunctionMDs.empty()) { 393 NamedMDNode *NMD = MergedM->getOrInsertNamedMetadata("cfi.functions"); 394 for (auto MD : CfiFunctionMDs) 395 NMD->addOperand(MD); 396 } 397 398 SmallVector<MDNode *, 8> FunctionAliases; 399 for (auto &A : M.aliases()) { 400 if (!isa<Function>(A.getAliasee())) 401 continue; 402 403 auto *F = cast<Function>(A.getAliasee()); 404 405 Metadata *Elts[] = { 406 MDString::get(Ctx, A.getName()), 407 MDString::get(Ctx, F->getName()), 408 ConstantAsMetadata::get( 409 ConstantInt::get(Type::getInt8Ty(Ctx), A.getVisibility())), 410 ConstantAsMetadata::get( 411 ConstantInt::get(Type::getInt8Ty(Ctx), A.isWeakForLinker())), 412 }; 413 414 FunctionAliases.push_back(MDTuple::get(Ctx, Elts)); 415 } 416 417 if (!FunctionAliases.empty()) { 418 NamedMDNode *NMD = MergedM->getOrInsertNamedMetadata("aliases"); 419 for (auto MD : FunctionAliases) 420 NMD->addOperand(MD); 421 } 422 423 SmallVector<MDNode *, 8> Symvers; 424 ModuleSymbolTable::CollectAsmSymvers(M, [&](StringRef Name, StringRef Alias) { 425 Function *F = M.getFunction(Name); 426 if (!F || F->use_empty()) 427 return; 428 429 Symvers.push_back(MDTuple::get( 430 Ctx, {MDString::get(Ctx, Name), MDString::get(Ctx, Alias)})); 431 }); 432 433 if (!Symvers.empty()) { 434 NamedMDNode *NMD = MergedM->getOrInsertNamedMetadata("symvers"); 435 for (auto MD : Symvers) 436 NMD->addOperand(MD); 437 } 438 439 simplifyExternals(*MergedM); 440 441 // FIXME: Try to re-use BSI and PFI from the original module here. 442 ProfileSummaryInfo PSI(M); 443 ModuleSummaryIndex Index = buildModuleSummaryIndex(M, nullptr, &PSI); 444 445 // Mark the merged module as requiring full LTO. We still want an index for 446 // it though, so that it can participate in summary-based dead stripping. 447 MergedM->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0)); 448 ModuleSummaryIndex MergedMIndex = 449 buildModuleSummaryIndex(*MergedM, nullptr, &PSI); 450 451 SmallVector<char, 0> Buffer; 452 453 BitcodeWriter W(Buffer); 454 // Save the module hash produced for the full bitcode, which will 455 // be used in the backends, and use that in the minimized bitcode 456 // produced for the full link. 457 ModuleHash ModHash = {{0}}; 458 W.writeModule(M, /*ShouldPreserveUseListOrder=*/false, &Index, 459 /*GenerateHash=*/true, &ModHash); 460 W.writeModule(*MergedM, /*ShouldPreserveUseListOrder=*/false, &MergedMIndex); 461 W.writeSymtab(); 462 W.writeStrtab(); 463 OS << Buffer; 464 465 // If a minimized bitcode module was requested for the thin link, only 466 // the information that is needed by thin link will be written in the 467 // given OS (the merged module will be written as usual). 468 if (ThinLinkOS) { 469 Buffer.clear(); 470 BitcodeWriter W2(Buffer); 471 StripDebugInfo(M); 472 W2.writeThinLinkBitcode(M, Index, ModHash); 473 W2.writeModule(*MergedM, /*ShouldPreserveUseListOrder=*/false, 474 &MergedMIndex); 475 W2.writeSymtab(); 476 W2.writeStrtab(); 477 *ThinLinkOS << Buffer; 478 } 479 } 480 481 // Check if the LTO Unit splitting has been enabled. 482 bool enableSplitLTOUnit(Module &M) { 483 bool EnableSplitLTOUnit = false; 484 if (auto *MD = mdconst::extract_or_null<ConstantInt>( 485 M.getModuleFlag("EnableSplitLTOUnit"))) 486 EnableSplitLTOUnit = MD->getZExtValue(); 487 return EnableSplitLTOUnit; 488 } 489 490 // Returns whether this module needs to be split because it uses type metadata. 491 bool hasTypeMetadata(Module &M) { 492 for (auto &GO : M.global_objects()) { 493 if (GO.hasMetadata(LLVMContext::MD_type)) 494 return true; 495 } 496 return false; 497 } 498 499 void writeThinLTOBitcode(raw_ostream &OS, raw_ostream *ThinLinkOS, 500 function_ref<AAResults &(Function &)> AARGetter, 501 Module &M, const ModuleSummaryIndex *Index) { 502 std::unique_ptr<ModuleSummaryIndex> NewIndex = nullptr; 503 // See if this module has any type metadata. If so, we try to split it 504 // or at least promote type ids to enable WPD. 505 if (hasTypeMetadata(M)) { 506 if (enableSplitLTOUnit(M)) 507 return splitAndWriteThinLTOBitcode(OS, ThinLinkOS, AARGetter, M); 508 // Promote type ids as needed for index-based WPD. 509 std::string ModuleId = getUniqueModuleId(&M); 510 if (!ModuleId.empty()) { 511 promoteTypeIds(M, ModuleId); 512 // Need to rebuild the index so that it contains type metadata 513 // for the newly promoted type ids. 514 // FIXME: Probably should not bother building the index at all 515 // in the caller of writeThinLTOBitcode (which does so via the 516 // ModuleSummaryIndexAnalysis pass), since we have to rebuild it 517 // anyway whenever there is type metadata (here or in 518 // splitAndWriteThinLTOBitcode). Just always build it once via the 519 // buildModuleSummaryIndex when Module(s) are ready. 520 ProfileSummaryInfo PSI(M); 521 NewIndex = std::make_unique<ModuleSummaryIndex>( 522 buildModuleSummaryIndex(M, nullptr, &PSI)); 523 Index = NewIndex.get(); 524 } 525 } 526 527 // Write it out as an unsplit ThinLTO module. 528 529 // Save the module hash produced for the full bitcode, which will 530 // be used in the backends, and use that in the minimized bitcode 531 // produced for the full link. 532 ModuleHash ModHash = {{0}}; 533 WriteBitcodeToFile(M, OS, /*ShouldPreserveUseListOrder=*/false, Index, 534 /*GenerateHash=*/true, &ModHash); 535 // If a minimized bitcode module was requested for the thin link, only 536 // the information that is needed by thin link will be written in the 537 // given OS. 538 if (ThinLinkOS && Index) 539 writeThinLinkBitcodeToFile(M, *ThinLinkOS, *Index, ModHash); 540 } 541 542 class WriteThinLTOBitcode : public ModulePass { 543 raw_ostream &OS; // raw_ostream to print on 544 // The output stream on which to emit a minimized module for use 545 // just in the thin link, if requested. 546 raw_ostream *ThinLinkOS; 547 548 public: 549 static char ID; // Pass identification, replacement for typeid 550 WriteThinLTOBitcode() : ModulePass(ID), OS(dbgs()), ThinLinkOS(nullptr) { 551 initializeWriteThinLTOBitcodePass(*PassRegistry::getPassRegistry()); 552 } 553 554 explicit WriteThinLTOBitcode(raw_ostream &o, raw_ostream *ThinLinkOS) 555 : ModulePass(ID), OS(o), ThinLinkOS(ThinLinkOS) { 556 initializeWriteThinLTOBitcodePass(*PassRegistry::getPassRegistry()); 557 } 558 559 StringRef getPassName() const override { return "ThinLTO Bitcode Writer"; } 560 561 bool runOnModule(Module &M) override { 562 const ModuleSummaryIndex *Index = 563 &(getAnalysis<ModuleSummaryIndexWrapperPass>().getIndex()); 564 writeThinLTOBitcode(OS, ThinLinkOS, LegacyAARGetter(*this), M, Index); 565 return true; 566 } 567 void getAnalysisUsage(AnalysisUsage &AU) const override { 568 AU.setPreservesAll(); 569 AU.addRequired<AssumptionCacheTracker>(); 570 AU.addRequired<ModuleSummaryIndexWrapperPass>(); 571 AU.addRequired<TargetLibraryInfoWrapperPass>(); 572 } 573 }; 574 } // anonymous namespace 575 576 char WriteThinLTOBitcode::ID = 0; 577 INITIALIZE_PASS_BEGIN(WriteThinLTOBitcode, "write-thinlto-bitcode", 578 "Write ThinLTO Bitcode", false, true) 579 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker) 580 INITIALIZE_PASS_DEPENDENCY(ModuleSummaryIndexWrapperPass) 581 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass) 582 INITIALIZE_PASS_END(WriteThinLTOBitcode, "write-thinlto-bitcode", 583 "Write ThinLTO Bitcode", false, true) 584 585 ModulePass *llvm::createWriteThinLTOBitcodePass(raw_ostream &Str, 586 raw_ostream *ThinLinkOS) { 587 return new WriteThinLTOBitcode(Str, ThinLinkOS); 588 } 589 590 PreservedAnalyses 591 llvm::ThinLTOBitcodeWriterPass::run(Module &M, ModuleAnalysisManager &AM) { 592 FunctionAnalysisManager &FAM = 593 AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 594 writeThinLTOBitcode(OS, ThinLinkOS, 595 [&FAM](Function &F) -> AAResults & { 596 return FAM.getResult<AAManager>(F); 597 }, 598 M, &AM.getResult<ModuleSummaryIndexAnalysis>(M)); 599 return PreservedAnalyses::all(); 600 } 601