llvm-project
773 строки · 24.1 Кб
1//===-LTOCodeGenerator.cpp - LLVM Link Time Optimizer ---------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Link Time Optimization library. This library is
10// intended to be used by linker to optimize code at link time.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/LTO/legacy/LTOCodeGenerator.h"
15
16#include "llvm/ADT/Statistic.h"
17#include "llvm/ADT/StringExtras.h"
18#include "llvm/Analysis/Passes.h"
19#include "llvm/Analysis/TargetLibraryInfo.h"
20#include "llvm/Analysis/TargetTransformInfo.h"
21#include "llvm/Bitcode/BitcodeWriter.h"
22#include "llvm/CodeGen/CommandFlags.h"
23#include "llvm/CodeGen/TargetSubtargetInfo.h"
24#include "llvm/Config/config.h"
25#include "llvm/IR/Constants.h"
26#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/DebugInfo.h"
28#include "llvm/IR/DerivedTypes.h"
29#include "llvm/IR/DiagnosticInfo.h"
30#include "llvm/IR/DiagnosticPrinter.h"
31#include "llvm/IR/LLVMContext.h"
32#include "llvm/IR/LLVMRemarkStreamer.h"
33#include "llvm/IR/LegacyPassManager.h"
34#include "llvm/IR/Mangler.h"
35#include "llvm/IR/Module.h"
36#include "llvm/IR/PassTimingInfo.h"
37#include "llvm/IR/Verifier.h"
38#include "llvm/LTO/LTO.h"
39#include "llvm/LTO/LTOBackend.h"
40#include "llvm/LTO/legacy/LTOModule.h"
41#include "llvm/LTO/legacy/UpdateCompilerUsed.h"
42#include "llvm/Linker/Linker.h"
43#include "llvm/MC/MCAsmInfo.h"
44#include "llvm/MC/MCContext.h"
45#include "llvm/MC/TargetRegistry.h"
46#include "llvm/Remarks/HotnessThresholdParser.h"
47#include "llvm/Support/CommandLine.h"
48#include "llvm/Support/FileSystem.h"
49#include "llvm/Support/MemoryBuffer.h"
50#include "llvm/Support/Process.h"
51#include "llvm/Support/Signals.h"
52#include "llvm/Support/TargetSelect.h"
53#include "llvm/Support/ToolOutputFile.h"
54#include "llvm/Support/YAMLTraits.h"
55#include "llvm/Support/raw_ostream.h"
56#include "llvm/Target/TargetOptions.h"
57#include "llvm/TargetParser/Host.h"
58#include "llvm/TargetParser/SubtargetFeature.h"
59#include "llvm/Transforms/IPO.h"
60#include "llvm/Transforms/IPO/Internalize.h"
61#include "llvm/Transforms/IPO/WholeProgramDevirt.h"
62#include "llvm/Transforms/ObjCARC.h"
63#include "llvm/Transforms/Utils/ModuleUtils.h"
64#include <optional>
65#include <system_error>
66using namespace llvm;
67
68const char* LTOCodeGenerator::getVersionString() {
69return PACKAGE_NAME " version " PACKAGE_VERSION;
70}
71
72namespace llvm {
73cl::opt<bool> LTODiscardValueNames(
74"lto-discard-value-names",
75cl::desc("Strip names from Value during LTO (other than GlobalValue)."),
76#ifdef NDEBUG
77cl::init(true),
78#else
79cl::init(false),
80#endif
81cl::Hidden);
82
83cl::opt<bool> RemarksWithHotness(
84"lto-pass-remarks-with-hotness",
85cl::desc("With PGO, include profile count in optimization remarks"),
86cl::Hidden);
87
88cl::opt<std::optional<uint64_t>, false, remarks::HotnessThresholdParser>
89RemarksHotnessThreshold(
90"lto-pass-remarks-hotness-threshold",
91cl::desc("Minimum profile count required for an "
92"optimization remark to be output."
93" Use 'auto' to apply the threshold from profile summary."),
94cl::value_desc("uint or 'auto'"), cl::init(0), cl::Hidden);
95
96cl::opt<std::string>
97RemarksFilename("lto-pass-remarks-output",
98cl::desc("Output filename for pass remarks"),
99cl::value_desc("filename"));
100
101cl::opt<std::string>
102RemarksPasses("lto-pass-remarks-filter",
103cl::desc("Only record optimization remarks from passes whose "
104"names match the given regular expression"),
105cl::value_desc("regex"));
106
107cl::opt<std::string> RemarksFormat(
108"lto-pass-remarks-format",
109cl::desc("The format used for serializing remarks (default: YAML)"),
110cl::value_desc("format"), cl::init("yaml"));
111
112cl::opt<std::string> LTOStatsFile(
113"lto-stats-file",
114cl::desc("Save statistics to the specified file"),
115cl::Hidden);
116
117cl::opt<std::string> AIXSystemAssemblerPath(
118"lto-aix-system-assembler",
119cl::desc("Path to a system assembler, picked up on AIX only"),
120cl::value_desc("path"));
121
122cl::opt<bool>
123LTORunCSIRInstr("cs-profile-generate",
124cl::desc("Perform context sensitive PGO instrumentation"));
125
126cl::opt<std::string>
127LTOCSIRProfile("cs-profile-path",
128cl::desc("Context sensitive profile file path"));
129} // namespace llvm
130
131LTOCodeGenerator::LTOCodeGenerator(LLVMContext &Context)
132: Context(Context), MergedModule(new Module("ld-temp.o", Context)),
133TheLinker(new Linker(*MergedModule)) {
134Context.setDiscardValueNames(LTODiscardValueNames);
135Context.enableDebugTypeODRUniquing();
136
137Config.CodeModel = std::nullopt;
138Config.StatsFile = LTOStatsFile;
139Config.PreCodeGenPassesHook = [](legacy::PassManager &PM) {
140PM.add(createObjCARCContractPass());
141};
142
143Config.RunCSIRInstr = LTORunCSIRInstr;
144Config.CSIRProfile = LTOCSIRProfile;
145}
146
147LTOCodeGenerator::~LTOCodeGenerator() = default;
148
149void LTOCodeGenerator::setAsmUndefinedRefs(LTOModule *Mod) {
150for (const StringRef &Undef : Mod->getAsmUndefinedRefs())
151AsmUndefinedRefs.insert(Undef);
152}
153
154bool LTOCodeGenerator::addModule(LTOModule *Mod) {
155assert(&Mod->getModule().getContext() == &Context &&
156"Expected module in same context");
157
158bool ret = TheLinker->linkInModule(Mod->takeModule());
159setAsmUndefinedRefs(Mod);
160
161// We've just changed the input, so let's make sure we verify it.
162HasVerifiedInput = false;
163
164return !ret;
165}
166
167void LTOCodeGenerator::setModule(std::unique_ptr<LTOModule> Mod) {
168assert(&Mod->getModule().getContext() == &Context &&
169"Expected module in same context");
170
171AsmUndefinedRefs.clear();
172
173MergedModule = Mod->takeModule();
174TheLinker = std::make_unique<Linker>(*MergedModule);
175setAsmUndefinedRefs(&*Mod);
176
177// We've just changed the input, so let's make sure we verify it.
178HasVerifiedInput = false;
179}
180
181void LTOCodeGenerator::setTargetOptions(const TargetOptions &Options) {
182Config.Options = Options;
183}
184
185void LTOCodeGenerator::setDebugInfo(lto_debug_model Debug) {
186switch (Debug) {
187case LTO_DEBUG_MODEL_NONE:
188EmitDwarfDebugInfo = false;
189return;
190
191case LTO_DEBUG_MODEL_DWARF:
192EmitDwarfDebugInfo = true;
193return;
194}
195llvm_unreachable("Unknown debug format!");
196}
197
198void LTOCodeGenerator::setOptLevel(unsigned Level) {
199Config.OptLevel = Level;
200Config.PTO.LoopVectorization = Config.OptLevel > 1;
201Config.PTO.SLPVectorization = Config.OptLevel > 1;
202std::optional<CodeGenOptLevel> CGOptLevelOrNone =
203CodeGenOpt::getLevel(Config.OptLevel);
204assert(CGOptLevelOrNone && "Unknown optimization level!");
205Config.CGOptLevel = *CGOptLevelOrNone;
206}
207
208bool LTOCodeGenerator::writeMergedModules(StringRef Path) {
209if (!determineTarget())
210return false;
211
212// We always run the verifier once on the merged module.
213verifyMergedModuleOnce();
214
215// mark which symbols can not be internalized
216applyScopeRestrictions();
217
218// create output file
219std::error_code EC;
220ToolOutputFile Out(Path, EC, sys::fs::OF_None);
221if (EC) {
222std::string ErrMsg = "could not open bitcode file for writing: ";
223ErrMsg += Path.str() + ": " + EC.message();
224emitError(ErrMsg);
225return false;
226}
227
228// write bitcode to it
229WriteBitcodeToFile(*MergedModule, Out.os(), ShouldEmbedUselists);
230Out.os().close();
231
232if (Out.os().has_error()) {
233std::string ErrMsg = "could not write bitcode file: ";
234ErrMsg += Path.str() + ": " + Out.os().error().message();
235emitError(ErrMsg);
236Out.os().clear_error();
237return false;
238}
239
240Out.keep();
241return true;
242}
243
244bool LTOCodeGenerator::useAIXSystemAssembler() {
245const auto &Triple = TargetMach->getTargetTriple();
246return Triple.isOSAIX() && Config.Options.DisableIntegratedAS;
247}
248
249bool LTOCodeGenerator::runAIXSystemAssembler(SmallString<128> &AssemblyFile) {
250assert(useAIXSystemAssembler() &&
251"Runing AIX system assembler when integrated assembler is available!");
252
253// Set the system assembler path.
254SmallString<256> AssemblerPath("/usr/bin/as");
255if (!llvm::AIXSystemAssemblerPath.empty()) {
256if (llvm::sys::fs::real_path(llvm::AIXSystemAssemblerPath, AssemblerPath,
257/* expand_tilde */ true)) {
258emitError(
259"Cannot find the assembler specified by lto-aix-system-assembler");
260return false;
261}
262}
263
264// Setup the LDR_CNTRL variable
265std::string LDR_CNTRL_var = "LDR_CNTRL=MAXDATA32=0xA0000000@DSA";
266if (std::optional<std::string> V = sys::Process::GetEnv("LDR_CNTRL"))
267LDR_CNTRL_var += ("@" + *V);
268
269// Prepare inputs for the assember.
270const auto &Triple = TargetMach->getTargetTriple();
271const char *Arch = Triple.isArch64Bit() ? "-a64" : "-a32";
272std::string ObjectFileName(AssemblyFile);
273ObjectFileName[ObjectFileName.size() - 1] = 'o';
274SmallVector<StringRef, 8> Args = {
275"/bin/env", LDR_CNTRL_var,
276AssemblerPath, Arch,
277"-many", "-o",
278ObjectFileName, AssemblyFile};
279
280// Invoke the assembler.
281int RC = sys::ExecuteAndWait(Args[0], Args);
282
283// Handle errors.
284if (RC < -1) {
285emitError("LTO assembler exited abnormally");
286return false;
287}
288if (RC < 0) {
289emitError("Unable to invoke LTO assembler");
290return false;
291}
292if (RC > 0) {
293emitError("LTO assembler invocation returned non-zero");
294return false;
295}
296
297// Cleanup.
298remove(AssemblyFile.c_str());
299
300// Fix the output file name.
301AssemblyFile = ObjectFileName;
302
303return true;
304}
305
306bool LTOCodeGenerator::compileOptimizedToFile(const char **Name) {
307if (useAIXSystemAssembler())
308setFileType(CodeGenFileType::AssemblyFile);
309
310// make unique temp output file to put generated code
311SmallString<128> Filename;
312
313auto AddStream =
314[&](size_t Task,
315const Twine &ModuleName) -> std::unique_ptr<CachedFileStream> {
316StringRef Extension(
317Config.CGFileType == CodeGenFileType::AssemblyFile ? "s" : "o");
318
319int FD;
320std::error_code EC =
321sys::fs::createTemporaryFile("lto-llvm", Extension, FD, Filename);
322if (EC)
323emitError(EC.message());
324
325return std::make_unique<CachedFileStream>(
326std::make_unique<llvm::raw_fd_ostream>(FD, true));
327};
328
329bool genResult = compileOptimized(AddStream, 1);
330
331if (!genResult) {
332sys::fs::remove(Twine(Filename));
333return false;
334}
335
336// If statistics were requested, save them to the specified file or
337// print them out after codegen.
338if (StatsFile)
339PrintStatisticsJSON(StatsFile->os());
340else if (AreStatisticsEnabled())
341PrintStatistics();
342
343if (useAIXSystemAssembler())
344if (!runAIXSystemAssembler(Filename))
345return false;
346
347NativeObjectPath = Filename.c_str();
348*Name = NativeObjectPath.c_str();
349return true;
350}
351
352std::unique_ptr<MemoryBuffer>
353LTOCodeGenerator::compileOptimized() {
354const char *name;
355if (!compileOptimizedToFile(&name))
356return nullptr;
357
358// read .o file into memory buffer
359ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr = MemoryBuffer::getFile(
360name, /*IsText=*/false, /*RequiresNullTerminator=*/false);
361if (std::error_code EC = BufferOrErr.getError()) {
362emitError(EC.message());
363sys::fs::remove(NativeObjectPath);
364return nullptr;
365}
366
367// remove temp files
368sys::fs::remove(NativeObjectPath);
369
370return std::move(*BufferOrErr);
371}
372
373bool LTOCodeGenerator::compile_to_file(const char **Name) {
374if (!optimize())
375return false;
376
377return compileOptimizedToFile(Name);
378}
379
380std::unique_ptr<MemoryBuffer> LTOCodeGenerator::compile() {
381if (!optimize())
382return nullptr;
383
384return compileOptimized();
385}
386
387bool LTOCodeGenerator::determineTarget() {
388if (TargetMach)
389return true;
390
391TripleStr = MergedModule->getTargetTriple();
392if (TripleStr.empty()) {
393TripleStr = sys::getDefaultTargetTriple();
394MergedModule->setTargetTriple(TripleStr);
395}
396llvm::Triple Triple(TripleStr);
397
398// create target machine from info for merged modules
399std::string ErrMsg;
400MArch = TargetRegistry::lookupTarget(TripleStr, ErrMsg);
401if (!MArch) {
402emitError(ErrMsg);
403return false;
404}
405
406// Construct LTOModule, hand over ownership of module and target. Use MAttr as
407// the default set of features.
408SubtargetFeatures Features(join(Config.MAttrs, ""));
409Features.getDefaultSubtargetFeatures(Triple);
410FeatureStr = Features.getString();
411if (Config.CPU.empty())
412Config.CPU = lto::getThinLTODefaultCPU(Triple);
413
414// If data-sections is not explicitly set or unset, set data-sections by
415// default to match the behaviour of lld and gold plugin.
416if (!codegen::getExplicitDataSections())
417Config.Options.DataSections = true;
418
419TargetMach = createTargetMachine();
420assert(TargetMach && "Unable to create target machine");
421
422return true;
423}
424
425std::unique_ptr<TargetMachine> LTOCodeGenerator::createTargetMachine() {
426assert(MArch && "MArch is not set!");
427return std::unique_ptr<TargetMachine>(MArch->createTargetMachine(
428TripleStr, Config.CPU, FeatureStr, Config.Options, Config.RelocModel,
429std::nullopt, Config.CGOptLevel));
430}
431
432// If a linkonce global is present in the MustPreserveSymbols, we need to make
433// sure we honor this. To force the compiler to not drop it, we add it to the
434// "llvm.compiler.used" global.
435void LTOCodeGenerator::preserveDiscardableGVs(
436Module &TheModule,
437llvm::function_ref<bool(const GlobalValue &)> mustPreserveGV) {
438std::vector<GlobalValue *> Used;
439auto mayPreserveGlobal = [&](GlobalValue &GV) {
440if (!GV.isDiscardableIfUnused() || GV.isDeclaration() ||
441!mustPreserveGV(GV))
442return;
443if (GV.hasAvailableExternallyLinkage())
444return emitWarning(
445(Twine("Linker asked to preserve available_externally global: '") +
446GV.getName() + "'").str());
447if (GV.hasInternalLinkage())
448return emitWarning((Twine("Linker asked to preserve internal global: '") +
449GV.getName() + "'").str());
450Used.push_back(&GV);
451};
452for (auto &GV : TheModule)
453mayPreserveGlobal(GV);
454for (auto &GV : TheModule.globals())
455mayPreserveGlobal(GV);
456for (auto &GV : TheModule.aliases())
457mayPreserveGlobal(GV);
458
459if (Used.empty())
460return;
461
462appendToCompilerUsed(TheModule, Used);
463}
464
465void LTOCodeGenerator::applyScopeRestrictions() {
466if (ScopeRestrictionsDone)
467return;
468
469// Declare a callback for the internalize pass that will ask for every
470// candidate GlobalValue if it can be internalized or not.
471Mangler Mang;
472SmallString<64> MangledName;
473auto mustPreserveGV = [&](const GlobalValue &GV) -> bool {
474// Unnamed globals can't be mangled, but they can't be preserved either.
475if (!GV.hasName())
476return false;
477
478// Need to mangle the GV as the "MustPreserveSymbols" StringSet is filled
479// with the linker supplied name, which on Darwin includes a leading
480// underscore.
481MangledName.clear();
482MangledName.reserve(GV.getName().size() + 1);
483Mang.getNameWithPrefix(MangledName, &GV, /*CannotUsePrivateLabel=*/false);
484return MustPreserveSymbols.count(MangledName);
485};
486
487// Preserve linkonce value on linker request
488preserveDiscardableGVs(*MergedModule, mustPreserveGV);
489
490if (!ShouldInternalize)
491return;
492
493if (ShouldRestoreGlobalsLinkage) {
494// Record the linkage type of non-local symbols so they can be restored
495// prior
496// to module splitting.
497auto RecordLinkage = [&](const GlobalValue &GV) {
498if (!GV.hasAvailableExternallyLinkage() && !GV.hasLocalLinkage() &&
499GV.hasName())
500ExternalSymbols.insert(std::make_pair(GV.getName(), GV.getLinkage()));
501};
502for (auto &GV : *MergedModule)
503RecordLinkage(GV);
504for (auto &GV : MergedModule->globals())
505RecordLinkage(GV);
506for (auto &GV : MergedModule->aliases())
507RecordLinkage(GV);
508}
509
510// Update the llvm.compiler_used globals to force preserving libcalls and
511// symbols referenced from asm
512updateCompilerUsed(*MergedModule, *TargetMach, AsmUndefinedRefs);
513
514internalizeModule(*MergedModule, mustPreserveGV);
515
516ScopeRestrictionsDone = true;
517}
518
519/// Restore original linkage for symbols that may have been internalized
520void LTOCodeGenerator::restoreLinkageForExternals() {
521if (!ShouldInternalize || !ShouldRestoreGlobalsLinkage)
522return;
523
524assert(ScopeRestrictionsDone &&
525"Cannot externalize without internalization!");
526
527if (ExternalSymbols.empty())
528return;
529
530auto externalize = [this](GlobalValue &GV) {
531if (!GV.hasLocalLinkage() || !GV.hasName())
532return;
533
534auto I = ExternalSymbols.find(GV.getName());
535if (I == ExternalSymbols.end())
536return;
537
538GV.setLinkage(I->second);
539};
540
541llvm::for_each(MergedModule->functions(), externalize);
542llvm::for_each(MergedModule->globals(), externalize);
543llvm::for_each(MergedModule->aliases(), externalize);
544}
545
546void LTOCodeGenerator::verifyMergedModuleOnce() {
547// Only run on the first call.
548if (HasVerifiedInput)
549return;
550HasVerifiedInput = true;
551
552bool BrokenDebugInfo = false;
553if (verifyModule(*MergedModule, &dbgs(), &BrokenDebugInfo))
554report_fatal_error("Broken module found, compilation aborted!");
555if (BrokenDebugInfo) {
556emitWarning("Invalid debug info found, debug info will be stripped");
557StripDebugInfo(*MergedModule);
558}
559}
560
561void LTOCodeGenerator::finishOptimizationRemarks() {
562if (DiagnosticOutputFile) {
563DiagnosticOutputFile->keep();
564// FIXME: LTOCodeGenerator dtor is not invoked on Darwin
565DiagnosticOutputFile->os().flush();
566}
567}
568
569/// Optimize merged modules using various IPO passes
570bool LTOCodeGenerator::optimize() {
571if (!this->determineTarget())
572return false;
573
574// libLTO parses options late, so re-set them here.
575Context.setDiscardValueNames(LTODiscardValueNames);
576
577auto DiagFileOrErr = lto::setupLLVMOptimizationRemarks(
578Context, RemarksFilename, RemarksPasses, RemarksFormat,
579RemarksWithHotness, RemarksHotnessThreshold);
580if (!DiagFileOrErr) {
581errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
582report_fatal_error("Can't get an output file for the remarks");
583}
584DiagnosticOutputFile = std::move(*DiagFileOrErr);
585
586// Setup output file to emit statistics.
587auto StatsFileOrErr = lto::setupStatsFile(LTOStatsFile);
588if (!StatsFileOrErr) {
589errs() << "Error: " << toString(StatsFileOrErr.takeError()) << "\n";
590report_fatal_error("Can't get an output file for the statistics");
591}
592StatsFile = std::move(StatsFileOrErr.get());
593
594// Currently there is no support for enabling whole program visibility via a
595// linker option in the old LTO API, but this call allows it to be specified
596// via the internal option. Must be done before WPD invoked via the optimizer
597// pipeline run below.
598updatePublicTypeTestCalls(*MergedModule,
599/* WholeProgramVisibilityEnabledInLTO */ false);
600updateVCallVisibilityInModule(
601*MergedModule,
602/* WholeProgramVisibilityEnabledInLTO */ false,
603// FIXME: These need linker information via a
604// TBD new interface.
605/*DynamicExportSymbols=*/{},
606/*ValidateAllVtablesHaveTypeInfos=*/false,
607/*IsVisibleToRegularObj=*/[](StringRef) { return true; });
608
609// We always run the verifier once on the merged module, the `DisableVerify`
610// parameter only applies to subsequent verify.
611verifyMergedModuleOnce();
612
613// Mark which symbols can not be internalized
614this->applyScopeRestrictions();
615
616// Add an appropriate DataLayout instance for this module...
617MergedModule->setDataLayout(TargetMach->createDataLayout());
618
619if (!SaveIRBeforeOptPath.empty()) {
620std::error_code EC;
621raw_fd_ostream OS(SaveIRBeforeOptPath, EC, sys::fs::OF_None);
622if (EC)
623report_fatal_error(Twine("Failed to open ") + SaveIRBeforeOptPath +
624" to save optimized bitcode\n");
625WriteBitcodeToFile(*MergedModule, OS,
626/* ShouldPreserveUseListOrder */ true);
627}
628
629ModuleSummaryIndex CombinedIndex(false);
630TargetMach = createTargetMachine();
631if (!opt(Config, TargetMach.get(), 0, *MergedModule, /*IsThinLTO=*/false,
632/*ExportSummary=*/&CombinedIndex, /*ImportSummary=*/nullptr,
633/*CmdArgs*/ std::vector<uint8_t>())) {
634emitError("LTO middle-end optimizations failed");
635return false;
636}
637
638return true;
639}
640
641bool LTOCodeGenerator::compileOptimized(AddStreamFn AddStream,
642unsigned ParallelismLevel) {
643if (!this->determineTarget())
644return false;
645
646// We always run the verifier once on the merged module. If it has already
647// been called in optimize(), this call will return early.
648verifyMergedModuleOnce();
649
650// Re-externalize globals that may have been internalized to increase scope
651// for splitting
652restoreLinkageForExternals();
653
654ModuleSummaryIndex CombinedIndex(false);
655
656Config.CodeGenOnly = true;
657Error Err = backend(Config, AddStream, ParallelismLevel, *MergedModule,
658CombinedIndex);
659assert(!Err && "unexpected code-generation failure");
660(void)Err;
661
662// If statistics were requested, save them to the specified file or
663// print them out after codegen.
664if (StatsFile)
665PrintStatisticsJSON(StatsFile->os());
666else if (AreStatisticsEnabled())
667PrintStatistics();
668
669reportAndResetTimings();
670
671finishOptimizationRemarks();
672
673return true;
674}
675
676void LTOCodeGenerator::setCodeGenDebugOptions(ArrayRef<StringRef> Options) {
677for (StringRef Option : Options)
678CodegenOptions.push_back(Option.str());
679}
680
681void LTOCodeGenerator::parseCodeGenDebugOptions() {
682if (!CodegenOptions.empty())
683llvm::parseCommandLineOptions(CodegenOptions);
684}
685
686void llvm::parseCommandLineOptions(std::vector<std::string> &Options) {
687if (!Options.empty()) {
688// ParseCommandLineOptions() expects argv[0] to be program name.
689std::vector<const char *> CodegenArgv(1, "libLLVMLTO");
690for (std::string &Arg : Options)
691CodegenArgv.push_back(Arg.c_str());
692cl::ParseCommandLineOptions(CodegenArgv.size(), CodegenArgv.data());
693}
694}
695
696void LTOCodeGenerator::DiagnosticHandler(const DiagnosticInfo &DI) {
697// Map the LLVM internal diagnostic severity to the LTO diagnostic severity.
698lto_codegen_diagnostic_severity_t Severity;
699switch (DI.getSeverity()) {
700case DS_Error:
701Severity = LTO_DS_ERROR;
702break;
703case DS_Warning:
704Severity = LTO_DS_WARNING;
705break;
706case DS_Remark:
707Severity = LTO_DS_REMARK;
708break;
709case DS_Note:
710Severity = LTO_DS_NOTE;
711break;
712}
713// Create the string that will be reported to the external diagnostic handler.
714std::string MsgStorage;
715raw_string_ostream Stream(MsgStorage);
716DiagnosticPrinterRawOStream DP(Stream);
717DI.print(DP);
718Stream.flush();
719
720// If this method has been called it means someone has set up an external
721// diagnostic handler. Assert on that.
722assert(DiagHandler && "Invalid diagnostic handler");
723(*DiagHandler)(Severity, MsgStorage.c_str(), DiagContext);
724}
725
726namespace {
727struct LTODiagnosticHandler : public DiagnosticHandler {
728LTOCodeGenerator *CodeGenerator;
729LTODiagnosticHandler(LTOCodeGenerator *CodeGenPtr)
730: CodeGenerator(CodeGenPtr) {}
731bool handleDiagnostics(const DiagnosticInfo &DI) override {
732CodeGenerator->DiagnosticHandler(DI);
733return true;
734}
735};
736}
737
738void
739LTOCodeGenerator::setDiagnosticHandler(lto_diagnostic_handler_t DiagHandler,
740void *Ctxt) {
741this->DiagHandler = DiagHandler;
742this->DiagContext = Ctxt;
743if (!DiagHandler)
744return Context.setDiagnosticHandler(nullptr);
745// Register the LTOCodeGenerator stub in the LLVMContext to forward the
746// diagnostic to the external DiagHandler.
747Context.setDiagnosticHandler(std::make_unique<LTODiagnosticHandler>(this),
748true);
749}
750
751namespace {
752class LTODiagnosticInfo : public DiagnosticInfo {
753const Twine &Msg;
754public:
755LTODiagnosticInfo(const Twine &DiagMsg, DiagnosticSeverity Severity=DS_Error)
756: DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
757void print(DiagnosticPrinter &DP) const override { DP << Msg; }
758};
759}
760
761void LTOCodeGenerator::emitError(const std::string &ErrMsg) {
762if (DiagHandler)
763(*DiagHandler)(LTO_DS_ERROR, ErrMsg.c_str(), DiagContext);
764else
765Context.diagnose(LTODiagnosticInfo(ErrMsg));
766}
767
768void LTOCodeGenerator::emitWarning(const std::string &ErrMsg) {
769if (DiagHandler)
770(*DiagHandler)(LTO_DS_WARNING, ErrMsg.c_str(), DiagContext);
771else
772Context.diagnose(LTODiagnosticInfo(ErrMsg, DS_Warning));
773}
774