blob: eb8aa27b0339ab41dac21a29c9eefd922cc10ae5 [file] [log] [blame]
Eugene Zelenko975293f2017-09-07 23:28:24 +00001//===- llvm-lto: a simple command-line program to link modules with LTO ---===//
Peter Collingbourne4e380b02013-09-19 22:15:52 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This program takes in a list of bitcode files, links them, performs link-time
11// optimization, and outputs an object file.
12//
13//===----------------------------------------------------------------------===//
14
Eugene Zelenko975293f2017-09-07 23:28:24 +000015#include "llvm-c/lto.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallString.h"
19#include "llvm/ADT/StringExtras.h"
20#include "llvm/ADT/StringRef.h"
Rafael Espindola282a4702013-10-31 20:51:58 +000021#include "llvm/ADT/StringSet.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000022#include "llvm/ADT/Twine.h"
Teresa Johnsonad176792016-11-11 05:34:58 +000023#include "llvm/Bitcode/BitcodeReader.h"
24#include "llvm/Bitcode/BitcodeWriter.h"
David Blaikie4333f972018-04-11 18:49:37 +000025#include "llvm/CodeGen/CommandFlags.inc"
Eugene Zelenko975293f2017-09-07 23:28:24 +000026#include "llvm/IR/DiagnosticInfo.h"
Mehdi Amini354f5202015-11-19 05:52:29 +000027#include "llvm/IR/DiagnosticPrinter.h"
Teresa Johnson91a88bb2015-10-19 14:30:44 +000028#include "llvm/IR/LLVMContext.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000029#include "llvm/IR/Module.h"
30#include "llvm/IR/ModuleSummaryIndex.h"
Mehdi Amini3c0e64c2016-04-20 01:04:26 +000031#include "llvm/IR/Verifier.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000032#include "llvm/IRReader/IRReader.h"
Peter Collingbourne5c732202016-07-14 21:21:16 +000033#include "llvm/LTO/legacy/LTOCodeGenerator.h"
34#include "llvm/LTO/legacy/LTOModule.h"
35#include "llvm/LTO/legacy/ThinLTOCodeGenerator.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000036#include "llvm/Support/Allocator.h"
37#include "llvm/Support/Casting.h"
Peter Collingbourne4e380b02013-09-19 22:15:52 +000038#include "llvm/Support/CommandLine.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000039#include "llvm/Support/Error.h"
40#include "llvm/Support/ErrorHandling.h"
41#include "llvm/Support/ErrorOr.h"
Benjamin Kramerd59664f2014-04-29 23:26:49 +000042#include "llvm/Support/FileSystem.h"
Rui Ueyama197194b2018-04-13 18:26:06 +000043#include "llvm/Support/InitLLVM.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000044#include "llvm/Support/MemoryBuffer.h"
Teresa Johnsonbbd10b42016-05-17 14:45:30 +000045#include "llvm/Support/Path.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000046#include "llvm/Support/SourceMgr.h"
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +000047#include "llvm/Support/TargetSelect.h"
Peter Collingbournec269ed52015-08-27 23:37:36 +000048#include "llvm/Support/ToolOutputFile.h"
Chandler Carruth07baed52014-01-13 08:04:33 +000049#include "llvm/Support/raw_ostream.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000050#include "llvm/Target/TargetOptions.h"
51#include <algorithm>
52#include <cassert>
53#include <cstdint>
54#include <cstdlib>
Peter Collingbournec269ed52015-08-27 23:37:36 +000055#include <list>
Eugene Zelenko975293f2017-09-07 23:28:24 +000056#include <map>
57#include <memory>
58#include <string>
59#include <system_error>
60#include <tuple>
61#include <utility>
62#include <vector>
Peter Collingbourne4e380b02013-09-19 22:15:52 +000063
64using namespace llvm;
65
Peter Collingbourne070843d2015-03-19 22:01:00 +000066static cl::opt<char>
Davide Italianob10e8932016-04-13 21:41:35 +000067 OptLevel("O", cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
68 "(default = '-O2')"),
69 cl::Prefix, cl::ZeroOrMore, cl::init('2'));
Peter Collingbourne4e380b02013-09-19 22:15:52 +000070
Mehdi Amini06a47802016-09-14 21:04:59 +000071static cl::opt<bool>
72 IndexStats("thinlto-index-stats",
73 cl::desc("Print statistic for the index in every input files"),
74 cl::init(false));
75
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +000076static cl::opt<bool> DisableVerify(
77 "disable-verify", cl::init(false),
78 cl::desc("Do not run the verifier during the optimization pipeline"));
79
Davide Italianob10e8932016-04-13 21:41:35 +000080static cl::opt<bool> DisableInline("disable-inlining", cl::init(false),
81 cl::desc("Do not run the inliner pass"));
Rafael Espindola0b385c72013-09-30 16:39:19 +000082
83static cl::opt<bool>
Davide Italianob10e8932016-04-13 21:41:35 +000084 DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
85 cl::desc("Do not run the GVN load PRE pass"));
Rafael Espindola0b385c72013-09-30 16:39:19 +000086
Davide Italianob10e8932016-04-13 21:41:35 +000087static cl::opt<bool> DisableLTOVectorization(
88 "disable-lto-vectorization", cl::init(false),
89 cl::desc("Do not run loop or slp vectorization during LTO"));
Arnold Schwaighofereb1a38f2014-10-26 21:50:58 +000090
Mehdi Aminib5a46c12017-03-28 18:55:44 +000091static cl::opt<bool> EnableFreestanding(
92 "lto-freestanding", cl::init(false),
93 cl::desc("Enable Freestanding (disable builtins / TLI) during LTO"));
94
Davide Italianob10e8932016-04-13 21:41:35 +000095static cl::opt<bool> UseDiagnosticHandler(
96 "use-diagnostic-handler", cl::init(false),
97 cl::desc("Use a diagnostic handler to test the handler interface"));
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +000098
Teresa Johnsonf72278f2015-11-02 18:02:11 +000099static cl::opt<bool>
100 ThinLTO("thinlto", cl::init(false),
101 cl::desc("Only write combined global index for ThinLTO backends"));
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000102
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000103enum ThinLTOModes {
104 THINLINK,
Teresa Johnson84174c32016-05-10 13:48:23 +0000105 THINDISTRIBUTE,
Teresa Johnson8570fe42016-05-10 15:54:09 +0000106 THINEMITIMPORTS,
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000107 THINPROMOTE,
108 THINIMPORT,
Mehdi Amini059464f2016-04-24 03:18:01 +0000109 THININTERNALIZE,
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000110 THINOPT,
111 THINCODEGEN,
112 THINALL
113};
114
115cl::opt<ThinLTOModes> ThinLTOMode(
116 "thinlto-action", cl::desc("Perform a single ThinLTO stage:"),
117 cl::values(
118 clEnumValN(
119 THINLINK, "thinlink",
120 "ThinLink: produces the index by linking only the summaries."),
Teresa Johnson84174c32016-05-10 13:48:23 +0000121 clEnumValN(THINDISTRIBUTE, "distributedindexes",
122 "Produces individual indexes for distributed backends."),
Teresa Johnson8570fe42016-05-10 15:54:09 +0000123 clEnumValN(THINEMITIMPORTS, "emitimports",
124 "Emit imports files for distributed backends."),
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000125 clEnumValN(THINPROMOTE, "promote",
126 "Perform pre-import promotion (requires -thinlto-index)."),
127 clEnumValN(THINIMPORT, "import", "Perform both promotion and "
128 "cross-module importing (requires "
129 "-thinlto-index)."),
Mehdi Amini059464f2016-04-24 03:18:01 +0000130 clEnumValN(THININTERNALIZE, "internalize",
131 "Perform internalization driven by -exported-symbol "
132 "(requires -thinlto-index)."),
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000133 clEnumValN(THINOPT, "optimize", "Perform ThinLTO optimizations."),
134 clEnumValN(THINCODEGEN, "codegen", "CodeGen (expected to match llc)"),
Mehdi Amini732afdd2016-10-08 19:41:06 +0000135 clEnumValN(THINALL, "run", "Perform ThinLTO end-to-end")));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000136
137static cl::opt<std::string>
138 ThinLTOIndex("thinlto-index",
139 cl::desc("Provide the index produced by a ThinLink, required "
140 "to perform the promotion and/or importing."));
141
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000142static cl::opt<std::string> ThinLTOPrefixReplace(
143 "thinlto-prefix-replace",
144 cl::desc("Control where files for distributed backends are "
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000145 "created. Expects 'oldprefix;newprefix' and if path "
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000146 "prefix of output file is oldprefix it will be "
147 "replaced with newprefix."));
148
Mehdi Amini03abce92016-05-05 16:33:51 +0000149static cl::opt<std::string> ThinLTOModuleId(
150 "thinlto-module-id",
151 cl::desc("For the module ID for the file to process, useful to "
152 "match what is in the index."));
153
Mehdi Aminiab4a8b62016-05-14 05:16:41 +0000154static cl::opt<std::string>
155 ThinLTOCacheDir("thinlto-cache-dir", cl::desc("Enable ThinLTO caching."));
156
Ben Dunbobbin9ecb8b52017-12-19 14:42:38 +0000157static cl::opt<int>
Ekaterina Romanovad345f732018-02-15 23:29:21 +0000158 ThinLTOCachePruningInterval("thinlto-cache-pruning-interval",
159 cl::init(1200), cl::desc("Set ThinLTO cache pruning interval."));
Ben Dunbobbin9ecb8b52017-12-19 14:42:38 +0000160
Ekaterina Romanovab8aeec42018-03-02 03:51:27 +0000161static cl::opt<int>
162 ThinLTOCacheMaxSizeBytes("thinlto-cache-max-size-bytes",
163 cl::desc("Set ThinLTO cache pruning directory maximum size in bytes."));
164
165static cl::opt<int>
166 ThinLTOCacheMaxSizeFiles("thinlto-cache-max-size-files", cl::init(1000000),
167 cl::desc("Set ThinLTO cache pruning directory maximum number of files."));
168
Teresa Johnsonc44a1222016-08-15 23:24:57 +0000169static cl::opt<std::string> ThinLTOSaveTempsPrefix(
170 "thinlto-save-temps",
171 cl::desc("Save ThinLTO temp files using filenames created by adding "
172 "suffixes to the given file path prefix."));
173
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000174static cl::opt<std::string> ThinLTOGeneratedObjectsDir(
175 "thinlto-save-objects",
176 cl::desc("Save ThinLTO generated object files using filenames created in "
177 "the given directory."));
178
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000179static cl::opt<bool>
Davide Italianob10e8932016-04-13 21:41:35 +0000180 SaveModuleFile("save-merged-module", cl::init(false),
181 cl::desc("Write merged LTO module to file before CodeGen"));
182
183static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
184 cl::desc("<input bitcode files>"));
185
186static cl::opt<std::string> OutputFilename("o", cl::init(""),
187 cl::desc("Override output filename"),
188 cl::value_desc("filename"));
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000189
Mehdi Amini059464f2016-04-24 03:18:01 +0000190static cl::list<std::string> ExportedSymbols(
191 "exported-symbol",
192 cl::desc("List of symbols to export from the resulting object file"),
193 cl::ZeroOrMore);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000194
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000195static cl::list<std::string>
Davide Italianob10e8932016-04-13 21:41:35 +0000196 DSOSymbols("dso-symbol",
197 cl::desc("Symbol to put in the symtab in the resulting dso"),
198 cl::ZeroOrMore);
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000199
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000200static cl::opt<bool> ListSymbolsOnly(
201 "list-symbols-only", cl::init(false),
202 cl::desc("Instead of running LTO, list the symbols in each IR file"));
203
Manman Ren6487ce92015-02-24 00:45:56 +0000204static cl::opt<bool> SetMergedModule(
205 "set-merged-module", cl::init(false),
206 cl::desc("Use the first input module as the merged module"));
207
Peter Collingbournec269ed52015-08-27 23:37:36 +0000208static cl::opt<unsigned> Parallelism("j", cl::Prefix, cl::init(1),
209 cl::desc("Number of backend threads"));
210
Tobias Edler von Koch3f4f6f3e2016-01-18 23:35:24 +0000211static cl::opt<bool> RestoreGlobalsLinkage(
212 "restore-linkage", cl::init(false),
213 cl::desc("Restore original linkage of globals prior to CodeGen"));
214
Mehdi Aminie75aa6f2016-07-11 23:10:18 +0000215static cl::opt<bool> CheckHasObjC(
216 "check-for-objc", cl::init(false),
217 cl::desc("Only check if the module has objective-C defined in it"));
218
Rafael Espindola282a4702013-10-31 20:51:58 +0000219namespace {
Eugene Zelenko975293f2017-09-07 23:28:24 +0000220
Rafael Espindola282a4702013-10-31 20:51:58 +0000221struct ModuleInfo {
222 std::vector<bool> CanBeHidden;
223};
Eugene Zelenko975293f2017-09-07 23:28:24 +0000224
225} // end anonymous namespace
Rafael Espindola282a4702013-10-31 20:51:58 +0000226
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000227static void handleDiagnostics(lto_codegen_diagnostic_severity_t Severity,
228 const char *Msg, void *) {
Yunzhong Gaoef436f02015-11-10 18:52:48 +0000229 errs() << "llvm-lto: ";
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +0000230 switch (Severity) {
231 case LTO_DS_NOTE:
232 errs() << "note: ";
233 break;
234 case LTO_DS_REMARK:
235 errs() << "remark: ";
236 break;
237 case LTO_DS_ERROR:
238 errs() << "error: ";
239 break;
240 case LTO_DS_WARNING:
241 errs() << "warning: ";
242 break;
243 }
244 errs() << Msg << "\n";
245}
246
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000247static std::string CurrentActivity;
Vivek Pandyab5ab8952017-09-15 20:10:09 +0000248
249namespace {
250 struct LLVMLTODiagnosticHandler : public DiagnosticHandler {
251 bool handleDiagnostics(const DiagnosticInfo &DI) override {
252 raw_ostream &OS = errs();
253 OS << "llvm-lto: ";
254 switch (DI.getSeverity()) {
255 case DS_Error:
256 OS << "error";
257 break;
258 case DS_Warning:
259 OS << "warning";
260 break;
261 case DS_Remark:
262 OS << "remark";
263 break;
264 case DS_Note:
265 OS << "note";
266 break;
267 }
268 if (!CurrentActivity.empty())
269 OS << ' ' << CurrentActivity;
270 OS << ": ";
271
272 DiagnosticPrinterRawOStream DP(OS);
273 DI.print(DP);
274 OS << '\n';
275
276 if (DI.getSeverity() == DS_Error)
277 exit(1);
278 return true;
279 }
280 };
Mehdi Amini354f5202015-11-19 05:52:29 +0000281 }
Mehdi Amini354f5202015-11-19 05:52:29 +0000282
Rafael Espindola5e128db2015-12-04 00:45:57 +0000283static void error(const Twine &Msg) {
284 errs() << "llvm-lto: " << Msg << '\n';
285 exit(1);
286}
287
288static void error(std::error_code EC, const Twine &Prefix) {
289 if (EC)
290 error(Prefix + ": " + EC.message());
291}
292
293template <typename T>
294static void error(const ErrorOr<T> &V, const Twine &Prefix) {
295 error(V.getError(), Prefix);
296}
297
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000298static void maybeVerifyModule(const Module &Mod) {
Mehdi Amini4c809462016-12-23 23:53:57 +0000299 if (!DisableVerify && verifyModule(Mod, &errs()))
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000300 error("Broken Module");
301}
302
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000303static std::unique_ptr<LTOModule>
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000304getLocalLTOModule(StringRef Path, std::unique_ptr<MemoryBuffer> &Buffer,
Rafael Espindola5e128db2015-12-04 00:45:57 +0000305 const TargetOptions &Options) {
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000306 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
307 MemoryBuffer::getFile(Path);
Rafael Espindola5e128db2015-12-04 00:45:57 +0000308 error(BufferOrErr, "error loading file '" + Path + "'");
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000309 Buffer = std::move(BufferOrErr.get());
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000310 CurrentActivity = ("loading file '" + Path + "'").str();
Petr Pavlu7ad9ec92016-03-01 13:13:49 +0000311 std::unique_ptr<LLVMContext> Context = llvm::make_unique<LLVMContext>();
Vivek Pandyab5ab8952017-09-15 20:10:09 +0000312 Context->setDiagnosticHandler(llvm::make_unique<LLVMLTODiagnosticHandler>(),
313 true);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000314 ErrorOr<std::unique_ptr<LTOModule>> Ret = LTOModule::createInLocalContext(
Petr Pavlu7ad9ec92016-03-01 13:13:49 +0000315 std::move(Context), Buffer->getBufferStart(), Buffer->getBufferSize(),
316 Options, Path);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000317 CurrentActivity = "";
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000318 maybeVerifyModule((*Ret)->getModule());
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000319 return std::move(*Ret);
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000320}
321
Mehdi Amini06a47802016-09-14 21:04:59 +0000322/// Print some statistics on the index for each input files.
323void printIndexStats() {
324 for (auto &Filename : InputFilenames) {
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000325 ExitOnError ExitOnErr("llvm-lto: error loading file '" + Filename + "': ");
326 std::unique_ptr<ModuleSummaryIndex> Index =
Eugene Zelenko975293f2017-09-07 23:28:24 +0000327 ExitOnErr(getModuleSummaryIndexForFile(Filename));
Mehdi Amini06a47802016-09-14 21:04:59 +0000328 // Skip files without a module summary.
329 if (!Index)
330 report_fatal_error(Filename + " does not contain an index");
331
332 unsigned Calls = 0, Refs = 0, Functions = 0, Alias = 0, Globals = 0;
333 for (auto &Summaries : *Index) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000334 for (auto &Summary : Summaries.second.SummaryList) {
Mehdi Amini06a47802016-09-14 21:04:59 +0000335 Refs += Summary->refs().size();
336 if (auto *FuncSummary = dyn_cast<FunctionSummary>(Summary.get())) {
337 Functions++;
338 Calls += FuncSummary->calls().size();
339 } else if (isa<AliasSummary>(Summary.get()))
340 Alias++;
341 else
342 Globals++;
343 }
344 }
345 outs() << "Index " << Filename << " contains "
346 << (Alias + Globals + Functions) << " nodes (" << Functions
347 << " functions, " << Alias << " alias, " << Globals
348 << " globals) and " << (Calls + Refs) << " edges (" << Refs
349 << " refs and " << Calls << " calls)\n";
350 }
351}
352
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000353/// List symbols in each IR file.
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000354///
355/// The main point here is to provide lit-testable coverage for the LTOModule
356/// functionality that's exposed by the C API to list symbols. Moreover, this
357/// provides testing coverage for modules that have been created in their own
358/// contexts.
Rafael Espindola5e128db2015-12-04 00:45:57 +0000359static void listSymbols(const TargetOptions &Options) {
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000360 for (auto &Filename : InputFilenames) {
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000361 std::unique_ptr<MemoryBuffer> Buffer;
362 std::unique_ptr<LTOModule> Module =
Rafael Espindola5e128db2015-12-04 00:45:57 +0000363 getLocalLTOModule(Filename, Buffer, Options);
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000364
365 // List the symbols.
366 outs() << Filename << ":\n";
367 for (int I = 0, E = Module->getSymbolCount(); I != E; ++I)
368 outs() << Module->getSymbolName(I) << "\n";
369 }
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000370}
371
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000372/// Create a combined index file from the input IR files and write it.
373///
374/// This is meant to enable testing of ThinLTO combined index generation,
375/// currently available via the gold plugin via -thinlto.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000376static void createCombinedModuleSummaryIndex() {
Eugene Leviant28d8a492018-01-22 13:35:40 +0000377 ModuleSummaryIndex CombinedIndex(/*IsPerformingAnalysis=*/false);
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000378 uint64_t NextModuleId = 0;
379 for (auto &Filename : InputFilenames) {
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000380 ExitOnError ExitOnErr("llvm-lto: error loading file '" + Filename + "': ");
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000381 std::unique_ptr<MemoryBuffer> MB =
382 ExitOnErr(errorOrToExpected(MemoryBuffer::getFileOrSTDIN(Filename)));
Teresa Johnson43e71ec42018-05-16 14:58:14 +0000383 ExitOnErr(readModuleSummaryIndex(*MB, CombinedIndex, NextModuleId++));
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000384 }
385 std::error_code EC;
386 assert(!OutputFilename.empty());
387 raw_fd_ostream OS(OutputFilename + ".thinlto.bc", EC,
388 sys::fs::OpenFlags::F_None);
Rafael Espindola5e128db2015-12-04 00:45:57 +0000389 error(EC, "error opening the file '" + OutputFilename + ".thinlto.bc'");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000390 WriteIndexToFile(CombinedIndex, OS);
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000391 OS.close();
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000392}
393
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000394/// Parse the thinlto_prefix_replace option into the \p OldPrefix and
395/// \p NewPrefix strings, if it was specified.
396static void getThinLTOOldAndNewPrefix(std::string &OldPrefix,
397 std::string &NewPrefix) {
398 assert(ThinLTOPrefixReplace.empty() ||
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000399 ThinLTOPrefixReplace.find(";") != StringRef::npos);
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000400 StringRef PrefixReplace = ThinLTOPrefixReplace;
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000401 std::pair<StringRef, StringRef> Split = PrefixReplace.split(";");
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000402 OldPrefix = Split.first.str();
403 NewPrefix = Split.second.str();
404}
405
406/// Given the original \p Path to an output file, replace any path
407/// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
408/// resulting directory if it does not yet exist.
409static std::string getThinLTOOutputFile(const std::string &Path,
410 const std::string &OldPrefix,
411 const std::string &NewPrefix) {
412 if (OldPrefix.empty() && NewPrefix.empty())
413 return Path;
414 SmallString<128> NewPath(Path);
415 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
416 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
417 if (!ParentPath.empty()) {
418 // Make sure the new directory exists, creating it if necessary.
419 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
420 error(EC, "error creating the directory '" + ParentPath + "'");
421 }
422 return NewPath.str();
423}
424
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000425namespace thinlto {
426
427std::vector<std::unique_ptr<MemoryBuffer>>
Teresa Johnson26ab5772016-03-15 00:04:37 +0000428loadAllFilesForIndex(const ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000429 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
430
Mehdi Amini385cf282016-03-26 03:35:38 +0000431 for (auto &ModPath : Index.modulePaths()) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000432 const auto &Filename = ModPath.first();
Alexander Kornienko656466e2017-07-04 15:13:02 +0000433 std::string CurrentActivity = ("loading file '" + Filename + "'").str();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000434 auto InputOrErr = MemoryBuffer::getFile(Filename);
435 error(InputOrErr, "error " + CurrentActivity);
436 InputBuffers.push_back(std::move(*InputOrErr));
437 }
438 return InputBuffers;
439}
440
Teresa Johnson26ab5772016-03-15 00:04:37 +0000441std::unique_ptr<ModuleSummaryIndex> loadCombinedIndex() {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000442 if (ThinLTOIndex.empty())
443 report_fatal_error("Missing -thinlto-index for ThinLTO promotion stage");
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000444 ExitOnError ExitOnErr("llvm-lto: error loading file '" + ThinLTOIndex +
445 "': ");
Eugene Zelenko975293f2017-09-07 23:28:24 +0000446 return ExitOnErr(getModuleSummaryIndexForFile(ThinLTOIndex));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000447}
448
449static std::unique_ptr<Module> loadModule(StringRef Filename,
450 LLVMContext &Ctx) {
451 SMDiagnostic Err;
452 std::unique_ptr<Module> M(parseIRFile(Filename, Err, Ctx));
453 if (!M) {
454 Err.print("llvm-lto", errs());
455 report_fatal_error("Can't load module for file " + Filename);
456 }
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000457 maybeVerifyModule(*M);
Mehdi Amini03abce92016-05-05 16:33:51 +0000458
459 if (ThinLTOModuleId.getNumOccurrences()) {
460 if (InputFilenames.size() != 1)
461 report_fatal_error("Can't override the module id for multiple files");
462 M->setModuleIdentifier(ThinLTOModuleId);
463 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000464 return M;
465}
466
467static void writeModuleToFile(Module &TheModule, StringRef Filename) {
468 std::error_code EC;
469 raw_fd_ostream OS(Filename, EC, sys::fs::OpenFlags::F_None);
470 error(EC, "error opening the file '" + Filename + "'");
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000471 maybeVerifyModule(TheModule);
Rafael Espindola6a86e252018-02-14 19:11:32 +0000472 WriteBitcodeToFile(TheModule, OS, /* ShouldPreserveUseListOrder */ true);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000473}
474
475class ThinLTOProcessing {
476public:
477 ThinLTOCodeGenerator ThinGenerator;
478
479 ThinLTOProcessing(const TargetOptions &Options) {
Rafael Espindola8c34dd82016-05-18 22:04:49 +0000480 ThinGenerator.setCodePICModel(getRelocModel());
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000481 ThinGenerator.setTargetOptions(Options);
Mehdi Aminiab4a8b62016-05-14 05:16:41 +0000482 ThinGenerator.setCacheDir(ThinLTOCacheDir);
Ben Dunbobbin9ecb8b52017-12-19 14:42:38 +0000483 ThinGenerator.setCachePruningInterval(ThinLTOCachePruningInterval);
Ekaterina Romanovab8aeec42018-03-02 03:51:27 +0000484 ThinGenerator.setCacheMaxSizeFiles(ThinLTOCacheMaxSizeFiles);
485 ThinGenerator.setCacheMaxSizeBytes(ThinLTOCacheMaxSizeBytes);
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000486 ThinGenerator.setFreestanding(EnableFreestanding);
Mehdi Amini059464f2016-04-24 03:18:01 +0000487
488 // Add all the exported symbols to the table of symbols to preserve.
489 for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
490 ThinGenerator.preserveSymbol(ExportedSymbols[i]);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000491 }
492
493 void run() {
494 switch (ThinLTOMode) {
495 case THINLINK:
496 return thinLink();
Teresa Johnson84174c32016-05-10 13:48:23 +0000497 case THINDISTRIBUTE:
498 return distributedIndexes();
Teresa Johnson8570fe42016-05-10 15:54:09 +0000499 case THINEMITIMPORTS:
500 return emitImports();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000501 case THINPROMOTE:
502 return promote();
503 case THINIMPORT:
504 return import();
Mehdi Amini059464f2016-04-24 03:18:01 +0000505 case THININTERNALIZE:
506 return internalize();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000507 case THINOPT:
508 return optimize();
509 case THINCODEGEN:
510 return codegen();
511 case THINALL:
512 return runAll();
513 }
514 }
515
516private:
517 /// Load the input files, create the combined index, and write it out.
518 void thinLink() {
519 // Perform "ThinLink": just produce the index
520 if (OutputFilename.empty())
521 report_fatal_error(
522 "OutputFilename is necessary to store the combined index.\n");
523
524 LLVMContext Ctx;
525 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
526 for (unsigned i = 0; i < InputFilenames.size(); ++i) {
527 auto &Filename = InputFilenames[i];
Alexander Kornienko656466e2017-07-04 15:13:02 +0000528 std::string CurrentActivity = "loading file '" + Filename + "'";
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000529 auto InputOrErr = MemoryBuffer::getFile(Filename);
530 error(InputOrErr, "error " + CurrentActivity);
531 InputBuffers.push_back(std::move(*InputOrErr));
532 ThinGenerator.addModule(Filename, InputBuffers.back()->getBuffer());
533 }
534
535 auto CombinedIndex = ThinGenerator.linkCombinedIndex();
Mehdi Amini00fa1402016-10-08 04:44:18 +0000536 if (!CombinedIndex)
537 report_fatal_error("ThinLink didn't create an index");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000538 std::error_code EC;
539 raw_fd_ostream OS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
540 error(EC, "error opening the file '" + OutputFilename + "'");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000541 WriteIndexToFile(*CombinedIndex, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000542 }
543
Teresa Johnson84174c32016-05-10 13:48:23 +0000544 /// Load the combined index from disk, then compute and generate
545 /// individual index files suitable for ThinLTO distributed backend builds
546 /// on the files mentioned on the command line (these must match the index
547 /// content).
548 void distributedIndexes() {
549 if (InputFilenames.size() != 1 && !OutputFilename.empty())
550 report_fatal_error("Can't handle a single output filename and multiple "
551 "input files, do not provide an output filename and "
552 "the output files will be suffixed from the input "
553 "ones.");
554
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000555 std::string OldPrefix, NewPrefix;
556 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
557
Teresa Johnson84174c32016-05-10 13:48:23 +0000558 auto Index = loadCombinedIndex();
559 for (auto &Filename : InputFilenames) {
560 // Build a map of module to the GUIDs and summary objects that should
561 // be written to its index.
562 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
563 ThinLTOCodeGenerator::gatherImportedSummariesForModule(
564 Filename, *Index, ModuleToSummariesForIndex);
565
566 std::string OutputName = OutputFilename;
567 if (OutputName.empty()) {
568 OutputName = Filename + ".thinlto.bc";
569 }
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000570 OutputName = getThinLTOOutputFile(OutputName, OldPrefix, NewPrefix);
Teresa Johnson84174c32016-05-10 13:48:23 +0000571 std::error_code EC;
572 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::F_None);
573 error(EC, "error opening the file '" + OutputName + "'");
574 WriteIndexToFile(*Index, OS, &ModuleToSummariesForIndex);
575 }
576 }
577
Teresa Johnson8570fe42016-05-10 15:54:09 +0000578 /// Load the combined index from disk, compute the imports, and emit
579 /// the import file lists for each module to disk.
580 void emitImports() {
581 if (InputFilenames.size() != 1 && !OutputFilename.empty())
582 report_fatal_error("Can't handle a single output filename and multiple "
583 "input files, do not provide an output filename and "
584 "the output files will be suffixed from the input "
585 "ones.");
586
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000587 std::string OldPrefix, NewPrefix;
588 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
589
Teresa Johnson8570fe42016-05-10 15:54:09 +0000590 auto Index = loadCombinedIndex();
591 for (auto &Filename : InputFilenames) {
592 std::string OutputName = OutputFilename;
593 if (OutputName.empty()) {
594 OutputName = Filename + ".imports";
595 }
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000596 OutputName = getThinLTOOutputFile(OutputName, OldPrefix, NewPrefix);
Teresa Johnson8570fe42016-05-10 15:54:09 +0000597 ThinLTOCodeGenerator::emitImports(Filename, OutputName, *Index);
598 }
599 }
600
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000601 /// Load the combined index from disk, then load every file referenced by
602 /// the index and add them to the generator, finally perform the promotion
603 /// on the files mentioned on the command line (these must match the index
604 /// content).
605 void promote() {
606 if (InputFilenames.size() != 1 && !OutputFilename.empty())
607 report_fatal_error("Can't handle a single output filename and multiple "
608 "input files, do not provide an output filename and "
609 "the output files will be suffixed from the input "
610 "ones.");
611
612 auto Index = loadCombinedIndex();
613 for (auto &Filename : InputFilenames) {
614 LLVMContext Ctx;
615 auto TheModule = loadModule(Filename, Ctx);
616
617 ThinGenerator.promote(*TheModule, *Index);
618
619 std::string OutputName = OutputFilename;
620 if (OutputName.empty()) {
621 OutputName = Filename + ".thinlto.promoted.bc";
622 }
623 writeModuleToFile(*TheModule, OutputName);
624 }
625 }
626
627 /// Load the combined index from disk, then load every file referenced by
628 /// the index and add them to the generator, then performs the promotion and
629 /// cross module importing on the files mentioned on the command line
630 /// (these must match the index content).
631 void import() {
632 if (InputFilenames.size() != 1 && !OutputFilename.empty())
633 report_fatal_error("Can't handle a single output filename and multiple "
634 "input files, do not provide an output filename and "
635 "the output files will be suffixed from the input "
636 "ones.");
637
638 auto Index = loadCombinedIndex();
639 auto InputBuffers = loadAllFilesForIndex(*Index);
640 for (auto &MemBuffer : InputBuffers)
641 ThinGenerator.addModule(MemBuffer->getBufferIdentifier(),
642 MemBuffer->getBuffer());
643
644 for (auto &Filename : InputFilenames) {
645 LLVMContext Ctx;
646 auto TheModule = loadModule(Filename, Ctx);
647
648 ThinGenerator.crossModuleImport(*TheModule, *Index);
649
650 std::string OutputName = OutputFilename;
651 if (OutputName.empty()) {
652 OutputName = Filename + ".thinlto.imported.bc";
653 }
654 writeModuleToFile(*TheModule, OutputName);
655 }
656 }
657
Mehdi Amini059464f2016-04-24 03:18:01 +0000658 void internalize() {
659 if (InputFilenames.size() != 1 && !OutputFilename.empty())
660 report_fatal_error("Can't handle a single output filename and multiple "
661 "input files, do not provide an output filename and "
662 "the output files will be suffixed from the input "
663 "ones.");
664
665 if (ExportedSymbols.empty())
666 errs() << "Warning: -internalize will not perform without "
667 "-exported-symbol\n";
668
669 auto Index = loadCombinedIndex();
670 auto InputBuffers = loadAllFilesForIndex(*Index);
671 for (auto &MemBuffer : InputBuffers)
672 ThinGenerator.addModule(MemBuffer->getBufferIdentifier(),
673 MemBuffer->getBuffer());
674
675 for (auto &Filename : InputFilenames) {
676 LLVMContext Ctx;
677 auto TheModule = loadModule(Filename, Ctx);
678
679 ThinGenerator.internalize(*TheModule, *Index);
680
681 std::string OutputName = OutputFilename;
682 if (OutputName.empty()) {
683 OutputName = Filename + ".thinlto.internalized.bc";
684 }
685 writeModuleToFile(*TheModule, OutputName);
686 }
687 }
688
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000689 void optimize() {
690 if (InputFilenames.size() != 1 && !OutputFilename.empty())
691 report_fatal_error("Can't handle a single output filename and multiple "
692 "input files, do not provide an output filename and "
693 "the output files will be suffixed from the input "
694 "ones.");
695 if (!ThinLTOIndex.empty())
696 errs() << "Warning: -thinlto-index ignored for optimize stage";
697
698 for (auto &Filename : InputFilenames) {
699 LLVMContext Ctx;
700 auto TheModule = loadModule(Filename, Ctx);
701
702 ThinGenerator.optimize(*TheModule);
703
704 std::string OutputName = OutputFilename;
705 if (OutputName.empty()) {
706 OutputName = Filename + ".thinlto.imported.bc";
707 }
708 writeModuleToFile(*TheModule, OutputName);
709 }
710 }
711
712 void codegen() {
713 if (InputFilenames.size() != 1 && !OutputFilename.empty())
714 report_fatal_error("Can't handle a single output filename and multiple "
715 "input files, do not provide an output filename and "
716 "the output files will be suffixed from the input "
717 "ones.");
718 if (!ThinLTOIndex.empty())
719 errs() << "Warning: -thinlto-index ignored for codegen stage";
720
Adrian Prantlcdd785b2017-05-19 17:54:58 +0000721 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000722 for (auto &Filename : InputFilenames) {
723 LLVMContext Ctx;
Adrian Prantlcdd785b2017-05-19 17:54:58 +0000724 auto InputOrErr = MemoryBuffer::getFile(Filename);
725 error(InputOrErr, "error " + CurrentActivity);
726 InputBuffers.push_back(std::move(*InputOrErr));
727 ThinGenerator.addModule(Filename, InputBuffers.back()->getBuffer());
728 }
729 ThinGenerator.setCodeGenOnly(true);
730 ThinGenerator.run();
731 for (auto BinName :
732 zip(ThinGenerator.getProducedBinaries(), InputFilenames)) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000733 std::string OutputName = OutputFilename;
Adrian Prantlcdd785b2017-05-19 17:54:58 +0000734 if (OutputName.empty())
735 OutputName = std::get<1>(BinName) + ".thinlto.o";
736 else if (OutputName == "-") {
737 outs() << std::get<0>(BinName)->getBuffer();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000738 return;
739 }
740
741 std::error_code EC;
742 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::F_None);
743 error(EC, "error opening the file '" + OutputName + "'");
Adrian Prantlcdd785b2017-05-19 17:54:58 +0000744 OS << std::get<0>(BinName)->getBuffer();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000745 }
746 }
747
748 /// Full ThinLTO process
749 void runAll() {
750 if (!OutputFilename.empty())
751 report_fatal_error("Do not provide an output filename for ThinLTO "
752 " processing, the output files will be suffixed from "
753 "the input ones.");
754
755 if (!ThinLTOIndex.empty())
756 errs() << "Warning: -thinlto-index ignored for full ThinLTO process";
757
758 LLVMContext Ctx;
759 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
760 for (unsigned i = 0; i < InputFilenames.size(); ++i) {
761 auto &Filename = InputFilenames[i];
Alexander Kornienko656466e2017-07-04 15:13:02 +0000762 std::string CurrentActivity = "loading file '" + Filename + "'";
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000763 auto InputOrErr = MemoryBuffer::getFile(Filename);
764 error(InputOrErr, "error " + CurrentActivity);
765 InputBuffers.push_back(std::move(*InputOrErr));
766 ThinGenerator.addModule(Filename, InputBuffers.back()->getBuffer());
767 }
768
Teresa Johnsonc44a1222016-08-15 23:24:57 +0000769 if (!ThinLTOSaveTempsPrefix.empty())
770 ThinGenerator.setSaveTempsDir(ThinLTOSaveTempsPrefix);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000771
772 if (!ThinLTOGeneratedObjectsDir.empty()) {
773 ThinGenerator.setGeneratedObjectsDirectory(ThinLTOGeneratedObjectsDir);
774 ThinGenerator.run();
775 return;
776 }
777
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000778 ThinGenerator.run();
779
780 auto &Binaries = ThinGenerator.getProducedBinaries();
781 if (Binaries.size() != InputFilenames.size())
782 report_fatal_error("Number of output objects does not match the number "
783 "of inputs");
784
785 for (unsigned BufID = 0; BufID < Binaries.size(); ++BufID) {
786 auto OutputName = InputFilenames[BufID] + ".thinlto.o";
787 std::error_code EC;
788 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::F_None);
789 error(EC, "error opening the file '" + OutputName + "'");
790 OS << Binaries[BufID]->getBuffer();
791 }
792 }
793
794 /// Load the combined index from disk, then load every file referenced by
795};
796
Eugene Zelenko975293f2017-09-07 23:28:24 +0000797} // end namespace thinlto
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000798
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000799int main(int argc, char **argv) {
Rui Ueyama197194b2018-04-13 18:26:06 +0000800 InitLLVM X(argc, argv);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000801 cl::ParseCommandLineOptions(argc, argv, "llvm LTO linker\n");
802
Rafael Espindola5e128db2015-12-04 00:45:57 +0000803 if (OptLevel < '0' || OptLevel > '3')
804 error("optimization level must be between 0 and 3");
Peter Collingbourne070843d2015-03-19 22:01:00 +0000805
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000806 // Initialize the configured targets.
807 InitializeAllTargets();
808 InitializeAllTargetMCs();
809 InitializeAllAsmPrinters();
810 InitializeAllAsmParsers();
811
Rafael Espindola0b385c72013-09-30 16:39:19 +0000812 // set up the TargetOptions for the machine
Eli Benderskyf0f21002014-02-19 17:09:35 +0000813 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
Rafael Espindola0b385c72013-09-30 16:39:19 +0000814
Rafael Espindola5e128db2015-12-04 00:45:57 +0000815 if (ListSymbolsOnly) {
816 listSymbols(Options);
817 return 0;
818 }
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000819
Mehdi Amini06a47802016-09-14 21:04:59 +0000820 if (IndexStats) {
821 printIndexStats();
822 return 0;
823 }
824
Mehdi Aminie75aa6f2016-07-11 23:10:18 +0000825 if (CheckHasObjC) {
826 for (auto &Filename : InputFilenames) {
Peter Collingbournecd513a42016-11-11 19:50:24 +0000827 ExitOnError ExitOnErr(std::string(*argv) + ": error loading file '" +
828 Filename + "': ");
829 std::unique_ptr<MemoryBuffer> BufferOrErr =
830 ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(Filename)));
Mehdi Aminie75aa6f2016-07-11 23:10:18 +0000831 auto Buffer = std::move(BufferOrErr.get());
Eugene Zelenko975293f2017-09-07 23:28:24 +0000832 if (ExitOnErr(isBitcodeContainingObjCCategory(*Buffer)))
Mehdi Aminie75aa6f2016-07-11 23:10:18 +0000833 outs() << "Bitcode " << Filename << " contains ObjC\n";
834 else
835 outs() << "Bitcode " << Filename << " does not contain ObjC\n";
836 }
837 return 0;
838 }
839
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000840 if (ThinLTOMode.getNumOccurrences()) {
841 if (ThinLTOMode.getNumOccurrences() > 1)
842 report_fatal_error("You can't specify more than one -thinlto-action");
843 thinlto::ThinLTOProcessing ThinLTOProcessor(Options);
844 ThinLTOProcessor.run();
845 return 0;
846 }
847
Rafael Espindola5e128db2015-12-04 00:45:57 +0000848 if (ThinLTO) {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000849 createCombinedModuleSummaryIndex();
Rafael Espindola5e128db2015-12-04 00:45:57 +0000850 return 0;
851 }
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000852
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000853 unsigned BaseArg = 0;
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000854
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000855 LLVMContext Context;
Vivek Pandyab5ab8952017-09-15 20:10:09 +0000856 Context.setDiagnosticHandler(llvm::make_unique<LLVMLTODiagnosticHandler>(),
857 true);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000858
859 LTOCodeGenerator CodeGen(Context);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000860
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +0000861 if (UseDiagnosticHandler)
862 CodeGen.setDiagnosticHandler(handleDiagnostics, nullptr);
863
Rafael Espindola8c34dd82016-05-18 22:04:49 +0000864 CodeGen.setCodePICModel(getRelocModel());
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000865 CodeGen.setFreestanding(EnableFreestanding);
James Molloy951e5292014-04-14 13:54:16 +0000866
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000867 CodeGen.setDebugInfo(LTO_DEBUG_MODEL_DWARF);
Rafael Espindola0b385c72013-09-30 16:39:19 +0000868 CodeGen.setTargetOptions(Options);
Tobias Edler von Koch3f4f6f3e2016-01-18 23:35:24 +0000869 CodeGen.setShouldRestoreGlobalsLinkage(RestoreGlobalsLinkage);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000870
Eugene Zelenko975293f2017-09-07 23:28:24 +0000871 StringSet<MallocAllocator> DSOSymbolsSet;
Rafael Espindola282a4702013-10-31 20:51:58 +0000872 for (unsigned i = 0; i < DSOSymbols.size(); ++i)
873 DSOSymbolsSet.insert(DSOSymbols[i]);
874
875 std::vector<std::string> KeptDSOSyms;
876
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000877 for (unsigned i = BaseArg; i < InputFilenames.size(); ++i) {
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000878 CurrentActivity = "loading file '" + InputFilenames[i] + "'";
879 ErrorOr<std::unique_ptr<LTOModule>> ModuleOrErr =
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000880 LTOModule::createFromFile(Context, InputFilenames[i], Options);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000881 std::unique_ptr<LTOModule> &Module = *ModuleOrErr;
882 CurrentActivity = "";
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000883
Peter Collingbourne552174392015-08-21 19:09:42 +0000884 unsigned NumSyms = Module->getSymbolCount();
885 for (unsigned I = 0; I < NumSyms; ++I) {
886 StringRef Name = Module->getSymbolName(I);
887 if (!DSOSymbolsSet.count(Name))
888 continue;
889 lto_symbol_attributes Attrs = Module->getSymbolAttributes(I);
890 unsigned Scope = Attrs & LTO_SYMBOL_SCOPE_MASK;
891 if (Scope != LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN)
892 KeptDSOSyms.push_back(Name);
893 }
Manman Ren6487ce92015-02-24 00:45:56 +0000894
895 // We use the first input module as the destination module when
896 // SetMergedModule is true.
897 if (SetMergedModule && i == BaseArg) {
898 // Transfer ownership to the code generator.
Peter Collingbourne9c8909d2015-08-24 22:22:53 +0000899 CodeGen.setModule(std::move(Module));
Yunzhong Gao46261a72015-09-11 20:01:53 +0000900 } else if (!CodeGen.addModule(Module.get())) {
901 // Print a message here so that we know addModule() did not abort.
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000902 error("error adding file '" + InputFilenames[i] + "'");
Yunzhong Gao46261a72015-09-11 20:01:53 +0000903 }
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000904 }
905
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000906 // Add all the exported symbols to the table of symbols to preserve.
907 for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000908 CodeGen.addMustPreserveSymbol(ExportedSymbols[i]);
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000909
Rafael Espindolacda29112013-10-03 18:29:09 +0000910 // Add all the dso symbols to the table of symbols to expose.
Rafael Espindola282a4702013-10-31 20:51:58 +0000911 for (unsigned i = 0; i < KeptDSOSyms.size(); ++i)
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000912 CodeGen.addMustPreserveSymbol(KeptDSOSyms[i]);
Rafael Espindolacda29112013-10-03 18:29:09 +0000913
Akira Hatanaka23b5f672015-01-30 01:14:28 +0000914 // Set cpu and attrs strings for the default target/subtarget.
915 CodeGen.setCpu(MCPU.c_str());
916
Peter Collingbourne070843d2015-03-19 22:01:00 +0000917 CodeGen.setOptLevel(OptLevel - '0');
918
Tom Roederfd1bc602014-04-25 21:46:51 +0000919 std::string attrs;
920 for (unsigned i = 0; i < MAttrs.size(); ++i) {
921 if (i > 0)
922 attrs.append(",");
923 attrs.append(MAttrs[i]);
924 }
925
926 if (!attrs.empty())
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000927 CodeGen.setAttr(attrs);
Tom Roederfd1bc602014-04-25 21:46:51 +0000928
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000929 if (FileType.getNumOccurrences())
930 CodeGen.setFileType(FileType);
931
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000932 if (!OutputFilename.empty()) {
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000933 if (!CodeGen.optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000934 DisableLTOVectorization)) {
935 // Diagnostic messages should have been printed by the handler.
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000936 error("error optimizing the code");
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000937 }
938
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000939 if (SaveModuleFile) {
940 std::string ModuleFilename = OutputFilename;
941 ModuleFilename += ".merged.bc";
942 std::string ErrMsg;
943
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000944 if (!CodeGen.writeMergedModules(ModuleFilename))
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000945 error("writing merged module failed.");
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000946 }
947
Reid Kleckner3fc649c2017-09-23 01:03:17 +0000948 std::list<ToolOutputFile> OSs;
Peter Collingbournec269ed52015-08-27 23:37:36 +0000949 std::vector<raw_pwrite_stream *> OSPtrs;
950 for (unsigned I = 0; I != Parallelism; ++I) {
951 std::string PartFilename = OutputFilename;
952 if (Parallelism != 1)
953 PartFilename += "." + utostr(I);
954 std::error_code EC;
955 OSs.emplace_back(PartFilename, EC, sys::fs::F_None);
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000956 if (EC)
957 error("error opening the file '" + PartFilename + "': " + EC.message());
Peter Collingbournec269ed52015-08-27 23:37:36 +0000958 OSPtrs.push_back(&OSs.back().os());
959 }
960
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000961 if (!CodeGen.compileOptimized(OSPtrs))
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000962 // Diagnostic messages should have been printed by the handler.
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000963 error("error compiling the code");
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000964
Reid Kleckner3fc649c2017-09-23 01:03:17 +0000965 for (ToolOutputFile &OS : OSs)
Peter Collingbournec269ed52015-08-27 23:37:36 +0000966 OS.keep();
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000967 } else {
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000968 if (Parallelism != 1)
969 error("-j must be specified together with -o");
Peter Collingbournec269ed52015-08-27 23:37:36 +0000970
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000971 if (SaveModuleFile)
972 error(": -save-merged-module must be specified with -o");
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000973
Craig Toppere6cb63e2014-04-25 04:24:47 +0000974 const char *OutputName = nullptr;
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000975 if (!CodeGen.compile_to_file(&OutputName, DisableVerify, DisableInline,
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000976 DisableGVNLoadPRE, DisableLTOVectorization))
977 error("error compiling the code");
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000978 // Diagnostic messages should have been printed by the handler.
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000979
980 outs() << "Wrote native object file '" << OutputName << "'\n";
981 }
982
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000983 return 0;
984}