1//===- llvm-lto: a simple command-line program to link modules with LTO ---===//
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 program takes in a list of bitcode files, links them, performs link-time
10// optimization, and outputs an object file.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm-c/lto.h"
15#include "llvm/ADT/ArrayRef.h"
16#include "llvm/ADT/STLExtras.h"
17#include "llvm/ADT/SmallString.h"
18#include "llvm/ADT/StringExtras.h"
19#include "llvm/ADT/StringRef.h"
20#include "llvm/ADT/StringSet.h"
21#include "llvm/ADT/Twine.h"
22#include "llvm/Bitcode/BitcodeReader.h"
23#include "llvm/Bitcode/BitcodeWriter.h"
24#include "llvm/CodeGen/CommandFlags.h"
25#include "llvm/IR/DiagnosticInfo.h"
26#include "llvm/IR/DiagnosticPrinter.h"
27#include "llvm/IR/LLVMContext.h"
28#include "llvm/IR/Module.h"
29#include "llvm/IR/ModuleSummaryIndex.h"
30#include "llvm/IR/Verifier.h"
31#include "llvm/IRReader/IRReader.h"
32#include "llvm/LTO/legacy/LTOCodeGenerator.h"
33#include "llvm/LTO/legacy/LTOModule.h"
34#include "llvm/LTO/legacy/ThinLTOCodeGenerator.h"
35#include "llvm/Support/Casting.h"
36#include "llvm/Support/CommandLine.h"
37#include "llvm/Support/Error.h"
38#include "llvm/Support/ErrorHandling.h"
39#include "llvm/Support/ErrorOr.h"
40#include "llvm/Support/FileSystem.h"
41#include "llvm/Support/InitLLVM.h"
42#include "llvm/Support/LibraryOptionsContext.h"
43#include "llvm/Support/MemoryBuffer.h"
44#include "llvm/Support/Path.h"
45#include "llvm/Support/SourceMgr.h"
46#include "llvm/Support/TargetSelect.h"
47#include "llvm/Support/WithColor.h"
48#include "llvm/Support/raw_ostream.h"
49#include "llvm/Target/TargetOptions.h"
50#include <cassert>
51#include <cstdint>
52#include <cstdlib>
53#include <memory>
54#include <string>
55#include <system_error>
56#include <utility>
57#include <vector>
58
59using namespace llvm;
60
61static cl::OptionCategory LTOCategory("LTO Options");
62
63static cl::opt<char>
64 OptLevel("O",
65 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
66 "(default = '-O2')"),
67 cl::Prefix, cl::init(Val: '2'), cl::cat(LTOCategory));
68
69static cl::opt<bool>
70 IndexStats("thinlto-index-stats",
71 cl::desc("Print statistic for the index in every input files"),
72 cl::init(Val: false), cl::cat(LTOCategory));
73
74static cl::opt<bool> DisableVerify(
75 "disable-verify", cl::init(Val: false),
76 cl::desc("Do not run the verifier during the optimization pipeline"),
77 cl::cat(LTOCategory));
78
79static cl::opt<bool> EnableFreestanding(
80 "lto-freestanding", cl::init(Val: false),
81 cl::desc("Enable Freestanding (disable builtins / TLI) during LTO"),
82 cl::cat(LTOCategory));
83
84static cl::opt<bool> UseDiagnosticHandler(
85 "use-diagnostic-handler", cl::init(Val: false),
86 cl::desc("Use a diagnostic handler to test the handler interface"),
87 cl::cat(LTOCategory));
88
89static cl::opt<bool>
90 ThinLTO("thinlto", cl::init(Val: false),
91 cl::desc("Only write combined global index for ThinLTO backends"),
92 cl::cat(LTOCategory));
93
94enum ThinLTOModes {
95 THINLINK,
96 THINDISTRIBUTE,
97 THINEMITIMPORTS,
98 THINPROMOTE,
99 THINIMPORT,
100 THININTERNALIZE,
101 THINOPT,
102 THINCODEGEN,
103 THINALL
104};
105
106static cl::opt<ThinLTOModes> ThinLTOMode(
107 "thinlto-action", cl::desc("Perform a single ThinLTO stage:"),
108 cl::values(
109 clEnumValN(
110 THINLINK, "thinlink",
111 "ThinLink: produces the index by linking only the summaries."),
112 clEnumValN(THINDISTRIBUTE, "distributedindexes",
113 "Produces individual indexes for distributed backends."),
114 clEnumValN(THINEMITIMPORTS, "emitimports",
115 "Emit imports files for distributed backends."),
116 clEnumValN(THINPROMOTE, "promote",
117 "Perform pre-import promotion (requires -thinlto-index)."),
118 clEnumValN(THINIMPORT, "import",
119 "Perform both promotion and "
120 "cross-module importing (requires "
121 "-thinlto-index)."),
122 clEnumValN(THININTERNALIZE, "internalize",
123 "Perform internalization driven by -exported-symbol "
124 "(requires -thinlto-index)."),
125 clEnumValN(THINOPT, "optimize", "Perform ThinLTO optimizations."),
126 clEnumValN(THINCODEGEN, "codegen", "CodeGen (expected to match llc)"),
127 clEnumValN(THINALL, "run", "Perform ThinLTO end-to-end")),
128 cl::cat(LTOCategory));
129
130static cl::opt<std::string>
131 ThinLTOIndex("thinlto-index",
132 cl::desc("Provide the index produced by a ThinLink, required "
133 "to perform the promotion and/or importing."),
134 cl::cat(LTOCategory));
135
136static cl::opt<std::string> ThinLTOPrefixReplace(
137 "thinlto-prefix-replace",
138 cl::desc("Control where files for distributed backends are "
139 "created. Expects 'oldprefix;newprefix' and if path "
140 "prefix of output file is oldprefix it will be "
141 "replaced with newprefix."),
142 cl::cat(LTOCategory));
143
144static cl::opt<std::string> ThinLTOModuleId(
145 "thinlto-module-id",
146 cl::desc("For the module ID for the file to process, useful to "
147 "match what is in the index."),
148 cl::cat(LTOCategory));
149
150static cl::opt<std::string> ThinLTOCacheDir("thinlto-cache-dir",
151 cl::desc("Enable ThinLTO caching."),
152 cl::cat(LTOCategory));
153
154static cl::opt<int> ThinLTOCachePruningInterval(
155 "thinlto-cache-pruning-interval", cl::init(Val: 1200),
156 cl::desc("Set ThinLTO cache pruning interval."), cl::cat(LTOCategory));
157
158static cl::opt<uint64_t> ThinLTOCacheMaxSizeBytes(
159 "thinlto-cache-max-size-bytes",
160 cl::desc("Set ThinLTO cache pruning directory maximum size in bytes."),
161 cl::cat(LTOCategory));
162
163static cl::opt<int> ThinLTOCacheMaxSizeFiles(
164 "thinlto-cache-max-size-files", cl::init(Val: 1000000),
165 cl::desc("Set ThinLTO cache pruning directory maximum number of files."),
166 cl::cat(LTOCategory));
167
168static cl::opt<unsigned> ThinLTOCacheEntryExpiration(
169 "thinlto-cache-entry-expiration", cl::init(Val: 604800) /* 1w */,
170 cl::desc("Set ThinLTO cache entry expiration time."), cl::cat(LTOCategory));
171
172static cl::opt<std::string> ThinLTOSaveTempsPrefix(
173 "thinlto-save-temps",
174 cl::desc("Save ThinLTO temp files using filenames created by adding "
175 "suffixes to the given file path prefix."),
176 cl::cat(LTOCategory));
177
178static cl::opt<std::string> ThinLTOGeneratedObjectsDir(
179 "thinlto-save-objects",
180 cl::desc("Save ThinLTO generated object files using filenames created in "
181 "the given directory."),
182 cl::cat(LTOCategory));
183
184static cl::opt<bool> SaveLinkedModuleFile(
185 "save-linked-module", cl::init(Val: false),
186 cl::desc("Write linked LTO module to file before optimize"),
187 cl::cat(LTOCategory));
188
189static cl::opt<bool>
190 SaveModuleFile("save-merged-module", cl::init(Val: false),
191 cl::desc("Write merged LTO module to file before CodeGen"),
192 cl::cat(LTOCategory));
193
194static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
195 cl::desc("<input bitcode files>"),
196 cl::cat(LTOCategory));
197
198static cl::opt<std::string> OutputFilename("o", cl::init(Val: ""),
199 cl::desc("Override output filename"),
200 cl::value_desc("filename"),
201 cl::cat(LTOCategory));
202
203static cl::list<std::string> ExportedSymbols(
204 "exported-symbol",
205 cl::desc("List of symbols to export from the resulting object file"),
206 cl::cat(LTOCategory));
207
208static cl::list<std::string>
209 DSOSymbols("dso-symbol",
210 cl::desc("Symbol to put in the symtab in the resulting dso"),
211 cl::cat(LTOCategory));
212
213static cl::opt<bool> ListSymbolsOnly(
214 "list-symbols-only", cl::init(Val: false),
215 cl::desc("Instead of running LTO, list the symbols in each IR file"),
216 cl::cat(LTOCategory));
217
218static cl::opt<bool> ListDependentLibrariesOnly(
219 "list-dependent-libraries-only", cl::init(Val: false),
220 cl::desc(
221 "Instead of running LTO, list the dependent libraries in each IR file"),
222 cl::cat(LTOCategory));
223
224static cl::opt<bool> QueryHasCtorDtor(
225 "query-hasCtorDtor", cl::init(Val: false),
226 cl::desc("Queries LTOModule::hasCtorDtor() on each IR file"));
227
228static cl::opt<bool>
229 SetMergedModule("set-merged-module", cl::init(Val: false),
230 cl::desc("Use the first input module as the merged module"),
231 cl::cat(LTOCategory));
232
233static cl::opt<unsigned> Parallelism("j", cl::Prefix, cl::init(Val: 1),
234 cl::desc("Number of backend threads"),
235 cl::cat(LTOCategory));
236
237static cl::opt<bool> RestoreGlobalsLinkage(
238 "restore-linkage", cl::init(Val: false),
239 cl::desc("Restore original linkage of globals prior to CodeGen"),
240 cl::cat(LTOCategory));
241
242static cl::opt<bool> CheckHasObjC(
243 "check-for-objc", cl::init(Val: false),
244 cl::desc("Only check if the module has objective-C defined in it"),
245 cl::cat(LTOCategory));
246
247static cl::opt<bool> PrintMachOCPUOnly(
248 "print-macho-cpu-only", cl::init(Val: false),
249 cl::desc("Instead of running LTO, print the mach-o cpu in each IR file"),
250 cl::cat(LTOCategory));
251
252static cl::opt<bool>
253 DebugPassManager("debug-pass-manager", cl::init(Val: false), cl::Hidden,
254 cl::desc("Print pass management debugging information"),
255 cl::cat(LTOCategory));
256
257static cl::opt<bool>
258 LTOSaveBeforeOpt("lto-save-before-opt", cl::init(Val: false),
259 cl::desc("Save the IR before running optimizations"));
260
261namespace {
262
263struct ModuleInfo {
264 BitVector CanBeHidden;
265};
266
267// An LLVMContext with the library options of the command line.
268struct ToolContext : LLVMContext {
269 explicit ToolContext(const cl::LibraryOptionsContext &LibraryOptions) {
270 getLibraryOptions().assign(Other: LibraryOptions);
271 }
272};
273
274} // end anonymous namespace
275
276static void handleDiagnostics(lto_codegen_diagnostic_severity_t Severity,
277 const char *Msg, void *) {
278 errs() << "llvm-lto: ";
279 switch (Severity) {
280 case LTO_DS_NOTE:
281 errs() << "note: ";
282 break;
283 case LTO_DS_REMARK:
284 errs() << "remark: ";
285 break;
286 case LTO_DS_ERROR:
287 errs() << "error: ";
288 break;
289 case LTO_DS_WARNING:
290 errs() << "warning: ";
291 break;
292 }
293 errs() << Msg << "\n";
294}
295
296static std::string CurrentActivity;
297
298namespace {
299 struct LLVMLTODiagnosticHandler : public DiagnosticHandler {
300 bool handleDiagnostics(const DiagnosticInfo &DI) override {
301 raw_ostream &OS = errs();
302 OS << "llvm-lto: ";
303 switch (DI.getSeverity()) {
304 case DS_Error:
305 OS << "error";
306 break;
307 case DS_Warning:
308 OS << "warning";
309 break;
310 case DS_Remark:
311 OS << "remark";
312 break;
313 case DS_Note:
314 OS << "note";
315 break;
316 }
317 if (!CurrentActivity.empty())
318 OS << ' ' << CurrentActivity;
319 OS << ": ";
320
321 DiagnosticPrinterRawOStream DP(OS);
322 DI.print(DP);
323 OS << '\n';
324
325 if (DI.getSeverity() == DS_Error)
326 exit(status: 1);
327 return true;
328 }
329 };
330 }
331
332static void error(const Twine &Msg) {
333 errs() << "llvm-lto: " << Msg << '\n';
334 exit(status: 1);
335}
336
337static void error(std::error_code EC, const Twine &Prefix) {
338 if (EC)
339 error(Msg: Prefix + ": " + EC.message());
340}
341
342template <typename T>
343static void error(const ErrorOr<T> &V, const Twine &Prefix) {
344 error(V.getError(), Prefix);
345}
346
347static void maybeVerifyModule(const Module &Mod) {
348 if (!DisableVerify && verifyModule(M: Mod, OS: &errs()))
349 error(Msg: "Broken Module");
350}
351
352static std::unique_ptr<LTOModule>
353getLocalLTOModule(StringRef Path, std::unique_ptr<MemoryBuffer> &Buffer,
354 const TargetOptions &Options) {
355 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
356 MemoryBuffer::getFile(Filename: Path);
357 error(V: BufferOrErr, Prefix: "error loading file '" + Path + "'");
358 Buffer = std::move(BufferOrErr.get());
359 CurrentActivity = ("loading file '" + Path + "'").str();
360 std::unique_ptr<LLVMContext> Context = std::make_unique<LLVMContext>();
361 Context->setDiagnosticHandler(DH: std::make_unique<LLVMLTODiagnosticHandler>(),
362 RespectFilters: true);
363 ErrorOr<std::unique_ptr<LTOModule>> Ret = LTOModule::createInLocalContext(
364 Context: std::move(Context), mem: Buffer->getBufferStart(), length: Buffer->getBufferSize(),
365 options: Options, path: Path);
366 CurrentActivity = "";
367 maybeVerifyModule(Mod: (*Ret)->getModule());
368 return std::move(*Ret);
369}
370
371/// Print some statistics on the index for each input files.
372static void printIndexStats() {
373 for (auto &Filename : InputFilenames) {
374 ExitOnError ExitOnErr("llvm-lto: error loading file '" + Filename + "': ");
375 std::unique_ptr<ModuleSummaryIndex> Index =
376 ExitOnErr(getModuleSummaryIndexForFile(Path: Filename));
377 // Skip files without a module summary.
378 if (!Index)
379 report_fatal_error(reason: Twine(Filename) + " does not contain an index");
380
381 unsigned Calls = 0, Refs = 0, Functions = 0, Alias = 0, Globals = 0;
382 for (auto &Summaries : *Index) {
383 for (auto &Summary : Summaries.second.getSummaryList()) {
384 Refs += Summary->refs().size();
385 if (auto *FuncSummary = dyn_cast<FunctionSummary>(Val: Summary.get())) {
386 Functions++;
387 Calls += FuncSummary->calls().size();
388 } else if (isa<AliasSummary>(Val: Summary.get()))
389 Alias++;
390 else
391 Globals++;
392 }
393 }
394 outs() << "Index " << Filename << " contains "
395 << (Alias + Globals + Functions) << " nodes (" << Functions
396 << " functions, " << Alias << " alias, " << Globals
397 << " globals) and " << (Calls + Refs) << " edges (" << Refs
398 << " refs and " << Calls << " calls)\n";
399 }
400}
401
402/// Print the lto symbol attributes.
403static void printLTOSymbolAttributes(lto_symbol_attributes Attrs) {
404 outs() << "{ ";
405 unsigned Permission = Attrs & LTO_SYMBOL_PERMISSIONS_MASK;
406 switch (Permission) {
407 case LTO_SYMBOL_PERMISSIONS_CODE:
408 outs() << "function ";
409 break;
410 case LTO_SYMBOL_PERMISSIONS_DATA:
411 outs() << "data ";
412 break;
413 case LTO_SYMBOL_PERMISSIONS_RODATA:
414 outs() << "constant ";
415 break;
416 }
417 unsigned Definition = Attrs & LTO_SYMBOL_DEFINITION_MASK;
418 switch (Definition) {
419 case LTO_SYMBOL_DEFINITION_REGULAR:
420 outs() << "defined ";
421 break;
422 case LTO_SYMBOL_DEFINITION_TENTATIVE:
423 outs() << "common ";
424 break;
425 case LTO_SYMBOL_DEFINITION_WEAK:
426 outs() << "weak ";
427 break;
428 case LTO_SYMBOL_DEFINITION_UNDEFINED:
429 outs() << "extern ";
430 break;
431 case LTO_SYMBOL_DEFINITION_WEAKUNDEF:
432 outs() << "extern-weak ";
433 break;
434 }
435 unsigned Scope = Attrs & LTO_SYMBOL_SCOPE_MASK;
436 switch (Scope) {
437 case LTO_SYMBOL_SCOPE_INTERNAL:
438 outs() << "internal ";
439 break;
440 case LTO_SYMBOL_SCOPE_HIDDEN:
441 outs() << "hidden ";
442 break;
443 case LTO_SYMBOL_SCOPE_PROTECTED:
444 outs() << "protected ";
445 break;
446 case LTO_SYMBOL_SCOPE_DEFAULT:
447 outs() << "default ";
448 break;
449 case LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN:
450 outs() << "omitted ";
451 break;
452 }
453 if (Attrs & LTO_SYMBOL_COMDAT)
454 outs() << "comdat ";
455 if (Attrs & LTO_SYMBOL_ALIAS)
456 outs() << "alias ";
457 outs() << "}";
458}
459
460/// Load each IR file and dump certain information based on active flags.
461///
462/// The main point here is to provide lit-testable coverage for the LTOModule
463/// functionality that's exposed by the C API. Moreover, this provides testing
464/// coverage for modules that have been created in their own contexts.
465static void testLTOModule(const TargetOptions &Options) {
466 for (auto &Filename : InputFilenames) {
467 std::unique_ptr<MemoryBuffer> Buffer;
468 std::unique_ptr<LTOModule> Module =
469 getLocalLTOModule(Path: Filename, Buffer, Options);
470
471 if (ListSymbolsOnly) {
472 // List the symbols.
473 outs() << Filename << ":\n";
474 for (int I = 0, E = Module->getSymbolCount(); I != E; ++I) {
475 outs() << Module->getSymbolName(index: I) << " ";
476 printLTOSymbolAttributes(Attrs: Module->getSymbolAttributes(index: I));
477 outs() << "\n";
478 }
479 for (int I = 0, E = Module->getAsmUndefSymbolCount(); I != E; ++I)
480 outs() << Module->getAsmUndefSymbolName(index: I) << " { asm extern }\n";
481 }
482 if (QueryHasCtorDtor)
483 outs() << Filename
484 << ": hasCtorDtor = " << (Module->hasCtorDtor() ? "true" : "false")
485 << "\n";
486 }
487}
488
489static std::unique_ptr<MemoryBuffer> loadFile(StringRef Filename) {
490 ExitOnError ExitOnErr("llvm-lto: error loading file '" + Filename.str() +
491 "': ");
492 return ExitOnErr(errorOrToExpected(EO: MemoryBuffer::getFileOrSTDIN(Filename)));
493}
494
495static void listDependentLibraries() {
496 for (auto &Filename : InputFilenames) {
497 auto Buffer = loadFile(Filename);
498 std::string E;
499 std::unique_ptr<lto::InputFile> Input(LTOModule::createInputFile(
500 buffer: Buffer->getBufferStart(), buffer_size: Buffer->getBufferSize(), path: Filename.c_str(),
501 out_error&: E));
502 if (!Input)
503 error(Msg: E);
504
505 // List the dependent libraries.
506 outs() << Filename << ":\n";
507 for (size_t I = 0, C = LTOModule::getDependentLibraryCount(input: Input.get());
508 I != C; ++I) {
509 size_t L = 0;
510 const char *S = LTOModule::getDependentLibrary(input: Input.get(), index: I, size: &L);
511 assert(S);
512 outs() << StringRef(S, L) << "\n";
513 }
514 }
515}
516
517static void printMachOCPUOnly(const cl::LibraryOptionsContext &LibraryOptions) {
518 LLVMContext Context;
519 Context.setDiagnosticHandler(DH: std::make_unique<LLVMLTODiagnosticHandler>(),
520 RespectFilters: true);
521 TargetOptions Options = codegen::getTargetOptions(LibraryOptions, TheTriple: Triple());
522 for (auto &Filename : InputFilenames) {
523 ErrorOr<std::unique_ptr<LTOModule>> ModuleOrErr =
524 LTOModule::createFromFile(Context, path: Filename, options: Options);
525 if (!ModuleOrErr)
526 error(V: ModuleOrErr, Prefix: "llvm-lto: ");
527
528 Expected<uint32_t> CPUType = (*ModuleOrErr)->getMachOCPUType();
529 Expected<uint32_t> CPUSubType = (*ModuleOrErr)->getMachOCPUSubType();
530 if (!CPUType)
531 error(Msg: "Error while printing mach-o cputype: " +
532 toString(E: CPUType.takeError()));
533 if (!CPUSubType)
534 error(Msg: "Error while printing mach-o cpusubtype: " +
535 toString(E: CPUSubType.takeError()));
536 outs() << llvm::format(Fmt: "%s:\ncputype: %u\ncpusubtype: %u\n",
537 Vals: Filename.c_str(), Vals: *CPUType, Vals: *CPUSubType);
538 }
539}
540
541/// Create a combined index file from the input IR files and write it.
542///
543/// This is meant to enable testing of ThinLTO combined index generation,
544/// currently available via the gold plugin via -thinlto.
545static void createCombinedModuleSummaryIndex() {
546 ModuleSummaryIndex CombinedIndex(/*HaveGVs=*/false);
547 for (auto &Filename : InputFilenames) {
548 ExitOnError ExitOnErr("llvm-lto: error loading file '" + Filename + "': ");
549 std::unique_ptr<MemoryBuffer> MB =
550 ExitOnErr(errorOrToExpected(EO: MemoryBuffer::getFileOrSTDIN(Filename)));
551 ExitOnErr(readModuleSummaryIndex(Buffer: *MB, CombinedIndex));
552 }
553 // In order to use this index for testing, specifically import testing, we
554 // need to update any indirect call edges created from SamplePGO, so that they
555 // point to the correct GUIDs.
556 updateIndirectCalls(Index&: CombinedIndex);
557 std::error_code EC;
558 assert(!OutputFilename.empty());
559 raw_fd_ostream OS(OutputFilename + ".thinlto.bc", EC,
560 sys::fs::OpenFlags::OF_None);
561 error(EC, Prefix: "error opening the file '" + OutputFilename + ".thinlto.bc'");
562 writeIndexToFile(Index: CombinedIndex, Out&: OS);
563 OS.close();
564}
565
566/// Parse the thinlto_prefix_replace option into the \p OldPrefix and
567/// \p NewPrefix strings, if it was specified.
568static void getThinLTOOldAndNewPrefix(std::string &OldPrefix,
569 std::string &NewPrefix) {
570 assert(ThinLTOPrefixReplace.empty() ||
571 ThinLTOPrefixReplace.find(';') != StringRef::npos);
572 StringRef PrefixReplace = ThinLTOPrefixReplace;
573 std::pair<StringRef, StringRef> Split = PrefixReplace.split(Separator: ";");
574 OldPrefix = Split.first.str();
575 NewPrefix = Split.second.str();
576}
577
578/// Given the original \p Path to an output file, replace any path
579/// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
580/// resulting directory if it does not yet exist.
581static std::string getThinLTOOutputFile(StringRef Path, StringRef OldPrefix,
582 StringRef NewPrefix) {
583 if (OldPrefix.empty() && NewPrefix.empty())
584 return std::string(Path);
585 SmallString<128> NewPath(Path);
586 llvm::sys::path::replace_path_prefix(Path&: NewPath, OldPrefix, NewPrefix);
587 StringRef ParentPath = llvm::sys::path::parent_path(path: NewPath.str());
588 if (!ParentPath.empty()) {
589 // Make sure the new directory exists, creating it if necessary.
590 if (std::error_code EC = llvm::sys::fs::create_directories(path: ParentPath))
591 error(EC, Prefix: "error creating the directory '" + ParentPath + "'");
592 }
593 return std::string(NewPath);
594}
595
596namespace thinlto {
597
598std::vector<std::unique_ptr<MemoryBuffer>>
599loadAllFilesForIndex(const ModuleSummaryIndex &Index) {
600 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
601
602 for (auto &ModPath : Index.modulePaths()) {
603 const auto &Filename = ModPath.first();
604 std::string CurrentActivity = ("loading file '" + Filename + "'").str();
605 auto InputOrErr = MemoryBuffer::getFile(Filename);
606 error(V: InputOrErr, Prefix: "error " + CurrentActivity);
607 InputBuffers.push_back(x: std::move(*InputOrErr));
608 }
609 return InputBuffers;
610}
611
612std::unique_ptr<ModuleSummaryIndex> loadCombinedIndex() {
613 if (ThinLTOIndex.empty())
614 report_fatal_error(reason: "Missing -thinlto-index for ThinLTO promotion stage");
615 ExitOnError ExitOnErr("llvm-lto: error loading file '" + ThinLTOIndex +
616 "': ");
617 return ExitOnErr(getModuleSummaryIndexForFile(Path: ThinLTOIndex));
618}
619
620static std::unique_ptr<lto::InputFile> loadInputFile(MemoryBufferRef Buffer) {
621 ExitOnError ExitOnErr("llvm-lto: error loading input '" +
622 Buffer.getBufferIdentifier().str() + "': ");
623 return ExitOnErr(lto::InputFile::create(Object: Buffer));
624}
625
626static std::unique_ptr<Module> loadModuleFromInput(lto::InputFile &File,
627 LLVMContext &CTX) {
628 auto &Mod = File.getSingleBitcodeModule();
629 auto ModuleOrErr = Mod.parseModule(Context&: CTX);
630 if (!ModuleOrErr) {
631 handleAllErrors(E: ModuleOrErr.takeError(), Handlers: [&](ErrorInfoBase &EIB) {
632 SMDiagnostic Err = SMDiagnostic(Mod.getModuleIdentifier(),
633 SourceMgr::DK_Error, EIB.message());
634 Err.print(ProgName: "llvm-lto", S&: errs());
635 });
636 report_fatal_error(reason: "Can't load module, abort.");
637 }
638 maybeVerifyModule(Mod: **ModuleOrErr);
639 if (ThinLTOModuleId.getNumOccurrences()) {
640 if (InputFilenames.size() != 1)
641 report_fatal_error(reason: "Can't override the module id for multiple files");
642 (*ModuleOrErr)->setModuleIdentifier(ThinLTOModuleId);
643 }
644 return std::move(*ModuleOrErr);
645}
646
647static void writeModuleToFile(Module &TheModule, StringRef Filename) {
648 std::error_code EC;
649 raw_fd_ostream OS(Filename, EC, sys::fs::OpenFlags::OF_None);
650 error(EC, Prefix: "error opening the file '" + Filename + "'");
651 maybeVerifyModule(Mod: TheModule);
652 WriteBitcodeToFile(M: TheModule, Out&: OS, /* ShouldPreserveUseListOrder */ true);
653}
654
655class ThinLTOProcessing {
656public:
657 const cl::LibraryOptionsContext &LibraryOptions;
658 ThinLTOCodeGenerator ThinGenerator;
659
660 ThinLTOProcessing(const cl::LibraryOptionsContext &LibraryOptions,
661 const TargetOptions &Options)
662 : LibraryOptions(LibraryOptions), ThinGenerator(LibraryOptions) {
663 ThinGenerator.setCodePICModel(
664 codegen::getExplicitRelocModel(C: LibraryOptions));
665 ThinGenerator.setTargetOptions(Options);
666 ThinGenerator.setCacheDir(ThinLTOCacheDir);
667 ThinGenerator.setCachePruningInterval(ThinLTOCachePruningInterval);
668 ThinGenerator.setCacheEntryExpiration(ThinLTOCacheEntryExpiration);
669 ThinGenerator.setCacheMaxSizeFiles(ThinLTOCacheMaxSizeFiles);
670 ThinGenerator.setCacheMaxSizeBytes(ThinLTOCacheMaxSizeBytes);
671 ThinGenerator.setFreestanding(EnableFreestanding);
672 ThinGenerator.setDebugPassManager(DebugPassManager);
673
674 // Add all the exported symbols to the table of symbols to preserve.
675 for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
676 ThinGenerator.preserveSymbol(Name: ExportedSymbols[i]);
677 }
678
679 void run() {
680 switch (ThinLTOMode) {
681 case THINLINK:
682 return thinLink();
683 case THINDISTRIBUTE:
684 return distributedIndexes();
685 case THINEMITIMPORTS:
686 return emitImports();
687 case THINPROMOTE:
688 return promote();
689 case THINIMPORT:
690 return import();
691 case THININTERNALIZE:
692 return internalize();
693 case THINOPT:
694 return optimize();
695 case THINCODEGEN:
696 return codegen();
697 case THINALL:
698 return runAll();
699 }
700 }
701
702private:
703 /// Load the input files, create the combined index, and write it out.
704 void thinLink() {
705 // Perform "ThinLink": just produce the index
706 if (OutputFilename.empty())
707 report_fatal_error(
708 reason: "OutputFilename is necessary to store the combined index.\n");
709
710 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
711 for (unsigned i = 0; i < InputFilenames.size(); ++i) {
712 auto &Filename = InputFilenames[i];
713 std::string CurrentActivity = "loading file '" + Filename + "'";
714 auto InputOrErr = MemoryBuffer::getFile(Filename);
715 error(V: InputOrErr, Prefix: "error " + CurrentActivity);
716 InputBuffers.push_back(x: std::move(*InputOrErr));
717 ThinGenerator.addModule(Identifier: Filename, Data: InputBuffers.back()->getBuffer());
718 }
719
720 auto CombinedIndex = ThinGenerator.linkCombinedIndex();
721 if (!CombinedIndex)
722 report_fatal_error(reason: "ThinLink didn't create an index");
723 std::error_code EC;
724 raw_fd_ostream OS(OutputFilename, EC, sys::fs::OpenFlags::OF_None);
725 error(EC, Prefix: "error opening the file '" + OutputFilename + "'");
726 writeIndexToFile(Index: *CombinedIndex, Out&: OS);
727 }
728
729 /// Load the combined index from disk, then compute and generate
730 /// individual index files suitable for ThinLTO distributed backend builds
731 /// on the files mentioned on the command line (these must match the index
732 /// content).
733 void distributedIndexes() {
734 if (InputFilenames.size() != 1 && !OutputFilename.empty())
735 report_fatal_error(reason: "Can't handle a single output filename and multiple "
736 "input files, do not provide an output filename and "
737 "the output files will be suffixed from the input "
738 "ones.");
739
740 std::string OldPrefix, NewPrefix;
741 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
742
743 auto Index = loadCombinedIndex();
744 for (auto &Filename : InputFilenames) {
745 ToolContext Ctx(LibraryOptions);
746 auto Buffer = loadFile(Filename);
747 auto Input = loadInputFile(Buffer: Buffer->getMemBufferRef());
748 auto TheModule = loadModuleFromInput(File&: *Input, CTX&: Ctx);
749
750 // Build a map of module to the GUIDs and summary objects that should
751 // be written to its index.
752 ModuleToSummariesForIndexTy ModuleToSummariesForIndex;
753 GVSummaryPtrSet DecSummaries;
754 ThinGenerator.gatherImportedSummariesForModule(
755 Module&: *TheModule, Index&: *Index, ModuleToSummariesForIndex, DecSummaries, File: *Input);
756
757 std::string OutputName = OutputFilename;
758 if (OutputName.empty()) {
759 OutputName = Filename + ".thinlto.bc";
760 }
761 OutputName = getThinLTOOutputFile(Path: OutputName, OldPrefix, NewPrefix);
762 std::error_code EC;
763 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::OF_None);
764 error(EC, Prefix: "error opening the file '" + OutputName + "'");
765 writeIndexToFile(Index: *Index, Out&: OS, ModuleToSummariesForIndex: &ModuleToSummariesForIndex, DecSummaries: &DecSummaries);
766 }
767 }
768
769 /// Load the combined index from disk, compute the imports, and emit
770 /// the import file lists for each module to disk.
771 void emitImports() {
772 if (InputFilenames.size() != 1 && !OutputFilename.empty())
773 report_fatal_error(reason: "Can't handle a single output filename and multiple "
774 "input files, do not provide an output filename and "
775 "the output files will be suffixed from the input "
776 "ones.");
777
778 std::string OldPrefix, NewPrefix;
779 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
780
781 auto Index = loadCombinedIndex();
782 for (auto &Filename : InputFilenames) {
783 ToolContext Ctx(LibraryOptions);
784 auto Buffer = loadFile(Filename);
785 auto Input = loadInputFile(Buffer: Buffer->getMemBufferRef());
786 auto TheModule = loadModuleFromInput(File&: *Input, CTX&: Ctx);
787 std::string OutputName = OutputFilename;
788 if (OutputName.empty()) {
789 OutputName = Filename + ".imports";
790 }
791 OutputName =
792 getThinLTOOutputFile(Path: OutputName, OldPrefix, NewPrefix);
793 ThinGenerator.emitImports(Module&: *TheModule, OutputName, Index&: *Index, File: *Input);
794 }
795 }
796
797 /// Load the combined index from disk, then load every file referenced by
798 /// the index and add them to the generator, finally perform the promotion
799 /// on the files mentioned on the command line (these must match the index
800 /// content).
801 void promote() {
802 if (InputFilenames.size() != 1 && !OutputFilename.empty())
803 report_fatal_error(reason: "Can't handle a single output filename and multiple "
804 "input files, do not provide an output filename and "
805 "the output files will be suffixed from the input "
806 "ones.");
807
808 auto Index = loadCombinedIndex();
809 for (auto &Filename : InputFilenames) {
810 ToolContext Ctx(LibraryOptions);
811 auto Buffer = loadFile(Filename);
812 auto Input = loadInputFile(Buffer: Buffer->getMemBufferRef());
813 auto TheModule = loadModuleFromInput(File&: *Input, CTX&: Ctx);
814
815 ThinGenerator.promote(Module&: *TheModule, Index&: *Index, File: *Input);
816
817 std::string OutputName = OutputFilename;
818 if (OutputName.empty()) {
819 OutputName = Filename + ".thinlto.promoted.bc";
820 }
821 writeModuleToFile(TheModule&: *TheModule, Filename: OutputName);
822 }
823 }
824
825 /// Load the combined index from disk, then load every file referenced by
826 /// the index and add them to the generator, then performs the promotion and
827 /// cross module importing on the files mentioned on the command line
828 /// (these must match the index content).
829 void import() {
830 if (InputFilenames.size() != 1 && !OutputFilename.empty())
831 report_fatal_error(reason: "Can't handle a single output filename and multiple "
832 "input files, do not provide an output filename and "
833 "the output files will be suffixed from the input "
834 "ones.");
835
836 auto Index = loadCombinedIndex();
837 auto InputBuffers = loadAllFilesForIndex(Index: *Index);
838 for (auto &MemBuffer : InputBuffers)
839 ThinGenerator.addModule(Identifier: MemBuffer->getBufferIdentifier(),
840 Data: MemBuffer->getBuffer());
841
842 for (auto &Filename : InputFilenames) {
843 ToolContext Ctx(LibraryOptions);
844 auto Buffer = loadFile(Filename);
845 auto Input = loadInputFile(Buffer: Buffer->getMemBufferRef());
846 auto TheModule = loadModuleFromInput(File&: *Input, CTX&: Ctx);
847
848 ThinGenerator.crossModuleImport(Module&: *TheModule, Index&: *Index, File: *Input);
849
850 std::string OutputName = OutputFilename;
851 if (OutputName.empty()) {
852 OutputName = Filename + ".thinlto.imported.bc";
853 }
854 writeModuleToFile(TheModule&: *TheModule, Filename: OutputName);
855 }
856 }
857
858 void internalize() {
859 if (InputFilenames.size() != 1 && !OutputFilename.empty())
860 report_fatal_error(reason: "Can't handle a single output filename and multiple "
861 "input files, do not provide an output filename and "
862 "the output files will be suffixed from the input "
863 "ones.");
864
865 if (ExportedSymbols.empty())
866 errs() << "Warning: -internalize will not perform without "
867 "-exported-symbol\n";
868
869 auto Index = loadCombinedIndex();
870 auto InputBuffers = loadAllFilesForIndex(Index: *Index);
871 for (auto &MemBuffer : InputBuffers)
872 ThinGenerator.addModule(Identifier: MemBuffer->getBufferIdentifier(),
873 Data: MemBuffer->getBuffer());
874
875 for (auto &Filename : InputFilenames) {
876 ToolContext Ctx(LibraryOptions);
877 auto Buffer = loadFile(Filename);
878 auto Input = loadInputFile(Buffer: Buffer->getMemBufferRef());
879 auto TheModule = loadModuleFromInput(File&: *Input, CTX&: Ctx);
880
881 ThinGenerator.internalize(Module&: *TheModule, Index&: *Index, File: *Input);
882
883 std::string OutputName = OutputFilename;
884 if (OutputName.empty()) {
885 OutputName = Filename + ".thinlto.internalized.bc";
886 }
887 writeModuleToFile(TheModule&: *TheModule, Filename: OutputName);
888 }
889 }
890
891 void optimize() {
892 if (InputFilenames.size() != 1 && !OutputFilename.empty())
893 report_fatal_error(reason: "Can't handle a single output filename and multiple "
894 "input files, do not provide an output filename and "
895 "the output files will be suffixed from the input "
896 "ones.");
897 if (!ThinLTOIndex.empty())
898 errs() << "Warning: -thinlto-index ignored for optimize stage";
899
900 for (auto &Filename : InputFilenames) {
901 ToolContext Ctx(LibraryOptions);
902 auto Buffer = loadFile(Filename);
903 auto Input = loadInputFile(Buffer: Buffer->getMemBufferRef());
904 auto TheModule = loadModuleFromInput(File&: *Input, CTX&: Ctx);
905
906 ThinGenerator.optimize(Module&: *TheModule);
907
908 std::string OutputName = OutputFilename;
909 if (OutputName.empty()) {
910 OutputName = Filename + ".thinlto.imported.bc";
911 }
912 writeModuleToFile(TheModule&: *TheModule, Filename: OutputName);
913 }
914 }
915
916 void codegen() {
917 if (InputFilenames.size() != 1 && !OutputFilename.empty())
918 report_fatal_error(reason: "Can't handle a single output filename and multiple "
919 "input files, do not provide an output filename and "
920 "the output files will be suffixed from the input "
921 "ones.");
922 if (!ThinLTOIndex.empty())
923 errs() << "Warning: -thinlto-index ignored for codegen stage";
924
925 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
926 for (auto &Filename : InputFilenames) {
927 auto InputOrErr = MemoryBuffer::getFile(Filename);
928 error(V: InputOrErr, Prefix: "error " + CurrentActivity);
929 InputBuffers.push_back(x: std::move(*InputOrErr));
930 ThinGenerator.addModule(Identifier: Filename, Data: InputBuffers.back()->getBuffer());
931 }
932 ThinGenerator.setCodeGenOnly(true);
933 ThinGenerator.run();
934 for (auto BinName :
935 zip(t&: ThinGenerator.getProducedBinaries(), u&: InputFilenames)) {
936 std::string OutputName = OutputFilename;
937 if (OutputName.empty())
938 OutputName = std::get<1>(t&: BinName) + ".thinlto.o";
939 else if (OutputName == "-") {
940 outs() << std::get<0>(t&: BinName)->getBuffer();
941 return;
942 }
943
944 std::error_code EC;
945 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::OF_None);
946 error(EC, Prefix: "error opening the file '" + OutputName + "'");
947 OS << std::get<0>(t&: BinName)->getBuffer();
948 }
949 }
950
951 /// Full ThinLTO process
952 void runAll() {
953 if (!OutputFilename.empty())
954 report_fatal_error(reason: "Do not provide an output filename for ThinLTO "
955 " processing, the output files will be suffixed from "
956 "the input ones.");
957
958 if (!ThinLTOIndex.empty())
959 errs() << "Warning: -thinlto-index ignored for full ThinLTO process";
960
961 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
962 for (unsigned i = 0; i < InputFilenames.size(); ++i) {
963 auto &Filename = InputFilenames[i];
964 std::string CurrentActivity = "loading file '" + Filename + "'";
965 auto InputOrErr = MemoryBuffer::getFile(Filename);
966 error(V: InputOrErr, Prefix: "error " + CurrentActivity);
967 InputBuffers.push_back(x: std::move(*InputOrErr));
968 ThinGenerator.addModule(Identifier: Filename, Data: InputBuffers.back()->getBuffer());
969 }
970
971 if (!ThinLTOSaveTempsPrefix.empty())
972 ThinGenerator.setSaveTempsDir(ThinLTOSaveTempsPrefix);
973
974 if (!ThinLTOGeneratedObjectsDir.empty()) {
975 ThinGenerator.setGeneratedObjectsDirectory(ThinLTOGeneratedObjectsDir);
976 ThinGenerator.run();
977 return;
978 }
979
980 ThinGenerator.run();
981
982 auto &Binaries = ThinGenerator.getProducedBinaries();
983 if (Binaries.size() != InputFilenames.size())
984 report_fatal_error(reason: "Number of output objects does not match the number "
985 "of inputs");
986
987 for (unsigned BufID = 0; BufID < Binaries.size(); ++BufID) {
988 auto OutputName = InputFilenames[BufID] + ".thinlto.o";
989 std::error_code EC;
990 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::OF_None);
991 error(EC, Prefix: "error opening the file '" + OutputName + "'");
992 OS << Binaries[BufID]->getBuffer();
993 }
994 }
995
996 /// Load the combined index from disk, then load every file referenced by
997};
998
999} // end namespace thinlto
1000
1001int main(int argc, char **argv) {
1002 InitLLVM X(argc, argv);
1003 cl::HideUnrelatedOptions(Categories: {&LTOCategory, &getColorCategory()});
1004
1005 // Initialize the configured targets.
1006 InitializeAllTargets();
1007 InitializeAllTargetMCs();
1008 InitializeAllAsmPrinters();
1009 InitializeAllAsmParsers();
1010
1011 cl::LibraryOptionsContext LibraryOptions;
1012 cl::parseCommandLineOptions(Context&: LibraryOptions, ToolOptions: codegen::getToolOptions(),
1013 Args: ArrayRef(argv, argc), Overview: "llvm LTO linker\n");
1014
1015 if (OptLevel < '0' || OptLevel > '3')
1016 error(Msg: "optimization level must be between 0 and 3");
1017
1018 // set up the TargetOptions for the machine
1019 TargetOptions Options = codegen::getTargetOptions(LibraryOptions, TheTriple: Triple());
1020
1021 if (ListSymbolsOnly || QueryHasCtorDtor) {
1022 testLTOModule(Options);
1023 return 0;
1024 }
1025
1026 if (ListDependentLibrariesOnly) {
1027 listDependentLibraries();
1028 return 0;
1029 }
1030
1031 if (IndexStats) {
1032 printIndexStats();
1033 return 0;
1034 }
1035
1036 if (CheckHasObjC) {
1037 for (auto &Filename : InputFilenames) {
1038 ExitOnError ExitOnErr(std::string(*argv) + ": error loading file '" +
1039 Filename + "': ");
1040 std::unique_ptr<MemoryBuffer> BufferOrErr =
1041 ExitOnErr(errorOrToExpected(EO: MemoryBuffer::getFile(Filename)));
1042 auto Buffer = std::move(BufferOrErr.get());
1043 if (ExitOnErr(isBitcodeContainingObjCCategory(Buffer: *Buffer)))
1044 outs() << "Bitcode " << Filename << " contains ObjC\n";
1045 else
1046 outs() << "Bitcode " << Filename << " does not contain ObjC\n";
1047 }
1048 return 0;
1049 }
1050
1051 if (PrintMachOCPUOnly) {
1052 printMachOCPUOnly(LibraryOptions);
1053 return 0;
1054 }
1055
1056 if (ThinLTOMode.getNumOccurrences()) {
1057 if (ThinLTOMode.getNumOccurrences() > 1)
1058 report_fatal_error(reason: "You can't specify more than one -thinlto-action");
1059 thinlto::ThinLTOProcessing ThinLTOProcessor(LibraryOptions, Options);
1060 ThinLTOProcessor.run();
1061 return 0;
1062 }
1063
1064 if (ThinLTO) {
1065 createCombinedModuleSummaryIndex();
1066 return 0;
1067 }
1068
1069 unsigned BaseArg = 0;
1070
1071 ToolContext Context(LibraryOptions);
1072 Context.setDiagnosticHandler(DH: std::make_unique<LLVMLTODiagnosticHandler>(),
1073 RespectFilters: true);
1074
1075 LTOCodeGenerator CodeGen(Context);
1076 CodeGen.setDisableVerify(DisableVerify);
1077
1078 if (UseDiagnosticHandler)
1079 CodeGen.setDiagnosticHandler(handleDiagnostics, nullptr);
1080
1081 CodeGen.setCodePICModel(codegen::getExplicitRelocModel(C: LibraryOptions));
1082 CodeGen.setFreestanding(EnableFreestanding);
1083 CodeGen.setDebugPassManager(DebugPassManager);
1084
1085 CodeGen.setDebugInfo(LTO_DEBUG_MODEL_DWARF);
1086 CodeGen.setTargetOptions(Options);
1087 CodeGen.setShouldRestoreGlobalsLinkage(RestoreGlobalsLinkage);
1088
1089 StringSet<MallocAllocator> DSOSymbolsSet(llvm::from_range, DSOSymbols);
1090
1091 std::vector<std::string> KeptDSOSyms;
1092
1093 for (unsigned i = BaseArg; i < InputFilenames.size(); ++i) {
1094 CurrentActivity = "loading file '" + InputFilenames[i] + "'";
1095 ErrorOr<std::unique_ptr<LTOModule>> ModuleOrErr =
1096 LTOModule::createFromFile(Context, path: InputFilenames[i], options: Options);
1097 std::unique_ptr<LTOModule> &Module = *ModuleOrErr;
1098 CurrentActivity = "";
1099
1100 unsigned NumSyms = Module->getSymbolCount();
1101 for (unsigned I = 0; I < NumSyms; ++I) {
1102 StringRef Name = Module->getSymbolName(index: I);
1103 if (!DSOSymbolsSet.count(Key: Name))
1104 continue;
1105 lto_symbol_attributes Attrs = Module->getSymbolAttributes(index: I);
1106 unsigned Scope = Attrs & LTO_SYMBOL_SCOPE_MASK;
1107 if (Scope != LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN)
1108 KeptDSOSyms.push_back(x: std::string(Name));
1109 }
1110
1111 // We use the first input module as the destination module when
1112 // SetMergedModule is true.
1113 if (SetMergedModule && i == BaseArg) {
1114 // Transfer ownership to the code generator.
1115 CodeGen.setModule(std::move(Module));
1116 } else if (!CodeGen.addModule(Module.get())) {
1117 // Print a message here so that we know addModule() did not abort.
1118 error(Msg: "error adding file '" + InputFilenames[i] + "'");
1119 }
1120 }
1121
1122 // Add all the exported symbols to the table of symbols to preserve.
1123 for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
1124 CodeGen.addMustPreserveSymbol(Sym: ExportedSymbols[i]);
1125
1126 // Add all the dso symbols to the table of symbols to expose.
1127 for (unsigned i = 0; i < KeptDSOSyms.size(); ++i)
1128 CodeGen.addMustPreserveSymbol(Sym: KeptDSOSyms[i]);
1129
1130 // Set cpu and attrs strings for the default target/subtarget.
1131 CodeGen.setCpu(codegen::getMCPU(C: LibraryOptions));
1132
1133 CodeGen.setOptLevel(OptLevel - '0');
1134 CodeGen.setAttrs(codegen::getMAttrs(C: LibraryOptions));
1135
1136 if (auto FT = codegen::getExplicitFileType(C: LibraryOptions))
1137 CodeGen.setFileType(*FT);
1138
1139 if (!OutputFilename.empty()) {
1140 if (LTOSaveBeforeOpt)
1141 CodeGen.setSaveIRBeforeOptPath(OutputFilename + ".0.preopt.bc");
1142
1143 if (SaveLinkedModuleFile) {
1144 std::string ModuleFilename = OutputFilename;
1145 ModuleFilename += ".linked.bc";
1146
1147 if (!CodeGen.writeMergedModules(Path: ModuleFilename))
1148 error(Msg: "writing linked module failed.");
1149 }
1150
1151 if (!CodeGen.optimize()) {
1152 // Diagnostic messages should have been printed by the handler.
1153 error(Msg: "error optimizing the code");
1154 }
1155
1156 if (SaveModuleFile) {
1157 std::string ModuleFilename = OutputFilename;
1158 ModuleFilename += ".merged.bc";
1159
1160 if (!CodeGen.writeMergedModules(Path: ModuleFilename))
1161 error(Msg: "writing merged module failed.");
1162 }
1163
1164 auto AddStream =
1165 [&](size_t Task,
1166 const Twine &ModuleName) -> std::unique_ptr<CachedFileStream> {
1167 std::string PartFilename = OutputFilename;
1168 if (Parallelism != 1)
1169 PartFilename += "." + utostr(X: Task);
1170
1171 std::error_code EC;
1172 auto S =
1173 std::make_unique<raw_fd_ostream>(args&: PartFilename, args&: EC, args: sys::fs::OF_None);
1174 if (EC)
1175 error(Msg: "error opening the file '" + PartFilename + "': " + EC.message());
1176 return std::make_unique<CachedFileStream>(args: std::move(S));
1177 };
1178
1179 if (!CodeGen.compileOptimized(AddStream, ParallelismLevel: Parallelism))
1180 // Diagnostic messages should have been printed by the handler.
1181 error(Msg: "error compiling the code");
1182
1183 } else {
1184 if (Parallelism != 1)
1185 error(Msg: "-j must be specified together with -o");
1186
1187 if (SaveModuleFile)
1188 error(Msg: ": -save-merged-module must be specified with -o");
1189
1190 const char *OutputName = nullptr;
1191 if (!CodeGen.compile_to_file(Name: &OutputName))
1192 error(Msg: "error compiling the code");
1193 // Diagnostic messages should have been printed by the handler.
1194
1195 outs() << "Wrote native object file '" << OutputName << "'\n";
1196 }
1197
1198 return 0;
1199}
1200