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