1 //===-ThinLTOCodeGenerator.cpp - LLVM Link Time Optimizer -----------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the Thin Link Time Optimization library. This library is 11 // intended to be used by linker to optimize code at link time. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/LTO/legacy/ThinLTOCodeGenerator.h" 16 17 #ifdef HAVE_LLVM_REVISION 18 #include "LLVMLTORevision.h" 19 #endif 20 21 #include "llvm/ADT/Statistic.h" 22 #include "llvm/ADT/StringExtras.h" 23 #include "llvm/Analysis/ModuleSummaryAnalysis.h" 24 #include "llvm/Analysis/ProfileSummaryInfo.h" 25 #include "llvm/Analysis/TargetLibraryInfo.h" 26 #include "llvm/Analysis/TargetTransformInfo.h" 27 #include "llvm/Bitcode/BitcodeReader.h" 28 #include "llvm/Bitcode/BitcodeWriter.h" 29 #include "llvm/Bitcode/BitcodeWriterPass.h" 30 #include "llvm/ExecutionEngine/ObjectMemoryBuffer.h" 31 #include "llvm/IR/DiagnosticPrinter.h" 32 #include "llvm/IR/LLVMContext.h" 33 #include "llvm/IR/LegacyPassManager.h" 34 #include "llvm/IR/Mangler.h" 35 #include "llvm/IRReader/IRReader.h" 36 #include "llvm/LTO/LTO.h" 37 #include "llvm/Linker/Linker.h" 38 #include "llvm/MC/SubtargetFeature.h" 39 #include "llvm/Object/IRObjectFile.h" 40 #include "llvm/Object/ModuleSummaryIndexObjectFile.h" 41 #include "llvm/Support/CachePruning.h" 42 #include "llvm/Support/Debug.h" 43 #include "llvm/Support/Error.h" 44 #include "llvm/Support/Path.h" 45 #include "llvm/Support/SHA1.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/Target/TargetMachine.h" 51 #include "llvm/Transforms/IPO.h" 52 #include "llvm/Transforms/IPO/FunctionImport.h" 53 #include "llvm/Transforms/IPO/Internalize.h" 54 #include "llvm/Transforms/IPO/PassManagerBuilder.h" 55 #include "llvm/Transforms/ObjCARC.h" 56 #include "llvm/Transforms/Utils/FunctionImportUtils.h" 57 58 #include <numeric> 59 60 using namespace llvm; 61 62 #define DEBUG_TYPE "thinlto" 63 64 namespace llvm { 65 // Flags -discard-value-names, defined in LTOCodeGenerator.cpp 66 extern cl::opt<bool> LTODiscardValueNames; 67 extern cl::opt<std::string> LTORemarksFilename; 68 extern cl::opt<bool> LTOPassRemarksWithHotness; 69 } 70 71 namespace { 72 73 static cl::opt<int> 74 ThreadCount("threads", cl::init(llvm::heavyweight_hardware_concurrency())); 75 76 // Simple helper to save temporary files for debug. 77 static void saveTempBitcode(const Module &TheModule, StringRef TempDir, 78 unsigned count, StringRef Suffix) { 79 if (TempDir.empty()) 80 return; 81 // User asked to save temps, let dump the bitcode file after import. 82 std::string SaveTempPath = (TempDir + llvm::utostr(count) + Suffix).str(); 83 std::error_code EC; 84 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None); 85 if (EC) 86 report_fatal_error(Twine("Failed to open ") + SaveTempPath + 87 " to save optimized bitcode\n"); 88 WriteBitcodeToFile(&TheModule, OS, /* ShouldPreserveUseListOrder */ true); 89 } 90 91 static const GlobalValueSummary * 92 getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) { 93 // If there is any strong definition anywhere, get it. 94 auto StrongDefForLinker = llvm::find_if( 95 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) { 96 auto Linkage = Summary->linkage(); 97 return !GlobalValue::isAvailableExternallyLinkage(Linkage) && 98 !GlobalValue::isWeakForLinker(Linkage); 99 }); 100 if (StrongDefForLinker != GVSummaryList.end()) 101 return StrongDefForLinker->get(); 102 // Get the first *linker visible* definition for this global in the summary 103 // list. 104 auto FirstDefForLinker = llvm::find_if( 105 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) { 106 auto Linkage = Summary->linkage(); 107 return !GlobalValue::isAvailableExternallyLinkage(Linkage); 108 }); 109 // Extern templates can be emitted as available_externally. 110 if (FirstDefForLinker == GVSummaryList.end()) 111 return nullptr; 112 return FirstDefForLinker->get(); 113 } 114 115 // Populate map of GUID to the prevailing copy for any multiply defined 116 // symbols. Currently assume first copy is prevailing, or any strong 117 // definition. Can be refined with Linker information in the future. 118 static void computePrevailingCopies( 119 const ModuleSummaryIndex &Index, 120 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy) { 121 auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) { 122 return GVSummaryList.size() > 1; 123 }; 124 125 for (auto &I : Index) { 126 if (HasMultipleCopies(I.second)) 127 PrevailingCopy[I.first] = getFirstDefinitionForLinker(I.second); 128 } 129 } 130 131 static StringMap<MemoryBufferRef> 132 generateModuleMap(const std::vector<MemoryBufferRef> &Modules) { 133 StringMap<MemoryBufferRef> ModuleMap; 134 for (auto &ModuleBuffer : Modules) { 135 assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) == 136 ModuleMap.end() && 137 "Expect unique Buffer Identifier"); 138 ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer; 139 } 140 return ModuleMap; 141 } 142 143 static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) { 144 if (renameModuleForThinLTO(TheModule, Index)) 145 report_fatal_error("renameModuleForThinLTO failed"); 146 } 147 148 static std::unique_ptr<Module> 149 loadModuleFromBuffer(const MemoryBufferRef &Buffer, LLVMContext &Context, 150 bool Lazy, bool IsImporting) { 151 SMDiagnostic Err; 152 Expected<std::unique_ptr<Module>> ModuleOrErr = 153 Lazy 154 ? getLazyBitcodeModule(Buffer, Context, 155 /* ShouldLazyLoadMetadata */ true, IsImporting) 156 : parseBitcodeFile(Buffer, Context); 157 if (!ModuleOrErr) { 158 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) { 159 SMDiagnostic Err = SMDiagnostic(Buffer.getBufferIdentifier(), 160 SourceMgr::DK_Error, EIB.message()); 161 Err.print("ThinLTO", errs()); 162 }); 163 report_fatal_error("Can't load module, abort."); 164 } 165 return std::move(ModuleOrErr.get()); 166 } 167 168 static void 169 crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index, 170 StringMap<MemoryBufferRef> &ModuleMap, 171 const FunctionImporter::ImportMapTy &ImportList) { 172 auto Loader = [&](StringRef Identifier) { 173 return loadModuleFromBuffer(ModuleMap[Identifier], TheModule.getContext(), 174 /*Lazy=*/true, /*IsImporting*/ true); 175 }; 176 177 FunctionImporter Importer(Index, Loader); 178 Expected<bool> Result = Importer.importFunctions(TheModule, ImportList); 179 if (!Result) { 180 handleAllErrors(Result.takeError(), [&](ErrorInfoBase &EIB) { 181 SMDiagnostic Err = SMDiagnostic(TheModule.getModuleIdentifier(), 182 SourceMgr::DK_Error, EIB.message()); 183 Err.print("ThinLTO", errs()); 184 }); 185 report_fatal_error("importFunctions failed"); 186 } 187 } 188 189 static void optimizeModule(Module &TheModule, TargetMachine &TM, 190 unsigned OptLevel) { 191 // Populate the PassManager 192 PassManagerBuilder PMB; 193 PMB.LibraryInfo = new TargetLibraryInfoImpl(TM.getTargetTriple()); 194 PMB.Inliner = createFunctionInliningPass(); 195 // FIXME: should get it from the bitcode? 196 PMB.OptLevel = OptLevel; 197 PMB.LoopVectorize = true; 198 PMB.SLPVectorize = true; 199 PMB.VerifyInput = true; 200 PMB.VerifyOutput = false; 201 202 legacy::PassManager PM; 203 204 // Add the TTI (required to inform the vectorizer about register size for 205 // instance) 206 PM.add(createTargetTransformInfoWrapperPass(TM.getTargetIRAnalysis())); 207 208 // Add optimizations 209 PMB.populateThinLTOPassManager(PM); 210 211 PM.run(TheModule); 212 } 213 214 // Convert the PreservedSymbols map from "Name" based to "GUID" based. 215 static DenseSet<GlobalValue::GUID> 216 computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols, 217 const Triple &TheTriple) { 218 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size()); 219 for (auto &Entry : PreservedSymbols) { 220 StringRef Name = Entry.first(); 221 if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_') 222 Name = Name.drop_front(); 223 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name)); 224 } 225 return GUIDPreservedSymbols; 226 } 227 228 std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule, 229 TargetMachine &TM) { 230 SmallVector<char, 128> OutputBuffer; 231 232 // CodeGen 233 { 234 raw_svector_ostream OS(OutputBuffer); 235 legacy::PassManager PM; 236 237 // If the bitcode files contain ARC code and were compiled with optimization, 238 // the ObjCARCContractPass must be run, so do it unconditionally here. 239 PM.add(createObjCARCContractPass()); 240 241 // Setup the codegen now. 242 if (TM.addPassesToEmitFile(PM, OS, TargetMachine::CGFT_ObjectFile, 243 /* DisableVerify */ true)) 244 report_fatal_error("Failed to setup codegen"); 245 246 // Run codegen now. resulting binary is in OutputBuffer. 247 PM.run(TheModule); 248 } 249 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer)); 250 } 251 252 /// Manage caching for a single Module. 253 class ModuleCacheEntry { 254 SmallString<128> EntryPath; 255 256 public: 257 // Create a cache entry. This compute a unique hash for the Module considering 258 // the current list of export/import, and offer an interface to query to 259 // access the content in the cache. 260 ModuleCacheEntry( 261 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID, 262 const FunctionImporter::ImportMapTy &ImportList, 263 const FunctionImporter::ExportSetTy &ExportList, 264 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR, 265 const GVSummaryMapTy &DefinedFunctions, 266 const DenseSet<GlobalValue::GUID> &PreservedSymbols, unsigned OptLevel, 267 const TargetMachineBuilder &TMBuilder) { 268 if (CachePath.empty()) 269 return; 270 271 if (!Index.modulePaths().count(ModuleID)) 272 // The module does not have an entry, it can't have a hash at all 273 return; 274 275 // Compute the unique hash for this entry 276 // This is based on the current compiler version, the module itself, the 277 // export list, the hash for every single module in the import list, the 278 // list of ResolvedODR for the module, and the list of preserved symbols. 279 280 // Include the hash for the current module 281 auto ModHash = Index.getModuleHash(ModuleID); 282 283 if (all_of(ModHash, [](uint32_t V) { return V == 0; })) 284 // No hash entry, no caching! 285 return; 286 287 SHA1 Hasher; 288 289 // Include the parts of the LTO configuration that affect code generation. 290 auto AddString = [&](StringRef Str) { 291 Hasher.update(Str); 292 Hasher.update(ArrayRef<uint8_t>{0}); 293 }; 294 auto AddUnsigned = [&](unsigned I) { 295 uint8_t Data[4]; 296 Data[0] = I; 297 Data[1] = I >> 8; 298 Data[2] = I >> 16; 299 Data[3] = I >> 24; 300 Hasher.update(ArrayRef<uint8_t>{Data, 4}); 301 }; 302 303 // Start with the compiler revision 304 Hasher.update(LLVM_VERSION_STRING); 305 #ifdef HAVE_LLVM_REVISION 306 Hasher.update(LLVM_REVISION); 307 #endif 308 309 // Hash the optimization level and the target machine settings. 310 AddString(TMBuilder.MCpu); 311 // FIXME: Hash more of Options. For now all clients initialize Options from 312 // command-line flags (which is unsupported in production), but may set 313 // RelaxELFRelocations. The clang driver can also pass FunctionSections, 314 // DataSections and DebuggerTuning via command line flags. 315 AddUnsigned(TMBuilder.Options.RelaxELFRelocations); 316 AddUnsigned(TMBuilder.Options.FunctionSections); 317 AddUnsigned(TMBuilder.Options.DataSections); 318 AddUnsigned((unsigned)TMBuilder.Options.DebuggerTuning); 319 AddString(TMBuilder.MAttr); 320 if (TMBuilder.RelocModel) 321 AddUnsigned(*TMBuilder.RelocModel); 322 AddUnsigned(TMBuilder.CGOptLevel); 323 AddUnsigned(OptLevel); 324 325 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash))); 326 for (auto F : ExportList) 327 // The export list can impact the internalization, be conservative here 328 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F))); 329 330 // Include the hash for every module we import functions from 331 for (auto &Entry : ImportList) { 332 auto ModHash = Index.getModuleHash(Entry.first()); 333 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash))); 334 } 335 336 // Include the hash for the resolved ODR. 337 for (auto &Entry : ResolvedODR) { 338 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first, 339 sizeof(GlobalValue::GUID))); 340 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second, 341 sizeof(GlobalValue::LinkageTypes))); 342 } 343 344 // Include the hash for the preserved symbols. 345 for (auto &Entry : PreservedSymbols) { 346 if (DefinedFunctions.count(Entry)) 347 Hasher.update( 348 ArrayRef<uint8_t>((const uint8_t *)&Entry, sizeof(GlobalValue::GUID))); 349 } 350 351 sys::path::append(EntryPath, CachePath, toHex(Hasher.result())); 352 } 353 354 // Access the path to this entry in the cache. 355 StringRef getEntryPath() { return EntryPath; } 356 357 // Try loading the buffer for this cache entry. 358 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() { 359 if (EntryPath.empty()) 360 return std::error_code(); 361 return MemoryBuffer::getFile(EntryPath); 362 } 363 364 // Cache the Produced object file 365 void write(const MemoryBuffer &OutputBuffer) { 366 if (EntryPath.empty()) 367 return; 368 369 // Write to a temporary to avoid race condition 370 SmallString<128> TempFilename; 371 int TempFD; 372 std::error_code EC = 373 sys::fs::createTemporaryFile("Thin", "tmp.o", TempFD, TempFilename); 374 if (EC) { 375 errs() << "Error: " << EC.message() << "\n"; 376 report_fatal_error("ThinLTO: Can't get a temporary file"); 377 } 378 { 379 raw_fd_ostream OS(TempFD, /* ShouldClose */ true); 380 OS << OutputBuffer.getBuffer(); 381 } 382 // Rename to final destination (hopefully race condition won't matter here) 383 EC = sys::fs::rename(TempFilename, EntryPath); 384 if (EC) { 385 sys::fs::remove(TempFilename); 386 raw_fd_ostream OS(EntryPath, EC, sys::fs::F_None); 387 if (EC) 388 report_fatal_error(Twine("Failed to open ") + EntryPath + 389 " to save cached entry\n"); 390 OS << OutputBuffer.getBuffer(); 391 } 392 } 393 }; 394 395 static std::unique_ptr<MemoryBuffer> 396 ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index, 397 StringMap<MemoryBufferRef> &ModuleMap, TargetMachine &TM, 398 const FunctionImporter::ImportMapTy &ImportList, 399 const FunctionImporter::ExportSetTy &ExportList, 400 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols, 401 const GVSummaryMapTy &DefinedGlobals, 402 const ThinLTOCodeGenerator::CachingOptions &CacheOptions, 403 bool DisableCodeGen, StringRef SaveTempsDir, 404 unsigned OptLevel, unsigned count) { 405 406 // "Benchmark"-like optimization: single-source case 407 bool SingleModule = (ModuleMap.size() == 1); 408 409 if (!SingleModule) { 410 promoteModule(TheModule, Index); 411 412 // Apply summary-based LinkOnce/Weak resolution decisions. 413 thinLTOResolveWeakForLinkerModule(TheModule, DefinedGlobals); 414 415 // Save temps: after promotion. 416 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc"); 417 } 418 419 // Be friendly and don't nuke totally the module when the client didn't 420 // supply anything to preserve. 421 if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) { 422 // Apply summary-based internalization decisions. 423 thinLTOInternalizeModule(TheModule, DefinedGlobals); 424 } 425 426 // Save internalized bitcode 427 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc"); 428 429 if (!SingleModule) { 430 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList); 431 432 // Save temps: after cross-module import. 433 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc"); 434 } 435 436 optimizeModule(TheModule, TM, OptLevel); 437 438 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc"); 439 440 if (DisableCodeGen) { 441 // Configured to stop before CodeGen, serialize the bitcode and return. 442 SmallVector<char, 128> OutputBuffer; 443 { 444 raw_svector_ostream OS(OutputBuffer); 445 ProfileSummaryInfo PSI(TheModule); 446 auto Index = buildModuleSummaryIndex(TheModule, nullptr, nullptr); 447 WriteBitcodeToFile(&TheModule, OS, true, &Index); 448 } 449 return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer)); 450 } 451 452 return codegenModule(TheModule, TM); 453 } 454 455 /// Resolve LinkOnce/Weak symbols. Record resolutions in the \p ResolvedODR map 456 /// for caching, and in the \p Index for application during the ThinLTO 457 /// backends. This is needed for correctness for exported symbols (ensure 458 /// at least one copy kept) and a compile-time optimization (to drop duplicate 459 /// copies when possible). 460 static void resolveWeakForLinkerInIndex( 461 ModuleSummaryIndex &Index, 462 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> 463 &ResolvedODR) { 464 465 DenseMap<GlobalValue::GUID, const GlobalValueSummary *> PrevailingCopy; 466 computePrevailingCopies(Index, PrevailingCopy); 467 468 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) { 469 const auto &Prevailing = PrevailingCopy.find(GUID); 470 // Not in map means that there was only one copy, which must be prevailing. 471 if (Prevailing == PrevailingCopy.end()) 472 return true; 473 return Prevailing->second == S; 474 }; 475 476 auto recordNewLinkage = [&](StringRef ModuleIdentifier, 477 GlobalValue::GUID GUID, 478 GlobalValue::LinkageTypes NewLinkage) { 479 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage; 480 }; 481 482 thinLTOResolveWeakForLinkerInIndex(Index, isPrevailing, recordNewLinkage); 483 } 484 485 // Initialize the TargetMachine builder for a given Triple 486 static void initTMBuilder(TargetMachineBuilder &TMBuilder, 487 const Triple &TheTriple) { 488 // Set a default CPU for Darwin triples (copied from LTOCodeGenerator). 489 // FIXME this looks pretty terrible... 490 if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) { 491 if (TheTriple.getArch() == llvm::Triple::x86_64) 492 TMBuilder.MCpu = "core2"; 493 else if (TheTriple.getArch() == llvm::Triple::x86) 494 TMBuilder.MCpu = "yonah"; 495 else if (TheTriple.getArch() == llvm::Triple::aarch64) 496 TMBuilder.MCpu = "cyclone"; 497 } 498 TMBuilder.TheTriple = std::move(TheTriple); 499 } 500 501 } // end anonymous namespace 502 503 void ThinLTOCodeGenerator::addModule(StringRef Identifier, StringRef Data) { 504 MemoryBufferRef Buffer(Data, Identifier); 505 if (Modules.empty()) { 506 // First module added, so initialize the triple and some options 507 LLVMContext Context; 508 StringRef TripleStr; 509 ErrorOr<std::string> TripleOrErr = 510 expectedToErrorOrAndEmitErrors(Context, getBitcodeTargetTriple(Buffer)); 511 if (TripleOrErr) 512 TripleStr = *TripleOrErr; 513 Triple TheTriple(TripleStr); 514 initTMBuilder(TMBuilder, Triple(TheTriple)); 515 } 516 #ifndef NDEBUG 517 else { 518 LLVMContext Context; 519 StringRef TripleStr; 520 ErrorOr<std::string> TripleOrErr = 521 expectedToErrorOrAndEmitErrors(Context, getBitcodeTargetTriple(Buffer)); 522 if (TripleOrErr) 523 TripleStr = *TripleOrErr; 524 assert(TMBuilder.TheTriple.str() == TripleStr && 525 "ThinLTO modules with different triple not supported"); 526 } 527 #endif 528 Modules.push_back(Buffer); 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>(TheTarget->createTargetMachine( 557 TheTriple.str(), MCpu, FeatureStr, Options, RelocModel, 558 CodeModel::Default, 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 uint64_t NextModuleId = 0; 568 for (auto &ModuleBuffer : Modules) { 569 Expected<std::unique_ptr<object::ModuleSummaryIndexObjectFile>> ObjOrErr = 570 object::ModuleSummaryIndexObjectFile::create(ModuleBuffer); 571 if (!ObjOrErr) { 572 // FIXME diagnose 573 logAllUnhandledErrors( 574 ObjOrErr.takeError(), errs(), 575 "error: can't create ModuleSummaryIndexObjectFile for buffer: "); 576 return nullptr; 577 } 578 auto Index = (*ObjOrErr)->takeIndex(); 579 if (CombinedIndex) { 580 CombinedIndex->mergeFrom(std::move(Index), ++NextModuleId); 581 } else { 582 CombinedIndex = std::move(Index); 583 } 584 } 585 return CombinedIndex; 586 } 587 588 /** 589 * Perform promotion and renaming of exported internal functions. 590 * Index is updated to reflect linkage changes from weak resolution. 591 */ 592 void ThinLTOCodeGenerator::promote(Module &TheModule, 593 ModuleSummaryIndex &Index) { 594 auto ModuleCount = Index.modulePaths().size(); 595 auto ModuleIdentifier = TheModule.getModuleIdentifier(); 596 597 // Collect for each module the list of function it defines (GUID -> Summary). 598 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries; 599 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries); 600 601 // Convert the preserved symbols set from string to GUID 602 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols( 603 PreservedSymbols, Triple(TheModule.getTargetTriple())); 604 605 // Compute "dead" symbols, we don't want to import/export these! 606 auto DeadSymbols = computeDeadSymbols(Index, GUIDPreservedSymbols); 607 608 // Generate import/export list 609 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount); 610 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount); 611 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists, 612 ExportLists, &DeadSymbols); 613 614 // Resolve LinkOnce/Weak symbols. 615 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR; 616 resolveWeakForLinkerInIndex(Index, ResolvedODR); 617 618 thinLTOResolveWeakForLinkerModule( 619 TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]); 620 621 // Promote the exported values in the index, so that they are promoted 622 // in the module. 623 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) { 624 const auto &ExportList = ExportLists.find(ModuleIdentifier); 625 return (ExportList != ExportLists.end() && 626 ExportList->second.count(GUID)) || 627 GUIDPreservedSymbols.count(GUID); 628 }; 629 thinLTOInternalizeAndPromoteInIndex(Index, isExported); 630 631 promoteModule(TheModule, Index); 632 } 633 634 /** 635 * Perform cross-module importing for the module identified by ModuleIdentifier. 636 */ 637 void ThinLTOCodeGenerator::crossModuleImport(Module &TheModule, 638 ModuleSummaryIndex &Index) { 639 auto ModuleMap = generateModuleMap(Modules); 640 auto ModuleCount = Index.modulePaths().size(); 641 642 // Collect for each module the list of function it defines (GUID -> Summary). 643 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount); 644 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries); 645 646 // Convert the preserved symbols set from string to GUID 647 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols( 648 PreservedSymbols, Triple(TheModule.getTargetTriple())); 649 650 // Compute "dead" symbols, we don't want to import/export these! 651 auto DeadSymbols = computeDeadSymbols(Index, GUIDPreservedSymbols); 652 653 // Generate import/export list 654 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount); 655 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount); 656 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists, 657 ExportLists, &DeadSymbols); 658 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()]; 659 660 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList); 661 } 662 663 /** 664 * Compute the list of summaries needed for importing into module. 665 */ 666 void ThinLTOCodeGenerator::gatherImportedSummariesForModule( 667 StringRef ModulePath, ModuleSummaryIndex &Index, 668 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) { 669 auto ModuleCount = Index.modulePaths().size(); 670 671 // Collect for each module the list of function it defines (GUID -> Summary). 672 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount); 673 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries); 674 675 // Generate import/export list 676 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount); 677 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount); 678 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists, 679 ExportLists); 680 681 llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries, 682 ImportLists[ModulePath], 683 ModuleToSummariesForIndex); 684 } 685 686 /** 687 * Emit the list of files needed for importing into module. 688 */ 689 void ThinLTOCodeGenerator::emitImports(StringRef ModulePath, 690 StringRef OutputName, 691 ModuleSummaryIndex &Index) { 692 auto ModuleCount = Index.modulePaths().size(); 693 694 // Collect for each module the list of function it defines (GUID -> Summary). 695 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount); 696 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries); 697 698 // Generate import/export list 699 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount); 700 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount); 701 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists, 702 ExportLists); 703 704 std::error_code EC; 705 if ((EC = EmitImportsFiles(ModulePath, OutputName, ImportLists[ModulePath]))) 706 report_fatal_error(Twine("Failed to open ") + OutputName + 707 " to save imports lists\n"); 708 } 709 710 /** 711 * Perform internalization. Index is updated to reflect linkage changes. 712 */ 713 void ThinLTOCodeGenerator::internalize(Module &TheModule, 714 ModuleSummaryIndex &Index) { 715 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple())); 716 auto ModuleCount = Index.modulePaths().size(); 717 auto ModuleIdentifier = TheModule.getModuleIdentifier(); 718 719 // Convert the preserved symbols set from string to GUID 720 auto GUIDPreservedSymbols = 721 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple); 722 723 // Collect for each module the list of function it defines (GUID -> Summary). 724 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount); 725 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries); 726 727 // Compute "dead" symbols, we don't want to import/export these! 728 auto DeadSymbols = computeDeadSymbols(Index, GUIDPreservedSymbols); 729 730 // Generate import/export list 731 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount); 732 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount); 733 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists, 734 ExportLists, &DeadSymbols); 735 auto &ExportList = ExportLists[ModuleIdentifier]; 736 737 // Be friendly and don't nuke totally the module when the client didn't 738 // supply anything to preserve. 739 if (ExportList.empty() && GUIDPreservedSymbols.empty()) 740 return; 741 742 // Internalization 743 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) { 744 const auto &ExportList = ExportLists.find(ModuleIdentifier); 745 return (ExportList != ExportLists.end() && 746 ExportList->second.count(GUID)) || 747 GUIDPreservedSymbols.count(GUID); 748 }; 749 thinLTOInternalizeAndPromoteInIndex(Index, isExported); 750 thinLTOInternalizeModule(TheModule, 751 ModuleToDefinedGVSummaries[ModuleIdentifier]); 752 } 753 754 /** 755 * Perform post-importing ThinLTO optimizations. 756 */ 757 void ThinLTOCodeGenerator::optimize(Module &TheModule) { 758 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple())); 759 760 // Optimize now 761 optimizeModule(TheModule, *TMBuilder.create(), OptLevel); 762 } 763 764 /** 765 * Perform ThinLTO CodeGen. 766 */ 767 std::unique_ptr<MemoryBuffer> ThinLTOCodeGenerator::codegen(Module &TheModule) { 768 initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple())); 769 return codegenModule(TheModule, *TMBuilder.create()); 770 } 771 772 /// Write out the generated object file, either from CacheEntryPath or from 773 /// OutputBuffer, preferring hard-link when possible. 774 /// Returns the path to the generated file in SavedObjectsDirectoryPath. 775 static std::string writeGeneratedObject(int count, StringRef CacheEntryPath, 776 StringRef SavedObjectsDirectoryPath, 777 const MemoryBuffer &OutputBuffer) { 778 SmallString<128> OutputPath(SavedObjectsDirectoryPath); 779 llvm::sys::path::append(OutputPath, Twine(count) + ".thinlto.o"); 780 OutputPath.c_str(); // Ensure the string is null terminated. 781 if (sys::fs::exists(OutputPath)) 782 sys::fs::remove(OutputPath); 783 784 // We don't return a memory buffer to the linker, just a list of files. 785 if (!CacheEntryPath.empty()) { 786 // Cache is enabled, hard-link the entry (or copy if hard-link fails). 787 auto Err = sys::fs::create_hard_link(CacheEntryPath, OutputPath); 788 if (!Err) 789 return OutputPath.str(); 790 // Hard linking failed, try to copy. 791 Err = sys::fs::copy_file(CacheEntryPath, OutputPath); 792 if (!Err) 793 return OutputPath.str(); 794 // Copy failed (could be because the CacheEntry was removed from the cache 795 // in the meantime by another process), fall back and try to write down the 796 // buffer to the output. 797 errs() << "error: can't link or copy from cached entry '" << CacheEntryPath 798 << "' to '" << OutputPath << "'\n"; 799 } 800 // No cache entry, just write out the buffer. 801 std::error_code Err; 802 raw_fd_ostream OS(OutputPath, Err, sys::fs::F_None); 803 if (Err) 804 report_fatal_error("Can't open output '" + OutputPath + "'\n"); 805 OS << OutputBuffer.getBuffer(); 806 return OutputPath.str(); 807 } 808 809 // Main entry point for the ThinLTO processing 810 void ThinLTOCodeGenerator::run() { 811 // Prepare the resulting object vector 812 assert(ProducedBinaries.empty() && "The generator should not be reused"); 813 if (SavedObjectsDirectoryPath.empty()) 814 ProducedBinaries.resize(Modules.size()); 815 else { 816 sys::fs::create_directories(SavedObjectsDirectoryPath); 817 bool IsDir; 818 sys::fs::is_directory(SavedObjectsDirectoryPath, IsDir); 819 if (!IsDir) 820 report_fatal_error("Unexistent dir: '" + SavedObjectsDirectoryPath + "'"); 821 ProducedBinaryFiles.resize(Modules.size()); 822 } 823 824 if (CodeGenOnly) { 825 // Perform only parallel codegen and return. 826 ThreadPool Pool; 827 int count = 0; 828 for (auto &ModuleBuffer : Modules) { 829 Pool.async([&](int count) { 830 LLVMContext Context; 831 Context.setDiscardValueNames(LTODiscardValueNames); 832 833 // Parse module now 834 auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false, 835 /*IsImporting*/ false); 836 837 // CodeGen 838 auto OutputBuffer = codegen(*TheModule); 839 if (SavedObjectsDirectoryPath.empty()) 840 ProducedBinaries[count] = std::move(OutputBuffer); 841 else 842 ProducedBinaryFiles[count] = writeGeneratedObject( 843 count, "", SavedObjectsDirectoryPath, *OutputBuffer); 844 }, count++); 845 } 846 847 return; 848 } 849 850 // Sequential linking phase 851 auto Index = linkCombinedIndex(); 852 853 // Save temps: index. 854 if (!SaveTempsDir.empty()) { 855 auto SaveTempPath = SaveTempsDir + "index.bc"; 856 std::error_code EC; 857 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None); 858 if (EC) 859 report_fatal_error(Twine("Failed to open ") + SaveTempPath + 860 " to save optimized bitcode\n"); 861 WriteIndexToFile(*Index, OS); 862 } 863 864 865 // Prepare the module map. 866 auto ModuleMap = generateModuleMap(Modules); 867 auto ModuleCount = Modules.size(); 868 869 // Collect for each module the list of function it defines (GUID -> Summary). 870 StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount); 871 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries); 872 873 // Convert the preserved symbols set from string to GUID, this is needed for 874 // computing the caching hash and the internalization. 875 auto GUIDPreservedSymbols = 876 computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple); 877 878 // Compute "dead" symbols, we don't want to import/export these! 879 auto DeadSymbols = computeDeadSymbols(*Index, GUIDPreservedSymbols); 880 881 // Collect the import/export lists for all modules from the call-graph in the 882 // combined index. 883 StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount); 884 StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount); 885 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists, 886 ExportLists, &DeadSymbols); 887 888 // We use a std::map here to be able to have a defined ordering when 889 // producing a hash for the cache entry. 890 // FIXME: we should be able to compute the caching hash for the entry based 891 // on the index, and nuke this map. 892 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR; 893 894 // Resolve LinkOnce/Weak symbols, this has to be computed early because it 895 // impacts the caching. 896 resolveWeakForLinkerInIndex(*Index, ResolvedODR); 897 898 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) { 899 const auto &ExportList = ExportLists.find(ModuleIdentifier); 900 return (ExportList != ExportLists.end() && 901 ExportList->second.count(GUID)) || 902 GUIDPreservedSymbols.count(GUID); 903 }; 904 905 // Use global summary-based analysis to identify symbols that can be 906 // internalized (because they aren't exported or preserved as per callback). 907 // Changes are made in the index, consumed in the ThinLTO backends. 908 thinLTOInternalizeAndPromoteInIndex(*Index, isExported); 909 910 // Make sure that every module has an entry in the ExportLists and 911 // ResolvedODR maps to enable threaded access to these maps below. 912 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) { 913 ExportLists[DefinedGVSummaries.first()]; 914 ResolvedODR[DefinedGVSummaries.first()]; 915 } 916 917 // Compute the ordering we will process the inputs: the rough heuristic here 918 // is to sort them per size so that the largest module get schedule as soon as 919 // possible. This is purely a compile-time optimization. 920 std::vector<int> ModulesOrdering; 921 ModulesOrdering.resize(Modules.size()); 922 std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0); 923 std::sort(ModulesOrdering.begin(), ModulesOrdering.end(), 924 [&](int LeftIndex, int RightIndex) { 925 auto LSize = Modules[LeftIndex].getBufferSize(); 926 auto RSize = Modules[RightIndex].getBufferSize(); 927 return LSize > RSize; 928 }); 929 930 // Parallel optimizer + codegen 931 { 932 ThreadPool Pool(ThreadCount); 933 for (auto IndexCount : ModulesOrdering) { 934 auto &ModuleBuffer = Modules[IndexCount]; 935 Pool.async([&](int count) { 936 auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier(); 937 auto &ExportList = ExportLists[ModuleIdentifier]; 938 939 auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier]; 940 941 // The module may be cached, this helps handling it. 942 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier, 943 ImportLists[ModuleIdentifier], ExportList, 944 ResolvedODR[ModuleIdentifier], 945 DefinedFunctions, GUIDPreservedSymbols, 946 OptLevel, TMBuilder); 947 auto CacheEntryPath = CacheEntry.getEntryPath(); 948 949 { 950 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer(); 951 DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss") << " '" 952 << CacheEntryPath << "' for buffer " << count << " " 953 << ModuleIdentifier << "\n"); 954 955 if (ErrOrBuffer) { 956 // Cache Hit! 957 if (SavedObjectsDirectoryPath.empty()) 958 ProducedBinaries[count] = std::move(ErrOrBuffer.get()); 959 else 960 ProducedBinaryFiles[count] = writeGeneratedObject( 961 count, CacheEntryPath, SavedObjectsDirectoryPath, 962 *ErrOrBuffer.get()); 963 return; 964 } 965 } 966 967 LLVMContext Context; 968 Context.setDiscardValueNames(LTODiscardValueNames); 969 Context.enableDebugTypeODRUniquing(); 970 auto DiagFileOrErr = lto::setupOptimizationRemarks( 971 Context, LTORemarksFilename, LTOPassRemarksWithHotness, count); 972 if (!DiagFileOrErr) { 973 errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n"; 974 report_fatal_error("ThinLTO: Can't get an output file for the " 975 "remarks"); 976 } 977 978 // Parse module now 979 auto TheModule = loadModuleFromBuffer(ModuleBuffer, Context, false, 980 /*IsImporting*/ false); 981 982 // Save temps: original file. 983 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc"); 984 985 auto &ImportList = ImportLists[ModuleIdentifier]; 986 // Run the main process now, and generates a binary 987 auto OutputBuffer = ProcessThinLTOModule( 988 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList, 989 ExportList, GUIDPreservedSymbols, 990 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions, 991 DisableCodeGen, SaveTempsDir, OptLevel, count); 992 993 // Commit to the cache (if enabled) 994 CacheEntry.write(*OutputBuffer); 995 996 if (SavedObjectsDirectoryPath.empty()) { 997 // We need to generated a memory buffer for the linker. 998 if (!CacheEntryPath.empty()) { 999 // Cache is enabled, reload from the cache 1000 // We do this to lower memory pressuree: the buffer is on the heap 1001 // and releasing it frees memory that can be used for the next input 1002 // file. The final binary link will read from the VFS cache 1003 // (hopefully!) or from disk if the memory pressure wasn't too high. 1004 auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer(); 1005 if (auto EC = ReloadedBufferOrErr.getError()) { 1006 // On error, keeping the preexisting buffer and printing a 1007 // diagnostic is more friendly than just crashing. 1008 errs() << "error: can't reload cached file '" << CacheEntryPath 1009 << "': " << EC.message() << "\n"; 1010 } else { 1011 OutputBuffer = std::move(*ReloadedBufferOrErr); 1012 } 1013 } 1014 ProducedBinaries[count] = std::move(OutputBuffer); 1015 return; 1016 } 1017 ProducedBinaryFiles[count] = writeGeneratedObject( 1018 count, CacheEntryPath, SavedObjectsDirectoryPath, *OutputBuffer); 1019 }, IndexCount); 1020 } 1021 } 1022 1023 CachePruning(CacheOptions.Path) 1024 .setPruningInterval(std::chrono::seconds(CacheOptions.PruningInterval)) 1025 .setEntryExpiration(std::chrono::seconds(CacheOptions.Expiration)) 1026 .setMaxSize(CacheOptions.MaxPercentageOfAvailableSpace) 1027 .prune(); 1028 1029 // If statistics were requested, print them out now. 1030 if (llvm::AreStatisticsEnabled()) 1031 llvm::PrintStatistics(); 1032 } 1033