LLVM 20.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"
26#include "llvm/IR/PassManager.h"
27#include "llvm/IR/Verifier.h"
28#include "llvm/LTO/LTO.h"
34#include "llvm/Support/Error.h"
37#include "llvm/Support/Path.h"
49#include <optional>
50
51using namespace llvm;
52using namespace lto;
53
54#define DEBUG_TYPE "lto-backend"
55
57 DoNotEmbed = 0,
60};
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
78namespace llvm {
80}
81
82[[noreturn]] static void reportOpenError(StringRef Path, Twine Msg) {
83 errs() << "failed to open " << Path << ": " << Msg << '\n';
84 errs().flush();
85 exit(1);
86}
87
88Error Config::addSaveTemps(std::string OutputFileName, bool UseInputModulePath,
89 const DenseSet<StringRef> &SaveTempsArgs) {
91
92 std::error_code EC;
93 if (SaveTempsArgs.empty() || SaveTempsArgs.contains("resolution")) {
95 std::make_unique<raw_fd_ostream>(OutputFileName + "resolution.txt", EC,
97 if (EC) {
98 ResolutionFile.reset();
99 return errorCodeToError(EC);
100 }
101 }
102
103 auto setHook = [&](std::string PathSuffix, ModuleHookFn &Hook) {
104 // Keep track of the hook provided by the linker, which also needs to run.
105 ModuleHookFn LinkerHook = Hook;
106 Hook = [=](unsigned Task, const Module &M) {
107 // If the linker's hook returned false, we need to pass that result
108 // through.
109 if (LinkerHook && !LinkerHook(Task, M))
110 return false;
111
112 std::string PathPrefix;
113 // If this is the combined module (not a ThinLTO backend compile) or the
114 // user hasn't requested using the input module's path, emit to a file
115 // named from the provided OutputFileName with the Task ID appended.
116 if (M.getModuleIdentifier() == "ld-temp.o" || !UseInputModulePath) {
117 PathPrefix = OutputFileName;
118 if (Task != (unsigned)-1)
119 PathPrefix += utostr(Task) + ".";
120 } else
121 PathPrefix = M.getModuleIdentifier() + ".";
122 std::string Path = PathPrefix + PathSuffix + ".bc";
123 std::error_code EC;
125 // Because -save-temps is a debugging feature, we report the error
126 // directly and exit.
127 if (EC)
128 reportOpenError(Path, EC.message());
129 WriteBitcodeToFile(M, OS, /*ShouldPreserveUseListOrder=*/false);
130 return true;
131 };
132 };
133
134 auto SaveCombinedIndex =
135 [=](const ModuleSummaryIndex &Index,
136 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
137 std::string Path = OutputFileName + "index.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 writeIndexToFile(Index, OS);
145
146 Path = OutputFileName + "index.dot";
148 if (EC)
149 reportOpenError(Path, EC.message());
150 Index.exportToDot(OSDot, GUIDPreservedSymbols);
151 return true;
152 };
153
154 if (SaveTempsArgs.empty()) {
155 setHook("0.preopt", PreOptModuleHook);
156 setHook("1.promote", PostPromoteModuleHook);
157 setHook("2.internalize", PostInternalizeModuleHook);
158 setHook("3.import", PostImportModuleHook);
159 setHook("4.opt", PostOptModuleHook);
160 setHook("5.precodegen", PreCodeGenModuleHook);
161 CombinedIndexHook = SaveCombinedIndex;
162 } else {
163 if (SaveTempsArgs.contains("preopt"))
164 setHook("0.preopt", PreOptModuleHook);
165 if (SaveTempsArgs.contains("promote"))
166 setHook("1.promote", PostPromoteModuleHook);
167 if (SaveTempsArgs.contains("internalize"))
168 setHook("2.internalize", PostInternalizeModuleHook);
169 if (SaveTempsArgs.contains("import"))
170 setHook("3.import", PostImportModuleHook);
171 if (SaveTempsArgs.contains("opt"))
172 setHook("4.opt", PostOptModuleHook);
173 if (SaveTempsArgs.contains("precodegen"))
174 setHook("5.precodegen", PreCodeGenModuleHook);
175 if (SaveTempsArgs.contains("combinedindex"))
176 CombinedIndexHook = SaveCombinedIndex;
177 }
178
179 return Error::success();
180}
181
182#define HANDLE_EXTENSION(Ext) \
183 llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
184#include "llvm/Support/Extension.def"
185#undef HANDLE_EXTENSION
186
188 PassBuilder &PB) {
189#define HANDLE_EXTENSION(Ext) \
190 get##Ext##PluginInfo().RegisterPassBuilderCallbacks(PB);
191#include "llvm/Support/Extension.def"
192#undef HANDLE_EXTENSION
193
194 // Load requested pass plugins and let them register pass builder callbacks
195 for (auto &PluginFN : PassPlugins) {
196 auto PassPlugin = PassPlugin::Load(PluginFN);
197 if (!PassPlugin)
198 report_fatal_error(PassPlugin.takeError(), /*gen_crash_diag=*/false);
200 }
201}
202
203static std::unique_ptr<TargetMachine>
204createTargetMachine(const Config &Conf, const Target *TheTarget, Module &M) {
205 StringRef TheTriple = M.getTargetTriple();
206 SubtargetFeatures Features;
207 Features.getDefaultSubtargetFeatures(Triple(TheTriple));
208 for (const std::string &A : Conf.MAttrs)
209 Features.AddFeature(A);
210
211 std::optional<Reloc::Model> RelocModel;
212 if (Conf.RelocModel)
213 RelocModel = *Conf.RelocModel;
214 else if (M.getModuleFlag("PIC Level"))
215 RelocModel =
216 M.getPICLevel() == PICLevel::NotPIC ? Reloc::Static : Reloc::PIC_;
217
218 std::optional<CodeModel::Model> CodeModel;
219 if (Conf.CodeModel)
220 CodeModel = *Conf.CodeModel;
221 else
222 CodeModel = M.getCodeModel();
223
224 std::unique_ptr<TargetMachine> TM(TheTarget->createTargetMachine(
225 TheTriple, Conf.CPU, Features.getString(), Conf.Options, RelocModel,
226 CodeModel, Conf.CGOptLevel));
227
228 assert(TM && "Failed to create target machine");
229
230 if (std::optional<uint64_t> LargeDataThreshold = M.getLargeDataThreshold())
231 TM->setLargeDataThreshold(*LargeDataThreshold);
232
233 return TM;
234}
235
236static void runNewPMPasses(const Config &Conf, Module &Mod, TargetMachine *TM,
237 unsigned OptLevel, bool IsThinLTO,
238 ModuleSummaryIndex *ExportSummary,
239 const ModuleSummaryIndex *ImportSummary) {
240 auto FS = vfs::getRealFileSystem();
241 std::optional<PGOOptions> PGOOpt;
242 if (!Conf.SampleProfile.empty())
243 PGOOpt = PGOOptions(Conf.SampleProfile, "", Conf.ProfileRemapping,
244 /*MemoryProfile=*/"", FS, PGOOptions::SampleUse,
247 else if (Conf.RunCSIRInstr) {
248 PGOOpt = PGOOptions("", Conf.CSIRProfile, Conf.ProfileRemapping,
249 /*MemoryProfile=*/"", FS, PGOOptions::IRUse,
251 Conf.AddFSDiscriminator);
252 } else if (!Conf.CSIRProfile.empty()) {
253 PGOOpt = PGOOptions(Conf.CSIRProfile, "", Conf.ProfileRemapping,
254 /*MemoryProfile=*/"", FS, PGOOptions::IRUse,
256 Conf.AddFSDiscriminator);
258 } else if (Conf.AddFSDiscriminator) {
259 PGOOpt = PGOOptions("", "", "", /*MemoryProfile=*/"", nullptr,
262 }
263 TM->setPGOOption(PGOOpt);
264
269
271 StandardInstrumentations SI(Mod.getContext(), Conf.DebugPassManager,
272 Conf.VerifyEach);
273 SI.registerCallbacks(PIC, &MAM);
274 PassBuilder PB(TM, Conf.PTO, PGOOpt, &PIC);
275
277
278 std::unique_ptr<TargetLibraryInfoImpl> TLII(
279 new TargetLibraryInfoImpl(Triple(TM->getTargetTriple())));
280 if (Conf.Freestanding)
281 TLII->disableAllFunctions();
282 FAM.registerPass([&] { return TargetLibraryAnalysis(*TLII); });
283
284 // Parse a custom AA pipeline if asked to.
285 if (!Conf.AAPipeline.empty()) {
286 AAManager AA;
287 if (auto Err = PB.parseAAPipeline(AA, Conf.AAPipeline)) {
288 report_fatal_error(Twine("unable to parse AA pipeline description '") +
289 Conf.AAPipeline + "': " + toString(std::move(Err)));
290 }
291 // Register the AA manager first so that our version is the one used.
292 FAM.registerPass([&] { return std::move(AA); });
293 }
294
295 // Register all the basic analyses with the managers.
301
303
304 if (!Conf.DisableVerify)
305 MPM.addPass(VerifierPass());
306
308
309 switch (OptLevel) {
310 default:
311 llvm_unreachable("Invalid optimization level");
312 case 0:
314 break;
315 case 1:
317 break;
318 case 2:
320 break;
321 case 3:
323 break;
324 }
325
326 // Parse a custom pipeline if asked to.
327 if (!Conf.OptPipeline.empty()) {
328 if (auto Err = PB.parsePassPipeline(MPM, Conf.OptPipeline)) {
329 report_fatal_error(Twine("unable to parse pass pipeline description '") +
330 Conf.OptPipeline + "': " + toString(std::move(Err)));
331 }
332 } else if (IsThinLTO) {
333 MPM.addPass(PB.buildThinLTODefaultPipeline(OL, ImportSummary));
334 } else {
335 MPM.addPass(PB.buildLTODefaultPipeline(OL, ExportSummary));
336 }
337
338 if (!Conf.DisableVerify)
339 MPM.addPass(VerifierPass());
340
342 std::string PipelineStr;
343 raw_string_ostream OS(PipelineStr);
344 MPM.printPipeline(OS, [&PIC](StringRef ClassName) {
345 auto PassName = PIC.getPassNameForClassName(ClassName);
346 return PassName.empty() ? ClassName : PassName;
347 });
348 outs() << "pipeline-passes: " << PipelineStr << '\n';
349 }
350
351 MPM.run(Mod, MAM);
352}
353
354static bool isEmptyModule(const Module &Mod) {
355 // Module is empty if it has no functions, no globals, no inline asm and no
356 // named metadata (aliases and ifuncs require functions or globals so we
357 // don't need to check those explicitly).
358 return Mod.empty() && Mod.global_empty() && Mod.named_metadata_empty() &&
359 Mod.getModuleInlineAsm().empty();
360}
361
362bool lto::opt(const Config &Conf, TargetMachine *TM, unsigned Task, Module &Mod,
363 bool IsThinLTO, ModuleSummaryIndex *ExportSummary,
364 const ModuleSummaryIndex *ImportSummary,
365 const std::vector<uint8_t> &CmdArgs) {
366 if (EmbedBitcode == LTOBitcodeEmbedding::EmbedPostMergePreOptimized) {
367 // FIXME: the motivation for capturing post-merge bitcode and command line
368 // is replicating the compilation environment from bitcode, without needing
369 // to understand the dependencies (the functions to be imported). This
370 // assumes a clang - based invocation, case in which we have the command
371 // line.
372 // It's not very clear how the above motivation would map in the
373 // linker-based case, so we currently don't plumb the command line args in
374 // that case.
375 if (CmdArgs.empty())
377 dbgs() << "Post-(Thin)LTO merge bitcode embedding was requested, but "
378 "command line arguments are not available");
380 /*EmbedBitcode*/ true, /*EmbedCmdline*/ true,
381 /*Cmdline*/ CmdArgs);
382 }
383 // No need to run any opt passes if the module is empty.
384 // In theory these passes should take almost no time for an empty
385 // module, however, this guards against doing any unnecessary summary-based
386 // analysis in the case of a ThinLTO build where this might be an empty
387 // regular LTO combined module, with a large combined index from ThinLTO.
388 if (!isEmptyModule(Mod)) {
389 // FIXME: Plumb the combined index into the new pass manager.
390 runNewPMPasses(Conf, Mod, TM, Conf.OptLevel, IsThinLTO, ExportSummary,
391 ImportSummary);
392 }
393 return !Conf.PostOptModuleHook || Conf.PostOptModuleHook(Task, Mod);
394}
395
396static void codegen(const Config &Conf, TargetMachine *TM,
397 AddStreamFn AddStream, unsigned Task, Module &Mod,
398 const ModuleSummaryIndex &CombinedIndex) {
399 if (Conf.PreCodeGenModuleHook && !Conf.PreCodeGenModuleHook(Task, Mod))
400 return;
401
402 if (EmbedBitcode == LTOBitcodeEmbedding::EmbedOptimized)
404 /*EmbedBitcode*/ true,
405 /*EmbedCmdline*/ false,
406 /*CmdArgs*/ std::vector<uint8_t>());
407
408 std::unique_ptr<ToolOutputFile> DwoOut;
410 if (!Conf.DwoDir.empty()) {
411 std::error_code EC;
412 if (auto EC = llvm::sys::fs::create_directories(Conf.DwoDir))
413 report_fatal_error(Twine("Failed to create directory ") + Conf.DwoDir +
414 ": " + EC.message());
415
416 DwoFile = Conf.DwoDir;
417 sys::path::append(DwoFile, std::to_string(Task) + ".dwo");
418 TM->Options.MCOptions.SplitDwarfFile = std::string(DwoFile);
419 } else
420 TM->Options.MCOptions.SplitDwarfFile = Conf.SplitDwarfFile;
421
422 if (!DwoFile.empty()) {
423 std::error_code EC;
424 DwoOut = std::make_unique<ToolOutputFile>(DwoFile, EC, sys::fs::OF_None);
425 if (EC)
426 report_fatal_error(Twine("Failed to open ") + DwoFile + ": " +
427 EC.message());
428 }
429
431 AddStream(Task, Mod.getModuleIdentifier());
432 if (Error Err = StreamOrErr.takeError())
433 report_fatal_error(std::move(Err));
434 std::unique_ptr<CachedFileStream> &Stream = *StreamOrErr;
435 TM->Options.ObjectFilenameForDebug = Stream->ObjectPathName;
436
437 legacy::PassManager CodeGenPasses;
438 TargetLibraryInfoImpl TLII(Triple(Mod.getTargetTriple()));
439 CodeGenPasses.add(new TargetLibraryInfoWrapperPass(TLII));
440 // No need to make index available if the module is empty.
441 // In theory these passes should not use the index for an empty
442 // module, however, this guards against doing any unnecessary summary-based
443 // analysis in the case of a ThinLTO build where this might be an empty
444 // regular LTO combined module, with a large combined index from ThinLTO.
445 if (!isEmptyModule(Mod))
446 CodeGenPasses.add(
448 if (Conf.PreCodeGenPassesHook)
449 Conf.PreCodeGenPassesHook(CodeGenPasses);
450 if (TM->addPassesToEmitFile(CodeGenPasses, *Stream->OS,
451 DwoOut ? &DwoOut->os() : nullptr,
452 Conf.CGFileType))
453 report_fatal_error("Failed to setup codegen");
454 CodeGenPasses.run(Mod);
455
456 if (DwoOut)
457 DwoOut->keep();
458}
459
460static void splitCodeGen(const Config &C, TargetMachine *TM,
461 AddStreamFn AddStream,
462 unsigned ParallelCodeGenParallelismLevel, Module &Mod,
463 const ModuleSummaryIndex &CombinedIndex) {
464 DefaultThreadPool CodegenThreadPool(
465 heavyweight_hardware_concurrency(ParallelCodeGenParallelismLevel));
466 unsigned ThreadCount = 0;
467 const Target *T = &TM->getTarget();
468
469 const auto HandleModulePartition =
470 [&](std::unique_ptr<Module> MPart) {
471 // We want to clone the module in a new context to multi-thread the
472 // codegen. We do it by serializing partition modules to bitcode
473 // (while still on the main thread, in order to avoid data races) and
474 // spinning up new threads which deserialize the partitions into
475 // separate contexts.
476 // FIXME: Provide a more direct way to do this in LLVM.
478 raw_svector_ostream BCOS(BC);
479 WriteBitcodeToFile(*MPart, BCOS);
480
481 // Enqueue the task
482 CodegenThreadPool.async(
483 [&](const SmallString<0> &BC, unsigned ThreadId) {
484 LTOLLVMContext Ctx(C);
486 parseBitcodeFile(MemoryBufferRef(BC.str(), "ld-temp.o"), Ctx);
487 if (!MOrErr)
488 report_fatal_error("Failed to read bitcode");
489 std::unique_ptr<Module> MPartInCtx = std::move(MOrErr.get());
490
491 std::unique_ptr<TargetMachine> TM =
492 createTargetMachine(C, T, *MPartInCtx);
493
494 codegen(C, TM.get(), AddStream, ThreadId, *MPartInCtx,
495 CombinedIndex);
496 },
497 // Pass BC using std::move to ensure that it get moved rather than
498 // copied into the thread's context.
499 std::move(BC), ThreadCount++);
500 };
501
502 // Try target-specific module splitting first, then fallback to the default.
503 if (!TM->splitModule(Mod, ParallelCodeGenParallelismLevel,
504 HandleModulePartition)) {
505 SplitModule(Mod, ParallelCodeGenParallelismLevel, HandleModulePartition,
506 false);
507 }
508
509 // Because the inner lambda (which runs in a worker thread) captures our local
510 // variables, we need to wait for the worker threads to terminate before we
511 // can leave the function scope.
512 CodegenThreadPool.wait();
513}
514
516 Module &Mod) {
517 if (!C.OverrideTriple.empty())
518 Mod.setTargetTriple(C.OverrideTriple);
519 else if (Mod.getTargetTriple().empty())
520 Mod.setTargetTriple(C.DefaultTriple);
521
522 std::string Msg;
523 const Target *T = TargetRegistry::lookupTarget(Mod.getTargetTriple(), Msg);
524 if (!T)
525 return make_error<StringError>(Msg, inconvertibleErrorCode());
526 return T;
527}
528
530 std::unique_ptr<ToolOutputFile> DiagOutputFile) {
531 // Make sure we flush the diagnostic remarks file in case the linker doesn't
532 // call the global destructors before exiting.
533 if (!DiagOutputFile)
534 return Error::success();
535 DiagOutputFile->keep();
536 DiagOutputFile->os().flush();
537 return Error::success();
538}
539
541 unsigned ParallelCodeGenParallelismLevel, Module &Mod,
542 ModuleSummaryIndex &CombinedIndex) {
544 if (!TOrErr)
545 return TOrErr.takeError();
546
547 std::unique_ptr<TargetMachine> TM = createTargetMachine(C, *TOrErr, Mod);
548
549 LLVM_DEBUG(dbgs() << "Running regular LTO\n");
550 if (!C.CodeGenOnly) {
551 if (!opt(C, TM.get(), 0, Mod, /*IsThinLTO=*/false,
552 /*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr,
553 /*CmdArgs*/ std::vector<uint8_t>()))
554 return Error::success();
555 }
556
557 if (ParallelCodeGenParallelismLevel == 1) {
558 codegen(C, TM.get(), AddStream, 0, Mod, CombinedIndex);
559 } else {
560 splitCodeGen(C, TM.get(), AddStream, ParallelCodeGenParallelismLevel, Mod,
561 CombinedIndex);
562 }
563 return Error::success();
564}
565
566static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals,
567 const ModuleSummaryIndex &Index) {
568 std::vector<GlobalValue*> DeadGVs;
569 for (auto &GV : Mod.global_values())
570 if (GlobalValueSummary *GVS = DefinedGlobals.lookup(GV.getGUID()))
571 if (!Index.isGlobalValueLive(GVS)) {
572 DeadGVs.push_back(&GV);
574 }
575
576 // Now that all dead bodies have been dropped, delete the actual objects
577 // themselves when possible.
578 for (GlobalValue *GV : DeadGVs) {
579 GV->removeDeadConstantUsers();
580 // Might reference something defined in native object (i.e. dropped a
581 // non-prevailing IR def, but we need to keep the declaration).
582 if (GV->use_empty())
583 GV->eraseFromParent();
584 }
585}
586
587Error lto::thinBackend(const Config &Conf, unsigned Task, AddStreamFn AddStream,
588 Module &Mod, const ModuleSummaryIndex &CombinedIndex,
589 const FunctionImporter::ImportMapTy &ImportList,
590 const GVSummaryMapTy &DefinedGlobals,
592 bool CodeGenOnly, AddStreamFn IRAddStream,
593 const std::vector<uint8_t> &CmdArgs) {
595 if (!TOrErr)
596 return TOrErr.takeError();
597
598 std::unique_ptr<TargetMachine> TM = createTargetMachine(Conf, *TOrErr, Mod);
599
600 // Setup optimization remarks.
601 auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
602 Mod.getContext(), Conf.RemarksFilename, Conf.RemarksPasses,
604 Task);
605 if (!DiagFileOrErr)
606 return DiagFileOrErr.takeError();
607 auto DiagnosticOutputFile = std::move(*DiagFileOrErr);
608
609 // Set the partial sample profile ratio in the profile summary module flag of
610 // the module, if applicable.
611 Mod.setPartialSampleProfileRatio(CombinedIndex);
612
613 LLVM_DEBUG(dbgs() << "Running ThinLTO\n");
614 if (CodeGenOnly) {
615 // If CodeGenOnly is set, we only perform code generation and skip
616 // optimization. This value may differ from Conf.CodeGenOnly.
617 codegen(Conf, TM.get(), AddStream, Task, Mod, CombinedIndex);
618 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
619 }
620
621 if (Conf.PreOptModuleHook && !Conf.PreOptModuleHook(Task, Mod))
622 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
623
624 auto OptimizeAndCodegen =
625 [&](Module &Mod, TargetMachine *TM,
626 std::unique_ptr<ToolOutputFile> DiagnosticOutputFile) {
627 // Perform optimization and code generation for ThinLTO.
628 if (!opt(Conf, TM, Task, Mod, /*IsThinLTO=*/true,
629 /*ExportSummary=*/nullptr, /*ImportSummary=*/&CombinedIndex,
630 CmdArgs))
631 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
632
633 // Save the current module before the first codegen round.
634 // Note that the second codegen round runs only `codegen()` without
635 // running `opt()`. We're not reaching here as it's bailed out earlier
636 // with `CodeGenOnly` which has been set in `SecondRoundThinBackend`.
637 if (IRAddStream)
638 cgdata::saveModuleForTwoRounds(Mod, Task, IRAddStream);
639
640 codegen(Conf, TM, AddStream, Task, Mod, CombinedIndex);
641 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
642 };
643
645 return OptimizeAndCodegen(Mod, TM.get(), std::move(DiagnosticOutputFile));
646
647 // When linking an ELF shared object, dso_local should be dropped. We
648 // conservatively do this for -fpic.
649 bool ClearDSOLocalOnDeclarations =
650 TM->getTargetTriple().isOSBinFormatELF() &&
651 TM->getRelocationModel() != Reloc::Static &&
652 Mod.getPIELevel() == PIELevel::Default;
653 renameModuleForThinLTO(Mod, CombinedIndex, ClearDSOLocalOnDeclarations);
654
655 dropDeadSymbols(Mod, DefinedGlobals, CombinedIndex);
656
657 thinLTOFinalizeInModule(Mod, DefinedGlobals, /*PropagateAttrs=*/true);
658
659 if (Conf.PostPromoteModuleHook && !Conf.PostPromoteModuleHook(Task, Mod))
660 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
661
662 if (!DefinedGlobals.empty())
663 thinLTOInternalizeModule(Mod, DefinedGlobals);
664
665 if (Conf.PostInternalizeModuleHook &&
666 !Conf.PostInternalizeModuleHook(Task, Mod))
667 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
668
669 auto ModuleLoader = [&](StringRef Identifier) {
670 assert(Mod.getContext().isODRUniquingDebugTypes() &&
671 "ODR Type uniquing should be enabled on the context");
672 if (ModuleMap) {
673 auto I = ModuleMap->find(Identifier);
674 assert(I != ModuleMap->end());
675 return I->second.getLazyModule(Mod.getContext(),
676 /*ShouldLazyLoadMetadata=*/true,
677 /*IsImporting*/ true);
678 }
679
681 llvm::MemoryBuffer::getFile(Identifier);
682 if (!MBOrErr)
683 return Expected<std::unique_ptr<llvm::Module>>(make_error<StringError>(
684 Twine("Error loading imported file ") + Identifier + " : ",
685 MBOrErr.getError()));
686
687 Expected<BitcodeModule> BMOrErr = findThinLTOModule(**MBOrErr);
688 if (!BMOrErr)
689 return Expected<std::unique_ptr<llvm::Module>>(make_error<StringError>(
690 Twine("Error loading imported file ") + Identifier + " : " +
691 toString(BMOrErr.takeError()),
693
695 BMOrErr->getLazyModule(Mod.getContext(),
696 /*ShouldLazyLoadMetadata=*/true,
697 /*IsImporting*/ true);
698 if (MOrErr)
699 (*MOrErr)->setOwnedMemoryBuffer(std::move(*MBOrErr));
700 return MOrErr;
701 };
702
703 FunctionImporter Importer(CombinedIndex, ModuleLoader,
704 ClearDSOLocalOnDeclarations);
705 if (Error Err = Importer.importFunctions(Mod, ImportList).takeError())
706 return Err;
707
708 // Do this after any importing so that imported code is updated.
709 updateMemProfAttributes(Mod, CombinedIndex);
711
712 if (Conf.PostImportModuleHook && !Conf.PostImportModuleHook(Task, Mod))
713 return finalizeOptimizationRemarks(std::move(DiagnosticOutputFile));
714
715 return OptimizeAndCodegen(Mod, TM.get(), std::move(DiagnosticOutputFile));
716}
717
719 if (ThinLTOAssumeMerged && BMs.size() == 1)
720 return BMs.begin();
721
722 for (BitcodeModule &BM : BMs) {
723 Expected<BitcodeLTOInfo> LTOInfo = BM.getLTOInfo();
724 if (LTOInfo && LTOInfo->IsThinLTO)
725 return &BM;
726 }
727 return nullptr;
728}
729
732 if (!BMsOrErr)
733 return BMsOrErr.takeError();
734
735 // The bitcode file may contain multiple modules, we want the one that is
736 // marked as being the ThinLTO module.
737 if (const BitcodeModule *Bm = lto::findThinLTOModule(*BMsOrErr))
738 return *Bm;
739
740 return make_error<StringError>("Could not find module summary",
742}
743
745 const ModuleSummaryIndex &CombinedIndex,
746 FunctionImporter::ImportMapTy &ImportList) {
748 return true;
749 // We can simply import the values mentioned in the combined index, since
750 // we should only invoke this using the individual indexes written out
751 // via a WriteIndexesThinBackend.
752 for (const auto &GlobalList : CombinedIndex) {
753 // Ignore entries for undefined references.
754 if (GlobalList.second.SummaryList.empty())
755 continue;
756
757 auto GUID = GlobalList.first;
758 for (const auto &Summary : GlobalList.second.SummaryList) {
759 // Skip the summaries for the importing module. These are included to
760 // e.g. record required linkage changes.
761 if (Summary->modulePath() == M.getModuleIdentifier())
762 continue;
763 // Add an entry to provoke importing by thinBackend.
764 ImportList.addGUID(Summary->modulePath(), GUID, Summary->importType());
765 }
766 }
767 return true;
768}
arm prera ldst opt
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)
Definition: CommandLine.h:686
#define LLVM_DEBUG(...)
Definition: Debug.h:106
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)
Definition: LTOBackend.cpp:82
LTOBitcodeEmbedding
Definition: LTOBackend.cpp:56
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)
Definition: LTOBackend.cpp:460
static void dropDeadSymbols(Module &Mod, const GVSummaryMapTy &DefinedGlobals, const ModuleSummaryIndex &Index)
Definition: LTOBackend.cpp:566
static Expected< const Target * > initAndLookupTarget(const Config &C, Module &Mod)
Definition: LTOBackend.cpp:515
static void codegen(const Config &Conf, TargetMachine *TM, AddStreamFn AddStream, unsigned Task, Module &Mod, const ModuleSummaryIndex &CombinedIndex)
Definition: LTOBackend.cpp:396
static bool isEmptyModule(const Module &Mod)
Definition: LTOBackend.cpp:354
static void RegisterPassPlugins(ArrayRef< std::string > PassPlugins, PassBuilder &PB)
Definition: LTOBackend.cpp:187
static void runNewPMPasses(const Config &Conf, Module &Mod, TargetMachine *TM, unsigned OptLevel, bool IsThinLTO, ModuleSummaryIndex *ExportSummary, const ModuleSummaryIndex *ImportSummary)
Definition: LTOBackend.cpp:236
This header provides classes for managing a pipeline of passes over loops in LLVM IR.
#define I(x, y, z)
Definition: MD5.cpp:58
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
LoopAnalysisManager LAM
FunctionAnalysisManager FAM
ModuleAnalysisManager MAM
PassInstrumentationCallbacks PIC
PassBuilder PB(Machine, PassOpts->PTO, std::nullopt, &PIC)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
raw_pwrite_stream & OS
This header defines a class that provides bookkeeping for all standard (i.e in-tree) pass instrumenta...
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.
A container for analyses that lazily runs them and caches their results.
Definition: PassManager.h:253
bool registerPass(PassBuilderT &&PassBuilder)
Register an analysis pass with the manager.
Definition: PassManager.h:471
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
size_t size() const
size - Get the array size.
Definition: ArrayRef.h:168
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:194
bool empty() const
Definition: DenseMap.h:98
Implements a dense probed hash-table based set.
Definition: DenseSet.h:278
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:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:337
Tagged union holding either a T or a Error.
Definition: Error.h:481
Error takeError()
Take ownership of the stored error.
Definition: Error.h:608
reference get()
Returns a reference to the stored T value.
Definition: Error.h:578
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...
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.
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:71
iterator find(const KeyT &Key)
Definition: MapVector.h:167
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:65
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
Definition: ArrayRef.h:310
iterator begin() const
Definition: ArrayRef.h:359
static const OptimizationLevel O3
Optimize for fast execution as much as possible.
static const OptimizationLevel O0
Disable as many optimizations as possible.
static const OptimizationLevel O2
Optimize for fast execution as much as possible without triggering significant incremental compile ti...
static const OptimizationLevel O1
Optimize quickly without destroying debuggability.
This class provides access to building LLVM's passes.
Definition: PassBuilder.h:105
Error parseAAPipeline(AAManager &AA, StringRef PipelineText)
Parse a textual alias analysis pipeline into the provided AA manager.
void registerLoopAnalyses(LoopAnalysisManager &LAM)
Registers all available loop analysis passes.
void crossRegisterProxies(LoopAnalysisManager &LAM, FunctionAnalysisManager &FAM, CGSCCAnalysisManager &CGAM, ModuleAnalysisManager &MAM, MachineFunctionAnalysisManager *MFAM=nullptr)
Cross register the analysis managers through their proxies.
Error parsePassPipeline(ModulePassManager &MPM, StringRef PipelineText)
Parse a textual pass pipeline description into a ModulePassManager.
ModulePassManager buildLTODefaultPipeline(OptimizationLevel Level, ModuleSummaryIndex *ExportSummary)
Build an LTO default optimization pipeline to a pass manager.
ModulePassManager buildThinLTODefaultPipeline(OptimizationLevel Level, const ModuleSummaryIndex *ImportSummary)
Build a ThinLTO default optimization pipeline to a pass manager.
void registerModuleAnalyses(ModuleAnalysisManager &MAM)
Registers all available module analysis passes.
void registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM)
Registers all available CGSCC analysis passes.
void registerFunctionAnalyses(FunctionAnalysisManager &FAM)
Registers all available function analysis passes.
void printPipeline(raw_ostream &OS, function_ref< StringRef(StringRef)> MapClassName2PassName)
Definition: PassManager.h:178
LLVM_ATTRIBUTE_MINSIZE std::enable_if_t<!std::is_same_v< PassT, PassManager > > addPass(PassT &&Pass)
Definition: PassManager.h:195
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:60
static Expected< PassPlugin > Load(const std::string &Filename)
Attempts to load a pass plugin from a given file.
Definition: PassPlugin.cpp:16
void registerPassBuilderCallbacks(PassBuilder &PB) const
Invoke the PassBuilder callback registration.
Definition: PassPlugin.h:82
A non-threaded implementation.
Definition: ThreadPool.h:218
void wait() override
Blocking wait for all the tasks to execute first.
Definition: ThreadPool.cpp:201
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.
Definition: SmallString.h:254
bool empty() const
Definition: SmallVector.h:81
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:51
Manages the enabling and disabling of subtarget specific features.
void getDefaultSubtargetFeatures(const Triple &Triple)
Adds the default features for the specified target triple.
std::string getString() const
Returns features as a string.
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.
Definition: TargetMachine.h:77
Target - Wrapper for Target specific information.
TargetMachine * createTargetMachine(StringRef 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:78
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
Create a verifier pass.
Definition: Verifier.h:132
bool contains(const_arg_type_t< ValueT > V) const
Check if the set contains the given element.
Definition: DenseSet.h:193
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.
Definition: raw_ostream.h:460
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:661
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:691
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.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
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 ...
Definition: CommandLine.h:711
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:443
BitcodeModule * findThinLTOModule(MutableArrayRef< BitcodeModule > BMs)
Returns the BitcodeModule that is ThinLTO.
Definition: LTOBackend.cpp:718
Error backend(const Config &C, AddStreamFn AddStream, unsigned ParallelCodeGenParallelismLevel, Module &M, ModuleSummaryIndex &CombinedIndex)
Runs a regular LTO backend.
Definition: LTOBackend.cpp:540
Error finalizeOptimizationRemarks(std::unique_ptr< ToolOutputFile > DiagOutputFile)
Definition: LTOBackend.cpp:529
bool initImportList(const Module &M, const ModuleSummaryIndex &CombinedIndex, FunctionImporter::ImportMapTy &ImportList)
Distributed ThinLTO: collect the referenced modules based on module summary and initialize ImportList...
Definition: LTOBackend.cpp:744
Expected< std::unique_ptr< ToolOutputFile > > 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:2091
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.
Definition: LTOBackend.cpp:362
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.
Definition: LTOBackend.cpp:587
void updateMemProfAttributes(Module &Mod, const ModuleSummaryIndex &Index)
Updates MemProf attributes (and metadata) based on whether the index has recorded that we are linking...
Definition: LTO.cpp:1219
@ OF_Text
The file should be opened in text mode on platforms like z/OS that make this distinction.
Definition: FileSystem.h:758
@ OF_TextWithCRLF
The file should be opened in text mode and use a carriage linefeed '\r '.
Definition: FileSystem.h:767
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:967
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition: Path.cpp:456
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.
Definition: AddressRanges.h:18
ThreadPoolStrategy heavyweight_hardware_concurrency(unsigned ThreadCount=0)
Returns a thread strategy for tasks requiring significant memory or other resources.
Definition: Threading.h:162
Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context, ParserCallbacks Callbacks={})
Read the specified bitcode file, returning the module.
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.
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:98
raw_fd_ostream & outs()
This returns a reference to a raw_fd_ostream for standard output.
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:42
bool convertToDeclaration(GlobalValue &GV)
Converts value GV to declaration, or replaces with a declaration if it is an alias.
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...
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 ...
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 (....
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.
void updatePublicTypeTestCalls(Module &M, bool WholeProgramVisibilityEnabledInLTO)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:163
void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:167
Expected< std::vector< BitcodeModule > > getBitcodeModuleList(MemoryBufferRef Buffer)
Returns a list of modules in the specified bitcode buffer.
cl::opt< bool > NoPGOWarnMismatch
Definition: MemProfiler.cpp:57
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.
void thinLTOInternalizeModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals)
Internalize TheModule based on the information recorded in the summaries during global summary-based ...
cl::opt< bool > PrintPipelinePasses
Common option used by multiple tools to print pipeline passes.
ImmutablePass * createImmutableModuleSummaryIndexWrapperPass(const ModuleSummaryIndex *Index)
const char * toString(DWARFSectionKind Kind)
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:111
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:27
This class manages callbacks registration, as well as provides a way for PassInstrumentation to pass ...
StringRef getPassNameForClassName(StringRef ClassName)
Get the pass name for a given pass class name.
static const Target * lookupTarget(StringRef Triple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
LTO configuration.
Definition: Config.h:41
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:224
bool DebugPassManager
Whether to emit the pass manager debuggging informations.
Definition: Config.h:171
bool AddFSDiscriminator
Add FSAFDO discriminators.
Definition: Config.h:189
std::optional< uint64_t > RemarksHotnessThreshold
The minimum hotness value a diagnostic needs in order to be included in optimization diagnostics.
Definition: Config.h:165
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...
Definition: LTOBackend.cpp:88
ModuleHookFn PreOptModuleHook
This module hook is called after linking (regular LTO) or loading (ThinLTO) the module,...
Definition: Config.h:228
CombinedIndexHookFn CombinedIndexHook
Definition: Config.h:260
std::optional< CodeModel::Model > CodeModel
Definition: Config.h:56
std::string AAPipeline
Definition: Config.h:110
std::function< void(legacy::PassManager &)> PreCodeGenPassesHook
For adding passes that run right before codegen.
Definition: Config.h:54
bool DisableVerify
Definition: Config.h:61
std::vector< std::string > MAttrs
Definition: Config.h:50
bool VerifyEach
Definition: Config.h:60
CodeGenOptLevel CGOptLevel
Definition: Config.h:57
PipelineTuningOptions PTO
Tunable parameters for passes in the default pipelines.
Definition: Config.h:198
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:195
std::string CPU
Definition: Config.h:48
std::string DwoDir
The directory to store .dwo files.
Definition: Config.h:130
std::string RemarksFilename
Optimization remarks file path.
Definition: Config.h:144
ModuleHookFn PostPromoteModuleHook
This hook is called after promoting any internal functions (ThinLTO-specific).
Definition: Config.h:232
std::string ProfileRemapping
Name remapping file for profile data.
Definition: Config.h:127
TargetOptions Options
Definition: Config.h:49
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:136
std::string SplitDwarfOutput
The path to write a .dwo file to.
Definition: Config.h:141
ModuleHookFn PostOptModuleHook
This module hook is called after optimization is complete.
Definition: Config.h:241
std::string RemarksPasses
Optimization remarks pass filter.
Definition: Config.h:147
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:105
bool RunCSIRInstr
Run PGO context sensitive IR instrumentation.
Definition: Config.h:71
ModuleHookFn PostInternalizeModuleHook
This hook is called after internalizing the module.
Definition: Config.h:235
unsigned OptLevel
Definition: Config.h:59
ModuleHookFn PostImportModuleHook
This hook is called after importing from other modules (ThinLTO-specific).
Definition: Config.h:238
bool RemarksWithHotness
Whether to emit optimization remarks with hotness informations.
Definition: Config.h:150
std::vector< std::string > PassPlugins
Definition: Config.h:52
std::string CSIRProfile
Context Sensitive PGO profile path.
Definition: Config.h:121
ModuleHookFn PreCodeGenModuleHook
This module hook is called before code generation.
Definition: Config.h:246
std::optional< Reloc::Model > RelocModel
Definition: Config.h:55
bool ShouldDiscardValueNames
Definition: Config.h:185
bool PGOWarnMismatch
Turn on/off the warning about a hash mismatch in the PGO profile data.
Definition: Config.h:74
CodeGenFileType CGFileType
Definition: Config.h:58
bool Freestanding
Flag to indicate that the optimizer should not assume builtins are present on the target.
Definition: Config.h:65
std::string SampleProfile
Sample PGO profile path.
Definition: Config.h:124
std::string RemarksFormat
The format used for serializing remarks (default: YAML).
Definition: Config.h:168
A derived class of LLVMContext that initializes itself according to a given Config object.
Definition: Config.h:299