blob: 27e5c5e122c27808be8ec3ca63c18d1df6e26ada [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"
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
Mehdi Aminib5a46c12017-03-28 18:55:44 +000065static cl::opt<bool> EnableFreestanding(
66 "lto-freestanding", cl::init(false),
67 cl::desc("Enable Freestanding (disable builtins / TLI) during LTO"));
68
Davide Italianob10e8932016-04-13 21:41:35 +000069static cl::opt<bool> UseDiagnosticHandler(
70 "use-diagnostic-handler", cl::init(false),
71 cl::desc("Use a diagnostic handler to test the handler interface"));
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +000072
Teresa Johnsonf72278f2015-11-02 18:02:11 +000073static cl::opt<bool>
74 ThinLTO("thinlto", cl::init(false),
75 cl::desc("Only write combined global index for ThinLTO backends"));
Teresa Johnson91a88bb2015-10-19 14:30:44 +000076
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000077enum ThinLTOModes {
78 THINLINK,
Teresa Johnson84174c32016-05-10 13:48:23 +000079 THINDISTRIBUTE,
Teresa Johnson8570fe42016-05-10 15:54:09 +000080 THINEMITIMPORTS,
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000081 THINPROMOTE,
82 THINIMPORT,
Mehdi Amini059464f2016-04-24 03:18:01 +000083 THININTERNALIZE,
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000084 THINOPT,
85 THINCODEGEN,
86 THINALL
87};
88
89cl::opt<ThinLTOModes> ThinLTOMode(
90 "thinlto-action", cl::desc("Perform a single ThinLTO stage:"),
91 cl::values(
92 clEnumValN(
93 THINLINK, "thinlink",
94 "ThinLink: produces the index by linking only the summaries."),
Teresa Johnson84174c32016-05-10 13:48:23 +000095 clEnumValN(THINDISTRIBUTE, "distributedindexes",
96 "Produces individual indexes for distributed backends."),
Teresa Johnson8570fe42016-05-10 15:54:09 +000097 clEnumValN(THINEMITIMPORTS, "emitimports",
98 "Emit imports files for distributed backends."),
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000099 clEnumValN(THINPROMOTE, "promote",
100 "Perform pre-import promotion (requires -thinlto-index)."),
101 clEnumValN(THINIMPORT, "import", "Perform both promotion and "
102 "cross-module importing (requires "
103 "-thinlto-index)."),
Mehdi Amini059464f2016-04-24 03:18:01 +0000104 clEnumValN(THININTERNALIZE, "internalize",
105 "Perform internalization driven by -exported-symbol "
106 "(requires -thinlto-index)."),
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000107 clEnumValN(THINOPT, "optimize", "Perform ThinLTO optimizations."),
108 clEnumValN(THINCODEGEN, "codegen", "CodeGen (expected to match llc)"),
Mehdi Amini732afdd2016-10-08 19:41:06 +0000109 clEnumValN(THINALL, "run", "Perform ThinLTO end-to-end")));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000110
111static cl::opt<std::string>
112 ThinLTOIndex("thinlto-index",
113 cl::desc("Provide the index produced by a ThinLink, required "
114 "to perform the promotion and/or importing."));
115
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000116static cl::opt<std::string> ThinLTOPrefixReplace(
117 "thinlto-prefix-replace",
118 cl::desc("Control where files for distributed backends are "
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000119 "created. Expects 'oldprefix;newprefix' and if path "
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000120 "prefix of output file is oldprefix it will be "
121 "replaced with newprefix."));
122
Mehdi Amini03abce92016-05-05 16:33:51 +0000123static cl::opt<std::string> ThinLTOModuleId(
124 "thinlto-module-id",
125 cl::desc("For the module ID for the file to process, useful to "
126 "match what is in the index."));
127
Mehdi Aminiab4a8b62016-05-14 05:16:41 +0000128static cl::opt<std::string>
129 ThinLTOCacheDir("thinlto-cache-dir", cl::desc("Enable ThinLTO caching."));
130
Teresa Johnsonc44a1222016-08-15 23:24:57 +0000131static cl::opt<std::string> ThinLTOSaveTempsPrefix(
132 "thinlto-save-temps",
133 cl::desc("Save ThinLTO temp files using filenames created by adding "
134 "suffixes to the given file path prefix."));
135
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000136static cl::opt<std::string> ThinLTOGeneratedObjectsDir(
137 "thinlto-save-objects",
138 cl::desc("Save ThinLTO generated object files using filenames created in "
139 "the given directory."));
140
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000141static cl::opt<bool>
Davide Italianob10e8932016-04-13 21:41:35 +0000142 SaveModuleFile("save-merged-module", cl::init(false),
143 cl::desc("Write merged LTO module to file before CodeGen"));
144
145static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
146 cl::desc("<input bitcode files>"));
147
148static cl::opt<std::string> OutputFilename("o", cl::init(""),
149 cl::desc("Override output filename"),
150 cl::value_desc("filename"));
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000151
Mehdi Amini059464f2016-04-24 03:18:01 +0000152static cl::list<std::string> ExportedSymbols(
153 "exported-symbol",
154 cl::desc("List of symbols to export from the resulting object file"),
155 cl::ZeroOrMore);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000156
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000157static cl::list<std::string>
Davide Italianob10e8932016-04-13 21:41:35 +0000158 DSOSymbols("dso-symbol",
159 cl::desc("Symbol to put in the symtab in the resulting dso"),
160 cl::ZeroOrMore);
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000161
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000162static cl::opt<bool> ListSymbolsOnly(
163 "list-symbols-only", cl::init(false),
164 cl::desc("Instead of running LTO, list the symbols in each IR file"));
165
Manman Ren6487ce92015-02-24 00:45:56 +0000166static cl::opt<bool> SetMergedModule(
167 "set-merged-module", cl::init(false),
168 cl::desc("Use the first input module as the merged module"));
169
Peter Collingbournec269ed52015-08-27 23:37:36 +0000170static cl::opt<unsigned> Parallelism("j", cl::Prefix, cl::init(1),
171 cl::desc("Number of backend threads"));
172
Tobias Edler von Koch3f4f6f3e2016-01-18 23:35:24 +0000173static cl::opt<bool> RestoreGlobalsLinkage(
174 "restore-linkage", cl::init(false),
175 cl::desc("Restore original linkage of globals prior to CodeGen"));
176
Mehdi Aminie75aa6f2016-07-11 23:10:18 +0000177static cl::opt<bool> CheckHasObjC(
178 "check-for-objc", cl::init(false),
179 cl::desc("Only check if the module has objective-C defined in it"));
180
Rafael Espindola282a4702013-10-31 20:51:58 +0000181namespace {
182struct ModuleInfo {
183 std::vector<bool> CanBeHidden;
184};
185}
186
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000187static void handleDiagnostics(lto_codegen_diagnostic_severity_t Severity,
188 const char *Msg, void *) {
Yunzhong Gaoef436f02015-11-10 18:52:48 +0000189 errs() << "llvm-lto: ";
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +0000190 switch (Severity) {
191 case LTO_DS_NOTE:
192 errs() << "note: ";
193 break;
194 case LTO_DS_REMARK:
195 errs() << "remark: ";
196 break;
197 case LTO_DS_ERROR:
198 errs() << "error: ";
199 break;
200 case LTO_DS_WARNING:
201 errs() << "warning: ";
202 break;
203 }
204 errs() << Msg << "\n";
205}
206
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000207static std::string CurrentActivity;
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000208static void diagnosticHandler(const DiagnosticInfo &DI, void *Context) {
Mehdi Amini354f5202015-11-19 05:52:29 +0000209 raw_ostream &OS = errs();
210 OS << "llvm-lto: ";
211 switch (DI.getSeverity()) {
212 case DS_Error:
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000213 OS << "error";
Mehdi Amini354f5202015-11-19 05:52:29 +0000214 break;
215 case DS_Warning:
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000216 OS << "warning";
Mehdi Amini354f5202015-11-19 05:52:29 +0000217 break;
218 case DS_Remark:
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000219 OS << "remark";
Mehdi Amini354f5202015-11-19 05:52:29 +0000220 break;
221 case DS_Note:
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000222 OS << "note";
Mehdi Amini354f5202015-11-19 05:52:29 +0000223 break;
224 }
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000225 if (!CurrentActivity.empty())
226 OS << ' ' << CurrentActivity;
227 OS << ": ";
Mehdi Amini354f5202015-11-19 05:52:29 +0000228
229 DiagnosticPrinterRawOStream DP(OS);
230 DI.print(DP);
231 OS << '\n';
232
233 if (DI.getSeverity() == DS_Error)
234 exit(1);
235}
236
Rafael Espindola5e128db2015-12-04 00:45:57 +0000237static void error(const Twine &Msg) {
238 errs() << "llvm-lto: " << Msg << '\n';
239 exit(1);
240}
241
242static void error(std::error_code EC, const Twine &Prefix) {
243 if (EC)
244 error(Prefix + ": " + EC.message());
245}
246
247template <typename T>
248static void error(const ErrorOr<T> &V, const Twine &Prefix) {
249 error(V.getError(), Prefix);
250}
251
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000252static void maybeVerifyModule(const Module &Mod) {
Mehdi Amini4c809462016-12-23 23:53:57 +0000253 if (!DisableVerify && verifyModule(Mod, &errs()))
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000254 error("Broken Module");
255}
256
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000257static std::unique_ptr<LTOModule>
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000258getLocalLTOModule(StringRef Path, std::unique_ptr<MemoryBuffer> &Buffer,
Rafael Espindola5e128db2015-12-04 00:45:57 +0000259 const TargetOptions &Options) {
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000260 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
261 MemoryBuffer::getFile(Path);
Rafael Espindola5e128db2015-12-04 00:45:57 +0000262 error(BufferOrErr, "error loading file '" + Path + "'");
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000263 Buffer = std::move(BufferOrErr.get());
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000264 CurrentActivity = ("loading file '" + Path + "'").str();
Petr Pavlu7ad9ec92016-03-01 13:13:49 +0000265 std::unique_ptr<LLVMContext> Context = llvm::make_unique<LLVMContext>();
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000266 Context->setDiagnosticHandler(diagnosticHandler, nullptr, true);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000267 ErrorOr<std::unique_ptr<LTOModule>> Ret = LTOModule::createInLocalContext(
Petr Pavlu7ad9ec92016-03-01 13:13:49 +0000268 std::move(Context), Buffer->getBufferStart(), Buffer->getBufferSize(),
269 Options, Path);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000270 CurrentActivity = "";
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000271 maybeVerifyModule((*Ret)->getModule());
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000272 return std::move(*Ret);
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000273}
274
Mehdi Amini06a47802016-09-14 21:04:59 +0000275/// Print some statistics on the index for each input files.
276void printIndexStats() {
277 for (auto &Filename : InputFilenames) {
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000278 ExitOnError ExitOnErr("llvm-lto: error loading file '" + Filename + "': ");
279 std::unique_ptr<ModuleSummaryIndex> Index =
280 ExitOnErr(llvm::getModuleSummaryIndexForFile(Filename));
Mehdi Amini06a47802016-09-14 21:04:59 +0000281 // 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) {
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000333 ExitOnError ExitOnErr("llvm-lto: error loading file '" + Filename + "': ");
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000334 std::unique_ptr<MemoryBuffer> MB =
335 ExitOnErr(errorOrToExpected(MemoryBuffer::getFileOrSTDIN(Filename)));
336 ExitOnErr(readModuleSummaryIndex(*MB, CombinedIndex, ++NextModuleId));
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000337 }
338 std::error_code EC;
339 assert(!OutputFilename.empty());
340 raw_fd_ostream OS(OutputFilename + ".thinlto.bc", EC,
341 sys::fs::OpenFlags::F_None);
Rafael Espindola5e128db2015-12-04 00:45:57 +0000342 error(EC, "error opening the file '" + OutputFilename + ".thinlto.bc'");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000343 WriteIndexToFile(CombinedIndex, OS);
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000344 OS.close();
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000345}
346
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000347/// Parse the thinlto_prefix_replace option into the \p OldPrefix and
348/// \p NewPrefix strings, if it was specified.
349static void getThinLTOOldAndNewPrefix(std::string &OldPrefix,
350 std::string &NewPrefix) {
351 assert(ThinLTOPrefixReplace.empty() ||
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000352 ThinLTOPrefixReplace.find(";") != StringRef::npos);
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000353 StringRef PrefixReplace = ThinLTOPrefixReplace;
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000354 std::pair<StringRef, StringRef> Split = PrefixReplace.split(";");
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000355 OldPrefix = Split.first.str();
356 NewPrefix = Split.second.str();
357}
358
359/// Given the original \p Path to an output file, replace any path
360/// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
361/// resulting directory if it does not yet exist.
362static std::string getThinLTOOutputFile(const std::string &Path,
363 const std::string &OldPrefix,
364 const std::string &NewPrefix) {
365 if (OldPrefix.empty() && NewPrefix.empty())
366 return Path;
367 SmallString<128> NewPath(Path);
368 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
369 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
370 if (!ParentPath.empty()) {
371 // Make sure the new directory exists, creating it if necessary.
372 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
373 error(EC, "error creating the directory '" + ParentPath + "'");
374 }
375 return NewPath.str();
376}
377
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000378namespace thinlto {
379
380std::vector<std::unique_ptr<MemoryBuffer>>
Teresa Johnson26ab5772016-03-15 00:04:37 +0000381loadAllFilesForIndex(const ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000382 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
383
Mehdi Amini385cf282016-03-26 03:35:38 +0000384 for (auto &ModPath : Index.modulePaths()) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000385 const auto &Filename = ModPath.first();
386 auto CurrentActivity = "loading file '" + Filename + "'";
387 auto InputOrErr = MemoryBuffer::getFile(Filename);
388 error(InputOrErr, "error " + CurrentActivity);
389 InputBuffers.push_back(std::move(*InputOrErr));
390 }
391 return InputBuffers;
392}
393
Teresa Johnson26ab5772016-03-15 00:04:37 +0000394std::unique_ptr<ModuleSummaryIndex> loadCombinedIndex() {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000395 if (ThinLTOIndex.empty())
396 report_fatal_error("Missing -thinlto-index for ThinLTO promotion stage");
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000397 ExitOnError ExitOnErr("llvm-lto: error loading file '" + ThinLTOIndex +
398 "': ");
399 return ExitOnErr(llvm::getModuleSummaryIndexForFile(ThinLTOIndex));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000400}
401
402static std::unique_ptr<Module> loadModule(StringRef Filename,
403 LLVMContext &Ctx) {
404 SMDiagnostic Err;
405 std::unique_ptr<Module> M(parseIRFile(Filename, Err, Ctx));
406 if (!M) {
407 Err.print("llvm-lto", errs());
408 report_fatal_error("Can't load module for file " + Filename);
409 }
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000410 maybeVerifyModule(*M);
Mehdi Amini03abce92016-05-05 16:33:51 +0000411
412 if (ThinLTOModuleId.getNumOccurrences()) {
413 if (InputFilenames.size() != 1)
414 report_fatal_error("Can't override the module id for multiple files");
415 M->setModuleIdentifier(ThinLTOModuleId);
416 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000417 return M;
418}
419
420static void writeModuleToFile(Module &TheModule, StringRef Filename) {
421 std::error_code EC;
422 raw_fd_ostream OS(Filename, EC, sys::fs::OpenFlags::F_None);
423 error(EC, "error opening the file '" + Filename + "'");
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000424 maybeVerifyModule(TheModule);
Teresa Johnson3c35e092016-04-04 21:19:31 +0000425 WriteBitcodeToFile(&TheModule, OS, /* ShouldPreserveUseListOrder */ true);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000426}
427
428class ThinLTOProcessing {
429public:
430 ThinLTOCodeGenerator ThinGenerator;
431
432 ThinLTOProcessing(const TargetOptions &Options) {
Rafael Espindola8c34dd82016-05-18 22:04:49 +0000433 ThinGenerator.setCodePICModel(getRelocModel());
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000434 ThinGenerator.setTargetOptions(Options);
Mehdi Aminiab4a8b62016-05-14 05:16:41 +0000435 ThinGenerator.setCacheDir(ThinLTOCacheDir);
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000436 ThinGenerator.setFreestanding(EnableFreestanding);
Mehdi Amini059464f2016-04-24 03:18:01 +0000437
438 // Add all the exported symbols to the table of symbols to preserve.
439 for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
440 ThinGenerator.preserveSymbol(ExportedSymbols[i]);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000441 }
442
443 void run() {
444 switch (ThinLTOMode) {
445 case THINLINK:
446 return thinLink();
Teresa Johnson84174c32016-05-10 13:48:23 +0000447 case THINDISTRIBUTE:
448 return distributedIndexes();
Teresa Johnson8570fe42016-05-10 15:54:09 +0000449 case THINEMITIMPORTS:
450 return emitImports();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000451 case THINPROMOTE:
452 return promote();
453 case THINIMPORT:
454 return import();
Mehdi Amini059464f2016-04-24 03:18:01 +0000455 case THININTERNALIZE:
456 return internalize();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000457 case THINOPT:
458 return optimize();
459 case THINCODEGEN:
460 return codegen();
461 case THINALL:
462 return runAll();
463 }
464 }
465
466private:
467 /// Load the input files, create the combined index, and write it out.
468 void thinLink() {
469 // Perform "ThinLink": just produce the index
470 if (OutputFilename.empty())
471 report_fatal_error(
472 "OutputFilename is necessary to store the combined index.\n");
473
474 LLVMContext Ctx;
475 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
476 for (unsigned i = 0; i < InputFilenames.size(); ++i) {
477 auto &Filename = InputFilenames[i];
478 StringRef CurrentActivity = "loading file '" + Filename + "'";
479 auto InputOrErr = MemoryBuffer::getFile(Filename);
480 error(InputOrErr, "error " + CurrentActivity);
481 InputBuffers.push_back(std::move(*InputOrErr));
482 ThinGenerator.addModule(Filename, InputBuffers.back()->getBuffer());
483 }
484
485 auto CombinedIndex = ThinGenerator.linkCombinedIndex();
Mehdi Amini00fa1402016-10-08 04:44:18 +0000486 if (!CombinedIndex)
487 report_fatal_error("ThinLink didn't create an index");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000488 std::error_code EC;
489 raw_fd_ostream OS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
490 error(EC, "error opening the file '" + OutputFilename + "'");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000491 WriteIndexToFile(*CombinedIndex, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000492 return;
493 }
494
Teresa Johnson84174c32016-05-10 13:48:23 +0000495 /// Load the combined index from disk, then compute and generate
496 /// individual index files suitable for ThinLTO distributed backend builds
497 /// on the files mentioned on the command line (these must match the index
498 /// content).
499 void distributedIndexes() {
500 if (InputFilenames.size() != 1 && !OutputFilename.empty())
501 report_fatal_error("Can't handle a single output filename and multiple "
502 "input files, do not provide an output filename and "
503 "the output files will be suffixed from the input "
504 "ones.");
505
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000506 std::string OldPrefix, NewPrefix;
507 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
508
Teresa Johnson84174c32016-05-10 13:48:23 +0000509 auto Index = loadCombinedIndex();
510 for (auto &Filename : InputFilenames) {
511 // Build a map of module to the GUIDs and summary objects that should
512 // be written to its index.
513 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
514 ThinLTOCodeGenerator::gatherImportedSummariesForModule(
515 Filename, *Index, ModuleToSummariesForIndex);
516
517 std::string OutputName = OutputFilename;
518 if (OutputName.empty()) {
519 OutputName = Filename + ".thinlto.bc";
520 }
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000521 OutputName = getThinLTOOutputFile(OutputName, OldPrefix, NewPrefix);
Teresa Johnson84174c32016-05-10 13:48:23 +0000522 std::error_code EC;
523 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::F_None);
524 error(EC, "error opening the file '" + OutputName + "'");
525 WriteIndexToFile(*Index, OS, &ModuleToSummariesForIndex);
526 }
527 }
528
Teresa Johnson8570fe42016-05-10 15:54:09 +0000529 /// Load the combined index from disk, compute the imports, and emit
530 /// the import file lists for each module to disk.
531 void emitImports() {
532 if (InputFilenames.size() != 1 && !OutputFilename.empty())
533 report_fatal_error("Can't handle a single output filename and multiple "
534 "input files, do not provide an output filename and "
535 "the output files will be suffixed from the input "
536 "ones.");
537
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000538 std::string OldPrefix, NewPrefix;
539 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
540
Teresa Johnson8570fe42016-05-10 15:54:09 +0000541 auto Index = loadCombinedIndex();
542 for (auto &Filename : InputFilenames) {
543 std::string OutputName = OutputFilename;
544 if (OutputName.empty()) {
545 OutputName = Filename + ".imports";
546 }
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000547 OutputName = getThinLTOOutputFile(OutputName, OldPrefix, NewPrefix);
Teresa Johnson8570fe42016-05-10 15:54:09 +0000548 ThinLTOCodeGenerator::emitImports(Filename, OutputName, *Index);
549 }
550 }
551
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000552 /// Load the combined index from disk, then load every file referenced by
553 /// the index and add them to the generator, finally perform the promotion
554 /// on the files mentioned on the command line (these must match the index
555 /// content).
556 void promote() {
557 if (InputFilenames.size() != 1 && !OutputFilename.empty())
558 report_fatal_error("Can't handle a single output filename and multiple "
559 "input files, do not provide an output filename and "
560 "the output files will be suffixed from the input "
561 "ones.");
562
563 auto Index = loadCombinedIndex();
564 for (auto &Filename : InputFilenames) {
565 LLVMContext Ctx;
566 auto TheModule = loadModule(Filename, Ctx);
567
568 ThinGenerator.promote(*TheModule, *Index);
569
570 std::string OutputName = OutputFilename;
571 if (OutputName.empty()) {
572 OutputName = Filename + ".thinlto.promoted.bc";
573 }
574 writeModuleToFile(*TheModule, OutputName);
575 }
576 }
577
578 /// Load the combined index from disk, then load every file referenced by
579 /// the index and add them to the generator, then performs the promotion and
580 /// cross module importing on the files mentioned on the command line
581 /// (these must match the index content).
582 void import() {
583 if (InputFilenames.size() != 1 && !OutputFilename.empty())
584 report_fatal_error("Can't handle a single output filename and multiple "
585 "input files, do not provide an output filename and "
586 "the output files will be suffixed from the input "
587 "ones.");
588
589 auto Index = loadCombinedIndex();
590 auto InputBuffers = loadAllFilesForIndex(*Index);
591 for (auto &MemBuffer : InputBuffers)
592 ThinGenerator.addModule(MemBuffer->getBufferIdentifier(),
593 MemBuffer->getBuffer());
594
595 for (auto &Filename : InputFilenames) {
596 LLVMContext Ctx;
597 auto TheModule = loadModule(Filename, Ctx);
598
599 ThinGenerator.crossModuleImport(*TheModule, *Index);
600
601 std::string OutputName = OutputFilename;
602 if (OutputName.empty()) {
603 OutputName = Filename + ".thinlto.imported.bc";
604 }
605 writeModuleToFile(*TheModule, OutputName);
606 }
607 }
608
Mehdi Amini059464f2016-04-24 03:18:01 +0000609 void internalize() {
610 if (InputFilenames.size() != 1 && !OutputFilename.empty())
611 report_fatal_error("Can't handle a single output filename and multiple "
612 "input files, do not provide an output filename and "
613 "the output files will be suffixed from the input "
614 "ones.");
615
616 if (ExportedSymbols.empty())
617 errs() << "Warning: -internalize will not perform without "
618 "-exported-symbol\n";
619
620 auto Index = loadCombinedIndex();
621 auto InputBuffers = loadAllFilesForIndex(*Index);
622 for (auto &MemBuffer : InputBuffers)
623 ThinGenerator.addModule(MemBuffer->getBufferIdentifier(),
624 MemBuffer->getBuffer());
625
626 for (auto &Filename : InputFilenames) {
627 LLVMContext Ctx;
628 auto TheModule = loadModule(Filename, Ctx);
629
630 ThinGenerator.internalize(*TheModule, *Index);
631
632 std::string OutputName = OutputFilename;
633 if (OutputName.empty()) {
634 OutputName = Filename + ".thinlto.internalized.bc";
635 }
636 writeModuleToFile(*TheModule, OutputName);
637 }
638 }
639
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000640 void optimize() {
641 if (InputFilenames.size() != 1 && !OutputFilename.empty())
642 report_fatal_error("Can't handle a single output filename and multiple "
643 "input files, do not provide an output filename and "
644 "the output files will be suffixed from the input "
645 "ones.");
646 if (!ThinLTOIndex.empty())
647 errs() << "Warning: -thinlto-index ignored for optimize stage";
648
649 for (auto &Filename : InputFilenames) {
650 LLVMContext Ctx;
651 auto TheModule = loadModule(Filename, Ctx);
652
653 ThinGenerator.optimize(*TheModule);
654
655 std::string OutputName = OutputFilename;
656 if (OutputName.empty()) {
657 OutputName = Filename + ".thinlto.imported.bc";
658 }
659 writeModuleToFile(*TheModule, OutputName);
660 }
661 }
662
663 void codegen() {
664 if (InputFilenames.size() != 1 && !OutputFilename.empty())
665 report_fatal_error("Can't handle a single output filename and multiple "
666 "input files, do not provide an output filename and "
667 "the output files will be suffixed from the input "
668 "ones.");
669 if (!ThinLTOIndex.empty())
670 errs() << "Warning: -thinlto-index ignored for codegen stage";
671
672 for (auto &Filename : InputFilenames) {
673 LLVMContext Ctx;
674 auto TheModule = loadModule(Filename, Ctx);
675
676 auto Buffer = ThinGenerator.codegen(*TheModule);
677 std::string OutputName = OutputFilename;
678 if (OutputName.empty()) {
679 OutputName = Filename + ".thinlto.o";
680 }
681 if (OutputName == "-") {
682 outs() << Buffer->getBuffer();
683 return;
684 }
685
686 std::error_code EC;
687 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::F_None);
688 error(EC, "error opening the file '" + OutputName + "'");
689 OS << Buffer->getBuffer();
690 }
691 }
692
693 /// Full ThinLTO process
694 void runAll() {
695 if (!OutputFilename.empty())
696 report_fatal_error("Do not provide an output filename for ThinLTO "
697 " processing, the output files will be suffixed from "
698 "the input ones.");
699
700 if (!ThinLTOIndex.empty())
701 errs() << "Warning: -thinlto-index ignored for full ThinLTO process";
702
703 LLVMContext Ctx;
704 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
705 for (unsigned i = 0; i < InputFilenames.size(); ++i) {
706 auto &Filename = InputFilenames[i];
707 StringRef CurrentActivity = "loading file '" + Filename + "'";
708 auto InputOrErr = MemoryBuffer::getFile(Filename);
709 error(InputOrErr, "error " + CurrentActivity);
710 InputBuffers.push_back(std::move(*InputOrErr));
711 ThinGenerator.addModule(Filename, InputBuffers.back()->getBuffer());
712 }
713
Teresa Johnsonc44a1222016-08-15 23:24:57 +0000714 if (!ThinLTOSaveTempsPrefix.empty())
715 ThinGenerator.setSaveTempsDir(ThinLTOSaveTempsPrefix);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000716
717 if (!ThinLTOGeneratedObjectsDir.empty()) {
718 ThinGenerator.setGeneratedObjectsDirectory(ThinLTOGeneratedObjectsDir);
719 ThinGenerator.run();
720 return;
721 }
722
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) {
Peter Collingbournecd513a42016-11-11 19:50:24 +0000776 ExitOnError ExitOnErr(std::string(*argv) + ": error loading file '" +
777 Filename + "': ");
778 std::unique_ptr<MemoryBuffer> BufferOrErr =
779 ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(Filename)));
Mehdi Aminie75aa6f2016-07-11 23:10:18 +0000780 auto Buffer = std::move(BufferOrErr.get());
Peter Collingbournecd513a42016-11-11 19:50:24 +0000781 if (ExitOnErr(llvm::isBitcodeContainingObjCCategory(*Buffer)))
Mehdi Aminie75aa6f2016-07-11 23:10:18 +0000782 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;
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000805 Context.setDiagnosticHandler(diagnosticHandler, 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());
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000813 CodeGen.setFreestanding(EnableFreestanding);
James Molloy951e5292014-04-14 13:54:16 +0000814
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000815 CodeGen.setDebugInfo(LTO_DEBUG_MODEL_DWARF);
Rafael Espindola0b385c72013-09-30 16:39:19 +0000816 CodeGen.setTargetOptions(Options);
Tobias Edler von Koch3f4f6f3e2016-01-18 23:35:24 +0000817 CodeGen.setShouldRestoreGlobalsLinkage(RestoreGlobalsLinkage);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000818
Rafael Espindola282a4702013-10-31 20:51:58 +0000819 llvm::StringSet<llvm::MallocAllocator> DSOSymbolsSet;
820 for (unsigned i = 0; i < DSOSymbols.size(); ++i)
821 DSOSymbolsSet.insert(DSOSymbols[i]);
822
823 std::vector<std::string> KeptDSOSyms;
824
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000825 for (unsigned i = BaseArg; i < InputFilenames.size(); ++i) {
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000826 CurrentActivity = "loading file '" + InputFilenames[i] + "'";
827 ErrorOr<std::unique_ptr<LTOModule>> ModuleOrErr =
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000828 LTOModule::createFromFile(Context, InputFilenames[i], Options);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000829 std::unique_ptr<LTOModule> &Module = *ModuleOrErr;
830 CurrentActivity = "";
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000831
Peter Collingbourne552174392015-08-21 19:09:42 +0000832 unsigned NumSyms = Module->getSymbolCount();
833 for (unsigned I = 0; I < NumSyms; ++I) {
834 StringRef Name = Module->getSymbolName(I);
835 if (!DSOSymbolsSet.count(Name))
836 continue;
837 lto_symbol_attributes Attrs = Module->getSymbolAttributes(I);
838 unsigned Scope = Attrs & LTO_SYMBOL_SCOPE_MASK;
839 if (Scope != LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN)
840 KeptDSOSyms.push_back(Name);
841 }
Manman Ren6487ce92015-02-24 00:45:56 +0000842
843 // We use the first input module as the destination module when
844 // SetMergedModule is true.
845 if (SetMergedModule && i == BaseArg) {
846 // Transfer ownership to the code generator.
Peter Collingbourne9c8909d2015-08-24 22:22:53 +0000847 CodeGen.setModule(std::move(Module));
Yunzhong Gao46261a72015-09-11 20:01:53 +0000848 } else if (!CodeGen.addModule(Module.get())) {
849 // Print a message here so that we know addModule() did not abort.
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000850 error("error adding file '" + InputFilenames[i] + "'");
Yunzhong Gao46261a72015-09-11 20:01:53 +0000851 }
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000852 }
853
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000854 // Add all the exported symbols to the table of symbols to preserve.
855 for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000856 CodeGen.addMustPreserveSymbol(ExportedSymbols[i]);
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000857
Rafael Espindolacda29112013-10-03 18:29:09 +0000858 // Add all the dso symbols to the table of symbols to expose.
Rafael Espindola282a4702013-10-31 20:51:58 +0000859 for (unsigned i = 0; i < KeptDSOSyms.size(); ++i)
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000860 CodeGen.addMustPreserveSymbol(KeptDSOSyms[i]);
Rafael Espindolacda29112013-10-03 18:29:09 +0000861
Akira Hatanaka23b5f672015-01-30 01:14:28 +0000862 // Set cpu and attrs strings for the default target/subtarget.
863 CodeGen.setCpu(MCPU.c_str());
864
Peter Collingbourne070843d2015-03-19 22:01:00 +0000865 CodeGen.setOptLevel(OptLevel - '0');
866
Tom Roederfd1bc602014-04-25 21:46:51 +0000867 std::string attrs;
868 for (unsigned i = 0; i < MAttrs.size(); ++i) {
869 if (i > 0)
870 attrs.append(",");
871 attrs.append(MAttrs[i]);
872 }
873
874 if (!attrs.empty())
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000875 CodeGen.setAttr(attrs);
Tom Roederfd1bc602014-04-25 21:46:51 +0000876
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000877 if (FileType.getNumOccurrences())
878 CodeGen.setFileType(FileType);
879
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000880 if (!OutputFilename.empty()) {
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000881 if (!CodeGen.optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000882 DisableLTOVectorization)) {
883 // Diagnostic messages should have been printed by the handler.
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000884 error("error optimizing the code");
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000885 }
886
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000887 if (SaveModuleFile) {
888 std::string ModuleFilename = OutputFilename;
889 ModuleFilename += ".merged.bc";
890 std::string ErrMsg;
891
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000892 if (!CodeGen.writeMergedModules(ModuleFilename))
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000893 error("writing merged module failed.");
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000894 }
895
Peter Collingbournec269ed52015-08-27 23:37:36 +0000896 std::list<tool_output_file> OSs;
897 std::vector<raw_pwrite_stream *> OSPtrs;
898 for (unsigned I = 0; I != Parallelism; ++I) {
899 std::string PartFilename = OutputFilename;
900 if (Parallelism != 1)
901 PartFilename += "." + utostr(I);
902 std::error_code EC;
903 OSs.emplace_back(PartFilename, EC, sys::fs::F_None);
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000904 if (EC)
905 error("error opening the file '" + PartFilename + "': " + EC.message());
Peter Collingbournec269ed52015-08-27 23:37:36 +0000906 OSPtrs.push_back(&OSs.back().os());
907 }
908
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000909 if (!CodeGen.compileOptimized(OSPtrs))
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000910 // Diagnostic messages should have been printed by the handler.
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000911 error("error compiling the code");
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000912
Peter Collingbournec269ed52015-08-27 23:37:36 +0000913 for (tool_output_file &OS : OSs)
914 OS.keep();
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000915 } else {
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000916 if (Parallelism != 1)
917 error("-j must be specified together with -o");
Peter Collingbournec269ed52015-08-27 23:37:36 +0000918
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000919 if (SaveModuleFile)
920 error(": -save-merged-module must be specified with -o");
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000921
Craig Toppere6cb63e2014-04-25 04:24:47 +0000922 const char *OutputName = nullptr;
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000923 if (!CodeGen.compile_to_file(&OutputName, DisableVerify, DisableInline,
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000924 DisableGVNLoadPRE, DisableLTOVectorization))
925 error("error compiling the code");
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000926 // Diagnostic messages should have been printed by the handler.
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000927
928 outs() << "Wrote native object file '" << OutputName << "'\n";
929 }
930
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000931 return 0;
932}