LLVM 23.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"
35#include "llvm/Support/Error.h"
38#include "llvm/Support/Path.h"
48#include <optional>
49
50using namespace llvm;
51using namespace lto;
52
53#define DEBUG_TYPE "lto-backend"
54
60
62 "lto-embed-bitcode", cl::init(LTOBitcodeEmbedding::DoNotEmbed),
64 "Do not embed"),
66 "Embed after all optimization passes"),
68 "post-merge-pre-opt",
69 "Embed post merge, but before optimizations")),
70 cl::desc("Embed LLVM bitcode in object files produced by LTO"));
71
73 "thinlto-assume-merged", cl::init(false),
74 cl::desc("Assume the input has already undergone ThinLTO function "
75 "importing and the other pre-optimization pipeline changes."));
76
78 SaveModulesList("filter-save-modules", cl::value_desc("module names"),
79 cl::desc("Only save bitcode for module whose name without "
80 "path matches this for -save-temps options"),
82
83namespace llvm {
85}
86
87[[noreturn]] static void reportOpenError(StringRef Path, Twine Msg) {
88 errs() << "failed to open " << Path << ": " << Msg << '\n';
89 errs().flush();
90 exit(1);
91}
92
93Error Config::addSaveTemps(std::string OutputFileName, bool UseInputModulePath,
94 const DenseSet<StringRef> &SaveTempsArgs) {
96
97 std::error_code EC;
98 if (SaveTempsArgs.empty() || SaveTempsArgs.contains("resolution")) {
100 std::make_unique<raw_fd_ostream>(OutputFileName + "resolution.txt", EC,
102 if (EC) {
103 ResolutionFile.reset();
104 return errorCodeToError(EC);
105 }
106 }
107
108 auto setHook = [&](std::string PathSuffix, ModuleHookFn &Hook) {
109 // Keep track of the hook provided by the linker, which also needs to run.
110 ModuleHookFn LinkerHook = Hook;
111 Hook = [=, SaveModNames = llvm::SmallVector<std::string, 1>(
112 SaveModulesList.begin(), SaveModulesList.end())](
113 unsigned Task, const Module &M) {
114 // If SaveModulesList is not empty, only do save-temps if the module's
115 // filename (without path) matches a name in the list.
116 if (!SaveModNames.empty() &&
118 SaveModNames,
119 std::string(llvm::sys::path::filename(M.getName()))))
120 return false;
121
122 // If the linker's hook returned false, we need to pass that result
123 // through.
124 if (LinkerHook && !LinkerHook(Task, M))
125 return false;
126
127 std::string PathPrefix;
128 // If this is the combined module (not a ThinLTO backend compile) or the
129 // user hasn't requested using the input module's path, emit to a file
130 // named from the provided OutputFileName with the Task ID appended.
131 if (M.getModuleIdentifier() == "ld-temp.o" || !UseInputModulePath) {
132 PathPrefix = OutputFileName;
133 if (Task != (unsigned)-1)
134 PathPrefix += utostr(Task) + ".";
135 } else
136 PathPrefix = M.getModuleIdentifier() + ".";
137 std::string Path = PathPrefix + PathSuffix + ".bc";
138 std::error_code EC;
140 // Because -save-temps is a debugging feature, we report the error
141 // directly and exit.
142 if (EC)
143 reportOpenError(Path, EC.message());
144 WriteBitcodeToFile(M, OS, /*ShouldPreserveUseListOrder=*/false);
145 return true;
146 };
147 };
148
149 auto SaveCombinedIndex =
150 [=](const ModuleSummaryIndex &Index,
151 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
152 std::string Path = OutputFileName + "index.bc";
153 std::error_code EC;
155 // Because -save-temps is a debugging feature, we report the error
156 // directly and exit.
157 if (EC)
158 reportOpenError(Path, EC.message());
159 writeIndexToFile(Index, OS);
160
161 Path = OutputFileName + "index.dot";
163 if (EC)
164 reportOpenError(Path, EC.message());
165 Index.exportToDot(OSDot, GUIDPreservedSymbols);
166 return true;
167 };
168
169 if (SaveTempsArgs.empty()) {
170 setHook("0.preopt", PreOptModuleHook);
171 setHook("1.promote", PostPromoteModuleHook);
172 setHook("2.internalize", PostInternalizeModuleHook);
173 setHook("3.import", PostImportModuleHook);
174 setHook("4.opt", PostOptModuleHook);
175 setHook("5.precodegen", PreCodeGenModuleHook);
176 CombinedIndexHook = SaveCombinedIndex;
177 } else {
178 if (SaveTempsArgs.contains("preopt"))
179 setHook("0.preopt", PreOptModuleHook);
180 if (SaveTempsArgs.contains("promote"))
181 setHook("1.promote", PostPromoteModuleHook);
182 if (SaveTempsArgs.contains("internalize"))
183 setHook("2.internalize", PostInternalizeModuleHook);
184 if (SaveTempsArgs.contains("import"))
185 setHook("3.import", PostImportModuleHook);
186 if (SaveTempsArgs.contains("opt"))
187 setHook("4.opt", PostOptModuleHook);
188 if (SaveTempsArgs.contains("precodegen"))
189 setHook("5.precodegen", PreCodeGenModuleHook);
190 if (SaveTempsArgs.contains("combinedindex"))
191 CombinedIndexHook = SaveCombinedIndex;
192 }
193
194 return Error::success();
195}
196
197#define HANDLE_EXTENSION(Ext) \
198 llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
199#include "llvm/Support/Extension.def"
200#undef HANDLE_EXTENSION
201
203 PassBuilder &PB) {
204#define HANDLE_EXTENSION(Ext) \
205 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
206#include "llvm/Support/Extension.def"
207#undef HANDLE_EXTENSION
208
209 // Load requested pass plugins and let them register pass builder callbacks
210 for (auto &PluginFN : PassPlugins) {
211 auto PassPlugin = PassPlugin::Load(PluginFN);
212 if (!PassPlugin)
215 }
216}
217
218static std::unique_ptr<TargetMachine>
219createTargetMachine(const Config &Conf, const Target *TheTarget, Module &M) {
220 const Triple &TheTriple = M.getTargetTriple();
221 SubtargetFeatures Features;
222 Features.getDefaultSubtargetFeatures(TheTriple);
223 for (const std::string &A : Conf.MAttrs)
224 Features.AddFeature(A);
225
226 std::optional<Reloc::Model> RelocModel;
227 if (Conf.RelocModel)
228 RelocModel = *Conf.RelocModel;
229 else if (M.getModuleFlag("PIC Level"))
230 RelocModel =
231 M.getPICLevel() == PICLevel::NotPIC ? Reloc::Static : Reloc::PIC_;
232
233 std::optional<CodeModel::Model> CodeModel;
234 if (Conf.CodeModel)
235 CodeModel = *Conf.CodeModel;
236 else
237 CodeModel = M.getCodeModel();
238
239 TargetOptions TargetOpts = Conf.Options;
240 if (TargetOpts.MCOptions.ABIName.empty()) {
241 TargetOpts.MCOptions.ABIName = M.getTargetABIFromMD();
242 }
243
244 std::unique_ptr<TargetMachine> TM(TheTarget->createTargetMachine(
245 TheTriple, Conf.CPU, Features.getString(), TargetOpts, RelocModel,
246 CodeModel, Conf.CGOptLevel));
247
248 assert(TM && "Failed to create target machine");
249
250 if (std::optional<uint64_t> LargeDataThreshold = M.getLargeDataThreshold())
251 TM->setLargeDataThreshold(*LargeDataThreshold);
252
253 return TM;
254}
255
256static void runNewPMPasses(const Config &Conf, Module &Mod, TargetMachine *TM,
257 unsigned OptLevel, bool IsThinLTO,
258 ModuleSummaryIndex *ExportSummary,
259 const ModuleSummaryIndex *ImportSummary) {
260 std::optional<PGOOptions> PGOOpt;
261 if (!Conf.SampleProfile.empty())
262 PGOOpt = PGOOptions(Conf.SampleProfile, "", Conf.ProfileRemapping,
263 /*MemoryProfile=*/"", PGOOptions::SampleUse,
266 else if (Conf.RunCSIRInstr) {
267 PGOOpt = PGOOptions("", Conf.CSIRProfile, Conf.ProfileRemapping,
268 /*MemoryProfile=*/"", PGOOptions::IRUse,
270 Conf.AddFSDiscriminator);
271 } else if (!Conf.CSIRProfile.empty()) {
272 PGOOpt =
274 /*MemoryProfile=*/"", PGOOptions::IRUse, PGOOptions::CSIRUse,
277 } else if (Conf.AddFSDiscriminator) {
278 PGOOpt = PGOOptions("", "", "", /*MemoryProfile=*/"", PGOOptions::NoAction,
281 }
282 TM->setPGOOption(PGOOpt);
283
288
291 Conf.VerifyEach);
292 SI.registerCallbacks(PIC, &MAM);
293 PassBuilder PB(TM, Conf.PTO, PGOOpt, &PIC);
294
296
297 std::unique_ptr<TargetLibraryInfoImpl> TLII(
299 if (Conf.Freestanding)
300 TLII->disableAllFunctions();
301 FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
302
303 // Parse a custom AA pipeline if asked to.
304 if (!Conf.AAPipeline.empty()) {
306 if (auto Err = PB.parseAAPipeline(AA, Conf.AAPipeline)) {
307 report_fatal_error(Twine("unable to parse AA pipeline description '") +
308 Conf.AAPipeline + "': " + toString(std::move(Err)));
309 }
310 // Register the AA manager first so that our version is the one used.
311 FAM.registerPass([&] { return std::move(AA); });
312 }
313
314 // Register all the basic analyses with the managers.
315 PB.registerModuleAnalyses(MAM);
316 PB.registerCGSCCAnalyses(CGAM);
317 PB.registerFunctionAnalyses(FAM);
318 PB.registerLoopAnalyses(LAM);
319 PB.crossRegisterProxies(LAM, FAM, CGAM, MAM);
320
322
323 if (!Conf.DisableVerify)
324 MPM.addPass(VerifierPass());
325
327
328 switch (OptLevel) {
329 default:
330 llvm_unreachable("Invalid optimization level");
331 case 0:
333 break;
334 case 1:
336 break;
337 case 2:
339 break;
340 case 3:
342 break;
343 }
344
345 // Parse a custom pipeline if asked to.
346 if (!Conf.OptPipeline.empty()) {
347 if (auto Err = PB.parsePassPipeline(MPM, Conf.OptPipeline)) {
348 report_fatal_error(Twine("unable to parse pass pipeline description '") +
349 Conf.OptPipeline + "': " + toString(std::move(Err)));
350 }
351 } else if (IsThinLTO) {
352 MPM.addPass(PB.buildThinLTODefaultPipeline(OL, ImportSummary));
353 } else {
354 MPM.addPass(PB.buildLTODefaultPipeline(OL, ExportSummary));
355 }
356
357 if (!Conf.DisableVerify)
358 MPM.addPass(VerifierPass());
359
361 std::string PipelineStr;
362 raw_string_ostream OS(PipelineStr);
363 MPM.printPipeline(OS, [&PIC](StringRef ClassName) {
364 auto PassName = PIC.getPassNameForClassName(ClassName);
365 return PassName.empty() ? ClassName : PassName;
366 });
367 outs() << "pipeline-passes: " << PipelineStr << '\n';
368 }
369
370 MPM.run(Mod, MAM);
371}
372
373static bool isEmptyModule(const Module &Mod) {
374 // Module is empty if it has no functions, no globals, no inline asm and no
375 // named metadata (aliases and ifuncs require functions or globals so we
376 // don't need to check those explicitly).
377 return Mod.empty() && Mod.global_empty() && Mod.named_metadata_empty() &&
378 Mod.getModuleInlineAsm().empty();
379}
380
381bool lto::opt(const Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
382 bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
383 const ModuleSummaryIndex *ImportSummary,
384 const std::vector<uint8_t> &CmdArgs) {
385 llvm::TimeTraceScope timeScope("opt");
387 // FIXME: the motivation for capturing post-merge bitcode and command line
388 // is replicating the compilation environment from bitcode, without needing
389 // to understand the dependencies (the functions to be imported). This
390 // assumes a clang - based invocation, case in which we have the command
391 // line.
392 // It's not very clear how the above motivation would map in the
393 // linker-based case, so we currently don't plumb the command line args in
394 // that case.
395 if (CmdArgs.empty())
397 dbgs() << "Post-(Thin)LTO merge bitcode embedding was requested, but "
398 "command line arguments are not available");
400 /*EmbedBitcode*/ true, /*EmbedCmdline*/ true,
401 /*Cmdline*/ CmdArgs);
402 }
403 // No need to run any opt passes if the module is empty.
404 // In theory these passes should take almost no time for an empty
405 // module, however, this guards against doing any unnecessary summary-based
406 // analysis in the case of a ThinLTO build where this might be an empty
407 // regular LTO combined module, with a large combined index from ThinLTO.
408 if (!isEmptyModule(Mod)) {
409 // FIXME: Plumb the combined index into the new pass manager.
410 runNewPMPasses(Conf, Mod, TM, Conf.OptLevel, IsThinLTO, ExportSummary,
411 ImportSummary);
412 }
413 return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
414}
415
416static void codegen(const Config &Conf, TargetMachine *TM,
417 AddStreamFn AddStream, unsigned Task, Module &Mod,
418 const ModuleSummaryIndex &CombinedIndex) {
419 llvm::TimeTraceScope timeScope("codegen");
420 if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
421 return;
422
425 /*EmbedBitcode*/ true,
426 /*EmbedCmdline*/ false,
427 /*CmdArgs*/ std::vector<uint8_t>());
428
429 std::unique_ptr<ToolOutputFile> DwoOut;
431 if (!Conf.DwoDir.empty()) {
432 std::error_code EC;
433 if (auto EC = llvm::sys::fs::create_directories(Conf.DwoDir))
434 report_fatal_error(Twine("Failed to create directory ") + Conf.DwoDir +
435 ": " + EC.message());
436
437 DwoFile = Conf.DwoDir;
438 sys::path::append(DwoFile, std::to_string(Task) + ".dwo");
439 TM->Options.MCOptions.SplitDwarfFile = std::string(DwoFile);
440 } else
442
443 if (!DwoFile.empty()) {
444 std::error_code EC;
445 DwoOut = std::make_unique<ToolOutputFile>(DwoFile, EC, sys::fs::OF_None);
446 if (EC)
447 report_fatal_error(Twine("Failed to open ") + DwoFile + ": " +
448 EC.message());
449 }
450
452 AddStream(Task, Mod.getModuleIdentifier());
453 if (Error Err = StreamOrErr.takeError())
454 report_fatal_error(std::move(Err));
455 std::unique_ptr<CachedFileStream> &Stream = *StreamOrErr;
456 TM->Options.ObjectFilenameForDebug = Stream->ObjectPathName;
457
458 // Create the codegen pipeline in its own scope so it gets deleted before
459 // Stream->commit() is called. The commit function of CacheStream deletes
460 // the raw stream, which is too early as streamers (e.g. MCAsmStreamer)
461 // keep the pointer and may use it until their destruction. See #138194.
462 {
463 legacy::PassManager CodeGenPasses;
464 TargetLibraryInfoImpl TLII(Mod.getTargetTriple(), TM->Options.VecLib);
465 CodeGenPasses.add(new TargetLibraryInfoWrapperPass(TLII));
466 CodeGenPasses.add(new RuntimeLibraryInfoWrapper(
467 Mod.getTargetTriple(), TM->Options.ExceptionModel,
470
471 // No need to make index available if the module is empty.
472 // In theory these passes should not use the index for an empty
473 // module, however, this guards against doing any unnecessary summary-based
474 // analysis in the case of a ThinLTO build where this might be an empty
475 // regular LTO combined module, with a large combined index from ThinLTO.
476 if (!isEmptyModule(Mod))
477 CodeGenPasses.add(
479 if (Conf.PreCodeGenPassesHook)
480 Conf.PreCodeGenPassesHook(CodeGenPasses);
481 if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS,
482 DwoOut ? &DwoOut->os() : nullptr,
483 Conf.CGFileType))
484 report_fatal_error("Failed to setup codegen");
485 CodeGenPasses.run(Mod);
486
487 if (DwoOut)
488 DwoOut->keep();
489 }
490
491 if (Error Err = Stream->commit())
492 report_fatal_error(std::move(Err));
493}
494
495static void splitCodeGen(const Config &C, TargetMachine *TM,
496 AddStreamFn AddStream,
497 unsigned ParallelCodeGenParallelismLevel, Module &Mod,
498 const ModuleSummaryIndex &CombinedIndex) {
499 DefaultThreadPool CodegenThreadPool(
500 heavyweight_hardware_concurrency(ParallelCodeGenParallelismLevel));
501 unsigned ThreadCount = 0;
502 const Target *T = &TM->getTarget();
503
504 const auto HandleModulePartition =
505 [&](std::unique_ptr<Module> MPart) {
506 // We want to clone the module in a new context to multi-thread the
507 // codegen. We do it by serializing partition modules to bitcode
508 // (while still on the main thread, in order to avoid data races) and
509 // spinning up new threads which deserialize the partitions into
510 // separate contexts.
511 // FIXME: Provide a more direct way to do this in LLVM.
513 raw_svector_ostream BCOS(BC);
514 WriteBitcodeToFile(*MPart, BCOS);
515
516 // Enqueue the task
517 CodegenThreadPool.async(
518 [&](const SmallString<0> &BC, unsigned ThreadId) {
519 LTOLLVMContext Ctx(C);
521 parseBitcodeFile(MemoryBufferRef(BC.str(), "ld-temp.o"), Ctx);
522 if (!MOrErr)
523 report_fatal_error("Failed to read bitcode");
524 std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
525
526 std::unique_ptr<TargetMachine> TM =
527 createTargetMachine(C, T, *MPartInCtx);
528
529 codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx,
530 CombinedIndex);
531 },
532 // Pass BC using std::move to ensure that it get moved rather than
533 // copied into the thread's context.
534 std::move(BC), ThreadCount++);
535 };
536
537 // Try target-specific module splitting first, then fallback to the default.
538 if (!TM->splitModule(Mod, ParallelCodeGenParallelismLevel,
539 HandleModulePartition)) {
540 SplitModule(Mod, ParallelCodeGenParallelismLevel, HandleModulePartition,
541 false);
542 }
543
544 // Because the inner lambda (which runs in a worker thread) captures our local
545 // variables, we need to wait for the worker threads to terminate before we
546 // can leave the function scope.
547 CodegenThreadPool.wait();
548}
549
551 Module &Mod) {
552 if (!C.OverrideTriple.empty())
553 Mod.setTargetTriple(Triple(C.OverrideTriple));
554 else if (Mod.getTargetTriple().empty())
555 Mod.setTargetTriple(Triple(C.DefaultTriple));
556
557 std::string Msg;
558 const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg);
559 if (!T)
561 return T;
562}
563
565 // Make sure we flush the diagnostic remarks file in case the linker doesn't
566 // call the global destructors before exiting.
567 if (!DiagOutputFile)
568 return Error::success();
569 DiagOutputFile.finalize();
570 DiagOutputFile->keep();
571 DiagOutputFile->os().flush();
572 return Error::success();
573}
574
576 unsigned ParallelCodeGenParallelismLevel, Module &Mod,
577 ModuleSummaryIndex &CombinedIndex) {
578 llvm::TimeTraceScope timeScope("LTO backend");
580 if (!TOrErr)
581 return TOrErr.takeError();
582
583 std::unique_ptr<TargetMachine> TM = createTargetMachine(C, *TOrErr, Mod);
584
585 LLVM_DEBUG(dbgs() << "Running regular LTO\n");
586 if (!C.CodeGenOnly) {
587 if (!opt(C, TM.get(), 0, Mod, /*IsThinLTO=*/false,
588 /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr,
589 /*CmdArgs*/ std::vector<uint8_t>()))
590 return Error::success();
591 }
592
593 if (ParallelCodeGenParallelismLevel == 1) {
594 codegen(C, TM.get(), AddStream, 0, Mod, CombinedIndex);
595 } else {
596 splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel, Mod,
597 CombinedIndex);
598 }
599 return Error::success();
600}
601
602static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals,
603 const ModuleSummaryIndex &Index) {
604 llvm::TimeTraceScope timeScope("Drop dead symbols");
605 std::vector<GlobalValue*> DeadGVs;
606 for (auto &GV : Mod.global_values())
607 if (GlobalValueSummary *GVS = DefinedGlobals.lookup(GV.getGUID()))
608 if (!Index.isGlobalValueLive(GVS)) {
609 DeadGVs.push_back(&GV);
611 }
612
613 // Now that all dead bodies have been dropped, delete the actual objects
614 // themselves when possible.
615 for (GlobalValue *GV : DeadGVs) {
616 GV->removeDeadConstantUsers();
617 // Might reference something defined in native object (i.e. dropped a
618 // non-prevailing IR def, but we need to keep the declaration).
619 if (GV->use_empty())
620 GV->eraseFromParent();
621 }
622}
623
624Error lto::thinBackend(const Config &Conf, unsigned Task, AddStreamFn AddStream,
625 Module &Mod, const ModuleSummaryIndex &CombinedIndex,
626 const FunctionImporter::ImportMapTy &ImportList,
627 const GVSummaryMapTy &DefinedGlobals,
629 bool CodeGenOnly, AddStreamFn IRAddStream,
630 const std::vector<uint8_t> &CmdArgs) {
631 llvm::TimeTraceScope timeScope("Thin backend", Mod.getModuleIdentifier());
633 if (!TOrErr)
634 return TOrErr.takeError();
635
636 std::unique_ptr<TargetMachine> TM = createTargetMachine(Conf, *TOrErr, Mod);
637
638 // Setup optimization remarks.
639 auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
640 Mod.getContext(), Conf.RemarksFilename, Conf.RemarksPasses,
642 Task);
643 if (!DiagFileOrErr)
644 return DiagFileOrErr.takeError();
645 auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
646
647 // Set the partial sample profile ratio in the profile summary module flag of
648 // the module, if applicable.
649 Mod.setPartialSampleProfileRatio(CombinedIndex);
650
651 LLVM_DEBUG(dbgs() << "Running ThinLTO\n");
652 if (CodeGenOnly) {
653 // If CodeGenOnly is set, we only perform code generation and skip
654 // optimization. This value may differ from Conf.CodeGenOnly.
655 codegen(Conf, TM.get(), AddStream, Task, Mod, CombinedIndex);
656 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
657 }
658
659 if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
660 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
661
662 auto OptimizeAndCodegen =
663 [&](Module &Mod, TargetMachine *TM,
664 LLVMRemarkFileHandle DiagnosticOutputFile) {
665 // Perform optimization and code generation for ThinLTO.
666 if (!opt(Conf, TM, Task, Mod, /*IsThinLTO=*/true,
667 /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex,
668 CmdArgs))
669 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
670
671 // Save the current module before the first codegen round.
672 // Note that the second codegen round runs only `codegen()` without
673 // running `opt()`. We're not reaching here as it's bailed out earlier
674 // with `CodeGenOnly` which has been set in `SecondRoundThinBackend`.
675 if (IRAddStream)
676 cgdata::saveModuleForTwoRounds(Mod, Task, IRAddStream);
677
678 codegen(Conf, TM, AddStream, Task, Mod, CombinedIndex);
679 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
680 };
681
683 return OptimizeAndCodegen(Mod, TM.get(), std::move(DiagnosticOutputFile));
684
685 // When linking an ELF shared object, dso_local should be dropped. We
686 // conservatively do this for -fpic.
687 bool ClearDSOLocalOnDeclarations =
688 TM->getTargetTriple().isOSBinFormatELF() &&
689 TM->getRelocationModel() != Reloc::Static &&
690 Mod.getPIELevel() == PIELevel::Default;
691 renameModuleForThinLTO(Mod, CombinedIndex, ClearDSOLocalOnDeclarations);
692
693 dropDeadSymbols(Mod, DefinedGlobals, CombinedIndex);
694
695 thinLTOFinalizeInModule(Mod, DefinedGlobals, /*PropagateAttrs=*/true);
696
697 if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
698 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
699
700 if (!DefinedGlobals.empty())
701 thinLTOInternalizeModule(Mod, DefinedGlobals);
702
703 if (Conf.PostInternalizeModuleHook &&
704 !Conf.PostInternalizeModuleHook(Task, Mod))
705 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
706
707 auto ModuleLoader = [&](StringRef Identifier) {
708 llvm::TimeTraceScope moduleLoaderScope("Module loader", Identifier);
709 assert(Mod.getContext().isODRUniquingDebugTypes() &&
710 "ODR Type uniquing should be enabled on the context");
711 if (ModuleMap) {
712 auto I = ModuleMap->find(Identifier);
713 assert(I != ModuleMap->end());
714 return I->second.getLazyModule(Mod.getContext(),
715 /*ShouldLazyLoadMetadata=*/true,
716 /*IsImporting*/ true);
717 }
718
720 llvm::MemoryBuffer::getFile(Identifier);
721 if (!MBOrErr)
723 Twine("Error loading imported file ") + Identifier + " : ",
724 MBOrErr.getError()));
725
726 Expected<BitcodeModule> BMOrErr = findThinLTOModule(**MBOrErr);
727 if (!BMOrErr)
729 Twine("Error loading imported file ") + Identifier + " : " +
730 toString(BMOrErr.takeError()),
732
734 BMOrErr->getLazyModule(Mod.getContext(),
735 /*ShouldLazyLoadMetadata=*/true,
736 /*IsImporting*/ true);
737 if (MOrErr)
738 (*MOrErr)->setOwnedMemoryBuffer(std::move(*MBOrErr));
739 return MOrErr;
740 };
741
742 {
743 llvm::TimeTraceScope importScope("Import functions");
744 FunctionImporter Importer(CombinedIndex, ModuleLoader,
745 ClearDSOLocalOnDeclarations);
746 if (Error Err = Importer.importFunctions(Mod, ImportList).takeError())
747 return Err;
748 }
749
750 // Do this after any importing so that imported code is updated.
752
753 if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
754 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
755
756 return OptimizeAndCodegen(Mod, TM.get(), std::move(DiagnosticOutputFile));
757}
758
760 if (ThinLTOAssumeMerged && BMs.size() == 1)
761 return BMs.begin();
762
763 for (BitcodeModule &BM : BMs) {
764 Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
765 if (LTOInfo && LTOInfo->IsThinLTO)
766 return &BM;
767 }
768 return nullptr;
769}
770
773 if (!BMsOrErr)
774 return BMsOrErr.takeError();
775
776 // The bitcode file may contain multiple modules, we want the one that is
777 // marked as being the ThinLTO module.
778 if (const BitcodeModule *Bm = lto::findThinLTOModule(*BMsOrErr))
779 return *Bm;
780
781 return make_error<StringError>("Could not find module summary",
783}
784
786 const ModuleSummaryIndex &CombinedIndex,
787 FunctionImporter::ImportMapTy &ImportList) {
789 return true;
790 // We can simply import the values mentioned in the combined index, since
791 // we should only invoke this using the individual indexes written out
792 // via a WriteIndexesThinBackend.
793 for (const auto &GlobalList : CombinedIndex) {
794 // Ignore entries for undefined references.
795 if (GlobalList.second.getSummaryList().empty())
796 continue;
797
798 auto GUID = GlobalList.first;
799 for (const auto &Summary : GlobalList.second.getSummaryList()) {
800 // Skip the summaries for the importing module. These are included to
801 // e.g. record required linkage changes.
802 if (Summary->modulePath() == M.getModuleIdentifier())
803 continue;
804 // Add an entry to provoke importing by thinBackend.
805 ImportList.addGUID(Summary->modulePath(), GUID, Summary->importType());
806 }
807 }
808 return true;
809}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
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 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 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 bool isEmptyModule(const Module &Mod)
static void RegisterPassPlugins(ArrayRef< std::string > PassPlugins, PassBuilder &PB)
static void runNewPMPasses(const Config &Conf, Module &Mod, TargetMachine *TM, unsigned OptLevel, bool IsThinLTO, ModuleSummaryIndex *ExportSummary, const ModuleSummaryIndex *ImportSummary)
#define I(x, y, z)
Definition MD5.cpp:57
#define T
This is the interface to build a ModuleSummaryIndex for a module.
static std::unique_ptr< TargetMachine > createTargetMachine(Function *F, CodeGenOptLevel OptLevel)
Create the TargetMachine object to query the backend for optimization preferences.
CGSCCAnalysisManager CGAM
if(auto Err=PB.parsePassPipeline(MPM, Passes)) return wrap(std MPM run * Mod
LoopAnalysisManager LAM
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
PassInstrumentationCallbacks PIC
PassBuilder PB(Machine, PassOpts->PTO, std::nullopt, &PIC)
This header defines a class that provides bookkeeping for all standard (i.e in-tree) pass instrumenta...
#define LLVM_DEBUG(...)
Definition Debug.h:114
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.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
size_t size() const
size - Get the array size.
Definition ArrayRef.h:142
Represents a module in a bitcode file.
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition DenseMap.h:205
bool empty() const
Definition DenseMap.h:109
Implements a dense probed hash-table based set.
Definition DenseSet.h:279
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.
This class implements a map that also provides access to all stored values in a deterministic order.
Definition MapVector.h:36
iterator end()
Definition MapVector.h:67
iterator find(const KeyT &Key)
Definition MapVector.h:154
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:67
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition ArrayRef.h:298
iterator begin() const
Definition ArrayRef.h:342
static LLVM_ABI const OptimizationLevel O3
Optimize for fast execution as much as possible.
static LLVM_ABI const OptimizationLevel O0
Disable as many optimizations as possible.
static LLVM_ABI const OptimizationLevel O2
Optimize for fast execution as much as possible without triggering significant incremental compile ti...
static LLVM_ABI const OptimizationLevel O1
Optimize quickly without destroying debuggability.
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:71
static LLVM_ABI Expected< PassPlugin > Load(const std::string &Filename)
Attempts to load a pass plugin from a given file.
void registerPassBuilderCallbacks(PassBuilder &PB) const
Invoke the PassBuilder callback registration.
Definition PassPlugin.h:93
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:26
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...
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
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.
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
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.
FloatABI::ABIType FloatABIType
FloatABIType - This setting is set by -float-abi=xxx option is specfied on the command line.
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.
EABI EABIVersion
EABIVersion - This flag specifies the EABI version.
ExceptionHandling ExceptionModel
What exception model to use.
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:47
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:175
PassManager manages ModulePassManagers.
void add(Pass *P) override
Add a pass to the queue of passes to run.
bool run(Module &M)
run - Execute all of the passes scheduled for execution.
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:165
@ C
The default llvm calling convention, compatible with C.
Definition CallingConv.h:34
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 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)
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:2166
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...
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)
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, AddStreamFn IRAddStream=nullptr, const std::vector< uint8_t > &CmdArgs=std::vector< uint8_t >())
Runs a ThinLTO backend.
@ OF_Text
The file should be opened in text mode on platforms like z/OS that make this distinction.
Definition FileSystem.h:755
@ OF_TextWithCRLF
The file should be opened in text mode and use a carriage linefeed '\r '.
Definition FileSystem.h:764
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:976
LLVM_ABI StringRef filename(StringRef path LLVM_LIFETIME_BOUND, Style style=Style::native)
Get filename.
Definition Path.cpp:578
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:457
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
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 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)
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 cl::opt< bool > PrintPipelinePasses
Common option used by multiple tools to print pipeline passes.
LLVM_ABI void updatePublicTypeTestCalls(Module &M, bool WholeProgramVisibilityEnabledInLTO)
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:207
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)
LLVM_ABI ImmutablePass * createImmutableModuleSummaryIndexWrapperPass(const ModuleSummaryIndex *Index)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1945
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:58
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:
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.
Definition Error.cpp:177
A struct capturing PGO tunables.
Definition PGOOptions.h:22
static const Target * lookupTarget(StringRef TripleStr, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
LTO configuration.
Definition Config.h:42
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:230
bool DebugPassManager
Whether to emit the pass manager debuggging informations.
Definition Config.h:177
bool AddFSDiscriminator
Add FSAFDO discriminators.
Definition Config.h:195
std::optional< uint64_t > RemarksHotnessThreshold
The minimum hotness value a diagnostic needs in order to be included in optimization diagnostics.
Definition Config.h:171
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:234
CombinedIndexHookFn CombinedIndexHook
Definition Config.h:266
std::optional< CodeModel::Model > CodeModel
Definition Config.h:57
std::string AAPipeline
Definition Config.h:116
std::function< void(legacy::PassManager &)> PreCodeGenPassesHook
For adding passes that run right before codegen.
Definition Config.h:55
bool DisableVerify
Definition Config.h:62
std::vector< std::string > MAttrs
Definition Config.h:51
CodeGenOptLevel CGOptLevel
Definition Config.h:58
PipelineTuningOptions PTO
Tunable parameters for passes in the default pipelines.
Definition Config.h:204
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:201
std::string CPU
Definition Config.h:49
std::string DwoDir
The directory to store .dwo files.
Definition Config.h:136
std::string RemarksFilename
Optimization remarks file path.
Definition Config.h:150
ModuleHookFn PostPromoteModuleHook
This hook is called after promoting any internal functions (ThinLTO-specific).
Definition Config.h:238
std::string ProfileRemapping
Name remapping file for profile data.
Definition Config.h:133
TargetOptions Options
Definition Config.h:50
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:142
std::string SplitDwarfOutput
The path to write a .dwo file to.
Definition Config.h:147
ModuleHookFn PostOptModuleHook
This module hook is called after optimization is complete.
Definition Config.h:247
std::string RemarksPasses
Optimization remarks pass filter.
Definition Config.h:153
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:111
bool RunCSIRInstr
Run PGO context sensitive IR instrumentation.
Definition Config.h:72
ModuleHookFn PostInternalizeModuleHook
This hook is called after internalizing the module.
Definition Config.h:241
unsigned OptLevel
Definition Config.h:60
ModuleHookFn PostImportModuleHook
This hook is called after importing from other modules (ThinLTO-specific).
Definition Config.h:244
bool RemarksWithHotness
Whether to emit optimization remarks with hotness informations.
Definition Config.h:156
std::vector< std::string > PassPlugins
Definition Config.h:53
std::string CSIRProfile
Context Sensitive PGO profile path.
Definition Config.h:127
ModuleHookFn PreCodeGenModuleHook
This module hook is called before code generation.
Definition Config.h:252
std::optional< Reloc::Model > RelocModel
Definition Config.h:56
bool ShouldDiscardValueNames
Definition Config.h:191
bool PGOWarnMismatch
Turn on/off the warning about a hash mismatch in the PGO profile data.
Definition Config.h:75
CodeGenFileType CGFileType
Definition Config.h:59
bool Freestanding
Flag to indicate that the optimizer should not assume builtins are present on the target.
Definition Config.h:66
std::string SampleProfile
Sample PGO profile path.
Definition Config.h:130
std::string RemarksFormat
The format used for serializing remarks (default: YAML).
Definition Config.h:174
A derived class of LLVMContext that initializes itself according to a given Config object.
Definition Config.h:305