LLVM 24.0.0git
ThinLTOCodeGenerator.cpp
Go to the documentation of this file.
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
16
17#include "llvm/ADT/ScopeExit.h"
18#include "llvm/ADT/Statistic.h"
27#include "llvm/Config/llvm-config.h"
28#include "llvm/IR/DebugInfo.h"
30#include "llvm/IR/LLVMContext.h"
33#include "llvm/IR/Mangler.h"
35#include "llvm/IR/Verifier.h"
37#include "llvm/LTO/LTO.h"
44#include "llvm/Support/Debug.h"
45#include "llvm/Support/Error.h"
49#include "llvm/Support/Path.h"
50#include "llvm/Support/SHA1.h"
63
64#if !defined(_MSC_VER) && !defined(__MINGW32__)
65#include <unistd.h>
66#else
67#include <io.h>
68#endif
69
70using namespace llvm;
71using namespace ThinLTOCodeGeneratorImpl;
72
73#define DEBUG_TYPE "thinlto"
74
75namespace llvm {
76// Flags -discard-value-names, defined in LTOCodeGenerator.cpp
87}
88
89// Default to using all available threads in the system, but using only one
90// thred per core, as indicated by the usage of
91// heavyweight_hardware_concurrency() below.
92static cl::opt<int> ThreadCount("threads", cl::init(0));
93
94// Simple helper to save temporary files for debug.
95static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
96 unsigned count, StringRef Suffix) {
97 if (TempDir.empty())
98 return;
99 // User asked to save temps, let dump the bitcode file after import.
100 std::string SaveTempPath = (TempDir + llvm::Twine(count) + Suffix).str();
101 std::error_code EC;
102 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::OF_None);
103 if (EC)
104 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
105 " to save optimized bitcode\n");
106 WriteBitcodeToFile(TheModule, OS, /* ShouldPreserveUseListOrder */ true);
107}
108
110 ArrayRef<std::unique_ptr<GlobalValueSummary>> GVSummaryList) {
111 // If there is any strong definition anywhere, get it.
112 auto StrongDefForLinker = llvm::find_if(
113 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
114 auto Linkage = Summary->linkage();
117 });
118 if (StrongDefForLinker != GVSummaryList.end())
119 return StrongDefForLinker->get();
120 // Get the first *linker visible* definition for this global in the summary
121 // list.
122 auto FirstDefForLinker = llvm::find_if(
123 GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
124 auto Linkage = Summary->linkage();
126 });
127 // Extern templates can be emitted as available_externally.
128 if (FirstDefForLinker == GVSummaryList.end())
129 return nullptr;
130 return FirstDefForLinker->get();
131}
132
133// Populate map of GUID to the prevailing copy for any multiply defined
134// symbols. Currently assume first copy is prevailing, or any strong
135// definition. Can be refined with Linker information in the future.
137 const ModuleSummaryIndex &Index,
139 auto HasMultipleCopies =
141 return GVSummaryList.size() > 1;
142 };
143
144 for (auto &I : Index) {
145 if (HasMultipleCopies(I.second.getSummaryList()))
146 PrevailingCopy[I.first] =
147 getFirstDefinitionForLinker(I.second.getSummaryList());
148 }
149}
150
152generateModuleMap(std::vector<std::unique_ptr<lto::InputFile>> &Modules) {
154 for (auto &M : Modules) {
155 LLVM_DEBUG(dbgs() << "Adding module " << M->getName() << " to ModuleMap\n");
156 assert(!ModuleMap.contains(M->getName()) &&
157 "Expect unique Buffer Identifier");
158 ModuleMap[M->getName()] = M.get();
159 }
160 return ModuleMap;
161}
162
163static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index,
164 bool ClearDSOLocalOnDeclarations) {
165 renameModuleForThinLTO(TheModule, Index, ClearDSOLocalOnDeclarations);
166}
167
168namespace {
169class ThinLTODiagnosticInfo : public DiagnosticInfo {
170 const Twine &Msg;
171public:
172 ThinLTODiagnosticInfo(const Twine &DiagMsg LLVM_LIFETIME_BOUND,
173 DiagnosticSeverity Severity = DS_Error)
174 : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
175 void print(DiagnosticPrinter &DP) const override { DP << Msg; }
176};
177}
178
179/// Verify the module and strip broken debug info.
180static void verifyLoadedModule(Module &TheModule) {
181 bool BrokenDebugInfo = false;
182 if (verifyModule(TheModule, &dbgs(), &BrokenDebugInfo))
183 report_fatal_error("Broken module found, compilation aborted!");
184 if (BrokenDebugInfo) {
185 TheModule.getContext().diagnose(ThinLTODiagnosticInfo(
186 "Invalid debug info found, debug info will be stripped", DS_Warning));
187 StripDebugInfo(TheModule);
188 }
189}
190
191static std::unique_ptr<Module> loadModuleFromInput(lto::InputFile *Input,
192 LLVMContext &Context,
193 bool Lazy,
194 bool IsImporting) {
195 auto &Mod = Input->getSingleBitcodeModule();
197 Lazy ? Mod.getLazyModule(Context,
198 /* ShouldLazyLoadMetadata */ true, IsImporting)
199 : Mod.parseModule(Context);
200 if (!ModuleOrErr) {
201 handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
202 SMDiagnostic Err = SMDiagnostic(Mod.getModuleIdentifier(),
203 SourceMgr::DK_Error, EIB.message());
204 Err.print("ThinLTO", errs());
205 });
206 report_fatal_error("Can't load module, abort.");
207 }
208 if (!Lazy)
209 verifyLoadedModule(*ModuleOrErr.get());
210 return std::move(*ModuleOrErr);
211}
212
213static void
216 const FunctionImporter::ImportMapTy &ImportList,
217 bool ClearDSOLocalOnDeclarations) {
218 auto Loader = [&](StringRef Identifier) {
219 auto &Input = ModuleMap[Identifier];
220 return loadModuleFromInput(Input, TheModule.getContext(),
221 /*Lazy=*/true, /*IsImporting*/ true);
222 };
223
224 FunctionImporter Importer(Index, Loader, ClearDSOLocalOnDeclarations);
225 Expected<bool> Result = Importer.importFunctions(TheModule, ImportList);
226 if (!Result) {
227 handleAllErrors(Result.takeError(), [&](ErrorInfoBase &EIB) {
228 SMDiagnostic Err = SMDiagnostic(TheModule.getModuleIdentifier(),
229 SourceMgr::DK_Error, EIB.message());
230 Err.print("ThinLTO", errs());
231 });
232 report_fatal_error("importFunctions failed");
233 }
234 // Verify again after cross-importing.
235 verifyLoadedModule(TheModule);
236}
237
238static void optimizeModule(Module &TheModule, TargetMachine &TM,
239 unsigned OptLevel, bool Freestanding,
240 bool DebugPassManager, ModuleSummaryIndex *Index) {
241 std::optional<PGOOptions> PGOOpt;
242 if (LTORunCSIRInstr) {
243 PGOOpt =
245 /*MemoryProfile=*/"", PGOOptions::IRUse,
247 } else if (!LTOCSIRProfile.empty()) {
248 PGOOpt = PGOOptions(LTOCSIRProfile, "", "",
249 /*MemoryProfile=*/"", PGOOptions::IRUse,
251 } else if (!SampleProfileFile.empty()) {
252 PGOOpt =
254 /*MemoryProfile=*/"", PGOOptions::SampleUse,
256 }
261
263 StandardInstrumentations SI(TheModule.getContext(), DebugPassManager);
264 SI.registerCallbacks(PIC, &MAM);
266 PTO.LoopVectorization = true;
267 PTO.SLPVectorization = true;
268 PassBuilder PB(TheModule.getContext(), &TM, PTO, PGOOpt, &PIC);
269
270 std::unique_ptr<TargetLibraryInfoImpl> TLII(
272 if (Freestanding)
273 TLII->disableAllFunctions();
274 FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
275
276 // Register all the basic analyses with the managers.
277 PB.registerModuleAnalyses(MAM);
278 PB.registerCGSCCAnalyses(CGAM);
279 PB.registerFunctionAnalyses(FAM);
280 PB.registerLoopAnalyses(LAM);
281 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
282
284
286
287 switch (OptLevel) {
288 default:
289 llvm_unreachable("Invalid optimization level");
290 case 0:
292 break;
293 case 1:
295 break;
296 case 2:
298 break;
299 case 3:
301 break;
302 }
303
304 MPM.addPass(PB.buildThinLTODefaultPipeline(OL, Index));
305
306 MPM.run(TheModule, MAM);
307}
308
309static void
311 DenseSet<GlobalValue::GUID> &PreservedGUID) {
312 Triple TT(File.getTargetTriple());
313 RTLIB::RuntimeLibcallsInfo Libcalls(TT);
314 TargetLibraryInfoImpl TLII(TT);
316 for (const auto &Sym : File.symbols())
317 if (Sym.isUsed() || Sym.isLibcall(TLI, Libcalls))
318 PreservedGUID.insert(
320}
321
322// Convert the PreservedSymbols map from "Name" based to "GUID" based.
324 const StringSet<> &PreservedSymbols,
325 const Triple &TheTriple,
327 // Iterate the symbols in the input file and if the input has preserved symbol
328 // compute the GUID for the symbol.
329 for (const auto &Sym : File.symbols()) {
330 if (PreservedSymbols.count(Sym.getName()) && !Sym.getIRName().empty())
332 GlobalValue::getGlobalIdentifier(Sym.getIRName(),
334 }
335}
336
339 const StringSet<> &PreservedSymbols,
340 const Triple &TheTriple) {
341 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
342 computeGUIDPreservedSymbols(File, PreservedSymbols, TheTriple,
343 GUIDPreservedSymbols);
344 return GUIDPreservedSymbols;
345}
346
347static std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
348 TargetMachine &TM) {
350
351 // CodeGen
352 {
355
356 // Setup the codegen now.
357 if (TM.addPassesToEmitFile(PM, OS, nullptr, CodeGenFileType::ObjectFile,
358 /* DisableVerify */ true))
359 report_fatal_error("Failed to setup codegen");
360
361 // Run codegen now. resulting binary is in OutputBuffer.
362 PM.run(TheModule);
363 }
364 return std::make_unique<SmallVectorMemoryBuffer>(
365 std::move(OutputBuffer), /*RequiresNullTerminator=*/false);
366}
367
368namespace {
369/// Manage caching for a single Module.
370class ModuleCacheEntry {
371 SmallString<128> EntryPath;
372
373public:
374 // Create a cache entry. This compute a unique hash for the Module considering
375 // the current list of export/import, and offer an interface to query to
376 // access the content in the cache.
377 ModuleCacheEntry(
378 StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
379 const FunctionImporter::ImportMapTy &ImportList,
380 const FunctionImporter::ExportSetTy &ExportList,
381 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
382 const GVSummaryMapTy &DefinedGVSummaries, unsigned OptLevel,
383 bool Freestanding, const TargetMachineBuilder &TMBuilder,
384 ArrayRef<std::string> MllvmArgs) {
385 if (CachePath.empty())
386 return;
387
388 if (!Index.modulePaths().count(ModuleID))
389 // The module does not have an entry, it can't have a hash at all
390 return;
391
392 if (all_of(Index.getModuleHash(ModuleID),
393 [](uint32_t V) { return V == 0; }))
394 // No hash entry, no caching!
395 return;
396
397 llvm::lto::Config Conf;
398 Conf.OptLevel = OptLevel;
399 Conf.Options = TMBuilder.Options;
400 Conf.CPU = TMBuilder.MCpu;
401 Conf.MAttrs.push_back(TMBuilder.MAttr);
402 Conf.RelocModel = TMBuilder.RelocModel;
403 Conf.CGOptLevel = TMBuilder.CGOptLevel;
404 Conf.Freestanding = Freestanding;
405 append_range(Conf.MllvmArgs, MllvmArgs);
406 std::string Key =
407 computeLTOCacheKey(Conf, Index, ModuleID, ImportList, ExportList,
408 ResolvedODR, DefinedGVSummaries);
409
410 // This choice of file name allows the cache to be pruned (see pruneCache()
411 // in include/llvm/Support/CachePruning.h).
412 sys::path::append(EntryPath, CachePath, Twine("llvmcache-", Key));
413 }
414
415 // Access the path to this entry in the cache.
416 StringRef getEntryPath() { return EntryPath; }
417
418 // Try loading the buffer for this cache entry.
419 ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
420 if (EntryPath.empty())
421 return std::error_code();
422 SmallString<64> ResultPath;
423 Expected<sys::fs::file_t> FDOrErr = sys::fs::openNativeFileForRead(
424 Twine(EntryPath), sys::fs::OF_UpdateAtime, &ResultPath);
425 if (!FDOrErr)
426 return errorToErrorCode(FDOrErr.takeError());
427 ErrorOr<std::unique_ptr<MemoryBuffer>> MBOrErr = MemoryBuffer::getOpenFile(
428 *FDOrErr, EntryPath, /*FileSize=*/-1, /*RequiresNullTerminator=*/false);
429 sys::fs::closeFile(*FDOrErr);
430 return MBOrErr;
431 }
432
433 // Cache the Produced object file
434 void write(const MemoryBuffer &OutputBuffer) {
435 if (EntryPath.empty())
436 return;
437
438 if (auto Err = llvm::writeToOutput(
439 EntryPath, [&OutputBuffer](llvm::raw_ostream &OS) -> llvm::Error {
440 OS << OutputBuffer.getBuffer();
441 return llvm::Error::success();
442 }))
443 report_fatal_error(llvm::formatv("ThinLTO: Can't write file {0}: {1}",
444 EntryPath,
445 toString(std::move(Err)).c_str()));
446 }
447};
448} // end anonymous namespace
449
450static std::unique_ptr<MemoryBuffer>
453 const FunctionImporter::ImportMapTy &ImportList,
454 const FunctionImporter::ExportSetTy &ExportList,
455 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
456 const GVSummaryMapTy &DefinedGlobals,
457 const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
458 bool DisableCodeGen, StringRef SaveTempsDir,
459 bool Freestanding, unsigned OptLevel, unsigned count,
460 bool DebugPassManager) {
461 // "Benchmark"-like optimization: single-source case
462 bool SingleModule = (ModuleMap.size() == 1);
463
464 // When linking an ELF shared object, dso_local should be dropped. We
465 // conservatively do this for -fpic.
466 bool ClearDSOLocalOnDeclarations =
467 TheModule.getTargetTriple().isOSBinFormatELF() &&
469 TheModule.getPIELevel() == PIELevel::Default;
470
471 if (!SingleModule) {
472 promoteModule(TheModule, Index, ClearDSOLocalOnDeclarations);
473
474 // Apply summary-based prevailing-symbol resolution decisions.
475 thinLTOFinalizeInModule(TheModule, DefinedGlobals, /*PropagateAttrs=*/true);
476
477 // Save temps: after promotion.
478 saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
479 }
480
481 // Be friendly and don't nuke totally the module when the client didn't
482 // supply anything to preserve.
483 if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
484 // Apply summary-based internalization decisions.
485 thinLTOInternalizeModule(TheModule, DefinedGlobals);
486 }
487
488 // Save internalized bitcode
489 saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
490
491 if (!SingleModule)
492 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList,
493 ClearDSOLocalOnDeclarations);
494
495 // Do this after any importing so that imported code is updated.
496 // See comment at call to updateVCallVisibilityInIndex() for why
497 // WholeProgramVisibilityEnabledInLTO is false.
499 /* WholeProgramVisibilityEnabledInLTO */ false);
500
501 // Save temps: after cross-module import.
502 saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
503
504 optimizeModule(TheModule, TM, OptLevel, Freestanding, DebugPassManager,
505 &Index);
506
507 saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
508
509 if (DisableCodeGen) {
510 // Configured to stop before CodeGen, serialize the bitcode and return.
512 {
514 ProfileSummaryInfo PSI(TheModule);
515 auto Index = buildModuleSummaryIndex(TheModule, nullptr, &PSI);
516 WriteBitcodeToFile(TheModule, OS, true, &Index);
517 }
518 return std::make_unique<SmallVectorMemoryBuffer>(
519 std::move(OutputBuffer), /*RequiresNullTerminator=*/false);
520 }
521
522 return codegenModule(TheModule, TM);
523}
524
525/// Resolve prevailing symbols. Record resolutions in the \p ResolvedODR map
526/// for caching, and in the \p Index for application during the ThinLTO
527/// backends. This is needed for correctness for exported symbols (ensure
528/// at least one copy kept) and a compile-time optimization (to drop duplicate
529/// copies when possible).
531 ModuleSummaryIndex &Index,
532 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
533 &ResolvedODR,
534 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
536 &PrevailingCopy) {
537
538 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
539 const auto &Prevailing = PrevailingCopy.find(GUID);
540 // Not in map means that there was only one copy, which must be prevailing.
541 if (Prevailing == PrevailingCopy.end())
542 return true;
543 return Prevailing->second == S;
544 };
545
546 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
548 GlobalValue::LinkageTypes NewLinkage) {
549 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
550 };
551
552 // TODO Conf.VisibilityScheme can be lto::Config::ELF for ELF.
553 lto::Config Conf;
554 thinLTOResolvePrevailingInIndex(Conf, Index, isPrevailing, recordNewLinkage,
555 GUIDPreservedSymbols);
556}
557
558// Initialize the TargetMachine builder for a given Triple
559static void initTMBuilder(TargetMachineBuilder &TMBuilder,
560 const Triple &TheTriple) {
561 if (TMBuilder.MCpu.empty())
562 TMBuilder.MCpu = lto::getThinLTODefaultCPU(TheTriple);
563 TMBuilder.TheTriple = std::move(TheTriple);
564 // If data-sections is not explicitly set or unset, set data-sections by
565 // default to match the behaviour of lld and gold plugin.
567 TMBuilder.Options.DataSections = true;
568}
569
571 MemoryBufferRef Buffer(Data, Identifier);
572
573 auto InputOrError = lto::InputFile::create(Buffer);
574 if (!InputOrError)
575 report_fatal_error(Twine("ThinLTO cannot create input file: ") +
576 toString(InputOrError.takeError()));
577
578 auto TripleStr = (*InputOrError)->getTargetTriple();
579 Triple TheTriple(TripleStr);
580
581 if (Modules.empty())
582 initTMBuilder(TMBuilder, Triple(TheTriple));
583 else if (TMBuilder.TheTriple != TheTriple) {
584 if (!TMBuilder.TheTriple.isCompatibleWith(TheTriple))
585 report_fatal_error("ThinLTO modules with incompatible triples not "
586 "supported");
587 initTMBuilder(TMBuilder, Triple(TMBuilder.TheTriple.merge(TheTriple)));
588 }
589
590 Modules.emplace_back(std::move(*InputOrError));
591}
592
594 PreservedSymbols.insert(Name);
595}
596
598 // FIXME: At the moment, we don't take advantage of this extra information,
599 // we're conservatively considering cross-references as preserved.
600 // CrossReferencedSymbols.insert(Name);
601 PreservedSymbols.insert(Name);
602}
603
604// TargetMachine factory
605std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
606 std::string ErrMsg;
607 const Target *TheTarget = TargetRegistry::lookupTarget(TheTriple, ErrMsg);
608 if (!TheTarget) {
609 report_fatal_error(Twine("Can't load target for this Triple: ") + ErrMsg);
610 }
611
612 // Use MAttr as the default set of features.
613 SubtargetFeatures Features(MAttr);
615 std::string FeatureStr = Features.getString();
616
617 std::unique_ptr<TargetMachine> TM(
618 TheTarget->createTargetMachine(TheTriple, MCpu, FeatureStr, Options,
619 RelocModel, std::nullopt, CGOptLevel));
620 assert(TM && "Cannot create target machine");
621
622 return TM;
623}
624
625/**
626 * Produce the combined summary index from all the bitcode files:
627 * "thin-link".
628 */
629std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
630 std::unique_ptr<ModuleSummaryIndex> CombinedIndex =
631 std::make_unique<ModuleSummaryIndex>(/*HaveGVs=*/false);
632 for (auto &Mod : Modules) {
633 auto &M = Mod->getSingleBitcodeModule();
634 if (Error Err = M.readSummary(*CombinedIndex, Mod->getName())) {
635 // FIXME diagnose
637 std::move(Err), errs(),
638 "error: can't create module summary index for buffer: ");
639 return nullptr;
640 }
641 }
642 return CombinedIndex;
643}
644
645namespace {
646struct IsExported {
648 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols;
649
650 IsExported(
652 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols)
653 : ExportLists(ExportLists), GUIDPreservedSymbols(GUIDPreservedSymbols) {}
654
655 bool operator()(StringRef ModuleIdentifier, ValueInfo VI) const {
656 const auto &ExportList = ExportLists.find(ModuleIdentifier);
657 return (ExportList != ExportLists.end() && ExportList->second.count(VI)) ||
658 GUIDPreservedSymbols.count(VI.getGUID());
659 }
660};
661
662struct IsPrevailing {
663 const DenseMap<GlobalValue::GUID, const GlobalValueSummary *> &PrevailingCopy;
664 IsPrevailing(const DenseMap<GlobalValue::GUID, const GlobalValueSummary *>
665 &PrevailingCopy)
666 : PrevailingCopy(PrevailingCopy) {}
667
668 bool operator()(GlobalValue::GUID GUID, const GlobalValueSummary *S) const {
669 const auto &Prevailing = PrevailingCopy.find(GUID);
670 // Not in map means that there was only one copy, which must be prevailing.
671 if (Prevailing == PrevailingCopy.end())
672 return true;
673 return Prevailing->second == S;
674 };
675};
676} // namespace
677
679 ModuleSummaryIndex &Index,
680 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
681 // We have no symbols resolution available. And can't do any better now in the
682 // case where the prevailing symbol is in a native object. It can be refined
683 // with linker information in the future.
684 auto isPrevailing = [&](GlobalValue::GUID G) {
686 };
687 computeDeadSymbolsWithConstProp(Index, GUIDPreservedSymbols, isPrevailing,
688 /* ImportEnabled = */ true);
689}
690
691/**
692 * Perform promotion and renaming of exported internal functions.
693 * Index is updated to reflect linkage changes from weak resolution.
694 */
696 const lto::InputFile &File) {
697 auto ModuleCount = Index.modulePaths().size();
698 auto ModuleIdentifier = TheModule.getModuleIdentifier();
699
700 // Collect for each module the list of function it defines (GUID -> Summary).
701 DenseMap<StringRef, GVSummaryMapTy> ModuleToDefinedGVSummaries;
702 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
703
704 // Convert the preserved symbols set from string to GUID
705 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
706 File, PreservedSymbols, TheModule.getTargetTriple());
707
708 // Add used symbol to the preserved symbols.
709 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
710
711 // Compute "dead" symbols, we don't want to import/export these!
712 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
713
714 // Compute prevailing symbols
716 computePrevailingCopies(Index, PrevailingCopy);
717
718 // Generate import/export list
719 FunctionImporter::ImportListsTy ImportLists(ModuleCount);
721 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries,
722 IsPrevailing(PrevailingCopy), ImportLists,
723 ExportLists);
724
725 // Resolve prevailing symbols
727 resolvePrevailingInIndex(Index, ResolvedODR, GUIDPreservedSymbols,
728 PrevailingCopy);
729
730 thinLTOFinalizeInModule(TheModule,
731 ModuleToDefinedGVSummaries[ModuleIdentifier],
732 /*PropagateAttrs=*/false);
733
734 // Promote the exported values in the index, so that they are promoted
735 // in the module.
737 Index, IsExported(ExportLists, GUIDPreservedSymbols),
738 IsPrevailing(PrevailingCopy));
739
740 // FIXME Set ClearDSOLocalOnDeclarations.
741 promoteModule(TheModule, Index, /*ClearDSOLocalOnDeclarations=*/false);
742}
743
744/**
745 * Perform cross-module importing for the module identified by ModuleIdentifier.
746 */
748 ModuleSummaryIndex &Index,
749 const lto::InputFile &File) {
750 auto ModuleMap = generateModuleMap(Modules);
751 auto ModuleCount = Index.modulePaths().size();
752
753 // Collect for each module the list of function it defines (GUID -> Summary).
754 DenseMap<StringRef, GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
755 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
756
757 // Convert the preserved symbols set from string to GUID
758 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
759 File, PreservedSymbols, 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 // Compute prevailing symbols
768 computePrevailingCopies(Index, PrevailingCopy);
769
770 // Generate import/export list
771 FunctionImporter::ImportListsTy ImportLists(ModuleCount);
773 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries,
774 IsPrevailing(PrevailingCopy), ImportLists,
775 ExportLists);
776 auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
777
778 // FIXME Set ClearDSOLocalOnDeclarations.
779 crossImportIntoModule(TheModule, Index, ModuleMap, ImportList,
780 /*ClearDSOLocalOnDeclarations=*/false);
781}
782
783/**
784 * Compute the list of summaries needed for importing into module.
785 */
787 Module &TheModule, ModuleSummaryIndex &Index,
788 ModuleToSummariesForIndexTy &ModuleToSummariesForIndex,
789 GVSummaryPtrSet &DecSummaries, const lto::InputFile &File) {
790 auto ModuleCount = Index.modulePaths().size();
791 auto ModuleIdentifier = TheModule.getModuleIdentifier();
792
793 // Collect for each module the list of function it defines (GUID -> Summary).
794 DenseMap<StringRef, GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
795 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
796
797 // Convert the preserved symbols set from string to GUID
798 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
799 File, PreservedSymbols, TheModule.getTargetTriple());
800
801 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
802
803 // Compute "dead" symbols, we don't want to import/export these!
804 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
805
806 // Compute prevailing symbols
808 computePrevailingCopies(Index, PrevailingCopy);
809
810 // Generate import/export list
811 FunctionImporter::ImportListsTy ImportLists(ModuleCount);
813 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries,
814 IsPrevailing(PrevailingCopy), ImportLists,
815 ExportLists);
816
818 ModuleIdentifier, ModuleToDefinedGVSummaries,
819 ImportLists[ModuleIdentifier], ModuleToSummariesForIndex, DecSummaries);
820}
821
822/**
823 * Emit the list of files needed for importing into module.
824 */
826 ModuleSummaryIndex &Index,
827 const lto::InputFile &File) {
828 auto ModuleCount = Index.modulePaths().size();
829 auto ModuleIdentifier = TheModule.getModuleIdentifier();
830
831 // Collect for each module the list of function it defines (GUID -> Summary).
832 DenseMap<StringRef, GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
833 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
834
835 // Convert the preserved symbols set from string to GUID
836 auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
837 File, PreservedSymbols, TheModule.getTargetTriple());
838
839 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
840
841 // Compute "dead" symbols, we don't want to import/export these!
842 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
843
844 // Compute prevailing symbols
846 computePrevailingCopies(Index, PrevailingCopy);
847
848 // Generate import/export list
849 FunctionImporter::ImportListsTy ImportLists(ModuleCount);
851 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries,
852 IsPrevailing(PrevailingCopy), ImportLists,
853 ExportLists);
854
855 // 'EmitImportsFiles' emits the list of modules from which to import from, and
856 // the set of keys in `ModuleToSummariesForIndex` should be a superset of keys
857 // in `DecSummaries`, so no need to use `DecSummaries` in `EmitImportsFiles`.
858 GVSummaryPtrSet DecSummaries;
859 ModuleToSummariesForIndexTy ModuleToSummariesForIndex;
861 ModuleIdentifier, ModuleToDefinedGVSummaries,
862 ImportLists[ModuleIdentifier], ModuleToSummariesForIndex, DecSummaries);
863
864 if (Error EC = EmitImportsFiles(ModuleIdentifier, OutputName,
865 ModuleToSummariesForIndex))
866 report_fatal_error(Twine("Failed to open ") + OutputName +
867 " to save imports lists\n");
868}
869
870/**
871 * Perform internalization. Runs promote and internalization together.
872 * Index is updated to reflect linkage changes.
873 */
875 ModuleSummaryIndex &Index,
876 const lto::InputFile &File) {
877 initTMBuilder(TMBuilder, TheModule.getTargetTriple());
878 auto ModuleCount = Index.modulePaths().size();
879 auto ModuleIdentifier = TheModule.getModuleIdentifier();
880
881 // Convert the preserved symbols set from string to GUID
882 auto GUIDPreservedSymbols =
883 computeGUIDPreservedSymbols(File, PreservedSymbols, TMBuilder.TheTriple);
884
885 addUsedSymbolToPreservedGUID(File, GUIDPreservedSymbols);
886
887 // Collect for each module the list of function it defines (GUID -> Summary).
888 DenseMap<StringRef, GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
889 Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
890
891 // Compute "dead" symbols, we don't want to import/export these!
892 computeDeadSymbolsInIndex(Index, GUIDPreservedSymbols);
893
894 // Compute prevailing symbols
896 computePrevailingCopies(Index, PrevailingCopy);
897
898 // Generate import/export list
899 FunctionImporter::ImportListsTy ImportLists(ModuleCount);
901 ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries,
902 IsPrevailing(PrevailingCopy), ImportLists,
903 ExportLists);
904 auto &ExportList = ExportLists[ModuleIdentifier];
905
906 // Be friendly and don't nuke totally the module when the client didn't
907 // supply anything to preserve.
908 if (ExportList.empty() && GUIDPreservedSymbols.empty())
909 return;
910
911 // Resolve prevailing symbols
913 resolvePrevailingInIndex(Index, ResolvedODR, GUIDPreservedSymbols,
914 PrevailingCopy);
915
916 // Promote the exported values in the index, so that they are promoted
917 // in the module.
919 Index, IsExported(ExportLists, GUIDPreservedSymbols),
920 IsPrevailing(PrevailingCopy));
921
922 // FIXME Set ClearDSOLocalOnDeclarations.
923 promoteModule(TheModule, Index, /*ClearDSOLocalOnDeclarations=*/false);
924
925 // Internalization
926 thinLTOFinalizeInModule(TheModule,
927 ModuleToDefinedGVSummaries[ModuleIdentifier],
928 /*PropagateAttrs=*/false);
929
930 thinLTOInternalizeModule(TheModule,
931 ModuleToDefinedGVSummaries[ModuleIdentifier]);
932}
933
934/**
935 * Perform post-importing ThinLTO optimizations.
936 */
938 initTMBuilder(TMBuilder, TheModule.getTargetTriple());
939
940 // Optimize now
941 optimizeModule(TheModule, *TMBuilder.create(), OptLevel, Freestanding,
942 DebugPassManager, nullptr);
943}
944
945/// Write out the generated object file, either from CacheEntryPath or from
946/// OutputBuffer, preferring hard-link when possible.
947/// Returns the path to the generated file in SavedObjectsDirectoryPath.
948std::string
950 const MemoryBuffer &OutputBuffer) {
951 auto ArchName = TMBuilder.TheTriple.getArchName();
952 SmallString<128> OutputPath(SavedObjectsDirectoryPath);
953 llvm::sys::path::append(OutputPath,
954 Twine(count) + "." + ArchName + ".thinlto.o");
955 OutputPath.c_str(); // Ensure the string is null terminated.
956 if (sys::fs::exists(OutputPath))
957 sys::fs::remove(OutputPath);
958
959 // We don't return a memory buffer to the linker, just a list of files.
960 if (!CacheEntryPath.empty()) {
961 // Cache is enabled, hard-link the entry (or copy if hard-link fails).
962 auto Err = sys::fs::create_hard_link(CacheEntryPath, OutputPath);
963 if (!Err)
964 return std::string(OutputPath);
965 // Hard linking failed, try to copy.
966 Err = sys::fs::copy_file(CacheEntryPath, OutputPath);
967 if (!Err)
968 return std::string(OutputPath);
969 // Copy failed (could be because the CacheEntry was removed from the cache
970 // in the meantime by another process), fall back and try to write down the
971 // buffer to the output.
972 errs() << "remark: can't link or copy from cached entry '" << CacheEntryPath
973 << "' to '" << OutputPath << "'\n";
974 }
975 // No cache entry, just write out the buffer.
976 std::error_code Err;
977 raw_fd_ostream OS(OutputPath, Err, sys::fs::OF_None);
978 if (Err)
979 report_fatal_error(Twine("Can't open output '") + OutputPath + "'\n");
980 OS << OutputBuffer.getBuffer();
981 return std::string(OutputPath);
982}
983
984// Main entry point for the ThinLTO processing
986 timeTraceProfilerBegin("ThinLink", StringRef(""));
987 llvm::scope_exit TimeTraceScopeExit([]() {
990 });
991 // Prepare the resulting object vector
992 assert(ProducedBinaries.empty() && "The generator should not be reused");
993 if (SavedObjectsDirectoryPath.empty())
994 ProducedBinaries.resize(Modules.size());
995 else {
996 sys::fs::create_directories(SavedObjectsDirectoryPath);
997 bool IsDir;
998 sys::fs::is_directory(SavedObjectsDirectoryPath, IsDir);
999 if (!IsDir)
1000 report_fatal_error(Twine("Unexistent dir: '") + SavedObjectsDirectoryPath + "'");
1001 ProducedBinaryFiles.resize(Modules.size());
1002 }
1003
1004 if (CodeGenOnly) {
1005 // Perform only parallel codegen and return.
1006 DefaultThreadPool Pool;
1007 int count = 0;
1008 for (auto &Mod : Modules) {
1009 Pool.async([&](int count) {
1010 LLVMContext Context;
1011 Context.getLibraryOptions().assign(LibraryOptions);
1012 Context.setDiscardValueNames(LTODiscardValueNames);
1013
1014 // Parse module now
1015 auto TheModule = loadModuleFromInput(Mod.get(), Context, false,
1016 /*IsImporting*/ false);
1017
1018 // CodeGen
1019 auto OutputBuffer = codegenModule(*TheModule, *TMBuilder.create());
1020 if (SavedObjectsDirectoryPath.empty())
1021 ProducedBinaries[count] = std::move(OutputBuffer);
1022 else
1023 ProducedBinaryFiles[count] =
1025 }, count++);
1026 }
1027
1028 return;
1029 }
1030
1031 // Sequential linking phase
1032 auto Index = linkCombinedIndex();
1033
1034 // Save temps: index.
1035 if (!SaveTempsDir.empty()) {
1036 auto SaveTempPath = SaveTempsDir + "index.bc";
1037 std::error_code EC;
1038 raw_fd_ostream OS(SaveTempPath, EC, sys::fs::OF_None);
1039 if (EC)
1040 report_fatal_error(Twine("Failed to open ") + SaveTempPath +
1041 " to save optimized bitcode\n");
1042 writeIndexToFile(*Index, OS);
1043 }
1044
1045
1046 // Prepare the module map.
1047 auto ModuleMap = generateModuleMap(Modules);
1048 auto ModuleCount = Modules.size();
1049
1050 // Collect for each module the list of function it defines (GUID -> Summary).
1051 DenseMap<StringRef, GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
1052 Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
1053
1054 // Convert the preserved symbols set from string to GUID, this is needed for
1055 // computing the caching hash and the internalization.
1056 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
1057 for (const auto &M : Modules)
1058 computeGUIDPreservedSymbols(*M, PreservedSymbols, TMBuilder.TheTriple,
1059 GUIDPreservedSymbols);
1060
1061 // Add used symbol from inputs to the preserved symbols.
1062 for (const auto &M : Modules)
1063 addUsedSymbolToPreservedGUID(*M, GUIDPreservedSymbols);
1064
1065 // Compute "dead" symbols, we don't want to import/export these!
1066 computeDeadSymbolsInIndex(*Index, GUIDPreservedSymbols);
1067
1068 // Currently there is no support for enabling whole program visibility via a
1069 // linker option in the old LTO API, but this call allows it to be specified
1070 // via the internal option. Must be done before WPD below.
1071 if (hasWholeProgramVisibility(/* WholeProgramVisibilityEnabledInLTO */ false))
1072 Index->setWithWholeProgramVisibility();
1073
1074 // FIXME: This needs linker information via a TBD new interface
1076 /*WholeProgramVisibilityEnabledInLTO=*/false,
1077 // FIXME: These need linker information via a
1078 // TBD new interface.
1079 /*DynamicExportSymbols=*/{},
1080 /*VisibleToRegularObjSymbols=*/{});
1081
1082 // Perform index-based WPD. This will return immediately if there are
1083 // no index entries in the typeIdMetadata map (e.g. if we are instead
1084 // performing IR-based WPD in hybrid regular/thin LTO mode).
1085 std::map<ValueInfo, std::vector<VTableSlotSummary>> LocalWPDTargetsMap;
1086 std::set<GlobalValue::GUID> ExportedGUIDs;
1087 runWholeProgramDevirtOnIndex(*Index, ExportedGUIDs, LocalWPDTargetsMap);
1088 GUIDPreservedSymbols.insert_range(ExportedGUIDs);
1089
1090 // Compute prevailing symbols
1092 computePrevailingCopies(*Index, PrevailingCopy);
1093
1094 // Collect the import/export lists for all modules from the call-graph in the
1095 // combined index.
1096 FunctionImporter::ImportListsTy ImportLists(ModuleCount);
1098 ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries,
1099 IsPrevailing(PrevailingCopy), ImportLists,
1100 ExportLists);
1101
1102 // We use a std::map here to be able to have a defined ordering when
1103 // producing a hash for the cache entry.
1104 // FIXME: we should be able to compute the caching hash for the entry based
1105 // on the index, and nuke this map.
1107
1108 // Resolve prevailing symbols, this has to be computed early because it
1109 // impacts the caching.
1110 resolvePrevailingInIndex(*Index, ResolvedODR, GUIDPreservedSymbols,
1111 PrevailingCopy);
1112
1113 // Use global summary-based analysis to identify symbols that can be
1114 // internalized (because they aren't exported or preserved as per callback).
1115 // Changes are made in the index, consumed in the ThinLTO backends.
1117 IsExported(ExportLists, GUIDPreservedSymbols),
1118 LocalWPDTargetsMap);
1120 *Index, IsExported(ExportLists, GUIDPreservedSymbols),
1121 IsPrevailing(PrevailingCopy));
1122
1123 thinLTOPropagateFunctionAttrs(*Index, IsPrevailing(PrevailingCopy));
1124
1125 // Make sure that every module has an entry in the ExportLists, ImportList,
1126 // GVSummary and ResolvedODR maps to enable threaded access to these maps
1127 // below.
1128 for (auto &Module : Modules) {
1129 auto ModuleIdentifier = Module->getName();
1130 ExportLists[ModuleIdentifier];
1131 ImportLists[ModuleIdentifier];
1132 ResolvedODR[ModuleIdentifier];
1133 ModuleToDefinedGVSummaries[ModuleIdentifier];
1134 }
1135
1136 std::vector<BitcodeModule *> ModulesVec;
1137 ModulesVec.reserve(Modules.size());
1138 for (auto &Mod : Modules)
1139 ModulesVec.push_back(&Mod->getSingleBitcodeModule());
1140 std::vector<int> ModulesOrdering = lto::generateModulesOrdering(ModulesVec);
1141
1144
1145 TimeTraceScopeExit.release();
1146
1147 // Parallel optimizer + codegen
1148 {
1150 for (auto IndexCount : ModulesOrdering) {
1151 auto &Mod = Modules[IndexCount];
1152 Pool.async([&](int count) {
1153 auto ModuleIdentifier = Mod->getName();
1154 auto &ExportList = ExportLists[ModuleIdentifier];
1155
1156 auto &DefinedGVSummaries = ModuleToDefinedGVSummaries[ModuleIdentifier];
1157
1158 // The module may be cached, this helps handling it.
1159 ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
1160 ImportLists[ModuleIdentifier], ExportList,
1161 ResolvedODR[ModuleIdentifier],
1162 DefinedGVSummaries, OptLevel, Freestanding,
1163 TMBuilder, MllvmArgs);
1164 auto CacheEntryPath = CacheEntry.getEntryPath();
1165
1166 {
1167 auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
1168 LLVM_DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss")
1169 << " '" << CacheEntryPath << "' for buffer "
1170 << count << " " << ModuleIdentifier << "\n");
1171
1172 if (ErrOrBuffer) {
1173 // Cache Hit!
1174 if (SavedObjectsDirectoryPath.empty())
1175 ProducedBinaries[count] = std::move(ErrOrBuffer.get());
1176 else
1177 ProducedBinaryFiles[count] = writeGeneratedObject(
1178 count, CacheEntryPath, *ErrOrBuffer.get());
1179 return;
1180 }
1181 }
1182
1183 LLVMContext Context;
1184 Context.getLibraryOptions().assign(LibraryOptions);
1185 Context.setDiscardValueNames(LTODiscardValueNames);
1186 Context.enableDebugTypeODRUniquing();
1187 auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
1190 if (!DiagFileOrErr) {
1191 errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
1192 report_fatal_error("ThinLTO: Can't get an output file for the "
1193 "remarks");
1194 }
1195
1196 // Parse module now
1197 auto TheModule = loadModuleFromInput(Mod.get(), Context, false,
1198 /*IsImporting*/ false);
1199
1200 // Save temps: original file.
1201 saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
1202
1203 auto &ImportList = ImportLists[ModuleIdentifier];
1204 // Run the main process now, and generates a binary
1206 *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
1207 ExportList, GUIDPreservedSymbols,
1208 ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
1209 DisableCodeGen, SaveTempsDir, Freestanding, OptLevel, count,
1210 DebugPassManager);
1211
1212 // Commit to the cache (if enabled)
1213 CacheEntry.write(*OutputBuffer);
1214
1215 if (SavedObjectsDirectoryPath.empty()) {
1216 // We need to generated a memory buffer for the linker.
1217 if (!CacheEntryPath.empty()) {
1218 // When cache is enabled, reload from the cache if possible.
1219 // Releasing the buffer from the heap and reloading it from the
1220 // cache file with mmap helps us to lower memory pressure.
1221 // The freed memory can be used for the next input file.
1222 // The final binary link will read from the VFS cache (hopefully!)
1223 // or from disk (if the memory pressure was too high).
1224 auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer();
1225 if (auto EC = ReloadedBufferOrErr.getError()) {
1226 // On error, keep the preexisting buffer and print a diagnostic.
1227 errs() << "remark: can't reload cached file '" << CacheEntryPath
1228 << "': " << EC.message() << "\n";
1229 } else {
1230 OutputBuffer = std::move(*ReloadedBufferOrErr);
1231 }
1232 }
1233 ProducedBinaries[count] = std::move(OutputBuffer);
1234 return;
1235 }
1236 ProducedBinaryFiles[count] = writeGeneratedObject(
1237 count, CacheEntryPath, *OutputBuffer);
1238 }, IndexCount);
1239 }
1240 }
1241
1242 Expected<bool> PrunedOrErr =
1243 pruneCache(CacheOptions.Path, CacheOptions.Policy, ProducedBinaries);
1244 if (!PrunedOrErr) {
1245 errs() << "Error: " << toString(PrunedOrErr.takeError()) << "\n";
1246 report_fatal_error("ThinLTO: failure to prune cache");
1247 }
1248
1249 // If statistics were requested, print them out now.
1253}
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file provides a bitcode writing pass.
#define LLVM_LIFETIME_BOUND
Definition Compiler.h:464
DXIL Finalize Linkage
Provides passes for computing function attributes based on interprocedural analyses.
This file implements a simple parser to decode commandline option for remarks hotness threshold that ...
#define I(x, y, z)
Definition MD5.cpp:57
#define G(x, y, z)
Definition MD5.cpp:55
This is the interface to build a ModuleSummaryIndex for a module.
CGSCCAnalysisManager CGAM
if(auto Err=PB.parsePassPipeline(MPM, Passes)) return wrap(std MPM run * Mod
LoopAnalysisManager LAM
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
PassBuilder PB(Mod->getContext(), Machine, PassOpts->PTO, std::nullopt, &PIC)
PassInstrumentationCallbacks PIC
This header defines classes/functions to handle pass execution timing information with interfaces for...
This file defines the scope_exit class, which executes user-defined cleanup logic at scope exit.
This header defines a class that provides bookkeeping for all standard (i.e in-tree) pass instrumenta...
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
This file contains some functions that are useful when dealing with strings.
#define LLVM_DEBUG(...)
Definition Debug.h:119
static void crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index, StringMap< lto::InputFile * > &ModuleMap, const FunctionImporter::ImportMapTy &ImportList, bool ClearDSOLocalOnDeclarations)
static void computeDeadSymbolsInIndex(ModuleSummaryIndex &Index, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols)
static StringMap< lto::InputFile * > generateModuleMap(std::vector< std::unique_ptr< lto::InputFile > > &Modules)
static void initTMBuilder(TargetMachineBuilder &TMBuilder, const Triple &TheTriple)
static void resolvePrevailingInIndex(ModuleSummaryIndex &Index, StringMap< std::map< GlobalValue::GUID, GlobalValue::LinkageTypes > > &ResolvedODR, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols, const DenseMap< GlobalValue::GUID, const GlobalValueSummary * > &PrevailingCopy)
Resolve prevailing symbols.
static const GlobalValueSummary * getFirstDefinitionForLinker(ArrayRef< std::unique_ptr< GlobalValueSummary > > GVSummaryList)
static void computePrevailingCopies(const ModuleSummaryIndex &Index, DenseMap< GlobalValue::GUID, const GlobalValueSummary * > &PrevailingCopy)
static void saveTempBitcode(const Module &TheModule, StringRef TempDir, unsigned count, StringRef Suffix)
static void verifyLoadedModule(Module &TheModule)
Verify the module and strip broken debug info.
static void addUsedSymbolToPreservedGUID(const lto::InputFile &File, DenseSet< GlobalValue::GUID > &PreservedGUID)
static std::unique_ptr< MemoryBuffer > ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index, StringMap< lto::InputFile * > &ModuleMap, TargetMachine &TM, const FunctionImporter::ImportMapTy &ImportList, const FunctionImporter::ExportSetTy &ExportList, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols, const GVSummaryMapTy &DefinedGlobals, const ThinLTOCodeGenerator::CachingOptions &CacheOptions, bool DisableCodeGen, StringRef SaveTempsDir, bool Freestanding, unsigned OptLevel, unsigned count, bool DebugPassManager)
static cl::opt< int > ThreadCount("threads", cl::init(0))
static std::unique_ptr< MemoryBuffer > codegenModule(Module &TheModule, TargetMachine &TM)
static void optimizeModule(Module &TheModule, TargetMachine &TM, unsigned OptLevel, bool Freestanding, bool DebugPassManager, ModuleSummaryIndex *Index)
static void computeGUIDPreservedSymbols(const lto::InputFile &File, const StringSet<> &PreservedSymbols, const Triple &TheTriple, DenseSet< GlobalValue::GUID > &GUIDs)
static std::unique_ptr< Module > loadModuleFromInput(lto::InputFile *Input, LLVMContext &Context, bool Lazy, bool IsImporting)
static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index, bool ClearDSOLocalOnDeclarations)
The Input class is used to parse a yaml document into in-memory structs and vectors.
char * getBuffer()
Definition Utility.h:220
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator find(const_arg_type_t< KeyT > Val)
Definition DenseMap.h:766
iterator end()
Definition DenseMap.h:686
Implements a dense probed hash-table based set.
Definition DenseSet.h:281
This is the base abstract class for diagnostic reporting in the backend.
Base class for error info classes.
Definition Error.h:44
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Tagged union holding either a T or a Error.
Definition Error.h:485
Error takeError()
Take ownership of the stored error.
Definition Error.h:612
reference get()
Returns a reference to the stored T value.
Definition Error.h:582
The map maintains the list of imports.
The function importer is automatically importing function from other modules based on the provided su...
LLVM_ABI Expected< bool > importFunctions(Module &M, const ImportMapTy &ImportList)
Import functions in Module M based on the supplied import list.
DenseSet< ValueInfo > ExportSetTy
The set contains an entry for every global value that the module exports.
Function and variable summary information to aid decisions and implementation of importing.
static LLVM_ABI GUID getGUIDAssumingExternalLinkage(StringRef GlobalName)
Return a 64-bit global unique ID constructed from the name of a global symbol.
Definition Globals.cpp:80
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
static bool isAvailableExternallyLinkage(LinkageTypes Linkage)
static LLVM_ABI std::string getGlobalIdentifier(StringRef Name, GlobalValue::LinkageTypes Linkage, StringRef FileName)
Return the modified name for a global value suitable to be used as the key for a global lookup (e....
Definition Globals.cpp:234
bool isWeakForLinker() const
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition GlobalValue.h:52
@ ExternalLinkage
Externally visible function.
Definition GlobalValue.h:53
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
LLVM_ABI cl::LibraryOptionsContext & getLibraryOptions() const
The library options this context reads in place of their process-wide values.
LLVM_ABI void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
This interface provides simple read-only access to a block of memory, and provides simple methods for...
static ErrorOr< std::unique_ptr< MemoryBuffer > > getOpenFile(sys::fs::file_t FD, const Twine &Filename, uint64_t FileSize, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Given an already-open file descriptor, read the file and return a MemoryBuffer.
StringRef getBuffer() const
Class to hold module path string table and global value map, and encapsulate methods for operating on...
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
const Triple & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition Module.h:328
LLVMContext & getContext() const
Get the global data context.
Definition Module.h:332
StringRef getName() const
Get a short "name" for the module.
Definition Module.h:316
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
Definition Module.h:299
PIELevel::Level getPIELevel() const
Returns the PIE level (small or large model)
Definition Module.cpp:653
This class provides access to building LLVM's passes.
This class manages callbacks registration, as well as provides a way for PassInstrumentation to pass ...
LLVM_ATTRIBUTE_MINSIZE std::enable_if_t<!std::is_same_v< PassT, PassManager > > addPass(PassT &&Pass)
PreservedAnalyses run(IRUnitT &IR, AnalysisManagerT &AM, ExtraArgTs... ExtraArgs)
Run all of the passes in this manager over the given unit of IR.
Tunable parameters for passes in the default pipelines.
Definition PassBuilder.h:48
bool SLPVectorization
Tuning option to enable/disable slp loop vectorization, set based on opt level.
Definition PassBuilder.h:63
bool LoopVectorization
Tuning option to enable/disable loop vectorization, set based on opt level.
Definition PassBuilder.h:59
Analysis providing profile information.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:26
const char * c_str()
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
This class provides an interface to register all the standard pass instrumentations and manages their...
unsigned size() const
Definition StringMap.h:104
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition StringMap.h:129
bool contains(StringRef Key) const
contains - Return true if the element is in the map, false otherwise.
Definition StringMap.h:270
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
Definition StringMap.h:275
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
constexpr bool empty() const
Check if the string is empty.
Definition StringRef.h:141
StringSet - A wrapper for StringMap that provides set-like functionality.
Definition StringSet.h:25
Manages the enabling and disabling of subtarget specific features.
LLVM_ABI void getDefaultSubtargetFeatures(const Triple &Triple)
Adds the default features for the specified target triple.
LLVM_ABI std::string getString() const
Returns features as a string.
Analysis pass providing the TargetLibraryInfo.
Implementation of the target library information.
Provides information about what library functions are available for the current target.
Primary interface to the complete machine description for the target machine.
virtual bool addPassesToEmitFile(PassManagerBase &, raw_pwrite_stream &, raw_pwrite_stream *, CodeGenFileType, bool=true, MachineModuleInfoWrapperPass *MMIWP=nullptr)
Add passes to the specified pass manager to get the specified file emitted.
const Triple & getTargetTriple() const
Reloc::Model getRelocationModel() const
Returns the code generation relocation model.
TargetOptions Options
VectorLibrary VecLib
Vector math library to use.
unsigned DataSections
Emit data into separate sections.
Target - Wrapper for Target specific information.
TargetMachine * createTargetMachine(const Triple &TT, StringRef CPU, StringRef Features, const TargetOptions &Options, std::optional< Reloc::Model > RM, std::optional< CodeModel::Model > CM=std::nullopt, CodeGenOptLevel OL=CodeGenOptLevel::Default, bool JIT=false) const
createTargetMachine - Create a target specific machine implementation for the specified Triple.
LLVM_ABI void preserveSymbol(StringRef Name)
Adds to a list of all global symbols that must exist in the final generated code.
LLVM_ABI void run()
Process all the modules that were added to the code generator in parallel.
LLVM_ABI void crossReferenceSymbol(StringRef Name)
Adds to a list of all global symbols that are cross-referenced between ThinLTO files.
LLVM_ABI void addModule(StringRef Identifier, StringRef Data)
Add given module to the code generator.
auto async(Function &&F, Args &&...ArgList)
Asynchronous submission of a task to the pool.
Definition ThreadPool.h:80
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
bool isOSBinFormatELF() const
Tests whether the OS uses the ELF binary format.
Definition Triple.h:867
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
void assign(const LibraryOptionsContext &Other)
std::pair< iterator, bool > insert(const ValueT &V)
Definition DenseSet.h:209
void insert_range(Range &&R)
Definition DenseSet.h:235
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition DenseSet.h:187
PassManager manages ModulePassManagers.
bool run(Module &M)
run - Execute all of the passes scheduled for execution.
An input file.
Definition LTO.h:115
static LLVM_ABI Expected< std::unique_ptr< InputFile > > create(MemoryBufferRef Object)
Create an InputFile.
Definition LTO.cpp:628
A raw_ostream that writes to a file descriptor.
A raw_ostream that writes to an SmallVector or SmallString.
LLVM_ABI void optimize(Module &Module)
Perform post-importing ThinLTO optimizations.
LLVM_ABI std::unique_ptr< ModuleSummaryIndex > linkCombinedIndex()
Produce the combined summary index from all the bitcode files: "thin-link".
LLVM_ABI void crossModuleImport(Module &Module, ModuleSummaryIndex &Index, const lto::InputFile &File)
Perform cross-module importing for the module identified by ModuleIdentifier.
LLVM_ABI void emitImports(Module &Module, StringRef OutputName, ModuleSummaryIndex &Index, const lto::InputFile &File)
Compute and emit the imported files for module at ModulePath.
LLVM_ABI void internalize(Module &Module, ModuleSummaryIndex &Index, const lto::InputFile &File)
Perform internalization.
LLVM_ABI void gatherImportedSummariesForModule(Module &Module, ModuleSummaryIndex &Index, ModuleToSummariesForIndexTy &ModuleToSummariesForIndex, GVSummaryPtrSet &DecSummaries, const lto::InputFile &File)
Compute the list of summaries and the subset of declaration summaries needed for importing into modul...
LLVM_ABI void promote(Module &Module, ModuleSummaryIndex &Index, const lto::InputFile &File)
Perform promotion and renaming of exported internal functions, and additionally resolve weak and link...
LLVM_ABI std::string writeGeneratedObject(int count, StringRef CacheEntryPath, const MemoryBuffer &OutputBuffer)
Write temporary object file to SavedObjectDirectoryPath, write symlink to Cache directory if needed.
Interfaces for registering analysis passes, producing common pass manager configurations,...
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
ThinLTOCodeGeneratorImpl - Namespace used for ThinLTOCodeGenerator implementation details.
initializer< Ty > init(const Ty &Val)
LLVM_ABI std::optional< bool > getExplicitDataSections()
LLVM_ABI StringLiteral getThinLTODefaultCPU(const Triple &TheTriple)
Definition LTO.cpp:1911
LLVM_ABI Expected< LLVMRemarkFileHandle > setupLLVMOptimizationRemarks(LLVMContext &Context, StringRef RemarksFilename, StringRef RemarksPasses, StringRef RemarksFormat, bool RemarksWithHotness, std::optional< uint64_t > RemarksHotnessThreshold=0, int Count=-1)
Setup optimization remarks.
Definition LTO.cpp:2342
LLVM_ABI std::vector< int > generateModulesOrdering(ArrayRef< BitcodeModule * > R)
Produces a container ordering for optimal multi-threaded processing.
Definition LTO.cpp:2386
LLVM_ABI std::error_code closeFile(file_t &F)
Close the file object.
LLVM_ABI std::error_code create_hard_link(const Twine &to, const Twine &from)
Create a hard link from from to to, or return an error.
LLVM_ABI bool exists(const basic_file_status &status)
Does file exist?
Definition Path.cpp:1107
@ OF_UpdateAtime
Force files Atime to be updated on access.
Definition FileSystem.h:817
LLVM_ABI std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
LLVM_ABI Expected< file_t > openNativeFileForRead(const Twine &Name, OpenFlags Flags=OF_None, SmallVectorImpl< char > *RealPath=nullptr)
Opens the file with the given name in a read-only mode, returning its open file descriptor.
LLVM_ABI std::error_code create_directories(const Twine &path, bool IgnoreExisting=true, perms Perms=owner_all|group_all)
Create all the non-existent directories in path.
Definition Path.cpp:993
LLVM_ABI std::error_code copy_file(const Twine &From, const Twine &To)
Copy the contents of From to To.
Definition Path.cpp:1042
LLVM_ABI bool is_directory(const basic_file_status &status)
Does status represent a directory?
Definition Path.cpp:1122
LLVM_ABI void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition Path.cpp:467
This is an optimization pass for GlobalISel generic memory operations.
ThreadPoolStrategy heavyweight_hardware_concurrency(unsigned ThreadCount=0)
Returns a thread strategy for tasks requiring significant memory or other resources.
Definition Threading.h:167
LLVM_ABI void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner={})
Log all errors (if any) in E to OS.
Definition Error.cpp:61
cl::opt< std::string > RemarksFormat("lto-pass-remarks-format", cl::desc("The format used for serializing remarks (default: YAML)"), cl::value_desc("format"), cl::init("yaml"))
LLVM_ABI void runWholeProgramDevirtOnIndex(ModuleSummaryIndex &Summary, std::set< GlobalValue::GUID > &ExportedGUIDs, std::map< ValueInfo, std::vector< VTableSlotSummary > > &LocalWPDTargetsMap, DenseSet< StringRef > *ExternallyVisibleSymbolNamesPtr=nullptr)
Perform index-based whole program devirtualization on the Summary index.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1755
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
cl::opt< bool > LTODiscardValueNames("lto-discard-value-names", cl::desc("Strip names from Value during LTO (other than GlobalValue)."), cl::init(false), cl::Hidden)
LLVM_ABI void WriteBitcodeToFile(const Module &M, raw_ostream &Out, bool ShouldPreserveUseListOrder=false, const ModuleSummaryIndex *Index=nullptr, bool GenerateHash=false, ModuleHash *ModHash=nullptr)
Write the specified module to the specified raw output stream.
cl::opt< std::string > RemarksPasses("lto-pass-remarks-filter", cl::desc("Only record optimization remarks from passes whose " "names match the given regular expression"), cl::value_desc("regex"))
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
Definition Error.h:1013
SmallVectorImpl< T >::const_pointer c_str(SmallVectorImpl< T > &str)
DenseMap< GlobalValue::GUID, GlobalValueSummary * > GVSummaryMapTy
Map of global value GUID to its summary, used to identify values defined in a particular module,...
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
Definition STLExtras.h:2224
@ O1
Optimize quickly without destroying debuggability.
@ O0
Disable as many optimizations as possible.
@ O3
Optimize for fast execution as much as possible.
@ O2
Optimize for fast execution as much as possible without triggering significant incremental compile ti...
LLVM_ABI bool thinLTOPropagateFunctionAttrs(ModuleSummaryIndex &Index, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing)
Propagate function attributes for function summaries along the index's callgraph during thinlink.
LLVM_ABI void renameModuleForThinLTO(Module &M, const ModuleSummaryIndex &Index, bool ClearDSOLocalOnDeclarations, SetVector< GlobalValue * > *GlobalsToImport=nullptr)
Perform in-place global value handling on the given Module for exported local functions renamed and p...
LLVM_ABI ModuleSummaryIndex buildModuleSummaryIndex(const Module &M, std::function< BlockFrequencyInfo *(const Function &F)> GetBFICallback, ProfileSummaryInfo *PSI, std::function< const StackSafetyInfo *(const Function &F)> GetSSICallback=[](const Function &F) -> const StackSafetyInfo *{ return nullptr;})
Direct function to compute a ModuleSummaryIndex from a given module.
LLVM_ABI void reportAndResetTimings(raw_ostream *OutStream=nullptr)
If -time-passes has been specified, report the timings immediately and then reset the timers to zero.
LLVM_ABI bool hasWholeProgramVisibility(bool WholeProgramVisibilityEnabledInLTO)
AnalysisManager< LazyCallGraph::SCC, LazyCallGraph & > CGSCCAnalysisManager
The CGSCC analysis manager.
LLVM_ABI void writeIndexToFile(const ModuleSummaryIndex &Index, raw_ostream &Out, const ModuleToSummariesForIndexTy *ModuleToSummariesForIndex=nullptr, const GVSummaryPtrSet *DecSummaries=nullptr)
Write the specified module summary index to the given raw output stream, where it will be written in ...
AnalysisManager< Loop, LoopStandardAnalysisResults & > LoopAnalysisManager
The loop analysis manager.
LLVM_ABI void ComputeCrossModuleImport(const ModuleSummaryIndex &Index, const DenseMap< StringRef, GVSummaryMapTy > &ModuleToDefinedGVSummaries, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, FunctionImporter::ImportListsTy &ImportLists, DenseMap< StringRef, FunctionImporter::ExportSetTy > &ExportLists)
Compute all the imports and exports for every module in the Index.
LLVM_ABI void updateIndexWPDForExports(ModuleSummaryIndex &Summary, function_ref< bool(StringRef, ValueInfo)> isExported, std::map< ValueInfo, std::vector< VTableSlotSummary > > &LocalWPDTargetsMap, DenseSet< StringRef > *ExternallyVisibleSymbolNamesPtr=nullptr)
Call after cross-module importing to update the recorded single impl devirt target names for any loca...
auto formatv(bool Validate, const char *Fmt, Ts &&...Vals)
LLVM_ABI void updatePublicTypeTestCalls(Module &M, bool WholeProgramVisibilityEnabledInLTO)
cl::opt< std::string > LTOCSIRProfile("cs-profile-path", cl::desc("Context sensitive profile file path"))
PassManager< Module > ModulePassManager
Convenience typedef for a pass manager over modules.
bool timeTraceProfilerEnabled()
Is the time trace profiler enabled, i.e. initialized?
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
LLVM_ABI Error writeToOutput(StringRef OutputFileName, std::function< Error(raw_ostream &)> Write)
This helper creates an output stream and then passes it to Write.
LLVM_ABI bool AreStatisticsEnabled()
Check if statistics are enabled.
std::map< std::string, GVSummaryMapTy, std::less<> > ModuleToSummariesForIndexTy
Map of a module name to the GUIDs and summaries we will import from that module.
cl::opt< bool > RemarksWithHotness("lto-pass-remarks-with-hotness", cl::desc("With PGO, include profile count in optimization remarks"), cl::Hidden)
LLVM_ABI void timeTraceProfilerEnd()
Manually end the last time section.
cl::opt< std::string > RemarksFilename("lto-pass-remarks-output", cl::desc("Output filename for pass remarks"), cl::value_desc("filename"))
LLVM_ABI void thinLTOResolvePrevailingInIndex(const lto::Config &C, ModuleSummaryIndex &Index, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, function_ref< void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)> recordNewLinkage, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols)
Resolve linkage for prevailing symbols in the Index.
Definition LTO.cpp:492
cl::opt< bool > LTORunCSIRInstr("cs-profile-generate", cl::desc("Perform context sensitive PGO instrumentation"))
LLVM_ATTRIBUTE_VISIBILITY_DEFAULT AnalysisKey InnerAnalysisManagerProxy< AnalysisManagerT, IRUnitT, ExtraArgTs... >::Key
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
LLVM_ABI bool StripDebugInfo(Module &M)
Strip debug info in the module if it exists.
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
LLVM_ABI void PrintStatistics()
Print statistics to the file returned by CreateInfoOutputFile().
LLVM_ABI void thinLTOInternalizeModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals)
Internalize TheModule based on the information recorded in the summaries during global summary-based ...
auto count(R &&Range, const E &Element)
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition STLExtras.h:2028
SingleThreadExecutor DefaultThreadPool
Definition ThreadPool.h:262
LLVM_ABI void gatherImportedSummariesForModule(StringRef ModulePath, const DenseMap< StringRef, GVSummaryMapTy > &ModuleToDefinedGVSummaries, const FunctionImporter::ImportMapTy &ImportList, ModuleToSummariesForIndexTy &ModuleToSummariesForIndex, GVSummaryPtrSet &DecSummaries)
Compute the set of summaries needed for a ThinLTO backend compilation of ModulePath.
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
DiagnosticSeverity
Defines the different supported severity of a diagnostic.
cl::opt< std::optional< uint64_t >, false, remarks::HotnessThresholdParser > RemarksHotnessThreshold("lto-pass-remarks-hotness-threshold", cl::desc("Minimum profile count required for an " "optimization remark to be output." " Use 'auto' to apply the threshold from profile summary."), cl::value_desc("uint or 'auto'"), cl::init(0), cl::Hidden)
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition STLExtras.h:1788
LLVM_ABI std::string computeLTOCacheKey(const lto::Config &Conf, const ModuleSummaryIndex &Index, StringRef ModuleID, const FunctionImporter::ImportMapTy &ImportList, const FunctionImporter::ExportSetTy &ExportList, const std::map< GlobalValue::GUID, GlobalValue::LinkageTypes > &ResolvedODR, const GVSummaryMapTy &DefinedGlobals, const DenseSet< GlobalValue::GUID > &CfiFunctionDefs={}, const DenseSet< GlobalValue::GUID > &CfiFunctionDecls={})
Computes a unique hash for the Module considering the current list of export/import and other global ...
Definition LTO.cpp:136
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
SmallPtrSet< GlobalValueSummary *, 0 > GVSummaryPtrSet
A set of global value summary pointers.
LLVM_ABI Expected< bool > pruneCache(StringRef Path, CachePruningPolicy Policy, const std::vector< std::unique_ptr< MemoryBuffer > > &Files={})
Perform pruning using the supplied policy, returns true if pruning occurred, i.e.
LLVM_ABI std::error_code errorToErrorCode(Error Err)
Helper for converting an ECError to a std::error_code.
Definition Error.cpp:113
LLVM_ABI void computeDeadSymbolsWithConstProp(ModuleSummaryIndex &Index, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols, function_ref< PrevailingType(GlobalValue::GUID)> isPrevailing, bool ImportEnabled)
Compute dead symbols and run constant propagation in combined index after that.
LLVM_ABI Error write(DWPWriter &Out, ArrayRef< std::string > Inputs, OnCuIndexOverflow OverflowOptValue, Dwarf64StrOffsetsPromotion StrOffsetsOptValue, raw_pwrite_stream *OS=nullptr)
Definition DWP.cpp:746
LLVM_ABI Error EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename, const ModuleToSummariesForIndexTy &ModuleToSummariesForIndex)
Emit into OutputFilename the files module ModulePath will import from.
LLVM_ABI bool verifyModule(const Module &M, raw_ostream *OS=nullptr, bool *BrokenDebugInfo=nullptr)
Check a module for errors.
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
LLVM_ABI TimeTraceProfilerEntry * timeTraceProfilerBegin(StringRef Name, StringRef Detail)
Manually begin a time section, with the given Name and Detail.
LLVM_ABI void thinLTOInternalizeAndPromoteInIndex(ModuleSummaryIndex &Index, function_ref< bool(StringRef, ValueInfo)> isExported, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, DenseSet< StringRef > *ExternallyVisibleSymbolNamesPtr=nullptr)
Update the linkages in the given Index to mark exported values as external and non-exported values as...
Definition LTO.cpp:610
LLVM_ABI void updateVCallVisibilityInIndex(ModuleSummaryIndex &Index, bool WholeProgramVisibilityEnabledInLTO, const DenseSet< GlobalValue::GUID > &DynamicExportSymbols, const DenseSet< GlobalValue::GUID > &VisibleToRegularObjSymbols)
If whole program visibility asserted, then upgrade all public vcall visibility metadata on vtable def...
cl::opt< std::string > SampleProfileFile
LLVM_ABI void thinLTOFinalizeInModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals, bool PropagateAttrs)
Based on the information recorded in the summaries during global summary-based analysis:
A struct capturing PGO tunables.
Definition PGOOptions.h:22
A simple container for information about the supported runtime calls.
static LLVM_ABI const Target * lookupTarget(const Triple &TheTriple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
Helper to gather options relevant to the target machine creation.
LLVM_ABI std::unique_ptr< TargetMachine > create() const
Struct that holds a reference to a particular GUID in a global value summary.
LTO configuration.
Definition Config.h:44
std::vector< std::string > MAttrs
Definition Config.h:56
std::vector< std::string > MllvmArgs
Definition Config.h:57
CodeGenOptLevel CGOptLevel
Definition Config.h:69
std::string CPU
Definition Config.h:54
TargetOptions Options
Definition Config.h:55
unsigned OptLevel
Definition Config.h:71
std::optional< Reloc::Model > RelocModel
Definition Config.h:67
bool Freestanding
Flag to indicate that the optimizer should not assume builtins are present on the target.
Definition Config.h:77