LLVM 24.0.0git
LTOBackend.cpp
Go to the documentation of this file.
1//===-LTOBackend.cpp - LLVM Link Time Optimizer Backend -------------------===//
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 "backend" phase of LTO, i.e. it performs
10// optimization and code generation on a loaded module. It is generally used
11// internally by the LTO class but can also be used independently, for example
12// to implement a standalone ThinLTO backend.
13//
14//===----------------------------------------------------------------------===//
15
16#include "llvm/LTO/LTOBackend.h"
27#include "llvm/IR/PassManager.h"
28#include "llvm/IR/Verifier.h"
29#include "llvm/LTO/LTO.h"
36#include "llvm/Support/Error.h"
39#include "llvm/Support/Path.h"
49#include <optional>
50
51using namespace llvm;
52using namespace lto;
53
54#define DEBUG_TYPE "lto-backend"
55
61
63 "lto-embed-bitcode", cl::init(LTOBitcodeEmbedding::DoNotEmbed),
65 "Do not embed"),
67 "Embed after all optimization passes"),
69 "post-merge-pre-opt",
70 "Embed post merge, but before optimizations")),
71 cl::desc("Embed LLVM bitcode in object files produced by LTO"));
72
74 "thinlto-assume-merged", cl::init(false),
75 cl::desc("Assume the input has already undergone ThinLTO function "
76 "importing and the other pre-optimization pipeline changes."));
77
79 SaveModulesList("filter-save-modules", cl::value_desc("module names"),
80 cl::desc("Only save bitcode for module whose name without "
81 "path matches this for -save-temps options"),
83
84namespace llvm {
86}
87
88[[noreturn]] static void reportOpenError(StringRef Path, Twine Msg) {
89 errs() << "failed to open " << Path << ": " << Msg << '\n';
90 errs().flush();
91 exit(1);
92}
93
94Error Config::addSaveTemps(std::string OutputFileName, bool UseInputModulePath,
95 const DenseSet<StringRef> &SaveTempsArgs) {
97
98 std::error_code EC;
99 if (SaveTempsArgs.empty() || SaveTempsArgs.contains("resolution")) {
101 std::make_unique<raw_fd_ostream>(OutputFileName + "resolution.txt", EC,
103 if (EC) {
104 ResolutionFile.reset();
105 return errorCodeToError(EC);
106 }
107 }
108
109 auto setHook = [&](std::string PathSuffix, ModuleHookFn &Hook) {
110 // Keep track of the hook provided by the linker, which also needs to run.
111 ModuleHookFn LinkerHook = Hook;
112 Hook = [=, SaveModNames = llvm::SmallVector<std::string, 1>(
113 SaveModulesList.begin(), SaveModulesList.end())](
114 unsigned Task, const Module &M) {
115 // If SaveModulesList is not empty, only do save-temps if the module's
116 // filename (without path) matches a name in the list.
117 if (!SaveModNames.empty() &&
119 SaveModNames,
120 std::string(llvm::sys::path::filename(M.getName()))))
121 return false;
122
123 // If the linker's hook returned false, we need to pass that result
124 // through.
125 if (LinkerHook && !LinkerHook(Task, M))
126 return false;
127
128 std::string PathPrefix;
129 // If this is the combined module (not a ThinLTO backend compile) or the
130 // user hasn't requested using the input module's path, emit to a file
131 // named from the provided OutputFileName with the Task ID appended.
132 if (M.getModuleIdentifier() == "ld-temp.o" || !UseInputModulePath) {
133 PathPrefix = OutputFileName;
134 if (Task != (unsigned)-1)
135 PathPrefix += utostr(Task) + ".";
136 } else
137 PathPrefix = M.getModuleIdentifier() + ".";
138 std::string Path = PathPrefix + PathSuffix + ".bc";
139 std::error_code EC;
141 // Because -save-temps is a debugging feature, we report the error
142 // directly and exit.
143 if (EC)
144 reportOpenError(Path, EC.message());
145 WriteBitcodeToFile(M, OS, /*ShouldPreserveUseListOrder=*/false);
146 return true;
147 };
148 };
149
150 auto SaveCombinedIndex =
151 [=](const ModuleSummaryIndex &Index,
152 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
153 std::string Path = OutputFileName + "index.bc";
154 std::error_code EC;
156 // Because -save-temps is a debugging feature, we report the error
157 // directly and exit.
158 if (EC)
159 reportOpenError(Path, EC.message());
160 writeIndexToFile(Index, OS);
161
162 Path = OutputFileName + "index.dot";
164 if (EC)
165 reportOpenError(Path, EC.message());
166 Index.exportToDot(OSDot, GUIDPreservedSymbols);
167 return true;
168 };
169
170 if (SaveTempsArgs.empty()) {
171 setHook("0.preopt", PreOptModuleHook);
172 setHook("1.promote", PostPromoteModuleHook);
173 setHook("2.internalize", PostInternalizeModuleHook);
174 setHook("3.import", PostImportModuleHook);
175 setHook("4.opt", PostOptModuleHook);
176 setHook("5.precodegen", PreCodeGenModuleHook);
177 CombinedIndexHook = SaveCombinedIndex;
178 } else {
179 if (SaveTempsArgs.contains("preopt"))
180 setHook("0.preopt", PreOptModuleHook);
181 if (SaveTempsArgs.contains("promote"))
182 setHook("1.promote", PostPromoteModuleHook);
183 if (SaveTempsArgs.contains("internalize"))
184 setHook("2.internalize", PostInternalizeModuleHook);
185 if (SaveTempsArgs.contains("import"))
186 setHook("3.import", PostImportModuleHook);
187 if (SaveTempsArgs.contains("opt"))
188 setHook("4.opt", PostOptModuleHook);
189 if (SaveTempsArgs.contains("precodegen"))
190 setHook("5.precodegen", PreCodeGenModuleHook);
191 if (SaveTempsArgs.contains("combinedindex"))
192 CombinedIndexHook = SaveCombinedIndex;
193 }
194
195 return Error::success();
196}
197
198#define HANDLE_EXTENSION(Ext) \
199 llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
200#include "llvm/Support/Extension.def"
201#undef HANDLE_EXTENSION
202
204 // lto::LTO::run() loaded plugins requested by file. Direct callers must pass
205 // them pre-loaded.
206 assert(Conf.PassPluginFilenames.empty() &&
207 "Pass-plugins must be loaded before running LTO backends");
208 return Conf.LoadedPassPlugins;
209}
210
211// Call pass builder registration callbacks for all pass-plugins
212static void RegisterPassPlugins(const Config &Conf, PassBuilder &PB) {
213 // Static built-in plugins
214#define HANDLE_EXTENSION(Ext) \
215 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
216#include "llvm/Support/Extension.def"
217#undef HANDLE_EXTENSION
218
219 // Dynamic plugins
220 for (const PassPlugin *Plugin : getPassPlugins(Conf))
221 Plugin->registerPassBuilderCallbacks(PB);
222}
223
224static std::unique_ptr<TargetMachine>
225createTargetMachine(const Config &Conf, const Target *TheTarget, Module &M) {
226 const Triple &TheTriple = M.getTargetTriple();
227 SubtargetFeatures Features;
228 Features.getDefaultSubtargetFeatures(TheTriple);
229 for (const std::string &A : Conf.MAttrs)
230 Features.AddFeature(A);
231
232 std::optional<Reloc::Model> RelocModel;
233 if (Conf.RelocModel)
234 RelocModel = *Conf.RelocModel;
235 else if (M.getModuleFlag("PIC Level"))
236 RelocModel =
237 M.getPICLevel() == PICLevel::NotPIC ? Reloc::Static : Reloc::PIC_;
238
239 std::optional<CodeModel::Model> CodeModel;
240 if (Conf.CodeModel)
241 CodeModel = *Conf.CodeModel;
242 else
243 CodeModel = M.getCodeModel();
244
245 TargetOptions TargetOpts = Conf.Options;
246 if (TargetOpts.MCOptions.ABIName.empty()) {
247 TargetOpts.MCOptions.ABIName = M.getTargetABIFromMD();
248 }
249 TargetOpts.MCOptions.LibraryOptions = &M.getContext().getLibraryOptions();
250
251 std::unique_ptr<TargetMachine> TM(TheTarget->createTargetMachine(
252 TheTriple, Conf.CPU, Features.getString(), TargetOpts, RelocModel,
253 CodeModel, Conf.CGOptLevel));
254
255 assert(TM && "Failed to create target machine");
256
257 if (std::optional<uint64_t> LargeDataThreshold = M.getLargeDataThreshold())
258 TM->setLargeDataThreshold(*LargeDataThreshold);
259
260 return TM;
261}
262
263static void runNewPMPasses(const Config &Conf, Module &Mod, TargetMachine *TM,
264 unsigned OptLevel, bool IsThinLTO,
265 ModuleSummaryIndex *ExportSummary,
266 const ModuleSummaryIndex *ImportSummary,
267 const DenseSet<StringRef> &BitcodeLibFuncs) {
268 std::optional<PGOOptions> PGOOpt;
269 if (!Conf.SampleProfile.empty())
270 PGOOpt = PGOOptions(Conf.SampleProfile, "", Conf.ProfileRemapping,
271 /*MemoryProfile=*/"", PGOOptions::SampleUse,
274 else if (Conf.RunCSIRInstr) {
275 PGOOpt = PGOOptions("", Conf.CSIRProfile, Conf.ProfileRemapping,
276 /*MemoryProfile=*/"", PGOOptions::IRUse,
278 Conf.AddFSDiscriminator);
279 } else if (!Conf.CSIRProfile.empty()) {
280 PGOOpt =
282 /*MemoryProfile=*/"", PGOOptions::IRUse, PGOOptions::CSIRUse,
285 } else if (Conf.AddFSDiscriminator) {
286 PGOOpt = PGOOptions("", "", "", /*MemoryProfile=*/"", PGOOptions::NoAction,
289 }
290 TM->setPGOOption(PGOOpt);
291
296
299 Conf.VerifyEach);
300 SI.registerCallbacks(PIC, &MAM);
301 PassBuilder PB(Mod.getContext(), TM, Conf.PTO, PGOOpt, &PIC);
302
303 RegisterPassPlugins(Conf, PB);
304
305 std::unique_ptr<TargetLibraryInfoImpl> TLII(
307 if (Conf.Freestanding)
308 TLII->disableAllFunctions();
309
310 // Determine whether or not its safe to emit calls to each libfunc. Libfuncs
311 // that might have been present in the current LTO unit, but are not, have
312 // lost their only opportunity to be defined, and calls must not be emitted to
313 // them.
314 // FIXME: BitcodeLibFuncs isn't yet set for distributed ThinLTO.
315 TargetLibraryInfo TLI(*TLII);
316 for (unsigned I = 0, E = static_cast<unsigned>(LibFunc::NumLibFuncs); I != E;
317 ++I) {
318 LibFunc F = static_cast<LibFunc>(I);
319 if (BitcodeLibFuncs.contains(TLI.getName(F)))
320 TLII->setUnavailable(F);
321 }
322
323 FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
324
325 // Parse a custom AA pipeline if asked to.
326 if (!Conf.AAPipeline.empty()) {
328 if (auto Err = PB.parseAAPipeline(AA, Conf.AAPipeline)) {
329 report_fatal_error(Twine("unable to parse AA pipeline description '") +
330 Conf.AAPipeline + "': " + toString(std::move(Err)));
331 }
332 // Register the AA manager first so that our version is the one used.
333 FAM.registerPass([&] { return std::move(AA); });
334 }
335
336 // Register all the basic analyses with the managers.
337 PB.registerModuleAnalyses(MAM);
338 PB.registerCGSCCAnalyses(CGAM);
339 PB.registerFunctionAnalyses(FAM);
340 PB.registerLoopAnalyses(LAM);
341 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
342
343 if (Conf.PassBuilderCallback)
345
347
348 if (!Conf.DisableVerify)
349 MPM.addPass(VerifierPass());
350
352
353 switch (OptLevel) {
354 default:
355 llvm_unreachable("Invalid optimization level");
356 case 0:
358 break;
359 case 1:
361 break;
362 case 2:
364 break;
365 case 3:
367 break;
368 }
369
370 // Parse a custom pipeline if asked to.
371 if (!Conf.OptPipeline.empty()) {
372 if (auto Err = PB.parsePassPipeline(MPM, Conf.OptPipeline)) {
373 report_fatal_error(Twine("unable to parse pass pipeline description '") +
374 Conf.OptPipeline + "': " + toString(std::move(Err)));
375 }
376 } else if (IsThinLTO) {
377 MPM.addPass(PB.buildThinLTODefaultPipeline(OL, ImportSummary));
378 } else {
379 MPM.addPass(PB.buildLTODefaultPipeline(OL, ExportSummary));
380 }
381
382 if (!Conf.DisableVerify)
383 MPM.addPass(VerifierPass());
384
385 if (PB.getPrintPipelinePasses()) {
386 std::string PipelineStr;
387 raw_string_ostream OS(PipelineStr);
388 MPM.printPipeline(OS, [&PIC](StringRef ClassName) {
389 auto PassName = PIC.getPassNameForClassName(ClassName);
390 return PassName.empty() ? ClassName : PassName;
391 });
392 outs() << "pipeline-passes: " << PipelineStr << '\n';
393 }
394
395 MPM.run(Mod, MAM);
396}
397
398static bool isEmptyModule(const Module &Mod) {
399 // Module is empty if it has no functions, no globals, no inline asm and no
400 // named metadata (aliases and ifuncs require functions or globals so we
401 // don't need to check those explicitly).
402 return Mod.empty() && Mod.global_empty() && Mod.named_metadata_empty() &&
403 Mod.getModuleInlineAsm().empty();
404}
405
406bool lto::opt(const Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
407 bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
408 const ModuleSummaryIndex *ImportSummary,
409 const std::vector<uint8_t> &CmdArgs,
410 ArrayRef<StringRef> BitcodeLibFuncs) {
411 llvm::TimeTraceScope timeScope("opt");
413 // FIXME: the motivation for capturing post-merge bitcode and command line
414 // is replicating the compilation environment from bitcode, without needing
415 // to understand the dependencies (the functions to be imported). This
416 // assumes a clang - based invocation, case in which we have the command
417 // line.
418 // It's not very clear how the above motivation would map in the
419 // linker-based case, so we currently don't plumb the command line args in
420 // that case.
421 if (CmdArgs.empty())
423 dbgs() << "Post-(Thin)LTO merge bitcode embedding was requested, but "
424 "command line arguments are not available");
426 /*EmbedBitcode*/ true, /*EmbedCmdline*/ true,
427 /*Cmdline*/ CmdArgs);
428 }
429 // No need to run any opt passes if the module is empty.
430 // In theory these passes should take almost no time for an empty
431 // module, however, this guards against doing any unnecessary summary-based
432 // analysis in the case of a ThinLTO build where this might be an empty
433 // regular LTO combined module, with a large combined index from ThinLTO.
434 if (!isEmptyModule(Mod)) {
435 DenseSet<StringRef> BitcodeLibFuncsSet(BitcodeLibFuncs.begin(),
436 BitcodeLibFuncs.end());
437 // FIXME: Plumb the combined index into the new pass manager.
438 runNewPMPasses(Conf, Mod, TM, Conf.OptLevel, IsThinLTO, ExportSummary,
439 ImportSummary, BitcodeLibFuncsSet);
440 }
441 return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
442}
443
444static void codegen(const Config &Conf, TargetMachine *TM,
445 AddStreamFn AddStream, unsigned Task, Module &Mod,
446 const ModuleSummaryIndex &CombinedIndex) {
447 llvm::TimeTraceScope timeScope("codegen");
448 if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
449 return;
450
453 /*EmbedBitcode*/ true,
454 /*EmbedCmdline*/ false,
455 /*CmdArgs*/ std::vector<uint8_t>());
456
458 if (!Conf.DwoDir.empty()) {
459 DwoFile = Conf.DwoDir;
460 sys::path::append(DwoFile, std::to_string(Task) + ".dwo");
461 TM->Options.MCOptions.SplitDwarfFile = std::string(DwoFile);
462 } else
464
466 AddStream(Task, Mod.getModuleIdentifier());
467 if (Error Err = StreamOrErr.takeError())
468 report_fatal_error(std::move(Err));
469 std::unique_ptr<CachedFileStream> &Stream = *StreamOrErr;
470 TM->Options.ObjectFilenameForDebug = Stream->ObjectPathName;
471
472 std::unique_ptr<ToolOutputFile> DwoOut;
473 if (!DwoFile.empty()) {
474 if (!Conf.DwoDir.empty())
475 if (auto EC = llvm::sys::fs::create_directories(Conf.DwoDir))
476 report_fatal_error(Twine("Failed to create directory ") + Conf.DwoDir +
477 ": " + EC.message());
478
479 std::error_code EC;
480 DwoOut = std::make_unique<ToolOutputFile>(DwoFile, EC, sys::fs::OF_None);
481 if (EC)
482 report_fatal_error(Twine("Failed to open ") + DwoFile + ": " +
483 EC.message());
484 }
485
486 const ModuleSummaryIndex *MSI =
487 !isEmptyModule(Mod) ? &CombinedIndex : nullptr;
488
489 // Allow plugins to handle or even take over code generation entirely.
490 for (const PassPlugin *Plugin : getPassPlugins(Conf)) {
491 if (Plugin->invokePreCodeGenCallback(
492 *TM, Mod, *Stream->OS, DwoOut ? &DwoOut->os() : nullptr,
493 Conf.CGFileType, /*DisableVerify=*/true,
494 /*DisableSimplifyLibCalls=*/false, MSI, vfs::getRealFileSystem())) {
495 if (DwoOut)
496 DwoOut->keep();
497 if (Error Err = Stream->commit())
498 report_fatal_error(std::move(Err));
499 return;
500 }
501 }
502
503 if (runCodeGenPipeline(*TM, Mod, *Stream->OS,
504 DwoOut ? &DwoOut->os() : nullptr, Conf.CGFileType,
505 /*DisableVerify=*/true,
506 /*DisableSimplifyLibCalls=*/false, MSI))
507 report_fatal_error("Failed to run codegen");
508 if (DwoOut)
509 DwoOut->keep();
510
511 if (Error Err = Stream->commit())
512 report_fatal_error(std::move(Err));
513}
514
515static void splitCodeGen(const Config &C, TargetMachine *TM,
516 AddStreamFn AddStream,
517 unsigned ParallelCodeGenParallelismLevel, Module &Mod,
518 const ModuleSummaryIndex &CombinedIndex) {
519 DefaultThreadPool CodegenThreadPool(
520 heavyweight_hardware_concurrency(ParallelCodeGenParallelismLevel));
521 unsigned ThreadCount = 0;
522 const Target *T = &TM->getTarget();
523
524 const auto HandleModulePartition =
525 [&](std::unique_ptr<Module> MPart) {
526 // We want to clone the module in a new context to multi-thread the
527 // codegen. We do it by serializing partition modules to bitcode
528 // (while still on the main thread, in order to avoid data races) and
529 // spinning up new threads which deserialize the partitions into
530 // separate contexts.
531 // FIXME: Provide a more direct way to do this in LLVM.
533 raw_svector_ostream BCOS(BC);
534 WriteBitcodeToFile(*MPart, BCOS);
535
536 // Enqueue the task
537 CodegenThreadPool.async(
538 [&](const SmallString<0> &BC, unsigned ThreadId) {
539 LTOLLVMContext Ctx(C);
541 parseBitcodeFile(MemoryBufferRef(BC.str(), "ld-temp.o"), Ctx);
542 if (!MOrErr)
543 report_fatal_error("Failed to read bitcode");
544 std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
545
546 std::unique_ptr<TargetMachine> TM =
547 createTargetMachine(C, T, *MPartInCtx);
548
549 codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx,
550 CombinedIndex);
551 },
552 // Pass BC using std::move to ensure that it get moved rather than
553 // copied into the thread's context.
554 std::move(BC), ThreadCount++);
555 };
556
557 // Try target-specific module splitting first, then fallback to the default.
558 if (!TM->splitModule(Mod, ParallelCodeGenParallelismLevel,
559 HandleModulePartition)) {
560 SplitModule(Mod, ParallelCodeGenParallelismLevel, HandleModulePartition,
561 false);
562 }
563
564 // Because the inner lambda (which runs in a worker thread) captures our local
565 // variables, we need to wait for the worker threads to terminate before we
566 // can leave the function scope.
567 CodegenThreadPool.wait();
568}
569
571 Module &Mod) {
572 if (!C.OverrideTriple.empty())
573 Mod.setTargetTriple(Triple(C.OverrideTriple));
574 else if (Mod.getTargetTriple().empty())
575 Mod.setTargetTriple(Triple(C.DefaultTriple));
576
577 std::string Msg;
578 const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg);
579 if (!T)
581 return T;
582}
583
585 // Make sure we flush the diagnostic remarks file in case the linker doesn't
586 // call the global destructors before exiting.
587 if (!DiagOutputFile)
588 return Error::success();
589 DiagOutputFile.finalize();
590 DiagOutputFile->keep();
591 DiagOutputFile->os().flush();
592 return Error::success();
593}
594
596 unsigned ParallelCodeGenParallelismLevel, Module &Mod,
597 ModuleSummaryIndex &CombinedIndex,
598 ArrayRef<StringRef> BitcodeLibFuncs) {
599 llvm::TimeTraceScope timeScope("LTO backend");
601 if (!TOrErr)
602 return TOrErr.takeError();
603
604 std::unique_ptr<TargetMachine> TM = createTargetMachine(C, *TOrErr, Mod);
605
606 LLVM_DEBUG(dbgs() << "Running regular LTO\n");
607 if (!C.CodeGenOnly) {
608 if (!opt(C, TM.get(), 0, Mod, /*IsThinLTO=*/false,
609 /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr,
610 /*CmdArgs*/ std::vector<uint8_t>(), BitcodeLibFuncs))
611 return Error::success();
612 }
613
614 if (ParallelCodeGenParallelismLevel == 1) {
615 codegen(C, TM.get(), AddStream, 0, Mod, CombinedIndex);
616 } else {
617 splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel, Mod,
618 CombinedIndex);
619 }
620 return Error::success();
621}
622
623static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals,
624 const ModuleSummaryIndex &Index) {
625 llvm::TimeTraceScope timeScope("Drop dead symbols");
626 std::vector<GlobalValue*> DeadGVs;
627
628 for (auto &GV : Mod.global_values()) {
629 auto GUID = GV.getGUIDIfAssigned();
630 if (!GUID)
631 continue;
632
633 if (GlobalValueSummary *GVS = DefinedGlobals.lookup(*GUID))
634 if (!Index.isGlobalValueLive(GVS)) {
635 DeadGVs.push_back(&GV);
637 }
638 }
639
640 // Now that all dead bodies have been dropped, delete the actual objects
641 // themselves when possible.
642 for (GlobalValue *GV : DeadGVs) {
643 GV->removeDeadConstantUsers();
644 // Might reference something defined in native object (i.e. dropped a
645 // non-prevailing IR def, but we need to keep the declaration).
646 if (GV->use_empty())
647 GV->eraseFromParent();
648 }
649}
650
651Error lto::thinBackend(const Config &Conf, unsigned Task, AddStreamFn AddStream,
652 Module &Mod, const ModuleSummaryIndex &CombinedIndex,
653 const FunctionImporter::ImportMapTy &ImportList,
654 const GVSummaryMapTy &DefinedGlobals,
656 bool CodeGenOnly, ArrayRef<StringRef> BitcodeLibFuncs,
657 AddStreamFn IRAddStream,
658 const std::vector<uint8_t> &CmdArgs) {
659 llvm::TimeTraceScope timeScope("Thin backend", Mod.getModuleIdentifier());
661 if (!TOrErr)
662 return TOrErr.takeError();
663
664 std::unique_ptr<TargetMachine> TM = createTargetMachine(Conf, *TOrErr, Mod);
665
666 // Setup optimization remarks.
667 auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
668 Mod.getContext(), Conf.RemarksFilename, Conf.RemarksPasses,
670 Task);
671 if (!DiagFileOrErr)
672 return DiagFileOrErr.takeError();
673 auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
674
675 // Set the partial sample profile ratio in the profile summary module flag of
676 // the module, if applicable.
677 Mod.setPartialSampleProfileRatio(CombinedIndex);
678
679 LLVM_DEBUG(dbgs() << "Running ThinLTO\n");
680 if (CodeGenOnly) {
681 // If CodeGenOnly is set, we only perform code generation and skip
682 // optimization. This value may differ from Conf.CodeGenOnly.
683 codegen(Conf, TM.get(), AddStream, Task, Mod, CombinedIndex);
684 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
685 }
686
687 if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
688 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
689
690 auto OptimizeAndCodegen =
691 [&](Module &Mod, TargetMachine *TM,
692 LLVMRemarkFileHandle DiagnosticOutputFile) {
693 // Perform optimization and code generation for ThinLTO.
694 if (!opt(Conf, TM, Task, Mod, /*IsThinLTO=*/true,
695 /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex,
696 CmdArgs, BitcodeLibFuncs))
697 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
698
699 // Save the current module before the first codegen round.
700 // Note that the second codegen round runs only `codegen()` without
701 // running `opt()`. We're not reaching here as it's bailed out earlier
702 // with `CodeGenOnly` which has been set in `SecondRoundThinBackend`.
703 if (IRAddStream)
704 cgdata::saveModuleForTwoRounds(Mod, Task, IRAddStream);
705
706 codegen(Conf, TM, AddStream, Task, Mod, CombinedIndex);
707 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
708 };
709
711 return OptimizeAndCodegen(Mod, TM.get(), std::move(DiagnosticOutputFile));
712
713 // When linking an ELF shared object, dso_local should be dropped. We
714 // conservatively do this for -fpic.
715 bool ClearDSOLocalOnDeclarations =
716 Mod.getTargetTriple().isOSBinFormatELF() &&
717 TM->getRelocationModel() != Reloc::Static &&
718 Mod.getPIELevel() == PIELevel::Default;
719 renameModuleForThinLTO(Mod, CombinedIndex, ClearDSOLocalOnDeclarations);
720
721 dropDeadSymbols(Mod, DefinedGlobals, CombinedIndex);
722
723 thinLTOFinalizeInModule(Mod, DefinedGlobals, /*PropagateAttrs=*/true);
724
725 if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
726 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
727
728 if (!DefinedGlobals.empty())
729 thinLTOInternalizeModule(Mod, DefinedGlobals);
730
731 if (Conf.PostInternalizeModuleHook &&
732 !Conf.PostInternalizeModuleHook(Task, Mod))
733 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
734
735 auto ModuleLoader = [&](StringRef Identifier) {
736 llvm::TimeTraceScope moduleLoaderScope("Module loader", Identifier);
737 assert(Mod.getContext().isODRUniquingDebugTypes() &&
738 "ODR Type uniquing should be enabled on the context");
739 if (ModuleMap) {
740 auto I = ModuleMap->find(Identifier);
741 assert(I != ModuleMap->end());
742 return I->second.getLazyModule(Mod.getContext(),
743 /*ShouldLazyLoadMetadata=*/true,
744 /*IsImporting*/ true);
745 }
746
748 llvm::MemoryBuffer::getFile(Identifier);
749 if (!MBOrErr)
751 Twine("Error loading imported file ") + Identifier + " : ",
752 MBOrErr.getError()));
753
754 Expected<BitcodeModule> BMOrErr = findThinLTOModule(**MBOrErr);
755 if (!BMOrErr)
757 Twine("Error loading imported file ") + Identifier + " : " +
758 toString(BMOrErr.takeError()),
760
762 BMOrErr->getLazyModule(Mod.getContext(),
763 /*ShouldLazyLoadMetadata=*/true,
764 /*IsImporting*/ true);
765 if (MOrErr)
766 (*MOrErr)->setOwnedMemoryBuffer(std::move(*MBOrErr));
767 return MOrErr;
768 };
769
770 {
771 llvm::TimeTraceScope importScope("Import functions");
772 FunctionImporter Importer(CombinedIndex, ModuleLoader,
773 ClearDSOLocalOnDeclarations);
774 if (Error Err = Importer.importFunctions(Mod, ImportList).takeError())
775 return Err;
776 }
777
778 // Do this after any importing so that imported code is updated.
780 CombinedIndex.withSpeculativeDevirt());
781
782 if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
783 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
784
785 return OptimizeAndCodegen(Mod, TM.get(), std::move(DiagnosticOutputFile));
786}
787
789 if (ThinLTOAssumeMerged && BMs.size() == 1)
790 return BMs.begin();
791
792 for (BitcodeModule &BM : BMs) {
793 Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
794 if (LTOInfo && LTOInfo->IsThinLTO)
795 return &BM;
796 }
797 return nullptr;
798}
799
802 if (!BMsOrErr)
803 return BMsOrErr.takeError();
804
805 // The bitcode file may contain multiple modules, we want the one that is
806 // marked as being the ThinLTO module.
807 if (const BitcodeModule *Bm = lto::findThinLTOModule(*BMsOrErr))
808 return *Bm;
809
810 return make_error<StringError>("Could not find module summary",
812}
813
815 const ModuleSummaryIndex &CombinedIndex,
816 FunctionImporter::ImportMapTy &ImportList) {
818 return true;
819 // We can simply import the values mentioned in the combined index, since
820 // we should only invoke this using the individual indexes written out
821 // via a WriteIndexesThinBackend.
822 for (const auto &GlobalList : CombinedIndex) {
823 // Ignore entries for undefined references.
824 if (GlobalList.second.getSummaryList().empty())
825 continue;
826
827 auto GUID = GlobalList.first;
828 for (const auto &Summary : GlobalList.second.getSummaryList()) {
829 // Skip the summaries for the importing module. These are included to
830 // e.g. record required linkage changes.
831 if (Summary->modulePath() == M.getModuleIdentifier())
832 continue;
833 // Add an entry to provoke importing by thinBackend.
834 ImportList.addGUID(Summary->modulePath(), GUID, Summary->importType());
835 }
836 }
837 return true;
838}
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This header provides classes for managing passes over SCCs of the call graph.
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
This header defines various interfaces for pass management in LLVM.
static cl::opt< bool > ThinLTOAssumeMerged("thinlto-assume-merged", cl::init(false), cl::desc("Assume the input has already undergone ThinLTO function " "importing and the other pre-optimization pipeline changes."))
static std::unique_ptr< TargetMachine > createTargetMachine(const Config &Conf, const Target *TheTarget, Module &M)
static void reportOpenError(StringRef Path, Twine Msg)
static cl::list< std::string > SaveModulesList("filter-save-modules", cl::value_desc("module names"), cl::desc("Only save bitcode for module whose name without " "path matches this for -save-temps options"), cl::CommaSeparated, cl::Hidden)
LTOBitcodeEmbedding
static cl::opt< LTOBitcodeEmbedding > EmbedBitcode("lto-embed-bitcode", cl::init(LTOBitcodeEmbedding::DoNotEmbed), cl::values(clEnumValN(LTOBitcodeEmbedding::DoNotEmbed, "none", "Do not embed"), clEnumValN(LTOBitcodeEmbedding::EmbedOptimized, "optimized", "Embed after all optimization passes"), clEnumValN(LTOBitcodeEmbedding::EmbedPostMergePreOptimized, "post-merge-pre-opt", "Embed post merge, but before optimizations")), cl::desc("Embed LLVM bitcode in object files produced by LTO"))
static void RegisterPassPlugins(const Config &Conf, PassBuilder &PB)
static void splitCodeGen(const Config &C, TargetMachine *TM, AddStreamFn AddStream, unsigned ParallelCodeGenParallelismLevel, Module &Mod, const ModuleSummaryIndex &CombinedIndex)
static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals, const ModuleSummaryIndex &Index)
static Expected< const Target * > initAndLookupTarget(const Config &C, Module &Mod)
static void runNewPMPasses(const Config &Conf, Module &Mod, TargetMachine *TM, unsigned OptLevel, bool IsThinLTO, ModuleSummaryIndex *ExportSummary, const ModuleSummaryIndex *ImportSummary, const DenseSet< StringRef > &BitcodeLibFuncs)
static ArrayRef< PassPlugin * > getPassPlugins(const Config &Conf)
static bool isEmptyModule(const Module &Mod)
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
#define T
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
const char * Msg
This header defines a class that provides bookkeeping for all standard (i.e in-tree) pass instrumenta...
#define LLVM_DEBUG(...)
Definition Debug.h:119
static cl::opt< int > ThreadCount("threads", cl::init(0))
Defines the virtual file system interface vfs::FileSystem.
static const char PassName[]
A manager for alias analyses.
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
iterator end() const
Definition ArrayRef.h:130
size_t size() const
Get the array size.
Definition ArrayRef.h:141
iterator begin() const
Definition ArrayRef.h:129
Represents a module in a bitcode file.
bool empty() const
Definition DenseMap.h:716
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
Definition DenseMap.h:793
Implements a dense probed hash-table based set.
Definition DenseSet.h:283
Represents either an error or a value T.
Definition ErrorOr.h:56
std::error_code getError() const
Definition ErrorOr.h:152
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.
void addGUID(StringRef FromModule, GlobalValue::GUID GUID, GlobalValueSummary::ImportKind ImportKind)
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.
Function and variable summary information to aid decisions and implementation of importing.
RAII handle that manages the lifetime of the ToolOutputFile used to output remarks.
const cl::LibraryOptionsContext * LibraryOptions
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:39
iterator find(const KeyT &Key)
Definition MapVector.h:157
iterator end()
Definition MapVector.h:70
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, bool IsText=false, bool RequiresNullTerminator=true, bool IsVolatile=false, std::optional< Align > Alignment=std::nullopt)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful,...
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
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
iterator begin() const
Definition ArrayRef.h:338
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)
void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
PreservedAnalyses run(IRUnitT &IR, AnalysisManagerT &AM, ExtraArgTs... ExtraArgs)
Run all of the passes in this manager over the given unit of IR.
A loaded pass plugin.
Definition PassPlugin.h:97
void wait() override
Blocking wait for all the tasks to execute first.
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition SmallString.h:28
StringRef str() const
Explicit conversion to StringRef.
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...
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
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.
LLVM_ABI void AddFeature(StringRef String, bool Enable=true)
Adds Features.
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.
const Triple & getTargetTriple() const
virtual bool splitModule(Module &M, unsigned NumParts, function_ref< void(std::unique_ptr< Module > MPart)> ModuleCallback)
Entry point for module splitting.
TargetOptions Options
const Target & getTarget() const
void setPGOOption(std::optional< PGOOptions > PGOOpt)
MCTargetOptions MCOptions
Machine level options.
VectorLibrary VecLib
Vector math library to use.
std::string ObjectFilenameForDebug
Stores the filename/path of the final .o/.obj file, to be written in the debug information.
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.
auto async(Function &&F, Args &&...ArgList)
Asynchronous submission of a task to the pool.
Definition ThreadPool.h:80
The TimeTraceScope is a helper class to call the begin and end functions of the time trace profiler.
void keep()
Indicate that the tool's job wrt this output file has been successful and the file should not be dele...
raw_fd_ostream & os()
Return the contained raw_fd_ostream.
Triple - Helper class for working with autoconf configuration names.
Definition Triple.h:48
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition Twine.h:82
Create a verifier pass.
Definition Verifier.h:134
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition DenseSet.h:183
A raw_ostream that writes to a file descriptor.
A raw_ostream that writes to an std::string.
A raw_ostream that writes to an SmallVector or SmallString.
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.
Abstract Attribute helper functions.
Definition Attributor.h:166
LLVM_ABI void saveModuleForTwoRounds(const Module &TheModule, unsigned Task, AddStreamFn AddStream)
Save TheModule before the first codegen round.
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
initializer< Ty > init(const Ty &Val)
LLVM_ABI bool opt(const Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod, bool IsThinLTO, ModuleSummaryIndex *ExportSummary, const ModuleSummaryIndex *ImportSummary, const std::vector< uint8_t > &CmdArgs, ArrayRef< StringRef > BitcodeLibFuncs)
Runs middle-end LTO optimizations on Mod.
LLVM_ABI Error thinBackend(const Config &C, unsigned Task, AddStreamFn AddStream, Module &M, const ModuleSummaryIndex &CombinedIndex, const FunctionImporter::ImportMapTy &ImportList, const GVSummaryMapTy &DefinedGlobals, MapVector< StringRef, BitcodeModule > *ModuleMap, bool CodeGenOnly, ArrayRef< StringRef > BitcodeLibFuncs, AddStreamFn IRAddStream=nullptr, const std::vector< uint8_t > &CmdArgs=std::vector< uint8_t >())
Runs a ThinLTO backend.
LLVM_ABI BitcodeModule * findThinLTOModule(MutableArrayRef< BitcodeModule > BMs)
Returns the BitcodeModule that is ThinLTO.
LLVM_ABI Error backend(const Config &C, AddStreamFn AddStream, unsigned ParallelCodeGenParallelismLevel, Module &M, ModuleSummaryIndex &CombinedIndex, ArrayRef< StringRef > BitcodeLibFuncs)
Runs a regular LTO backend.
LLVM_ABI Error finalizeOptimizationRemarks(LLVMRemarkFileHandle DiagOutputFile)
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:2383
LLVM_ABI bool initImportList(const Module &M, const ModuleSummaryIndex &CombinedIndex, FunctionImporter::ImportMapTy &ImportList)
Distributed ThinLTO: collect the referenced modules based on module summary and initialize ImportList...
@ OF_Text
The file should be opened in text mode on platforms like z/OS that make this distinction.
Definition FileSystem.h:793
@ OF_TextWithCRLF
The file should be opened in text mode and use a carriage linefeed '\r '.
Definition FileSystem.h:802
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 StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
Definition Path.cpp:594
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
LLVM_ABI IntrusiveRefCntPtr< FileSystem > getRealFileSystem()
Gets an vfs::FileSystem for the 'real' file system, as seen by the operating system.
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 Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, ParserCallbacks Callbacks={})
Read the specified bitcode file, returning the module.
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.
LLVM_ABI void updatePublicTypeTestCalls(Module &M, bool WholeProgramVisibilityEnabledInLTO, bool DevirtSpeculativelyInIndex=false)
Convert llvm.public.type.test calls to llvm.type.test when whole program visibility is available,...
LLVM_ABI std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition Error.cpp:94
LLVM_ABI raw_fd_ostream & outs()
This returns a reference to a raw_fd_ostream for standard output.
DenseMap< GlobalValue::GUID, GlobalValueSummary * > GVSummaryMapTy
Map of global value GUID to its summary, used to identify values defined in a particular module,...
LLVM_ABI bool convertToDeclaration(GlobalValue &GV)
Converts value GV to declaration, or replaces with a declaration if it is an alias.
std::string utostr(uint64_t X, bool isNeg=false)
@ 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 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...
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 embedBitcodeInModule(Module &M, MemoryBufferRef Buf, bool EmbedBitcode, bool EmbedCmdline, const std::vector< uint8_t > &CmdArgs)
If EmbedBitcode is set, save a copy of the llvm IR as data in the __LLVM,__bitcode section (....
LLVM_ABI void SplitModule(Module &M, unsigned N, function_ref< void(std::unique_ptr< Module > MPart)> ModuleCallback, bool PreserveLocals=false, bool RoundRobin=false)
Splits the module M into N linkable partitions.
LLVM_ABI Error runCodeGenPipeline(TargetMachine &TM, Module &M, raw_pwrite_stream &OS, raw_pwrite_stream *DwoOS, CodeGenFileType CGFT, bool DisableVerify=true, bool DisableSimplifyLibCalls=false, const ModuleSummaryIndex *MSI=nullptr, IntrusiveRefCntPtr< vfs::FileSystem > VFS=vfs::getRealFileSystem())
PassManager< Module > ModulePassManager
Convenience typedef for a pass manager over modules.
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 Expected< std::vector< BitcodeModule > > getBitcodeModuleList(MemoryBufferRef Buffer)
Returns a list of modules in the specified bitcode buffer.
cl::opt< bool > NoPGOWarnMismatch
Error make_error(ArgTs &&... Args)
Make a Error instance representing failure using the given error info type.
Definition Error.h:340
LLVM_ABI raw_fd_ostream & errs()
This returns a reference to a raw_ostream for standard error.
@ Mod
The access may modify the value stored in memory.
Definition ModRef.h:34
LLVM_ABI void thinLTOInternalizeModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals)
Internalize TheModule based on the information recorded in the summaries during global summary-based ...
SingleThreadExecutor DefaultThreadPool
Definition ThreadPool.h:262
std::string toString(const APInt &I, unsigned Radix, bool Signed, bool formatAsCLiteral=false, bool UpperCase=true, bool InsertSeparators=false)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
LLVM_ABI Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition Error.cpp:107
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
std::function< Expected< std::unique_ptr< CachedFileStream > >( unsigned Task, const Twine &ModuleName)> AddStreamFn
This type defines the callback to add a file that is generated on the fly.
Definition Caching.h:79
AnalysisManager< Module > ModuleAnalysisManager
Convenience typedef for the Module analysis manager.
Definition MIRParser.h:39
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
static LLVM_ABI const Target * lookupTarget(const Triple &TheTriple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
LTO configuration.
Definition Config.h:44
std::function< bool(unsigned Task, const Module &)> ModuleHookFn
The following callbacks deal with tasks, which normally represent the entire optimization and code ge...
Definition Config.h:240
bool DebugPassManager
Whether to emit the pass manager debuggging informations.
Definition Config.h:187
bool AddFSDiscriminator
Add FSAFDO discriminators.
Definition Config.h:205
std::optional< uint64_t > RemarksHotnessThreshold
The minimum hotness value a diagnostic needs in order to be included in optimization diagnostics.
Definition Config.h:181
LLVM_ABI Error addSaveTemps(std::string OutputFileName, bool UseInputModulePath=false, const DenseSet< StringRef > &SaveTempsArgs={})
This is a convenience function that configures this Config object to write temporary files named afte...
ModuleHookFn PreOptModuleHook
This module hook is called after linking (regular LTO) or loading (ThinLTO) the module,...
Definition Config.h:244
CombinedIndexHookFn CombinedIndexHook
Definition Config.h:276
std::optional< CodeModel::Model > CodeModel
Definition Config.h:67
std::string AAPipeline
Definition Config.h:126
bool DisableVerify
Definition Config.h:72
std::vector< std::string > MAttrs
Definition Config.h:56
std::function< void(PassBuilder &)> PassBuilderCallback
Definition Config.h:65
CodeGenOptLevel CGOptLevel
Definition Config.h:68
PipelineTuningOptions PTO
Tunable parameters for passes in the default pipelines.
Definition Config.h:214
std::vector< llvm::PassPlugin * > LoadedPassPlugins
Definition Config.h:60
std::unique_ptr< raw_ostream > ResolutionFile
If this field is set, LTO will write input file paths and symbol resolutions here in llvm-lto2 comman...
Definition Config.h:211
std::string CPU
Definition Config.h:54
std::string DwoDir
The directory to store .dwo files.
Definition Config.h:146
std::string RemarksFilename
Optimization remarks file path.
Definition Config.h:160
std::vector< std::string > PassPluginFilenames
Definition Config.h:64
ModuleHookFn PostPromoteModuleHook
This hook is called after promoting any internal functions (ThinLTO-specific).
Definition Config.h:248
std::string ProfileRemapping
Name remapping file for profile data.
Definition Config.h:143
TargetOptions Options
Definition Config.h:55
std::string SplitDwarfFile
The name for the split debug info file used for the DW_AT_[GNU_]dwo_name attribute in the skeleton CU...
Definition Config.h:152
std::string SplitDwarfOutput
The path to write a .dwo file to.
Definition Config.h:157
ModuleHookFn PostOptModuleHook
This module hook is called after optimization is complete.
Definition Config.h:257
std::string RemarksPasses
Optimization remarks pass filter.
Definition Config.h:163
std::string OptPipeline
If this field is set, the set of passes run in the middle-end optimizer will be the one specified by ...
Definition Config.h:121
bool RunCSIRInstr
Run PGO context sensitive IR instrumentation.
Definition Config.h:82
ModuleHookFn PostInternalizeModuleHook
This hook is called after internalizing the module.
Definition Config.h:251
unsigned OptLevel
Definition Config.h:70
ModuleHookFn PostImportModuleHook
This hook is called after importing from other modules (ThinLTO-specific).
Definition Config.h:254
bool RemarksWithHotness
Whether to emit optimization remarks with hotness informations.
Definition Config.h:166
std::string CSIRProfile
Context Sensitive PGO profile path.
Definition Config.h:137
ModuleHookFn PreCodeGenModuleHook
This module hook is called before code generation.
Definition Config.h:262
std::optional< Reloc::Model > RelocModel
Definition Config.h:66
bool ShouldDiscardValueNames
Definition Config.h:201
bool PGOWarnMismatch
Turn on/off the warning about a hash mismatch in the PGO profile data.
Definition Config.h:85
CodeGenFileType CGFileType
Definition Config.h:69
bool Freestanding
Flag to indicate that the optimizer should not assume builtins are present on the target.
Definition Config.h:76
std::string SampleProfile
Sample PGO profile path.
Definition Config.h:140
std::string RemarksFormat
The format used for serializing remarks (default: YAML).
Definition Config.h:184
A derived class of LLVMContext that initializes itself according to a given Config object.
Definition Config.h:339