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