1 //===-ThinLTOCodeGenerator.cpp - LLVM Link Time Optimizer -----------------===// 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 file implements the Thin Link Time Optimization library. This library is 10 // intended to be used by linker to optimize code at link time. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/LTO/legacy/ThinLTOCodeGenerator.h" 15 16 #include "llvm/ADT/Statistic.h" 17 #include "llvm/ADT/StringExtras.h" 18 #include "llvm/Analysis/ModuleSummaryAnalysis.h" 19 #include "llvm/Analysis/ProfileSummaryInfo.h" 20 #include "llvm/Analysis/TargetLibraryInfo.h" 21 #include "llvm/Analysis/TargetTransformInfo.h" 22 #include "llvm/Bitcode/BitcodeReader.h" 23 #include "llvm/Bitcode/BitcodeWriter.h" 24 #include "llvm/Bitcode/BitcodeWriterPass.h" 25 #include "llvm/Config/llvm-config.h" 26 #include "llvm/IR/DebugInfo.h" 27 #include "llvm/IR/DiagnosticPrinter.h" 28 #include "llvm/IR/LLVMContext.h" 29 #include "llvm/IR/LegacyPassManager.h" 30 #include "llvm/IR/Mangler.h" 31 #include "llvm/IR/PassTimingInfo.h" 32 #include "llvm/IR/RemarkStreamer.h" 33 #include "llvm/IR/Verifier.h" 34 #include "llvm/IRReader/IRReader.h" 35 #include "llvm/LTO/LTO.h" 36 #include "llvm/LTO/SummaryBasedOptimizations.h" 37 #include "llvm/MC/SubtargetFeature.h" 38 #include "llvm/Object/IRObjectFile.h" 39 #include "llvm/Support/CachePruning.h" 40 #include "llvm/Support/Debug.h" 41 #include "llvm/Support/Error.h" 42 #include "llvm/Support/FileUtilities.h" 43 #include "llvm/Support/Path.h" 44 #include "llvm/Support/SHA1.h" 45 #include "llvm/Support/SmallVectorMemoryBuffer.h" 46 #include "llvm/Support/TargetRegistry.h" 47 #include "llvm/Support/ThreadPool.h" 48 #include "llvm/Support/Threading.h" 49 #include "llvm/Support/ToolOutputFile.h" 50 #include "llvm/Support/VCSRevision.h" 51 #include "llvm/Target/TargetMachine.h" 52 #include "llvm/Transforms/IPO.h" 53 #include "llvm/Transforms/IPO/FunctionImport.h" 54 #include "llvm/Transforms/IPO/Internalize.h" 55 #include "llvm/Transforms/IPO/PassManagerBuilder.h" 56 #include "llvm/Transforms/IPO/WholeProgramDevirt.h" 57 #include "llvm/Transforms/ObjCARC.h" 58 #include "llvm/Transforms/Utils/FunctionImportUtils.h" 59 60 #include <numeric> 61 62 #if !defined(_MSC_VER) && !defined(__MINGW32__) 63 #include <unistd.h> 64 #else 65 #include <io.h> 66 #endif 67 68 using namespace llvm; 69 70 #define DEBUG_TYPE "thinlto" 71 72 namespace llvm { 73 // Flags -discard-value-names, defined in LTOCodeGenerator.cpp 74 extern cl::opt<bool> LTODiscardValueNames; 75 extern cl::opt<std::string> RemarksFilename; 76 extern cl::opt<std::string> RemarksPasses; 77 extern cl::opt<bool> RemarksWithHotness; 78 extern cl::opt<std::string> RemarksFormat; 79 } 80 81 namespace { 82 83 static cl::opt<int> 84 ThreadCount("threads", cl::init(llvm::heavyweight_hardware_concurrency())); 85 86 // Simple helper to save temporary files for debug. 87 static void saveTempBitcode(const Module &TheModule, StringRef TempDir, 88 unsigned count, StringRef Suffix) { 89 if (TempDir.empty()) 90 return; 91 // User asked to save temps, let dump the bitcode file after import. 92 std::string SaveTempPath = (TempDir + llvm::Twine(count) + Suffix).str(); 93 std::error_code EC; 94 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::OF_None); 95 if (EC) 96 report_fatal_error(Twine("Failed to open ") + SaveTempPath + 97 " to save optimized bitcode\n"); 98 WriteBitcodeToFile(TheModule, OS, /* ShouldPreserveUseListOrder */ true); 99 } 100 101 static const GlobalValueSummary * 102 getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) { 103 // If there is any strong definition anywhere, get it. 104 auto StrongDefForLinker = llvm::find_if( 105 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) { 106 auto Linkage = Summary->linkage(); 107 return !GlobalValue::isAvailableExternallyLinkage(Linkage) && 108 !GlobalValue::isWeakForLinker(Linkage); 109 }); 110 if (StrongDefForLinker != GVSummaryList.end()) 111 return StrongDefForLinker->get(); 112 // Get the first *linker visible* definition for this global in the summary 113 // list. 114 auto FirstDefForLinker = llvm::find_if( 115 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) { 116 auto Linkage = Summary->linkage(); 117 return !GlobalValue::isAvailableExternallyLinkage(Linkage); 118 }); 119 // Extern templates can be emitted as available_externally. 120 if (FirstDefForLinker == GVSummaryList.end()) 121 return nullptr; 122 return FirstDefForLinker->get(); 123 } 124 125 // Populate map of GUID to the prevailing copy for any multiply defined 126 // symbols. Currently assume first copy is prevailing, or any strong 127 // definition. Can be refined with Linker information in the future. 128 static void computePrevailingCopies( 129 const ModuleSummaryIndex &Index, 130 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy) { 131 auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) { 132 return GVSummaryList.size() > 1; 133 }; 134 135 for (auto &I : Index) { 136 if (HasMultipleCopies(I.second.SummaryList)) 137 PrevailingCopy[I.first] = 138 getFirstDefinitionForLinker(I.second.SummaryList); 139 } 140 } 141 142 static StringMap<lto::InputFile *> 143 generateModuleMap(std::vector<std::unique_ptr<lto::InputFile>> &Modules) { 144 StringMap<lto::InputFile *> ModuleMap; 145 for (auto &M : Modules) { 146 assert(ModuleMap.find(M->getName()) == ModuleMap.end() && 147 "Expect unique Buffer Identifier"); 148 ModuleMap[M->getName()] = M.get(); 149 } 150 return ModuleMap; 151 } 152 153 static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) { 154 if (renameModuleForThinLTO(TheModule, Index)) 155 report_fatal_error("renameModuleForThinLTO failed"); 156 } 157 158 namespace { 159 class ThinLTODiagnosticInfo : public DiagnosticInfo { 160 const Twine &Msg; 161 public: 162 ThinLTODiagnosticInfo(const Twine &DiagMsg, 163 DiagnosticSeverity Severity = DS_Error) 164 : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {} 165 void print(DiagnosticPrinter &DP) const override { DP << Msg; } 166 }; 167 } 168 169 /// Verify the module and strip broken debug info. 170 static void verifyLoadedModule(Module &TheModule) { 171 bool BrokenDebugInfo = false; 172 if (verifyModule(TheModule, &dbgs(), &BrokenDebugInfo)) 173 report_fatal_error("Broken module found, compilation aborted!"); 174 if (BrokenDebugInfo) { 175 TheModule.getContext().diagnose(ThinLTODiagnosticInfo( 176 "Invalid debug info found, debug info will be stripped", DS_Warning)); 177 StripDebugInfo(TheModule); 178 } 179 } 180 181 static std::unique_ptr<Module> loadModuleFromInput(lto::InputFile *Input, 182 LLVMContext &Context, 183 bool Lazy, 184 bool IsImporting) { 185 auto &Mod = Input->getSingleBitcodeModule(); 186 SMDiagnostic Err; 187 Expected<std::unique_ptr<Module>> ModuleOrErr = 188 Lazy ? Mod.getLazyModule(Context, 189 /* ShouldLazyLoadMetadata */ true, IsImporting) 190 : Mod.parseModule(Context); 191 if (!ModuleOrErr) { 192 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) { 193 SMDiagnostic Err = SMDiagnostic(Mod.getModuleIdentifier(), 194 SourceMgr::DK_Error, EIB.message()); 195 Err.print("ThinLTO", errs()); 196 }); 197 report_fatal_error("Can't load module, abort."); 198 } 199 if (!Lazy) 200 verifyLoadedModule(*ModuleOrErr.get()); 201 return std::move(*ModuleOrErr); 202 } 203 204 static void 205 crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index, 206 StringMap<lto::InputFile*> &ModuleMap, 207 const FunctionImporter::ImportMapTy &ImportList) { 208 auto Loader = [&](StringRef Identifier) { 209 auto &Input = ModuleMap[Identifier]; 210 return loadModuleFromInput(Input, TheModule.getContext(), 211 /*Lazy=*/true, /*IsImporting*/ true); 212 }; 213 214 FunctionImporter Importer(Index, Loader); 215 Expected<bool> Result = Importer.importFunctions(TheModule, ImportList); 216 if (!Result) { 217 handleAllErrors(Result.takeError(), [&](ErrorInfoBase &EIB) { 218 SMDiagnostic Err = SMDiagnostic(TheModule.getModuleIdentifier(), 219 SourceMgr::DK_Error, EIB.message()); 220 Err.print("ThinLTO", errs()); 221 }); 222 report_fatal_error("importFunctions failed"); 223 } 224 // Verify again after cross-importing. 225 verifyLoadedModule(TheModule); 226 } 227 228 static void optimizeModule(Module &TheModule, TargetMachine &TM, 229 unsigned OptLevel, bool Freestanding, 230 ModuleSummaryIndex *Index) { 231 // Populate the PassManager 232 PassManagerBuilder PMB; 233 PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple()); 234 if (Freestanding) 235 PMB.LibraryInfo->disableAllFunctions(); 236 PMB.Inliner = createFunctionInliningPass(); 237 // FIXME: should get it from the bitcode? 238 PMB.OptLevel = OptLevel; 239 PMB.LoopVectorize = true; 240 PMB.SLPVectorize = true; 241 // Already did this in verifyLoadedModule(). 242 PMB.VerifyInput = false; 243 PMB.VerifyOutput = false; 244 PMB.ImportSummary = Index; 245 246 legacy::PassManager PM; 247 248 // Add the TTI (required to inform the vectorizer about register size for 249 // instance) 250 PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis())); 251 252 // Add optimizations 253 PMB.populateThinLTOPassManager(PM); 254 255 PM.run(TheModule); 256 } 257 258 static void 259 addUsedSymbolToPreservedGUID(const lto::InputFile &File, 260 DenseSet<GlobalValue::GUID> &PreservedGUID) { 261 for (const auto &Sym : File.symbols()) { 262 if (Sym.isUsed()) 263 PreservedGUID.insert(GlobalValue::getGUID(Sym.getIRName())); 264 } 265 } 266 267 // Convert the PreservedSymbols map from "Name" based to "GUID" based. 268 static DenseSet<GlobalValue::GUID> 269 computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols, 270 const Triple &TheTriple) { 271 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size()); 272 for (auto &Entry : PreservedSymbols) { 273 StringRef Name = Entry.first(); 274 if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_') 275 Name = Name.drop_front(); 276 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name)); 277 } 278 return GUIDPreservedSymbols; 279 } 280 281 std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule, 282 TargetMachine &TM) { 283 SmallVector<char, 128> OutputBuffer; 284 285 // CodeGen 286 { 287 raw_svector_ostream OS(OutputBuffer); 288 legacy::PassManager PM; 289 290 // If the bitcode files contain ARC code and were compiled with optimization, 291 // the ObjCARCContractPass must be run, so do it unconditionally here. 292 PM.add(createObjCARCContractPass()); 293 294 // Setup the codegen now. 295 if (TM.addPassesToEmitFile(PM, OS, nullptr, TargetMachine::CGFT_ObjectFile, 296 /* DisableVerify */ true)) 297 report_fatal_error("Failed to setup codegen"); 298 299 // Run codegen now. resulting binary is in OutputBuffer. 300 PM.run(TheModule); 301 } 302 return std::make_unique<SmallVectorMemoryBuffer>(std::move(OutputBuffer)); 303 } 304 305 /// Manage caching for a single Module. 306 class ModuleCacheEntry { 307 SmallString<128> EntryPath; 308 309 public: 310 // Create a cache entry. This compute a unique hash for the Module considering 311 // the current list of export/import, and offer an interface to query to 312 // access the content in the cache. 313 ModuleCacheEntry( 314 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID, 315 const FunctionImporter::ImportMapTy &ImportList, 316 const FunctionImporter::ExportSetTy &ExportList, 317 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR, 318 const GVSummaryMapTy &DefinedGVSummaries, unsigned OptLevel, 319 bool Freestanding, const TargetMachineBuilder &TMBuilder) { 320 if (CachePath.empty()) 321 return; 322 323 if (!Index.modulePaths().count(ModuleID)) 324 // The module does not have an entry, it can't have a hash at all 325 return; 326 327 if (all_of(Index.getModuleHash(ModuleID), 328 [](uint32_t V) { return V == 0; })) 329 // No hash entry, no caching! 330 return; 331 332 llvm::lto::Config Conf; 333 Conf.OptLevel = OptLevel; 334 Conf.Options = TMBuilder.Options; 335 Conf.CPU = TMBuilder.MCpu; 336 Conf.MAttrs.push_back(TMBuilder.MAttr); 337 Conf.RelocModel = TMBuilder.RelocModel; 338 Conf.CGOptLevel = TMBuilder.CGOptLevel; 339 Conf.Freestanding = Freestanding; 340 SmallString<40> Key; 341 computeLTOCacheKey(Key, Conf, Index, ModuleID, ImportList, ExportList, 342 ResolvedODR, DefinedGVSummaries); 343 344 // This choice of file name allows the cache to be pruned (see pruneCache() 345 // in include/llvm/Support/CachePruning.h). 346 sys::path::append(EntryPath, CachePath, "llvmcache-" + Key); 347 } 348 349 // Access the path to this entry in the cache. 350 StringRef getEntryPath() { return EntryPath; } 351 352 // Try loading the buffer for this cache entry. 353 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() { 354 if (EntryPath.empty()) 355 return std::error_code(); 356 SmallString<64> ResultPath; 357 Expected<sys::fs::file_t> FDOrErr = sys::fs::openNativeFileForRead( 358 Twine(EntryPath), sys::fs::OF_UpdateAtime, &ResultPath); 359 if (!FDOrErr) 360 return errorToErrorCode(FDOrErr.takeError()); 361 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = MemoryBuffer::getOpenFile( 362 *FDOrErr, EntryPath, /*FileSize=*/-1, /*RequiresNullTerminator=*/false); 363 sys::fs::closeFile(*FDOrErr); 364 return MBOrErr; 365 } 366 367 // Cache the Produced object file 368 void write(const MemoryBuffer &OutputBuffer) { 369 if (EntryPath.empty()) 370 return; 371 372 // Write to a temporary to avoid race condition 373 SmallString<128> TempFilename; 374 SmallString<128> CachePath(EntryPath); 375 llvm::sys::path::remove_filename(CachePath); 376 sys::path::append(TempFilename, CachePath, "Thin-%%%%%%.tmp.o"); 377 378 if (auto Err = handleErrors( 379 llvm::writeFileAtomically(TempFilename, EntryPath, 380 OutputBuffer.getBuffer()), 381 [](const llvm::AtomicFileWriteError &E) { 382 std::string ErrorMsgBuffer; 383 llvm::raw_string_ostream S(ErrorMsgBuffer); 384 E.log(S); 385 386 if (E.Error == 387 llvm::atomic_write_error::failed_to_create_uniq_file) { 388 errs() << "Error: " << ErrorMsgBuffer << "\n"; 389 report_fatal_error("ThinLTO: Can't get a temporary file"); 390 } 391 })) { 392 // FIXME 393 consumeError(std::move(Err)); 394 } 395 } 396 }; 397 398 static std::unique_ptr<MemoryBuffer> 399 ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index, 400 StringMap<lto::InputFile *> &ModuleMap, TargetMachine &TM, 401 const FunctionImporter::ImportMapTy &ImportList, 402 const FunctionImporter::ExportSetTy &ExportList, 403 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols, 404 const GVSummaryMapTy &DefinedGlobals, 405 const ThinLTOCodeGenerator::CachingOptions &CacheOptions, 406 bool DisableCodeGen, StringRef SaveTempsDir, 407 bool Freestanding, unsigned OptLevel, unsigned count) { 408 409 // "Benchmark"-like optimization: single-source case 410 bool SingleModule = (ModuleMap.size() == 1); 411 412 if (!SingleModule) { 413 promoteModule(TheModule, Index); 414 415 // Apply summary-based prevailing-symbol resolution decisions. 416 thinLTOResolvePrevailingInModule(TheModule, DefinedGlobals); 417 418 // Save temps: after promotion. 419 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc"); 420 } 421 422 // Be friendly and don't nuke totally the module when the client didn't 423 // supply anything to preserve. 424 if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) { 425 // Apply summary-based internalization decisions. 426 thinLTOInternalizeModule(TheModule, DefinedGlobals); 427 } 428 429 // Save internalized bitcode 430 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc"); 431 432 if (!SingleModule) { 433 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList); 434 435 // Save temps: after cross-module import. 436 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc"); 437 } 438 439 optimizeModule(TheModule, TM, OptLevel, Freestanding, &Index); 440 441 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc"); 442 443 if (DisableCodeGen) { 444 // Configured to stop before CodeGen, serialize the bitcode and return. 445 SmallVector<char, 128> OutputBuffer; 446 { 447 raw_svector_ostream OS(OutputBuffer); 448 ProfileSummaryInfo PSI(TheModule); 449 auto Index = buildModuleSummaryIndex(TheModule, nullptr, &PSI); 450 WriteBitcodeToFile(TheModule, OS, true, &Index); 451 } 452 return std::make_unique<SmallVectorMemoryBuffer>(std::move(OutputBuffer)); 453 } 454 455 return codegenModule(TheModule, TM); 456 } 457 458 /// Resolve prevailing symbols. Record resolutions in the \p ResolvedODR map 459 /// for caching, and in the \p Index for application during the ThinLTO 460 /// backends. This is needed for correctness for exported symbols (ensure 461 /// at least one copy kept) and a compile-time optimization (to drop duplicate 462 /// copies when possible). 463 static void resolvePrevailingInIndex( 464 ModuleSummaryIndex &Index, 465 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> 466 &ResolvedODR, 467 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols, 468 const DenseMap<GlobalValue::GUID, const GlobalValueSummary *> 469 &PrevailingCopy) { 470 471 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) { 472 const auto &Prevailing = PrevailingCopy.find(GUID); 473 // Not in map means that there was only one copy, which must be prevailing. 474 if (Prevailing == PrevailingCopy.end()) 475 return true; 476 return Prevailing->second == S; 477 }; 478 479 auto recordNewLinkage = [&](StringRef ModuleIdentifier, 480 GlobalValue::GUID GUID, 481 GlobalValue::LinkageTypes NewLinkage) { 482 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage; 483 }; 484 485 thinLTOResolvePrevailingInIndex(Index, isPrevailing, recordNewLinkage, 486 GUIDPreservedSymbols); 487 } 488 489 // Initialize the TargetMachine builder for a given Triple 490 static void initTMBuilder(TargetMachineBuilder &TMBuilder, 491 const Triple &TheTriple) { 492 // Set a default CPU for Darwin triples (copied from LTOCodeGenerator). 493 // FIXME this looks pretty terrible... 494 if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) { 495 if (TheTriple.getArch() == llvm::Triple::x86_64) 496 TMBuilder.MCpu = "core2"; 497 else if (TheTriple.getArch() == llvm::Triple::x86) 498 TMBuilder.MCpu = "yonah"; 499 else if (TheTriple.getArch() == llvm::Triple::aarch64 || 500 TheTriple.getArch() == llvm::Triple::aarch64_32) 501 TMBuilder.MCpu = "cyclone"; 502 } 503 TMBuilder.TheTriple = std::move(TheTriple); 504 } 505 506 } // end anonymous namespace 507 508 void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) { 509 MemoryBufferRef Buffer(Data, Identifier); 510 511 auto InputOrError = lto::InputFile::create(Buffer); 512 if (!InputOrError) 513 report_fatal_error("ThinLTO cannot create input file: " + 514 toString(InputOrError.takeError())); 515 516 auto TripleStr = (*InputOrError)->getTargetTriple(); 517 Triple TheTriple(TripleStr); 518 519 if (Modules.empty()) 520 initTMBuilder(TMBuilder, Triple(TheTriple)); 521 else if (TMBuilder.TheTriple != TheTriple) { 522 if (!TMBuilder.TheTriple.isCompatibleWith(TheTriple)) 523 report_fatal_error("ThinLTO modules with incompatible triples not " 524 "supported"); 525 initTMBuilder(TMBuilder, Triple(TMBuilder.TheTriple.merge(TheTriple))); 526 } 527 528 Modules.emplace_back(std::move(*InputOrError)); 529 } 530 531 void ThinLTOCodeGenerator::preserveSymbol(StringRef Name) { 532 PreservedSymbols.insert(Name); 533 } 534 535 void ThinLTOCodeGenerator::crossReferenceSymbol(StringRef Name) { 536 // FIXME: At the moment, we don't take advantage of this extra information, 537 // we're conservatively considering cross-references as preserved. 538 // CrossReferencedSymbols.insert(Name); 539 PreservedSymbols.insert(Name); 540 } 541 542 // TargetMachine factory 543 std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const { 544 std::string ErrMsg; 545 const Target *TheTarget = 546 TargetRegistry::lookupTarget(TheTriple.str(), ErrMsg); 547 if (!TheTarget) { 548 report_fatal_error("Can't load target for this Triple: " + ErrMsg); 549 } 550 551 // Use MAttr as the default set of features. 552 SubtargetFeatures Features(MAttr); 553 Features.getDefaultSubtargetFeatures(TheTriple); 554 std::string FeatureStr = Features.getString(); 555 556 return std::unique_ptr<TargetMachine>( 557 TheTarget->createTargetMachine(TheTriple.str(), MCpu, FeatureStr, Options, 558 RelocModel, None, CGOptLevel)); 559 } 560 561 /** 562 * Produce the combined summary index from all the bitcode files: 563 * "thin-link". 564 */ 565 std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() { 566 std::unique_ptr<ModuleSummaryIndex> CombinedIndex = 567 std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false); 568 uint64_t NextModuleId = 0; 569 for (auto &Mod : Modules) { 570 auto &M = Mod->getSingleBitcodeModule(); 571 if (Error Err = 572 M.readSummary(*CombinedIndex, Mod->getName(), NextModuleId++)) { 573 // FIXME diagnose 574 logAllUnhandledErrors( 575 std::move(Err), errs(), 576 "error: can't create module summary index for buffer: "); 577 return nullptr; 578 } 579 } 580 return CombinedIndex; 581 } 582 583 namespace { 584 struct IsExported { 585 const StringMap<FunctionImporter::ExportSetTy> &ExportLists; 586 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols; 587 588 IsExported(const StringMap<FunctionImporter::ExportSetTy> &ExportLists, 589 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) 590 : ExportLists(ExportLists), GUIDPreservedSymbols(GUIDPreservedSymbols) {} 591 592 bool operator()(StringRef ModuleIdentifier, GlobalValue::GUID GUID) const { 593 const auto &ExportList = ExportLists.find(ModuleIdentifier); 594 return (ExportList != ExportLists.end() && 595 ExportList->second.count(GUID)) || 596 GUIDPreservedSymbols.count(GUID); 597 } 598 }; 599 600 struct IsPrevailing { 601 const DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy; 602 IsPrevailing(const DenseMap<GlobalValue::GUID, const GlobalValueSummary *> 603 &PrevailingCopy) 604 : PrevailingCopy(PrevailingCopy) {} 605 606 bool operator()(GlobalValue::GUID GUID, const GlobalValueSummary *S) const { 607 const auto &Prevailing = PrevailingCopy.find(GUID); 608 // Not in map means that there was only one copy, which must be prevailing. 609 if (Prevailing == PrevailingCopy.end()) 610 return true; 611 return Prevailing->second == S; 612 }; 613 }; 614 } // namespace 615 616 static void computeDeadSymbolsInIndex( 617 ModuleSummaryIndex &Index, 618 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) { 619 // We have no symbols resolution available. And can't do any better now in the 620 // case where the prevailing symbol is in a native object. It can be refined 621 // with linker information in the future. 622 auto isPrevailing = [&](GlobalValue::GUID G) { 623 return PrevailingType::Unknown; 624 }; 625 computeDeadSymbolsWithConstProp(Index, GUIDPreservedSymbols, isPrevailing, 626 /* ImportEnabled = */ true); 627 } 628 629 /** 630 * Perform promotion and renaming of exported internal functions. 631 * Index is updated to reflect linkage changes from weak resolution. 632 */ 633 void ThinLTOCodeGenerator::promote(Module &TheModule, ModuleSummaryIndex &Index, 634 const lto::InputFile &File) { 635 auto ModuleCount = Index.modulePaths().size(); 636 auto ModuleIdentifier = TheModule.getModuleIdentifier(); 637 638 // Collect for each module the list of function it defines (GUID -> Summary). 639 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries; 640 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries); 641 642 // Convert the preserved symbols set from string to GUID 643 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols( 644 PreservedSymbols, Triple(TheModule.getTargetTriple())); 645 646 // Add used symbol to the preserved symbols. 647 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols); 648 649 // Compute "dead" symbols, we don't want to import/export these! 650 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols); 651 652 // Generate import/export list 653 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount); 654 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount); 655 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists, 656 ExportLists); 657 658 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy; 659 computePrevailingCopies(Index, PrevailingCopy); 660 661 // Resolve prevailing symbols 662 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR; 663 resolvePrevailingInIndex(Index, ResolvedODR, GUIDPreservedSymbols, 664 PrevailingCopy); 665 666 thinLTOResolvePrevailingInModule( 667 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]); 668 669 // Promote the exported values in the index, so that they are promoted 670 // in the module. 671 thinLTOInternalizeAndPromoteInIndex( 672 Index, IsExported(ExportLists, GUIDPreservedSymbols), 673 IsPrevailing(PrevailingCopy)); 674 675 promoteModule(TheModule, Index); 676 } 677 678 /** 679 * Perform cross-module importing for the module identified by ModuleIdentifier. 680 */ 681 void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule, 682 ModuleSummaryIndex &Index, 683 const lto::InputFile &File) { 684 auto ModuleMap = generateModuleMap(Modules); 685 auto ModuleCount = Index.modulePaths().size(); 686 687 // Collect for each module the list of function it defines (GUID -> Summary). 688 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount); 689 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries); 690 691 // Convert the preserved symbols set from string to GUID 692 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols( 693 PreservedSymbols, Triple(TheModule.getTargetTriple())); 694 695 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols); 696 697 // Compute "dead" symbols, we don't want to import/export these! 698 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols); 699 700 // Generate import/export list 701 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount); 702 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount); 703 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists, 704 ExportLists); 705 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()]; 706 707 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList); 708 } 709 710 /** 711 * Compute the list of summaries needed for importing into module. 712 */ 713 void ThinLTOCodeGenerator::gatherImportedSummariesForModule( 714 Module &TheModule, ModuleSummaryIndex &Index, 715 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex, 716 const lto::InputFile &File) { 717 auto ModuleCount = Index.modulePaths().size(); 718 auto ModuleIdentifier = TheModule.getModuleIdentifier(); 719 720 // Collect for each module the list of function it defines (GUID -> Summary). 721 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount); 722 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries); 723 724 // Convert the preserved symbols set from string to GUID 725 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols( 726 PreservedSymbols, Triple(TheModule.getTargetTriple())); 727 728 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols); 729 730 // Compute "dead" symbols, we don't want to import/export these! 731 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols); 732 733 // Generate import/export list 734 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount); 735 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount); 736 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists, 737 ExportLists); 738 739 llvm::gatherImportedSummariesForModule( 740 ModuleIdentifier, ModuleToDefinedGVSummaries, 741 ImportLists[ModuleIdentifier], ModuleToSummariesForIndex); 742 } 743 744 /** 745 * Emit the list of files needed for importing into module. 746 */ 747 void ThinLTOCodeGenerator::emitImports(Module &TheModule, StringRef OutputName, 748 ModuleSummaryIndex &Index, 749 const lto::InputFile &File) { 750 auto ModuleCount = Index.modulePaths().size(); 751 auto ModuleIdentifier = TheModule.getModuleIdentifier(); 752 753 // Collect for each module the list of function it defines (GUID -> Summary). 754 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount); 755 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries); 756 757 // Convert the preserved symbols set from string to GUID 758 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols( 759 PreservedSymbols, Triple(TheModule.getTargetTriple())); 760 761 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols); 762 763 // Compute "dead" symbols, we don't want to import/export these! 764 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols); 765 766 // Generate import/export list 767 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount); 768 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount); 769 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists, 770 ExportLists); 771 772 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex; 773 llvm::gatherImportedSummariesForModule( 774 ModuleIdentifier, ModuleToDefinedGVSummaries, 775 ImportLists[ModuleIdentifier], ModuleToSummariesForIndex); 776 777 std::error_code EC; 778 if ((EC = EmitImportsFiles(ModuleIdentifier, OutputName, 779 ModuleToSummariesForIndex))) 780 report_fatal_error(Twine("Failed to open ") + OutputName + 781 " to save imports lists\n"); 782 } 783 784 /** 785 * Perform internalization. Runs promote and internalization together. 786 * Index is updated to reflect linkage changes. 787 */ 788 void ThinLTOCodeGenerator::internalize(Module &TheModule, 789 ModuleSummaryIndex &Index, 790 const lto::InputFile &File) { 791 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple())); 792 auto ModuleCount = Index.modulePaths().size(); 793 auto ModuleIdentifier = TheModule.getModuleIdentifier(); 794 795 // Convert the preserved symbols set from string to GUID 796 auto GUIDPreservedSymbols = 797 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple); 798 799 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols); 800 801 // Collect for each module the list of function it defines (GUID -> Summary). 802 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount); 803 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries); 804 805 // Compute "dead" symbols, we don't want to import/export these! 806 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols); 807 808 // Generate import/export list 809 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount); 810 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount); 811 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists, 812 ExportLists); 813 auto &ExportList = ExportLists[ModuleIdentifier]; 814 815 // Be friendly and don't nuke totally the module when the client didn't 816 // supply anything to preserve. 817 if (ExportList.empty() && GUIDPreservedSymbols.empty()) 818 return; 819 820 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy; 821 computePrevailingCopies(Index, PrevailingCopy); 822 823 // Resolve prevailing symbols 824 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR; 825 resolvePrevailingInIndex(Index, ResolvedODR, GUIDPreservedSymbols, 826 PrevailingCopy); 827 828 // Promote the exported values in the index, so that they are promoted 829 // in the module. 830 thinLTOInternalizeAndPromoteInIndex( 831 Index, IsExported(ExportLists, GUIDPreservedSymbols), 832 IsPrevailing(PrevailingCopy)); 833 834 promoteModule(TheModule, Index); 835 836 // Internalization 837 thinLTOResolvePrevailingInModule( 838 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]); 839 840 thinLTOInternalizeModule(TheModule, 841 ModuleToDefinedGVSummaries[ModuleIdentifier]); 842 } 843 844 /** 845 * Perform post-importing ThinLTO optimizations. 846 */ 847 void ThinLTOCodeGenerator::optimize(Module &TheModule) { 848 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple())); 849 850 // Optimize now 851 optimizeModule(TheModule, *TMBuilder.create(), OptLevel, Freestanding, 852 nullptr); 853 } 854 855 /// Write out the generated object file, either from CacheEntryPath or from 856 /// OutputBuffer, preferring hard-link when possible. 857 /// Returns the path to the generated file in SavedObjectsDirectoryPath. 858 std::string 859 ThinLTOCodeGenerator::writeGeneratedObject(int count, StringRef CacheEntryPath, 860 const MemoryBuffer &OutputBuffer) { 861 auto ArchName = TMBuilder.TheTriple.getArchName(); 862 SmallString<128> OutputPath(SavedObjectsDirectoryPath); 863 llvm::sys::path::append(OutputPath, 864 Twine(count) + "." + ArchName + ".thinlto.o"); 865 OutputPath.c_str(); // Ensure the string is null terminated. 866 if (sys::fs::exists(OutputPath)) 867 sys::fs::remove(OutputPath); 868 869 // We don't return a memory buffer to the linker, just a list of files. 870 if (!CacheEntryPath.empty()) { 871 // Cache is enabled, hard-link the entry (or copy if hard-link fails). 872 auto Err = sys::fs::create_hard_link(CacheEntryPath, OutputPath); 873 if (!Err) 874 return OutputPath.str(); 875 // Hard linking failed, try to copy. 876 Err = sys::fs::copy_file(CacheEntryPath, OutputPath); 877 if (!Err) 878 return OutputPath.str(); 879 // Copy failed (could be because the CacheEntry was removed from the cache 880 // in the meantime by another process), fall back and try to write down the 881 // buffer to the output. 882 errs() << "error: can't link or copy from cached entry '" << CacheEntryPath 883 << "' to '" << OutputPath << "'\n"; 884 } 885 // No cache entry, just write out the buffer. 886 std::error_code Err; 887 raw_fd_ostream OS(OutputPath, Err, sys::fs::OF_None); 888 if (Err) 889 report_fatal_error("Can't open output '" + OutputPath + "'\n"); 890 OS << OutputBuffer.getBuffer(); 891 return OutputPath.str(); 892 } 893 894 // Main entry point for the ThinLTO processing 895 void ThinLTOCodeGenerator::run() { 896 // Prepare the resulting object vector 897 assert(ProducedBinaries.empty() && "The generator should not be reused"); 898 if (SavedObjectsDirectoryPath.empty()) 899 ProducedBinaries.resize(Modules.size()); 900 else { 901 sys::fs::create_directories(SavedObjectsDirectoryPath); 902 bool IsDir; 903 sys::fs::is_directory(SavedObjectsDirectoryPath, IsDir); 904 if (!IsDir) 905 report_fatal_error("Unexistent dir: '" + SavedObjectsDirectoryPath + "'"); 906 ProducedBinaryFiles.resize(Modules.size()); 907 } 908 909 if (CodeGenOnly) { 910 // Perform only parallel codegen and return. 911 ThreadPool Pool; 912 int count = 0; 913 for (auto &Mod : Modules) { 914 Pool.async([&](int count) { 915 LLVMContext Context; 916 Context.setDiscardValueNames(LTODiscardValueNames); 917 918 // Parse module now 919 auto TheModule = loadModuleFromInput(Mod.get(), Context, false, 920 /*IsImporting*/ false); 921 922 // CodeGen 923 auto OutputBuffer = codegenModule(*TheModule, *TMBuilder.create()); 924 if (SavedObjectsDirectoryPath.empty()) 925 ProducedBinaries[count] = std::move(OutputBuffer); 926 else 927 ProducedBinaryFiles[count] = 928 writeGeneratedObject(count, "", *OutputBuffer); 929 }, count++); 930 } 931 932 return; 933 } 934 935 // Sequential linking phase 936 auto Index = linkCombinedIndex(); 937 938 // Save temps: index. 939 if (!SaveTempsDir.empty()) { 940 auto SaveTempPath = SaveTempsDir + "index.bc"; 941 std::error_code EC; 942 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::OF_None); 943 if (EC) 944 report_fatal_error(Twine("Failed to open ") + SaveTempPath + 945 " to save optimized bitcode\n"); 946 WriteIndexToFile(*Index, OS); 947 } 948 949 950 // Prepare the module map. 951 auto ModuleMap = generateModuleMap(Modules); 952 auto ModuleCount = Modules.size(); 953 954 // Collect for each module the list of function it defines (GUID -> Summary). 955 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount); 956 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries); 957 958 // Convert the preserved symbols set from string to GUID, this is needed for 959 // computing the caching hash and the internalization. 960 auto GUIDPreservedSymbols = 961 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple); 962 963 // Add used symbol from inputs to the preserved symbols. 964 for (const auto &M : Modules) 965 addUsedSymbolToPreservedGUID(*M, GUIDPreservedSymbols); 966 967 // Compute "dead" symbols, we don't want to import/export these! 968 computeDeadSymbolsInIndex(*Index, GUIDPreservedSymbols); 969 970 // Synthesize entry counts for functions in the combined index. 971 computeSyntheticCounts(*Index); 972 973 // Perform index-based WPD. This will return immediately if there are 974 // no index entries in the typeIdMetadata map (e.g. if we are instead 975 // performing IR-based WPD in hybrid regular/thin LTO mode). 976 std::map<ValueInfo, std::vector<VTableSlotSummary>> LocalWPDTargetsMap; 977 std::set<GlobalValue::GUID> ExportedGUIDs; 978 runWholeProgramDevirtOnIndex(*Index, ExportedGUIDs, LocalWPDTargetsMap); 979 for (auto GUID : ExportedGUIDs) 980 GUIDPreservedSymbols.insert(GUID); 981 982 // Collect the import/export lists for all modules from the call-graph in the 983 // combined index. 984 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount); 985 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount); 986 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists, 987 ExportLists); 988 989 // We use a std::map here to be able to have a defined ordering when 990 // producing a hash for the cache entry. 991 // FIXME: we should be able to compute the caching hash for the entry based 992 // on the index, and nuke this map. 993 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR; 994 995 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy; 996 computePrevailingCopies(*Index, PrevailingCopy); 997 998 // Resolve prevailing symbols, this has to be computed early because it 999 // impacts the caching. 1000 resolvePrevailingInIndex(*Index, ResolvedODR, GUIDPreservedSymbols, 1001 PrevailingCopy); 1002 1003 // Use global summary-based analysis to identify symbols that can be 1004 // internalized (because they aren't exported or preserved as per callback). 1005 // Changes are made in the index, consumed in the ThinLTO backends. 1006 updateIndexWPDForExports(*Index, 1007 IsExported(ExportLists, GUIDPreservedSymbols), 1008 LocalWPDTargetsMap); 1009 thinLTOInternalizeAndPromoteInIndex( 1010 *Index, IsExported(ExportLists, GUIDPreservedSymbols), 1011 IsPrevailing(PrevailingCopy)); 1012 1013 // Make sure that every module has an entry in the ExportLists, ImportList, 1014 // GVSummary and ResolvedODR maps to enable threaded access to these maps 1015 // below. 1016 for (auto &Module : Modules) { 1017 auto ModuleIdentifier = Module->getName(); 1018 ExportLists[ModuleIdentifier]; 1019 ImportLists[ModuleIdentifier]; 1020 ResolvedODR[ModuleIdentifier]; 1021 ModuleToDefinedGVSummaries[ModuleIdentifier]; 1022 } 1023 1024 // Compute the ordering we will process the inputs: the rough heuristic here 1025 // is to sort them per size so that the largest module get schedule as soon as 1026 // possible. This is purely a compile-time optimization. 1027 std::vector<int> ModulesOrdering; 1028 ModulesOrdering.resize(Modules.size()); 1029 std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0); 1030 llvm::sort(ModulesOrdering, [&](int LeftIndex, int RightIndex) { 1031 auto LSize = 1032 Modules[LeftIndex]->getSingleBitcodeModule().getBuffer().size(); 1033 auto RSize = 1034 Modules[RightIndex]->getSingleBitcodeModule().getBuffer().size(); 1035 return LSize > RSize; 1036 }); 1037 1038 // Parallel optimizer + codegen 1039 { 1040 ThreadPool Pool(ThreadCount); 1041 for (auto IndexCount : ModulesOrdering) { 1042 auto &Mod = Modules[IndexCount]; 1043 Pool.async([&](int count) { 1044 auto ModuleIdentifier = Mod->getName(); 1045 auto &ExportList = ExportLists[ModuleIdentifier]; 1046 1047 auto &DefinedGVSummaries = ModuleToDefinedGVSummaries[ModuleIdentifier]; 1048 1049 // The module may be cached, this helps handling it. 1050 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier, 1051 ImportLists[ModuleIdentifier], ExportList, 1052 ResolvedODR[ModuleIdentifier], 1053 DefinedGVSummaries, OptLevel, Freestanding, 1054 TMBuilder); 1055 auto CacheEntryPath = CacheEntry.getEntryPath(); 1056 1057 { 1058 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer(); 1059 LLVM_DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss") 1060 << " '" << CacheEntryPath << "' for buffer " 1061 << count << " " << ModuleIdentifier << "\n"); 1062 1063 if (ErrOrBuffer) { 1064 // Cache Hit! 1065 if (SavedObjectsDirectoryPath.empty()) 1066 ProducedBinaries[count] = std::move(ErrOrBuffer.get()); 1067 else 1068 ProducedBinaryFiles[count] = writeGeneratedObject( 1069 count, CacheEntryPath, *ErrOrBuffer.get()); 1070 return; 1071 } 1072 } 1073 1074 LLVMContext Context; 1075 Context.setDiscardValueNames(LTODiscardValueNames); 1076 Context.enableDebugTypeODRUniquing(); 1077 auto DiagFileOrErr = lto::setupOptimizationRemarks( 1078 Context, RemarksFilename, RemarksPasses, RemarksFormat, 1079 RemarksWithHotness, count); 1080 if (!DiagFileOrErr) { 1081 errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n"; 1082 report_fatal_error("ThinLTO: Can't get an output file for the " 1083 "remarks"); 1084 } 1085 1086 // Parse module now 1087 auto TheModule = loadModuleFromInput(Mod.get(), Context, false, 1088 /*IsImporting*/ false); 1089 1090 // Save temps: original file. 1091 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc"); 1092 1093 auto &ImportList = ImportLists[ModuleIdentifier]; 1094 // Run the main process now, and generates a binary 1095 auto OutputBuffer = ProcessThinLTOModule( 1096 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList, 1097 ExportList, GUIDPreservedSymbols, 1098 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions, 1099 DisableCodeGen, SaveTempsDir, Freestanding, OptLevel, count); 1100 1101 // Commit to the cache (if enabled) 1102 CacheEntry.write(*OutputBuffer); 1103 1104 if (SavedObjectsDirectoryPath.empty()) { 1105 // We need to generated a memory buffer for the linker. 1106 if (!CacheEntryPath.empty()) { 1107 // When cache is enabled, reload from the cache if possible. 1108 // Releasing the buffer from the heap and reloading it from the 1109 // cache file with mmap helps us to lower memory pressure. 1110 // The freed memory can be used for the next input file. 1111 // The final binary link will read from the VFS cache (hopefully!) 1112 // or from disk (if the memory pressure was too high). 1113 auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer(); 1114 if (auto EC = ReloadedBufferOrErr.getError()) { 1115 // On error, keep the preexisting buffer and print a diagnostic. 1116 errs() << "error: can't reload cached file '" << CacheEntryPath 1117 << "': " << EC.message() << "\n"; 1118 } else { 1119 OutputBuffer = std::move(*ReloadedBufferOrErr); 1120 } 1121 } 1122 ProducedBinaries[count] = std::move(OutputBuffer); 1123 return; 1124 } 1125 ProducedBinaryFiles[count] = writeGeneratedObject( 1126 count, CacheEntryPath, *OutputBuffer); 1127 }, IndexCount); 1128 } 1129 } 1130 1131 pruneCache(CacheOptions.Path, CacheOptions.Policy); 1132 1133 // If statistics were requested, print them out now. 1134 if (llvm::AreStatisticsEnabled()) 1135 llvm::PrintStatistics(); 1136 reportAndResetTimings(); 1137 } 1138