blob: 2e9d8b7ed2f302236439636a7716eff531986998 [file] [log] [blame]
Peter Collingbourne4e380b02013-09-19 22:15:52 +00001//===-- llvm-lto: a simple command-line program to link modules with LTO --===//
2//
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
Rafael Espindola282a4702013-10-31 20:51:58 +000015#include "llvm/ADT/StringSet.h"
Teresa Johnson91a88bb2015-10-19 14:30:44 +000016#include "llvm/Bitcode/ReaderWriter.h"
Rafael Espindola0b385c72013-09-30 16:39:19 +000017#include "llvm/CodeGen/CommandFlags.h"
Mehdi Amini354f5202015-11-19 05:52:29 +000018#include "llvm/IR/DiagnosticPrinter.h"
Teresa Johnson91a88bb2015-10-19 14:30:44 +000019#include "llvm/IR/LLVMContext.h"
Mehdi Amini3c0e64c2016-04-20 01:04:26 +000020#include "llvm/IR/Verifier.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000021#include "llvm/IRReader/IRReader.h"
Peter Collingbourne5c732202016-07-14 21:21:16 +000022#include "llvm/LTO/legacy/LTOCodeGenerator.h"
23#include "llvm/LTO/legacy/LTOModule.h"
24#include "llvm/LTO/legacy/ThinLTOCodeGenerator.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000025#include "llvm/Object/ModuleSummaryIndexObjectFile.h"
Peter Collingbourne4e380b02013-09-19 22:15:52 +000026#include "llvm/Support/CommandLine.h"
Benjamin Kramerd59664f2014-04-29 23:26:49 +000027#include "llvm/Support/FileSystem.h"
Peter Collingbourne4e380b02013-09-19 22:15:52 +000028#include "llvm/Support/ManagedStatic.h"
Teresa Johnsonbbd10b42016-05-17 14:45:30 +000029#include "llvm/Support/Path.h"
Peter Collingbourne4e380b02013-09-19 22:15:52 +000030#include "llvm/Support/PrettyStackTrace.h"
31#include "llvm/Support/Signals.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000032#include "llvm/Support/SourceMgr.h"
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +000033#include "llvm/Support/TargetSelect.h"
Peter Collingbournec269ed52015-08-27 23:37:36 +000034#include "llvm/Support/ToolOutputFile.h"
Chandler Carruth07baed52014-01-13 08:04:33 +000035#include "llvm/Support/raw_ostream.h"
Peter Collingbournec269ed52015-08-27 23:37:36 +000036#include <list>
Peter Collingbourne4e380b02013-09-19 22:15:52 +000037
38using namespace llvm;
39
Peter Collingbourne070843d2015-03-19 22:01:00 +000040static cl::opt<char>
Davide Italianob10e8932016-04-13 21:41:35 +000041 OptLevel("O", cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
42 "(default = '-O2')"),
43 cl::Prefix, cl::ZeroOrMore, cl::init('2'));
Peter Collingbourne4e380b02013-09-19 22:15:52 +000044
Mehdi Amini06a47802016-09-14 21:04:59 +000045static cl::opt<bool>
46 IndexStats("thinlto-index-stats",
47 cl::desc("Print statistic for the index in every input files"),
48 cl::init(false));
49
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +000050static cl::opt<bool> DisableVerify(
51 "disable-verify", cl::init(false),
52 cl::desc("Do not run the verifier during the optimization pipeline"));
53
Davide Italianob10e8932016-04-13 21:41:35 +000054static cl::opt<bool> DisableInline("disable-inlining", cl::init(false),
55 cl::desc("Do not run the inliner pass"));
Rafael Espindola0b385c72013-09-30 16:39:19 +000056
57static cl::opt<bool>
Davide Italianob10e8932016-04-13 21:41:35 +000058 DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
59 cl::desc("Do not run the GVN load PRE pass"));
Rafael Espindola0b385c72013-09-30 16:39:19 +000060
Davide Italianob10e8932016-04-13 21:41:35 +000061static cl::opt<bool> DisableLTOVectorization(
62 "disable-lto-vectorization", cl::init(false),
63 cl::desc("Do not run loop or slp vectorization during LTO"));
Arnold Schwaighofereb1a38f2014-10-26 21:50:58 +000064
Davide Italianob10e8932016-04-13 21:41:35 +000065static cl::opt<bool> UseDiagnosticHandler(
66 "use-diagnostic-handler", cl::init(false),
67 cl::desc("Use a diagnostic handler to test the handler interface"));
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +000068
Teresa Johnsonf72278f2015-11-02 18:02:11 +000069static cl::opt<bool>
70 ThinLTO("thinlto", cl::init(false),
71 cl::desc("Only write combined global index for ThinLTO backends"));
Teresa Johnson91a88bb2015-10-19 14:30:44 +000072
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000073enum ThinLTOModes {
74 THINLINK,
Teresa Johnson84174c32016-05-10 13:48:23 +000075 THINDISTRIBUTE,
Teresa Johnson8570fe42016-05-10 15:54:09 +000076 THINEMITIMPORTS,
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000077 THINPROMOTE,
78 THINIMPORT,
Mehdi Amini059464f2016-04-24 03:18:01 +000079 THININTERNALIZE,
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000080 THINOPT,
81 THINCODEGEN,
82 THINALL
83};
84
85cl::opt<ThinLTOModes> ThinLTOMode(
86 "thinlto-action", cl::desc("Perform a single ThinLTO stage:"),
87 cl::values(
88 clEnumValN(
89 THINLINK, "thinlink",
90 "ThinLink: produces the index by linking only the summaries."),
Teresa Johnson84174c32016-05-10 13:48:23 +000091 clEnumValN(THINDISTRIBUTE, "distributedindexes",
92 "Produces individual indexes for distributed backends."),
Teresa Johnson8570fe42016-05-10 15:54:09 +000093 clEnumValN(THINEMITIMPORTS, "emitimports",
94 "Emit imports files for distributed backends."),
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000095 clEnumValN(THINPROMOTE, "promote",
96 "Perform pre-import promotion (requires -thinlto-index)."),
97 clEnumValN(THINIMPORT, "import", "Perform both promotion and "
98 "cross-module importing (requires "
99 "-thinlto-index)."),
Mehdi Amini059464f2016-04-24 03:18:01 +0000100 clEnumValN(THININTERNALIZE, "internalize",
101 "Perform internalization driven by -exported-symbol "
102 "(requires -thinlto-index)."),
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000103 clEnumValN(THINOPT, "optimize", "Perform ThinLTO optimizations."),
104 clEnumValN(THINCODEGEN, "codegen", "CodeGen (expected to match llc)"),
105 clEnumValN(THINALL, "run", "Perform ThinLTO end-to-end"),
106 clEnumValEnd));
107
108static cl::opt<std::string>
109 ThinLTOIndex("thinlto-index",
110 cl::desc("Provide the index produced by a ThinLink, required "
111 "to perform the promotion and/or importing."));
112
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000113static cl::opt<std::string> ThinLTOPrefixReplace(
114 "thinlto-prefix-replace",
115 cl::desc("Control where files for distributed backends are "
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000116 "created. Expects 'oldprefix;newprefix' and if path "
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000117 "prefix of output file is oldprefix it will be "
118 "replaced with newprefix."));
119
Mehdi Amini03abce92016-05-05 16:33:51 +0000120static cl::opt<std::string> ThinLTOModuleId(
121 "thinlto-module-id",
122 cl::desc("For the module ID for the file to process, useful to "
123 "match what is in the index."));
124
Mehdi Aminiab4a8b62016-05-14 05:16:41 +0000125static cl::opt<std::string>
126 ThinLTOCacheDir("thinlto-cache-dir", cl::desc("Enable ThinLTO caching."));
127
Teresa Johnsonc44a1222016-08-15 23:24:57 +0000128static cl::opt<std::string> ThinLTOSaveTempsPrefix(
129 "thinlto-save-temps",
130 cl::desc("Save ThinLTO temp files using filenames created by adding "
131 "suffixes to the given file path prefix."));
132
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000133static cl::opt<bool>
Davide Italianob10e8932016-04-13 21:41:35 +0000134 SaveModuleFile("save-merged-module", cl::init(false),
135 cl::desc("Write merged LTO module to file before CodeGen"));
136
137static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
138 cl::desc("<input bitcode files>"));
139
140static cl::opt<std::string> OutputFilename("o", cl::init(""),
141 cl::desc("Override output filename"),
142 cl::value_desc("filename"));
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000143
Mehdi Amini059464f2016-04-24 03:18:01 +0000144static cl::list<std::string> ExportedSymbols(
145 "exported-symbol",
146 cl::desc("List of symbols to export from the resulting object file"),
147 cl::ZeroOrMore);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000148
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000149static cl::list<std::string>
Davide Italianob10e8932016-04-13 21:41:35 +0000150 DSOSymbols("dso-symbol",
151 cl::desc("Symbol to put in the symtab in the resulting dso"),
152 cl::ZeroOrMore);
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000153
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000154static cl::opt<bool> ListSymbolsOnly(
155 "list-symbols-only", cl::init(false),
156 cl::desc("Instead of running LTO, list the symbols in each IR file"));
157
Manman Ren6487ce92015-02-24 00:45:56 +0000158static cl::opt<bool> SetMergedModule(
159 "set-merged-module", cl::init(false),
160 cl::desc("Use the first input module as the merged module"));
161
Peter Collingbournec269ed52015-08-27 23:37:36 +0000162static cl::opt<unsigned> Parallelism("j", cl::Prefix, cl::init(1),
163 cl::desc("Number of backend threads"));
164
Tobias Edler von Koch3f4f6f3e2016-01-18 23:35:24 +0000165static cl::opt<bool> RestoreGlobalsLinkage(
166 "restore-linkage", cl::init(false),
167 cl::desc("Restore original linkage of globals prior to CodeGen"));
168
Mehdi Aminie75aa6f2016-07-11 23:10:18 +0000169static cl::opt<bool> CheckHasObjC(
170 "check-for-objc", cl::init(false),
171 cl::desc("Only check if the module has objective-C defined in it"));
172
Rafael Espindola282a4702013-10-31 20:51:58 +0000173namespace {
174struct ModuleInfo {
175 std::vector<bool> CanBeHidden;
176};
177}
178
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000179static void handleDiagnostics(lto_codegen_diagnostic_severity_t Severity,
180 const char *Msg, void *) {
Yunzhong Gaoef436f02015-11-10 18:52:48 +0000181 errs() << "llvm-lto: ";
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +0000182 switch (Severity) {
183 case LTO_DS_NOTE:
184 errs() << "note: ";
185 break;
186 case LTO_DS_REMARK:
187 errs() << "remark: ";
188 break;
189 case LTO_DS_ERROR:
190 errs() << "error: ";
191 break;
192 case LTO_DS_WARNING:
193 errs() << "warning: ";
194 break;
195 }
196 errs() << Msg << "\n";
197}
198
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000199static std::string CurrentActivity;
Mehdi Amini354f5202015-11-19 05:52:29 +0000200static void diagnosticHandler(const DiagnosticInfo &DI) {
201 raw_ostream &OS = errs();
202 OS << "llvm-lto: ";
203 switch (DI.getSeverity()) {
204 case DS_Error:
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000205 OS << "error";
Mehdi Amini354f5202015-11-19 05:52:29 +0000206 break;
207 case DS_Warning:
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000208 OS << "warning";
Mehdi Amini354f5202015-11-19 05:52:29 +0000209 break;
210 case DS_Remark:
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000211 OS << "remark";
Mehdi Amini354f5202015-11-19 05:52:29 +0000212 break;
213 case DS_Note:
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000214 OS << "note";
Mehdi Amini354f5202015-11-19 05:52:29 +0000215 break;
216 }
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000217 if (!CurrentActivity.empty())
218 OS << ' ' << CurrentActivity;
219 OS << ": ";
Mehdi Amini354f5202015-11-19 05:52:29 +0000220
221 DiagnosticPrinterRawOStream DP(OS);
222 DI.print(DP);
223 OS << '\n';
224
225 if (DI.getSeverity() == DS_Error)
226 exit(1);
227}
228
Petr Pavlu7ad9ec92016-03-01 13:13:49 +0000229static void diagnosticHandlerWithContext(const DiagnosticInfo &DI,
230 void *Context) {
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000231 diagnosticHandler(DI);
232}
233
Rafael Espindola5e128db2015-12-04 00:45:57 +0000234static void error(const Twine &Msg) {
235 errs() << "llvm-lto: " << Msg << '\n';
236 exit(1);
237}
238
239static void error(std::error_code EC, const Twine &Prefix) {
240 if (EC)
241 error(Prefix + ": " + EC.message());
242}
243
244template <typename T>
245static void error(const ErrorOr<T> &V, const Twine &Prefix) {
246 error(V.getError(), Prefix);
247}
248
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000249static void maybeVerifyModule(const Module &Mod) {
250 if (!DisableVerify && verifyModule(Mod))
251 error("Broken Module");
252}
253
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000254static std::unique_ptr<LTOModule>
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000255getLocalLTOModule(StringRef Path, std::unique_ptr<MemoryBuffer> &Buffer,
Rafael Espindola5e128db2015-12-04 00:45:57 +0000256 const TargetOptions &Options) {
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000257 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
258 MemoryBuffer::getFile(Path);
Rafael Espindola5e128db2015-12-04 00:45:57 +0000259 error(BufferOrErr, "error loading file '" + Path + "'");
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000260 Buffer = std::move(BufferOrErr.get());
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000261 CurrentActivity = ("loading file '" + Path + "'").str();
Petr Pavlu7ad9ec92016-03-01 13:13:49 +0000262 std::unique_ptr<LLVMContext> Context = llvm::make_unique<LLVMContext>();
263 Context->setDiagnosticHandler(diagnosticHandlerWithContext, nullptr, true);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000264 ErrorOr<std::unique_ptr<LTOModule>> Ret = LTOModule::createInLocalContext(
Petr Pavlu7ad9ec92016-03-01 13:13:49 +0000265 std::move(Context), Buffer->getBufferStart(), Buffer->getBufferSize(),
266 Options, Path);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000267 CurrentActivity = "";
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000268 maybeVerifyModule((*Ret)->getModule());
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000269 return std::move(*Ret);
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000270}
271
Mehdi Amini06a47802016-09-14 21:04:59 +0000272/// Print some statistics on the index for each input files.
273void printIndexStats() {
274 for (auto &Filename : InputFilenames) {
275 CurrentActivity = "loading file '" + Filename + "'";
276 ErrorOr<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
277 llvm::getModuleSummaryIndexForFile(Filename, diagnosticHandler);
278 error(IndexOrErr, "error " + CurrentActivity);
279 std::unique_ptr<ModuleSummaryIndex> Index = std::move(IndexOrErr.get());
280 CurrentActivity = "";
281 // Skip files without a module summary.
282 if (!Index)
283 report_fatal_error(Filename + " does not contain an index");
284
285 unsigned Calls = 0, Refs = 0, Functions = 0, Alias = 0, Globals = 0;
286 for (auto &Summaries : *Index) {
287 for (auto &Summary : Summaries.second) {
288 Refs += Summary->refs().size();
289 if (auto *FuncSummary = dyn_cast<FunctionSummary>(Summary.get())) {
290 Functions++;
291 Calls += FuncSummary->calls().size();
292 } else if (isa<AliasSummary>(Summary.get()))
293 Alias++;
294 else
295 Globals++;
296 }
297 }
298 outs() << "Index " << Filename << " contains "
299 << (Alias + Globals + Functions) << " nodes (" << Functions
300 << " functions, " << Alias << " alias, " << Globals
301 << " globals) and " << (Calls + Refs) << " edges (" << Refs
302 << " refs and " << Calls << " calls)\n";
303 }
304}
305
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000306/// \brief List symbols in each IR file.
307///
308/// The main point here is to provide lit-testable coverage for the LTOModule
309/// functionality that's exposed by the C API to list symbols. Moreover, this
310/// provides testing coverage for modules that have been created in their own
311/// contexts.
Rafael Espindola5e128db2015-12-04 00:45:57 +0000312static void listSymbols(const TargetOptions &Options) {
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000313 for (auto &Filename : InputFilenames) {
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000314 std::unique_ptr<MemoryBuffer> Buffer;
315 std::unique_ptr<LTOModule> Module =
Rafael Espindola5e128db2015-12-04 00:45:57 +0000316 getLocalLTOModule(Filename, Buffer, Options);
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000317
318 // List the symbols.
319 outs() << Filename << ":\n";
320 for (int I = 0, E = Module->getSymbolCount(); I != E; ++I)
321 outs() << Module->getSymbolName(I) << "\n";
322 }
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000323}
324
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000325/// Create a combined index file from the input IR files and write it.
326///
327/// This is meant to enable testing of ThinLTO combined index generation,
328/// currently available via the gold plugin via -thinlto.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000329static void createCombinedModuleSummaryIndex() {
330 ModuleSummaryIndex CombinedIndex;
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000331 uint64_t NextModuleId = 0;
332 for (auto &Filename : InputFilenames) {
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000333 CurrentActivity = "loading file '" + Filename + "'";
Teresa Johnson26ab5772016-03-15 00:04:37 +0000334 ErrorOr<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
335 llvm::getModuleSummaryIndexForFile(Filename, diagnosticHandler);
Mehdi Amini155da5b2016-03-19 00:17:32 +0000336 error(IndexOrErr, "error " + CurrentActivity);
Teresa Johnson26ab5772016-03-15 00:04:37 +0000337 std::unique_ptr<ModuleSummaryIndex> Index = std::move(IndexOrErr.get());
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000338 CurrentActivity = "";
Teresa Johnson26ab5772016-03-15 00:04:37 +0000339 // Skip files without a module summary.
Teresa Johnson6290dbc2015-11-21 21:55:48 +0000340 if (!Index)
341 continue;
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000342 CombinedIndex.mergeFrom(std::move(Index), ++NextModuleId);
343 }
344 std::error_code EC;
345 assert(!OutputFilename.empty());
346 raw_fd_ostream OS(OutputFilename + ".thinlto.bc", EC,
347 sys::fs::OpenFlags::F_None);
Rafael Espindola5e128db2015-12-04 00:45:57 +0000348 error(EC, "error opening the file '" + OutputFilename + ".thinlto.bc'");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000349 WriteIndexToFile(CombinedIndex, OS);
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000350 OS.close();
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000351}
352
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000353/// Parse the thinlto_prefix_replace option into the \p OldPrefix and
354/// \p NewPrefix strings, if it was specified.
355static void getThinLTOOldAndNewPrefix(std::string &OldPrefix,
356 std::string &NewPrefix) {
357 assert(ThinLTOPrefixReplace.empty() ||
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000358 ThinLTOPrefixReplace.find(";") != StringRef::npos);
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000359 StringRef PrefixReplace = ThinLTOPrefixReplace;
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000360 std::pair<StringRef, StringRef> Split = PrefixReplace.split(";");
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000361 OldPrefix = Split.first.str();
362 NewPrefix = Split.second.str();
363}
364
365/// Given the original \p Path to an output file, replace any path
366/// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
367/// resulting directory if it does not yet exist.
368static std::string getThinLTOOutputFile(const std::string &Path,
369 const std::string &OldPrefix,
370 const std::string &NewPrefix) {
371 if (OldPrefix.empty() && NewPrefix.empty())
372 return Path;
373 SmallString<128> NewPath(Path);
374 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
375 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
376 if (!ParentPath.empty()) {
377 // Make sure the new directory exists, creating it if necessary.
378 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
379 error(EC, "error creating the directory '" + ParentPath + "'");
380 }
381 return NewPath.str();
382}
383
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000384namespace thinlto {
385
386std::vector<std::unique_ptr<MemoryBuffer>>
Teresa Johnson26ab5772016-03-15 00:04:37 +0000387loadAllFilesForIndex(const ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000388 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
389
Mehdi Amini385cf282016-03-26 03:35:38 +0000390 for (auto &ModPath : Index.modulePaths()) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000391 const auto &Filename = ModPath.first();
392 auto CurrentActivity = "loading file '" + Filename + "'";
393 auto InputOrErr = MemoryBuffer::getFile(Filename);
394 error(InputOrErr, "error " + CurrentActivity);
395 InputBuffers.push_back(std::move(*InputOrErr));
396 }
397 return InputBuffers;
398}
399
Teresa Johnson26ab5772016-03-15 00:04:37 +0000400std::unique_ptr<ModuleSummaryIndex> loadCombinedIndex() {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000401 if (ThinLTOIndex.empty())
402 report_fatal_error("Missing -thinlto-index for ThinLTO promotion stage");
403 auto CurrentActivity = "loading file '" + ThinLTOIndex + "'";
Teresa Johnson26ab5772016-03-15 00:04:37 +0000404 ErrorOr<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
405 llvm::getModuleSummaryIndexForFile(ThinLTOIndex, diagnosticHandler);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000406 error(IndexOrErr, "error " + CurrentActivity);
407 return std::move(IndexOrErr.get());
408}
409
410static std::unique_ptr<Module> loadModule(StringRef Filename,
411 LLVMContext &Ctx) {
412 SMDiagnostic Err;
413 std::unique_ptr<Module> M(parseIRFile(Filename, Err, Ctx));
414 if (!M) {
415 Err.print("llvm-lto", errs());
416 report_fatal_error("Can't load module for file " + Filename);
417 }
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000418 maybeVerifyModule(*M);
Mehdi Amini03abce92016-05-05 16:33:51 +0000419
420 if (ThinLTOModuleId.getNumOccurrences()) {
421 if (InputFilenames.size() != 1)
422 report_fatal_error("Can't override the module id for multiple files");
423 M->setModuleIdentifier(ThinLTOModuleId);
424 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000425 return M;
426}
427
428static void writeModuleToFile(Module &TheModule, StringRef Filename) {
429 std::error_code EC;
430 raw_fd_ostream OS(Filename, EC, sys::fs::OpenFlags::F_None);
431 error(EC, "error opening the file '" + Filename + "'");
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000432 maybeVerifyModule(TheModule);
Teresa Johnson3c35e092016-04-04 21:19:31 +0000433 WriteBitcodeToFile(&TheModule, OS, /* ShouldPreserveUseListOrder */ true);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000434}
435
436class ThinLTOProcessing {
437public:
438 ThinLTOCodeGenerator ThinGenerator;
439
440 ThinLTOProcessing(const TargetOptions &Options) {
Rafael Espindola8c34dd82016-05-18 22:04:49 +0000441 ThinGenerator.setCodePICModel(getRelocModel());
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000442 ThinGenerator.setTargetOptions(Options);
Mehdi Aminiab4a8b62016-05-14 05:16:41 +0000443 ThinGenerator.setCacheDir(ThinLTOCacheDir);
Mehdi Amini059464f2016-04-24 03:18:01 +0000444
445 // Add all the exported symbols to the table of symbols to preserve.
446 for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
447 ThinGenerator.preserveSymbol(ExportedSymbols[i]);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000448 }
449
450 void run() {
451 switch (ThinLTOMode) {
452 case THINLINK:
453 return thinLink();
Teresa Johnson84174c32016-05-10 13:48:23 +0000454 case THINDISTRIBUTE:
455 return distributedIndexes();
Teresa Johnson8570fe42016-05-10 15:54:09 +0000456 case THINEMITIMPORTS:
457 return emitImports();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000458 case THINPROMOTE:
459 return promote();
460 case THINIMPORT:
461 return import();
Mehdi Amini059464f2016-04-24 03:18:01 +0000462 case THININTERNALIZE:
463 return internalize();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000464 case THINOPT:
465 return optimize();
466 case THINCODEGEN:
467 return codegen();
468 case THINALL:
469 return runAll();
470 }
471 }
472
473private:
474 /// Load the input files, create the combined index, and write it out.
475 void thinLink() {
476 // Perform "ThinLink": just produce the index
477 if (OutputFilename.empty())
478 report_fatal_error(
479 "OutputFilename is necessary to store the combined index.\n");
480
481 LLVMContext Ctx;
482 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
483 for (unsigned i = 0; i < InputFilenames.size(); ++i) {
484 auto &Filename = InputFilenames[i];
485 StringRef CurrentActivity = "loading file '" + Filename + "'";
486 auto InputOrErr = MemoryBuffer::getFile(Filename);
487 error(InputOrErr, "error " + CurrentActivity);
488 InputBuffers.push_back(std::move(*InputOrErr));
489 ThinGenerator.addModule(Filename, InputBuffers.back()->getBuffer());
490 }
491
492 auto CombinedIndex = ThinGenerator.linkCombinedIndex();
493 std::error_code EC;
494 raw_fd_ostream OS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
495 error(EC, "error opening the file '" + OutputFilename + "'");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000496 WriteIndexToFile(*CombinedIndex, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000497 return;
498 }
499
Teresa Johnson84174c32016-05-10 13:48:23 +0000500 /// Load the combined index from disk, then compute and generate
501 /// individual index files suitable for ThinLTO distributed backend builds
502 /// on the files mentioned on the command line (these must match the index
503 /// content).
504 void distributedIndexes() {
505 if (InputFilenames.size() != 1 && !OutputFilename.empty())
506 report_fatal_error("Can't handle a single output filename and multiple "
507 "input files, do not provide an output filename and "
508 "the output files will be suffixed from the input "
509 "ones.");
510
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000511 std::string OldPrefix, NewPrefix;
512 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
513
Teresa Johnson84174c32016-05-10 13:48:23 +0000514 auto Index = loadCombinedIndex();
515 for (auto &Filename : InputFilenames) {
516 // Build a map of module to the GUIDs and summary objects that should
517 // be written to its index.
518 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
519 ThinLTOCodeGenerator::gatherImportedSummariesForModule(
520 Filename, *Index, ModuleToSummariesForIndex);
521
522 std::string OutputName = OutputFilename;
523 if (OutputName.empty()) {
524 OutputName = Filename + ".thinlto.bc";
525 }
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000526 OutputName = getThinLTOOutputFile(OutputName, OldPrefix, NewPrefix);
Teresa Johnson84174c32016-05-10 13:48:23 +0000527 std::error_code EC;
528 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::F_None);
529 error(EC, "error opening the file '" + OutputName + "'");
530 WriteIndexToFile(*Index, OS, &ModuleToSummariesForIndex);
531 }
532 }
533
Teresa Johnson8570fe42016-05-10 15:54:09 +0000534 /// Load the combined index from disk, compute the imports, and emit
535 /// the import file lists for each module to disk.
536 void emitImports() {
537 if (InputFilenames.size() != 1 && !OutputFilename.empty())
538 report_fatal_error("Can't handle a single output filename and multiple "
539 "input files, do not provide an output filename and "
540 "the output files will be suffixed from the input "
541 "ones.");
542
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000543 std::string OldPrefix, NewPrefix;
544 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
545
Teresa Johnson8570fe42016-05-10 15:54:09 +0000546 auto Index = loadCombinedIndex();
547 for (auto &Filename : InputFilenames) {
548 std::string OutputName = OutputFilename;
549 if (OutputName.empty()) {
550 OutputName = Filename + ".imports";
551 }
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000552 OutputName = getThinLTOOutputFile(OutputName, OldPrefix, NewPrefix);
Teresa Johnson8570fe42016-05-10 15:54:09 +0000553 ThinLTOCodeGenerator::emitImports(Filename, OutputName, *Index);
554 }
555 }
556
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000557 /// Load the combined index from disk, then load every file referenced by
558 /// the index and add them to the generator, finally perform the promotion
559 /// on the files mentioned on the command line (these must match the index
560 /// content).
561 void promote() {
562 if (InputFilenames.size() != 1 && !OutputFilename.empty())
563 report_fatal_error("Can't handle a single output filename and multiple "
564 "input files, do not provide an output filename and "
565 "the output files will be suffixed from the input "
566 "ones.");
567
568 auto Index = loadCombinedIndex();
569 for (auto &Filename : InputFilenames) {
570 LLVMContext Ctx;
571 auto TheModule = loadModule(Filename, Ctx);
572
573 ThinGenerator.promote(*TheModule, *Index);
574
575 std::string OutputName = OutputFilename;
576 if (OutputName.empty()) {
577 OutputName = Filename + ".thinlto.promoted.bc";
578 }
579 writeModuleToFile(*TheModule, OutputName);
580 }
581 }
582
583 /// Load the combined index from disk, then load every file referenced by
584 /// the index and add them to the generator, then performs the promotion and
585 /// cross module importing on the files mentioned on the command line
586 /// (these must match the index content).
587 void import() {
588 if (InputFilenames.size() != 1 && !OutputFilename.empty())
589 report_fatal_error("Can't handle a single output filename and multiple "
590 "input files, do not provide an output filename and "
591 "the output files will be suffixed from the input "
592 "ones.");
593
594 auto Index = loadCombinedIndex();
595 auto InputBuffers = loadAllFilesForIndex(*Index);
596 for (auto &MemBuffer : InputBuffers)
597 ThinGenerator.addModule(MemBuffer->getBufferIdentifier(),
598 MemBuffer->getBuffer());
599
600 for (auto &Filename : InputFilenames) {
601 LLVMContext Ctx;
602 auto TheModule = loadModule(Filename, Ctx);
603
604 ThinGenerator.crossModuleImport(*TheModule, *Index);
605
606 std::string OutputName = OutputFilename;
607 if (OutputName.empty()) {
608 OutputName = Filename + ".thinlto.imported.bc";
609 }
610 writeModuleToFile(*TheModule, OutputName);
611 }
612 }
613
Mehdi Amini059464f2016-04-24 03:18:01 +0000614 void internalize() {
615 if (InputFilenames.size() != 1 && !OutputFilename.empty())
616 report_fatal_error("Can't handle a single output filename and multiple "
617 "input files, do not provide an output filename and "
618 "the output files will be suffixed from the input "
619 "ones.");
620
621 if (ExportedSymbols.empty())
622 errs() << "Warning: -internalize will not perform without "
623 "-exported-symbol\n";
624
625 auto Index = loadCombinedIndex();
626 auto InputBuffers = loadAllFilesForIndex(*Index);
627 for (auto &MemBuffer : InputBuffers)
628 ThinGenerator.addModule(MemBuffer->getBufferIdentifier(),
629 MemBuffer->getBuffer());
630
631 for (auto &Filename : InputFilenames) {
632 LLVMContext Ctx;
633 auto TheModule = loadModule(Filename, Ctx);
634
635 ThinGenerator.internalize(*TheModule, *Index);
636
637 std::string OutputName = OutputFilename;
638 if (OutputName.empty()) {
639 OutputName = Filename + ".thinlto.internalized.bc";
640 }
641 writeModuleToFile(*TheModule, OutputName);
642 }
643 }
644
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000645 void optimize() {
646 if (InputFilenames.size() != 1 && !OutputFilename.empty())
647 report_fatal_error("Can't handle a single output filename and multiple "
648 "input files, do not provide an output filename and "
649 "the output files will be suffixed from the input "
650 "ones.");
651 if (!ThinLTOIndex.empty())
652 errs() << "Warning: -thinlto-index ignored for optimize stage";
653
654 for (auto &Filename : InputFilenames) {
655 LLVMContext Ctx;
656 auto TheModule = loadModule(Filename, Ctx);
657
658 ThinGenerator.optimize(*TheModule);
659
660 std::string OutputName = OutputFilename;
661 if (OutputName.empty()) {
662 OutputName = Filename + ".thinlto.imported.bc";
663 }
664 writeModuleToFile(*TheModule, OutputName);
665 }
666 }
667
668 void codegen() {
669 if (InputFilenames.size() != 1 && !OutputFilename.empty())
670 report_fatal_error("Can't handle a single output filename and multiple "
671 "input files, do not provide an output filename and "
672 "the output files will be suffixed from the input "
673 "ones.");
674 if (!ThinLTOIndex.empty())
675 errs() << "Warning: -thinlto-index ignored for codegen stage";
676
677 for (auto &Filename : InputFilenames) {
678 LLVMContext Ctx;
679 auto TheModule = loadModule(Filename, Ctx);
680
681 auto Buffer = ThinGenerator.codegen(*TheModule);
682 std::string OutputName = OutputFilename;
683 if (OutputName.empty()) {
684 OutputName = Filename + ".thinlto.o";
685 }
686 if (OutputName == "-") {
687 outs() << Buffer->getBuffer();
688 return;
689 }
690
691 std::error_code EC;
692 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::F_None);
693 error(EC, "error opening the file '" + OutputName + "'");
694 OS << Buffer->getBuffer();
695 }
696 }
697
698 /// Full ThinLTO process
699 void runAll() {
700 if (!OutputFilename.empty())
701 report_fatal_error("Do not provide an output filename for ThinLTO "
702 " processing, the output files will be suffixed from "
703 "the input ones.");
704
705 if (!ThinLTOIndex.empty())
706 errs() << "Warning: -thinlto-index ignored for full ThinLTO process";
707
708 LLVMContext Ctx;
709 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
710 for (unsigned i = 0; i < InputFilenames.size(); ++i) {
711 auto &Filename = InputFilenames[i];
712 StringRef CurrentActivity = "loading file '" + Filename + "'";
713 auto InputOrErr = MemoryBuffer::getFile(Filename);
714 error(InputOrErr, "error " + CurrentActivity);
715 InputBuffers.push_back(std::move(*InputOrErr));
716 ThinGenerator.addModule(Filename, InputBuffers.back()->getBuffer());
717 }
718
Teresa Johnsonc44a1222016-08-15 23:24:57 +0000719 if (!ThinLTOSaveTempsPrefix.empty())
720 ThinGenerator.setSaveTempsDir(ThinLTOSaveTempsPrefix);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000721 ThinGenerator.run();
722
723 auto &Binaries = ThinGenerator.getProducedBinaries();
724 if (Binaries.size() != InputFilenames.size())
725 report_fatal_error("Number of output objects does not match the number "
726 "of inputs");
727
728 for (unsigned BufID = 0; BufID < Binaries.size(); ++BufID) {
729 auto OutputName = InputFilenames[BufID] + ".thinlto.o";
730 std::error_code EC;
731 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::F_None);
732 error(EC, "error opening the file '" + OutputName + "'");
733 OS << Binaries[BufID]->getBuffer();
734 }
735 }
736
737 /// Load the combined index from disk, then load every file referenced by
738};
739
740} // namespace thinlto
741
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000742int main(int argc, char **argv) {
743 // Print a stack trace if we signal out.
Richard Smith2ad6d482016-06-09 00:53:21 +0000744 sys::PrintStackTraceOnErrorSignal(argv[0]);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000745 PrettyStackTraceProgram X(argc, argv);
746
747 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
748 cl::ParseCommandLineOptions(argc, argv, "llvm LTO linker\n");
749
Rafael Espindola5e128db2015-12-04 00:45:57 +0000750 if (OptLevel < '0' || OptLevel > '3')
751 error("optimization level must be between 0 and 3");
Peter Collingbourne070843d2015-03-19 22:01:00 +0000752
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000753 // Initialize the configured targets.
754 InitializeAllTargets();
755 InitializeAllTargetMCs();
756 InitializeAllAsmPrinters();
757 InitializeAllAsmParsers();
758
Rafael Espindola0b385c72013-09-30 16:39:19 +0000759 // set up the TargetOptions for the machine
Eli Benderskyf0f21002014-02-19 17:09:35 +0000760 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
Rafael Espindola0b385c72013-09-30 16:39:19 +0000761
Rafael Espindola5e128db2015-12-04 00:45:57 +0000762 if (ListSymbolsOnly) {
763 listSymbols(Options);
764 return 0;
765 }
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000766
Mehdi Amini06a47802016-09-14 21:04:59 +0000767 if (IndexStats) {
768 printIndexStats();
769 return 0;
770 }
771
Mehdi Aminie75aa6f2016-07-11 23:10:18 +0000772 if (CheckHasObjC) {
773 for (auto &Filename : InputFilenames) {
774 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
775 MemoryBuffer::getFile(Filename);
776 error(BufferOrErr, "error loading file '" + Filename + "'");
777 auto Buffer = std::move(BufferOrErr.get());
778 LLVMContext Ctx;
779 if (llvm::isBitcodeContainingObjCCategory(*Buffer, Ctx))
780 outs() << "Bitcode " << Filename << " contains ObjC\n";
781 else
782 outs() << "Bitcode " << Filename << " does not contain ObjC\n";
783 }
784 return 0;
785 }
786
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000787 if (ThinLTOMode.getNumOccurrences()) {
788 if (ThinLTOMode.getNumOccurrences() > 1)
789 report_fatal_error("You can't specify more than one -thinlto-action");
790 thinlto::ThinLTOProcessing ThinLTOProcessor(Options);
791 ThinLTOProcessor.run();
792 return 0;
793 }
794
Rafael Espindola5e128db2015-12-04 00:45:57 +0000795 if (ThinLTO) {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000796 createCombinedModuleSummaryIndex();
Rafael Espindola5e128db2015-12-04 00:45:57 +0000797 return 0;
798 }
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000799
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000800 unsigned BaseArg = 0;
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000801
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000802 LLVMContext Context;
Petr Pavlu7ad9ec92016-03-01 13:13:49 +0000803 Context.setDiagnosticHandler(diagnosticHandlerWithContext, nullptr, true);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000804
805 LTOCodeGenerator CodeGen(Context);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000806
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +0000807 if (UseDiagnosticHandler)
808 CodeGen.setDiagnosticHandler(handleDiagnostics, nullptr);
809
Rafael Espindola8c34dd82016-05-18 22:04:49 +0000810 CodeGen.setCodePICModel(getRelocModel());
James Molloy951e5292014-04-14 13:54:16 +0000811
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000812 CodeGen.setDebugInfo(LTO_DEBUG_MODEL_DWARF);
Rafael Espindola0b385c72013-09-30 16:39:19 +0000813 CodeGen.setTargetOptions(Options);
Tobias Edler von Koch3f4f6f3e2016-01-18 23:35:24 +0000814 CodeGen.setShouldRestoreGlobalsLinkage(RestoreGlobalsLinkage);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000815
Rafael Espindola282a4702013-10-31 20:51:58 +0000816 llvm::StringSet<llvm::MallocAllocator> DSOSymbolsSet;
817 for (unsigned i = 0; i < DSOSymbols.size(); ++i)
818 DSOSymbolsSet.insert(DSOSymbols[i]);
819
820 std::vector<std::string> KeptDSOSyms;
821
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000822 for (unsigned i = BaseArg; i < InputFilenames.size(); ++i) {
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000823 CurrentActivity = "loading file '" + InputFilenames[i] + "'";
824 ErrorOr<std::unique_ptr<LTOModule>> ModuleOrErr =
825 LTOModule::createFromFile(Context, InputFilenames[i].c_str(), Options);
826 std::unique_ptr<LTOModule> &Module = *ModuleOrErr;
827 CurrentActivity = "";
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000828
Peter Collingbourne552174392015-08-21 19:09:42 +0000829 unsigned NumSyms = Module->getSymbolCount();
830 for (unsigned I = 0; I < NumSyms; ++I) {
831 StringRef Name = Module->getSymbolName(I);
832 if (!DSOSymbolsSet.count(Name))
833 continue;
834 lto_symbol_attributes Attrs = Module->getSymbolAttributes(I);
835 unsigned Scope = Attrs & LTO_SYMBOL_SCOPE_MASK;
836 if (Scope != LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN)
837 KeptDSOSyms.push_back(Name);
838 }
Manman Ren6487ce92015-02-24 00:45:56 +0000839
840 // We use the first input module as the destination module when
841 // SetMergedModule is true.
842 if (SetMergedModule && i == BaseArg) {
843 // Transfer ownership to the code generator.
Peter Collingbourne9c8909d2015-08-24 22:22:53 +0000844 CodeGen.setModule(std::move(Module));
Yunzhong Gao46261a72015-09-11 20:01:53 +0000845 } else if (!CodeGen.addModule(Module.get())) {
846 // Print a message here so that we know addModule() did not abort.
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000847 error("error adding file '" + InputFilenames[i] + "'");
Yunzhong Gao46261a72015-09-11 20:01:53 +0000848 }
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000849 }
850
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000851 // Add all the exported symbols to the table of symbols to preserve.
852 for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
853 CodeGen.addMustPreserveSymbol(ExportedSymbols[i].c_str());
854
Rafael Espindolacda29112013-10-03 18:29:09 +0000855 // Add all the dso symbols to the table of symbols to expose.
Rafael Espindola282a4702013-10-31 20:51:58 +0000856 for (unsigned i = 0; i < KeptDSOSyms.size(); ++i)
857 CodeGen.addMustPreserveSymbol(KeptDSOSyms[i].c_str());
Rafael Espindolacda29112013-10-03 18:29:09 +0000858
Akira Hatanaka23b5f672015-01-30 01:14:28 +0000859 // Set cpu and attrs strings for the default target/subtarget.
860 CodeGen.setCpu(MCPU.c_str());
861
Peter Collingbourne070843d2015-03-19 22:01:00 +0000862 CodeGen.setOptLevel(OptLevel - '0');
863
Tom Roederfd1bc602014-04-25 21:46:51 +0000864 std::string attrs;
865 for (unsigned i = 0; i < MAttrs.size(); ++i) {
866 if (i > 0)
867 attrs.append(",");
868 attrs.append(MAttrs[i]);
869 }
870
871 if (!attrs.empty())
872 CodeGen.setAttr(attrs.c_str());
873
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000874 if (FileType.getNumOccurrences())
875 CodeGen.setFileType(FileType);
876
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000877 if (!OutputFilename.empty()) {
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000878 if (!CodeGen.optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000879 DisableLTOVectorization)) {
880 // Diagnostic messages should have been printed by the handler.
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000881 error("error optimizing the code");
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000882 }
883
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000884 if (SaveModuleFile) {
885 std::string ModuleFilename = OutputFilename;
886 ModuleFilename += ".merged.bc";
887 std::string ErrMsg;
888
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000889 if (!CodeGen.writeMergedModules(ModuleFilename.c_str()))
890 error("writing merged module failed.");
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000891 }
892
Peter Collingbournec269ed52015-08-27 23:37:36 +0000893 std::list<tool_output_file> OSs;
894 std::vector<raw_pwrite_stream *> OSPtrs;
895 for (unsigned I = 0; I != Parallelism; ++I) {
896 std::string PartFilename = OutputFilename;
897 if (Parallelism != 1)
898 PartFilename += "." + utostr(I);
899 std::error_code EC;
900 OSs.emplace_back(PartFilename, EC, sys::fs::F_None);
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000901 if (EC)
902 error("error opening the file '" + PartFilename + "': " + EC.message());
Peter Collingbournec269ed52015-08-27 23:37:36 +0000903 OSPtrs.push_back(&OSs.back().os());
904 }
905
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000906 if (!CodeGen.compileOptimized(OSPtrs))
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000907 // Diagnostic messages should have been printed by the handler.
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000908 error("error compiling the code");
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000909
Peter Collingbournec269ed52015-08-27 23:37:36 +0000910 for (tool_output_file &OS : OSs)
911 OS.keep();
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000912 } else {
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000913 if (Parallelism != 1)
914 error("-j must be specified together with -o");
Peter Collingbournec269ed52015-08-27 23:37:36 +0000915
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000916 if (SaveModuleFile)
917 error(": -save-merged-module must be specified with -o");
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000918
Craig Toppere6cb63e2014-04-25 04:24:47 +0000919 const char *OutputName = nullptr;
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000920 if (!CodeGen.compile_to_file(&OutputName, DisableVerify, DisableInline,
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000921 DisableGVNLoadPRE, DisableLTOVectorization))
922 error("error compiling the code");
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000923 // Diagnostic messages should have been printed by the handler.
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000924
925 outs() << "Wrote native object file '" << OutputName << "'\n";
926 }
927
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000928 return 0;
929}