blob: 50c5f2348dd1843e012243a8f380833d08b3589b [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 Johnsonad176792016-11-11 05:34:58 +000016#include "llvm/Bitcode/BitcodeReader.h"
17#include "llvm/Bitcode/BitcodeWriter.h"
Rafael Espindola0b385c72013-09-30 16:39:19 +000018#include "llvm/CodeGen/CommandFlags.h"
Mehdi Amini354f5202015-11-19 05:52:29 +000019#include "llvm/IR/DiagnosticPrinter.h"
Teresa Johnson91a88bb2015-10-19 14:30:44 +000020#include "llvm/IR/LLVMContext.h"
Mehdi Amini3c0e64c2016-04-20 01:04:26 +000021#include "llvm/IR/Verifier.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000022#include "llvm/IRReader/IRReader.h"
Peter Collingbourne5c732202016-07-14 21:21:16 +000023#include "llvm/LTO/legacy/LTOCodeGenerator.h"
24#include "llvm/LTO/legacy/LTOModule.h"
25#include "llvm/LTO/legacy/ThinLTOCodeGenerator.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000026#include "llvm/Object/ModuleSummaryIndexObjectFile.h"
Peter Collingbourne4e380b02013-09-19 22:15:52 +000027#include "llvm/Support/CommandLine.h"
Benjamin Kramerd59664f2014-04-29 23:26:49 +000028#include "llvm/Support/FileSystem.h"
Peter Collingbourne4e380b02013-09-19 22:15:52 +000029#include "llvm/Support/ManagedStatic.h"
Teresa Johnsonbbd10b42016-05-17 14:45:30 +000030#include "llvm/Support/Path.h"
Peter Collingbourne4e380b02013-09-19 22:15:52 +000031#include "llvm/Support/PrettyStackTrace.h"
32#include "llvm/Support/Signals.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000033#include "llvm/Support/SourceMgr.h"
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +000034#include "llvm/Support/TargetSelect.h"
Peter Collingbournec269ed52015-08-27 23:37:36 +000035#include "llvm/Support/ToolOutputFile.h"
Chandler Carruth07baed52014-01-13 08:04:33 +000036#include "llvm/Support/raw_ostream.h"
Peter Collingbournec269ed52015-08-27 23:37:36 +000037#include <list>
Peter Collingbourne4e380b02013-09-19 22:15:52 +000038
39using namespace llvm;
40
Peter Collingbourne070843d2015-03-19 22:01:00 +000041static cl::opt<char>
Davide Italianob10e8932016-04-13 21:41:35 +000042 OptLevel("O", cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
43 "(default = '-O2')"),
44 cl::Prefix, cl::ZeroOrMore, cl::init('2'));
Peter Collingbourne4e380b02013-09-19 22:15:52 +000045
Mehdi Amini06a47802016-09-14 21:04:59 +000046static cl::opt<bool>
47 IndexStats("thinlto-index-stats",
48 cl::desc("Print statistic for the index in every input files"),
49 cl::init(false));
50
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +000051static cl::opt<bool> DisableVerify(
52 "disable-verify", cl::init(false),
53 cl::desc("Do not run the verifier during the optimization pipeline"));
54
Davide Italianob10e8932016-04-13 21:41:35 +000055static cl::opt<bool> DisableInline("disable-inlining", cl::init(false),
56 cl::desc("Do not run the inliner pass"));
Rafael Espindola0b385c72013-09-30 16:39:19 +000057
58static cl::opt<bool>
Davide Italianob10e8932016-04-13 21:41:35 +000059 DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
60 cl::desc("Do not run the GVN load PRE pass"));
Rafael Espindola0b385c72013-09-30 16:39:19 +000061
Davide Italianob10e8932016-04-13 21:41:35 +000062static cl::opt<bool> DisableLTOVectorization(
63 "disable-lto-vectorization", cl::init(false),
64 cl::desc("Do not run loop or slp vectorization during LTO"));
Arnold Schwaighofereb1a38f2014-10-26 21:50:58 +000065
Davide Italianob10e8932016-04-13 21:41:35 +000066static cl::opt<bool> UseDiagnosticHandler(
67 "use-diagnostic-handler", cl::init(false),
68 cl::desc("Use a diagnostic handler to test the handler interface"));
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +000069
Teresa Johnsonf72278f2015-11-02 18:02:11 +000070static cl::opt<bool>
71 ThinLTO("thinlto", cl::init(false),
72 cl::desc("Only write combined global index for ThinLTO backends"));
Teresa Johnson91a88bb2015-10-19 14:30:44 +000073
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000074enum ThinLTOModes {
75 THINLINK,
Teresa Johnson84174c32016-05-10 13:48:23 +000076 THINDISTRIBUTE,
Teresa Johnson8570fe42016-05-10 15:54:09 +000077 THINEMITIMPORTS,
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000078 THINPROMOTE,
79 THINIMPORT,
Mehdi Amini059464f2016-04-24 03:18:01 +000080 THININTERNALIZE,
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000081 THINOPT,
82 THINCODEGEN,
83 THINALL
84};
85
86cl::opt<ThinLTOModes> ThinLTOMode(
87 "thinlto-action", cl::desc("Perform a single ThinLTO stage:"),
88 cl::values(
89 clEnumValN(
90 THINLINK, "thinlink",
91 "ThinLink: produces the index by linking only the summaries."),
Teresa Johnson84174c32016-05-10 13:48:23 +000092 clEnumValN(THINDISTRIBUTE, "distributedindexes",
93 "Produces individual indexes for distributed backends."),
Teresa Johnson8570fe42016-05-10 15:54:09 +000094 clEnumValN(THINEMITIMPORTS, "emitimports",
95 "Emit imports files for distributed backends."),
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000096 clEnumValN(THINPROMOTE, "promote",
97 "Perform pre-import promotion (requires -thinlto-index)."),
98 clEnumValN(THINIMPORT, "import", "Perform both promotion and "
99 "cross-module importing (requires "
100 "-thinlto-index)."),
Mehdi Amini059464f2016-04-24 03:18:01 +0000101 clEnumValN(THININTERNALIZE, "internalize",
102 "Perform internalization driven by -exported-symbol "
103 "(requires -thinlto-index)."),
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000104 clEnumValN(THINOPT, "optimize", "Perform ThinLTO optimizations."),
105 clEnumValN(THINCODEGEN, "codegen", "CodeGen (expected to match llc)"),
Mehdi Amini732afdd2016-10-08 19:41:06 +0000106 clEnumValN(THINALL, "run", "Perform ThinLTO end-to-end")));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000107
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();
Mehdi Amini00fa1402016-10-08 04:44:18 +0000493 if (!CombinedIndex)
494 report_fatal_error("ThinLink didn't create an index");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000495 std::error_code EC;
496 raw_fd_ostream OS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
497 error(EC, "error opening the file '" + OutputFilename + "'");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000498 WriteIndexToFile(*CombinedIndex, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000499 return;
500 }
501
Teresa Johnson84174c32016-05-10 13:48:23 +0000502 /// Load the combined index from disk, then compute and generate
503 /// individual index files suitable for ThinLTO distributed backend builds
504 /// on the files mentioned on the command line (these must match the index
505 /// content).
506 void distributedIndexes() {
507 if (InputFilenames.size() != 1 && !OutputFilename.empty())
508 report_fatal_error("Can't handle a single output filename and multiple "
509 "input files, do not provide an output filename and "
510 "the output files will be suffixed from the input "
511 "ones.");
512
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000513 std::string OldPrefix, NewPrefix;
514 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
515
Teresa Johnson84174c32016-05-10 13:48:23 +0000516 auto Index = loadCombinedIndex();
517 for (auto &Filename : InputFilenames) {
518 // Build a map of module to the GUIDs and summary objects that should
519 // be written to its index.
520 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
521 ThinLTOCodeGenerator::gatherImportedSummariesForModule(
522 Filename, *Index, ModuleToSummariesForIndex);
523
524 std::string OutputName = OutputFilename;
525 if (OutputName.empty()) {
526 OutputName = Filename + ".thinlto.bc";
527 }
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000528 OutputName = getThinLTOOutputFile(OutputName, OldPrefix, NewPrefix);
Teresa Johnson84174c32016-05-10 13:48:23 +0000529 std::error_code EC;
530 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::F_None);
531 error(EC, "error opening the file '" + OutputName + "'");
532 WriteIndexToFile(*Index, OS, &ModuleToSummariesForIndex);
533 }
534 }
535
Teresa Johnson8570fe42016-05-10 15:54:09 +0000536 /// Load the combined index from disk, compute the imports, and emit
537 /// the import file lists for each module to disk.
538 void emitImports() {
539 if (InputFilenames.size() != 1 && !OutputFilename.empty())
540 report_fatal_error("Can't handle a single output filename and multiple "
541 "input files, do not provide an output filename and "
542 "the output files will be suffixed from the input "
543 "ones.");
544
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000545 std::string OldPrefix, NewPrefix;
546 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
547
Teresa Johnson8570fe42016-05-10 15:54:09 +0000548 auto Index = loadCombinedIndex();
549 for (auto &Filename : InputFilenames) {
550 std::string OutputName = OutputFilename;
551 if (OutputName.empty()) {
552 OutputName = Filename + ".imports";
553 }
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000554 OutputName = getThinLTOOutputFile(OutputName, OldPrefix, NewPrefix);
Teresa Johnson8570fe42016-05-10 15:54:09 +0000555 ThinLTOCodeGenerator::emitImports(Filename, OutputName, *Index);
556 }
557 }
558
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000559 /// Load the combined index from disk, then load every file referenced by
560 /// the index and add them to the generator, finally perform the promotion
561 /// on the files mentioned on the command line (these must match the index
562 /// content).
563 void promote() {
564 if (InputFilenames.size() != 1 && !OutputFilename.empty())
565 report_fatal_error("Can't handle a single output filename and multiple "
566 "input files, do not provide an output filename and "
567 "the output files will be suffixed from the input "
568 "ones.");
569
570 auto Index = loadCombinedIndex();
571 for (auto &Filename : InputFilenames) {
572 LLVMContext Ctx;
573 auto TheModule = loadModule(Filename, Ctx);
574
575 ThinGenerator.promote(*TheModule, *Index);
576
577 std::string OutputName = OutputFilename;
578 if (OutputName.empty()) {
579 OutputName = Filename + ".thinlto.promoted.bc";
580 }
581 writeModuleToFile(*TheModule, OutputName);
582 }
583 }
584
585 /// Load the combined index from disk, then load every file referenced by
586 /// the index and add them to the generator, then performs the promotion and
587 /// cross module importing on the files mentioned on the command line
588 /// (these must match the index content).
589 void import() {
590 if (InputFilenames.size() != 1 && !OutputFilename.empty())
591 report_fatal_error("Can't handle a single output filename and multiple "
592 "input files, do not provide an output filename and "
593 "the output files will be suffixed from the input "
594 "ones.");
595
596 auto Index = loadCombinedIndex();
597 auto InputBuffers = loadAllFilesForIndex(*Index);
598 for (auto &MemBuffer : InputBuffers)
599 ThinGenerator.addModule(MemBuffer->getBufferIdentifier(),
600 MemBuffer->getBuffer());
601
602 for (auto &Filename : InputFilenames) {
603 LLVMContext Ctx;
604 auto TheModule = loadModule(Filename, Ctx);
605
606 ThinGenerator.crossModuleImport(*TheModule, *Index);
607
608 std::string OutputName = OutputFilename;
609 if (OutputName.empty()) {
610 OutputName = Filename + ".thinlto.imported.bc";
611 }
612 writeModuleToFile(*TheModule, OutputName);
613 }
614 }
615
Mehdi Amini059464f2016-04-24 03:18:01 +0000616 void internalize() {
617 if (InputFilenames.size() != 1 && !OutputFilename.empty())
618 report_fatal_error("Can't handle a single output filename and multiple "
619 "input files, do not provide an output filename and "
620 "the output files will be suffixed from the input "
621 "ones.");
622
623 if (ExportedSymbols.empty())
624 errs() << "Warning: -internalize will not perform without "
625 "-exported-symbol\n";
626
627 auto Index = loadCombinedIndex();
628 auto InputBuffers = loadAllFilesForIndex(*Index);
629 for (auto &MemBuffer : InputBuffers)
630 ThinGenerator.addModule(MemBuffer->getBufferIdentifier(),
631 MemBuffer->getBuffer());
632
633 for (auto &Filename : InputFilenames) {
634 LLVMContext Ctx;
635 auto TheModule = loadModule(Filename, Ctx);
636
637 ThinGenerator.internalize(*TheModule, *Index);
638
639 std::string OutputName = OutputFilename;
640 if (OutputName.empty()) {
641 OutputName = Filename + ".thinlto.internalized.bc";
642 }
643 writeModuleToFile(*TheModule, OutputName);
644 }
645 }
646
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000647 void optimize() {
648 if (InputFilenames.size() != 1 && !OutputFilename.empty())
649 report_fatal_error("Can't handle a single output filename and multiple "
650 "input files, do not provide an output filename and "
651 "the output files will be suffixed from the input "
652 "ones.");
653 if (!ThinLTOIndex.empty())
654 errs() << "Warning: -thinlto-index ignored for optimize stage";
655
656 for (auto &Filename : InputFilenames) {
657 LLVMContext Ctx;
658 auto TheModule = loadModule(Filename, Ctx);
659
660 ThinGenerator.optimize(*TheModule);
661
662 std::string OutputName = OutputFilename;
663 if (OutputName.empty()) {
664 OutputName = Filename + ".thinlto.imported.bc";
665 }
666 writeModuleToFile(*TheModule, OutputName);
667 }
668 }
669
670 void codegen() {
671 if (InputFilenames.size() != 1 && !OutputFilename.empty())
672 report_fatal_error("Can't handle a single output filename and multiple "
673 "input files, do not provide an output filename and "
674 "the output files will be suffixed from the input "
675 "ones.");
676 if (!ThinLTOIndex.empty())
677 errs() << "Warning: -thinlto-index ignored for codegen stage";
678
679 for (auto &Filename : InputFilenames) {
680 LLVMContext Ctx;
681 auto TheModule = loadModule(Filename, Ctx);
682
683 auto Buffer = ThinGenerator.codegen(*TheModule);
684 std::string OutputName = OutputFilename;
685 if (OutputName.empty()) {
686 OutputName = Filename + ".thinlto.o";
687 }
688 if (OutputName == "-") {
689 outs() << Buffer->getBuffer();
690 return;
691 }
692
693 std::error_code EC;
694 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::F_None);
695 error(EC, "error opening the file '" + OutputName + "'");
696 OS << Buffer->getBuffer();
697 }
698 }
699
700 /// Full ThinLTO process
701 void runAll() {
702 if (!OutputFilename.empty())
703 report_fatal_error("Do not provide an output filename for ThinLTO "
704 " processing, the output files will be suffixed from "
705 "the input ones.");
706
707 if (!ThinLTOIndex.empty())
708 errs() << "Warning: -thinlto-index ignored for full ThinLTO process";
709
710 LLVMContext Ctx;
711 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
712 for (unsigned i = 0; i < InputFilenames.size(); ++i) {
713 auto &Filename = InputFilenames[i];
714 StringRef CurrentActivity = "loading file '" + Filename + "'";
715 auto InputOrErr = MemoryBuffer::getFile(Filename);
716 error(InputOrErr, "error " + CurrentActivity);
717 InputBuffers.push_back(std::move(*InputOrErr));
718 ThinGenerator.addModule(Filename, InputBuffers.back()->getBuffer());
719 }
720
Teresa Johnsonc44a1222016-08-15 23:24:57 +0000721 if (!ThinLTOSaveTempsPrefix.empty())
722 ThinGenerator.setSaveTempsDir(ThinLTOSaveTempsPrefix);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000723 ThinGenerator.run();
724
725 auto &Binaries = ThinGenerator.getProducedBinaries();
726 if (Binaries.size() != InputFilenames.size())
727 report_fatal_error("Number of output objects does not match the number "
728 "of inputs");
729
730 for (unsigned BufID = 0; BufID < Binaries.size(); ++BufID) {
731 auto OutputName = InputFilenames[BufID] + ".thinlto.o";
732 std::error_code EC;
733 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::F_None);
734 error(EC, "error opening the file '" + OutputName + "'");
735 OS << Binaries[BufID]->getBuffer();
736 }
737 }
738
739 /// Load the combined index from disk, then load every file referenced by
740};
741
742} // namespace thinlto
743
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000744int main(int argc, char **argv) {
745 // Print a stack trace if we signal out.
Richard Smith2ad6d482016-06-09 00:53:21 +0000746 sys::PrintStackTraceOnErrorSignal(argv[0]);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000747 PrettyStackTraceProgram X(argc, argv);
748
749 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
750 cl::ParseCommandLineOptions(argc, argv, "llvm LTO linker\n");
751
Rafael Espindola5e128db2015-12-04 00:45:57 +0000752 if (OptLevel < '0' || OptLevel > '3')
753 error("optimization level must be between 0 and 3");
Peter Collingbourne070843d2015-03-19 22:01:00 +0000754
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000755 // Initialize the configured targets.
756 InitializeAllTargets();
757 InitializeAllTargetMCs();
758 InitializeAllAsmPrinters();
759 InitializeAllAsmParsers();
760
Rafael Espindola0b385c72013-09-30 16:39:19 +0000761 // set up the TargetOptions for the machine
Eli Benderskyf0f21002014-02-19 17:09:35 +0000762 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
Rafael Espindola0b385c72013-09-30 16:39:19 +0000763
Rafael Espindola5e128db2015-12-04 00:45:57 +0000764 if (ListSymbolsOnly) {
765 listSymbols(Options);
766 return 0;
767 }
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000768
Mehdi Amini06a47802016-09-14 21:04:59 +0000769 if (IndexStats) {
770 printIndexStats();
771 return 0;
772 }
773
Mehdi Aminie75aa6f2016-07-11 23:10:18 +0000774 if (CheckHasObjC) {
775 for (auto &Filename : InputFilenames) {
776 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
777 MemoryBuffer::getFile(Filename);
778 error(BufferOrErr, "error loading file '" + Filename + "'");
779 auto Buffer = std::move(BufferOrErr.get());
780 LLVMContext Ctx;
781 if (llvm::isBitcodeContainingObjCCategory(*Buffer, Ctx))
782 outs() << "Bitcode " << Filename << " contains ObjC\n";
783 else
784 outs() << "Bitcode " << Filename << " does not contain ObjC\n";
785 }
786 return 0;
787 }
788
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000789 if (ThinLTOMode.getNumOccurrences()) {
790 if (ThinLTOMode.getNumOccurrences() > 1)
791 report_fatal_error("You can't specify more than one -thinlto-action");
792 thinlto::ThinLTOProcessing ThinLTOProcessor(Options);
793 ThinLTOProcessor.run();
794 return 0;
795 }
796
Rafael Espindola5e128db2015-12-04 00:45:57 +0000797 if (ThinLTO) {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000798 createCombinedModuleSummaryIndex();
Rafael Espindola5e128db2015-12-04 00:45:57 +0000799 return 0;
800 }
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000801
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000802 unsigned BaseArg = 0;
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000803
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000804 LLVMContext Context;
Petr Pavlu7ad9ec92016-03-01 13:13:49 +0000805 Context.setDiagnosticHandler(diagnosticHandlerWithContext, nullptr, true);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000806
807 LTOCodeGenerator CodeGen(Context);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000808
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +0000809 if (UseDiagnosticHandler)
810 CodeGen.setDiagnosticHandler(handleDiagnostics, nullptr);
811
Rafael Espindola8c34dd82016-05-18 22:04:49 +0000812 CodeGen.setCodePICModel(getRelocModel());
James Molloy951e5292014-04-14 13:54:16 +0000813
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000814 CodeGen.setDebugInfo(LTO_DEBUG_MODEL_DWARF);
Rafael Espindola0b385c72013-09-30 16:39:19 +0000815 CodeGen.setTargetOptions(Options);
Tobias Edler von Koch3f4f6f3e2016-01-18 23:35:24 +0000816 CodeGen.setShouldRestoreGlobalsLinkage(RestoreGlobalsLinkage);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000817
Rafael Espindola282a4702013-10-31 20:51:58 +0000818 llvm::StringSet<llvm::MallocAllocator> DSOSymbolsSet;
819 for (unsigned i = 0; i < DSOSymbols.size(); ++i)
820 DSOSymbolsSet.insert(DSOSymbols[i]);
821
822 std::vector<std::string> KeptDSOSyms;
823
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000824 for (unsigned i = BaseArg; i < InputFilenames.size(); ++i) {
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000825 CurrentActivity = "loading file '" + InputFilenames[i] + "'";
826 ErrorOr<std::unique_ptr<LTOModule>> ModuleOrErr =
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000827 LTOModule::createFromFile(Context, InputFilenames[i], Options);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000828 std::unique_ptr<LTOModule> &Module = *ModuleOrErr;
829 CurrentActivity = "";
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000830
Peter Collingbourne552174392015-08-21 19:09:42 +0000831 unsigned NumSyms = Module->getSymbolCount();
832 for (unsigned I = 0; I < NumSyms; ++I) {
833 StringRef Name = Module->getSymbolName(I);
834 if (!DSOSymbolsSet.count(Name))
835 continue;
836 lto_symbol_attributes Attrs = Module->getSymbolAttributes(I);
837 unsigned Scope = Attrs & LTO_SYMBOL_SCOPE_MASK;
838 if (Scope != LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN)
839 KeptDSOSyms.push_back(Name);
840 }
Manman Ren6487ce92015-02-24 00:45:56 +0000841
842 // We use the first input module as the destination module when
843 // SetMergedModule is true.
844 if (SetMergedModule && i == BaseArg) {
845 // Transfer ownership to the code generator.
Peter Collingbourne9c8909d2015-08-24 22:22:53 +0000846 CodeGen.setModule(std::move(Module));
Yunzhong Gao46261a72015-09-11 20:01:53 +0000847 } else if (!CodeGen.addModule(Module.get())) {
848 // Print a message here so that we know addModule() did not abort.
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000849 error("error adding file '" + InputFilenames[i] + "'");
Yunzhong Gao46261a72015-09-11 20:01:53 +0000850 }
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000851 }
852
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000853 // Add all the exported symbols to the table of symbols to preserve.
854 for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000855 CodeGen.addMustPreserveSymbol(ExportedSymbols[i]);
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000856
Rafael Espindolacda29112013-10-03 18:29:09 +0000857 // Add all the dso symbols to the table of symbols to expose.
Rafael Espindola282a4702013-10-31 20:51:58 +0000858 for (unsigned i = 0; i < KeptDSOSyms.size(); ++i)
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000859 CodeGen.addMustPreserveSymbol(KeptDSOSyms[i]);
Rafael Espindolacda29112013-10-03 18:29:09 +0000860
Akira Hatanaka23b5f672015-01-30 01:14:28 +0000861 // Set cpu and attrs strings for the default target/subtarget.
862 CodeGen.setCpu(MCPU.c_str());
863
Peter Collingbourne070843d2015-03-19 22:01:00 +0000864 CodeGen.setOptLevel(OptLevel - '0');
865
Tom Roederfd1bc602014-04-25 21:46:51 +0000866 std::string attrs;
867 for (unsigned i = 0; i < MAttrs.size(); ++i) {
868 if (i > 0)
869 attrs.append(",");
870 attrs.append(MAttrs[i]);
871 }
872
873 if (!attrs.empty())
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000874 CodeGen.setAttr(attrs);
Tom Roederfd1bc602014-04-25 21:46:51 +0000875
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000876 if (FileType.getNumOccurrences())
877 CodeGen.setFileType(FileType);
878
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000879 if (!OutputFilename.empty()) {
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000880 if (!CodeGen.optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000881 DisableLTOVectorization)) {
882 // Diagnostic messages should have been printed by the handler.
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000883 error("error optimizing the code");
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000884 }
885
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000886 if (SaveModuleFile) {
887 std::string ModuleFilename = OutputFilename;
888 ModuleFilename += ".merged.bc";
889 std::string ErrMsg;
890
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000891 if (!CodeGen.writeMergedModules(ModuleFilename))
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000892 error("writing merged module failed.");
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000893 }
894
Peter Collingbournec269ed52015-08-27 23:37:36 +0000895 std::list<tool_output_file> OSs;
896 std::vector<raw_pwrite_stream *> OSPtrs;
897 for (unsigned I = 0; I != Parallelism; ++I) {
898 std::string PartFilename = OutputFilename;
899 if (Parallelism != 1)
900 PartFilename += "." + utostr(I);
901 std::error_code EC;
902 OSs.emplace_back(PartFilename, EC, sys::fs::F_None);
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000903 if (EC)
904 error("error opening the file '" + PartFilename + "': " + EC.message());
Peter Collingbournec269ed52015-08-27 23:37:36 +0000905 OSPtrs.push_back(&OSs.back().os());
906 }
907
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000908 if (!CodeGen.compileOptimized(OSPtrs))
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000909 // Diagnostic messages should have been printed by the handler.
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000910 error("error compiling the code");
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000911
Peter Collingbournec269ed52015-08-27 23:37:36 +0000912 for (tool_output_file &OS : OSs)
913 OS.keep();
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000914 } else {
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000915 if (Parallelism != 1)
916 error("-j must be specified together with -o");
Peter Collingbournec269ed52015-08-27 23:37:36 +0000917
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000918 if (SaveModuleFile)
919 error(": -save-merged-module must be specified with -o");
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000920
Craig Toppere6cb63e2014-04-25 04:24:47 +0000921 const char *OutputName = nullptr;
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000922 if (!CodeGen.compile_to_file(&OutputName, DisableVerify, DisableInline,
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000923 DisableGVNLoadPRE, DisableLTOVectorization))
924 error("error compiling the code");
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000925 // Diagnostic messages should have been printed by the handler.
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000926
927 outs() << "Wrote native object file '" << OutputName << "'\n";
928 }
929
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000930 return 0;
931}