blob: 84dce23aee2cf8d8bf988f11f7af3b764ecd815b [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 Collingbourne4ccf0f12013-09-24 23:52:22 +000022#include "llvm/LTO/LTOCodeGenerator.h"
Teresa Johnsoncec0cae2016-03-14 21:18:10 +000023#include "llvm/LTO/LTOModule.h"
Teresa Johnson26ab5772016-03-15 00:04:37 +000024#include "llvm/LTO/ThinLTOCodeGenerator.h"
25#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
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +000045static cl::opt<bool> DisableVerify(
46 "disable-verify", cl::init(false),
47 cl::desc("Do not run the verifier during the optimization pipeline"));
48
Davide Italianob10e8932016-04-13 21:41:35 +000049static cl::opt<bool> DisableInline("disable-inlining", cl::init(false),
50 cl::desc("Do not run the inliner pass"));
Rafael Espindola0b385c72013-09-30 16:39:19 +000051
52static cl::opt<bool>
Davide Italianob10e8932016-04-13 21:41:35 +000053 DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
54 cl::desc("Do not run the GVN load PRE pass"));
Rafael Espindola0b385c72013-09-30 16:39:19 +000055
Davide Italianob10e8932016-04-13 21:41:35 +000056static cl::opt<bool> DisableLTOVectorization(
57 "disable-lto-vectorization", cl::init(false),
58 cl::desc("Do not run loop or slp vectorization during LTO"));
Arnold Schwaighofereb1a38f2014-10-26 21:50:58 +000059
Davide Italianob10e8932016-04-13 21:41:35 +000060static cl::opt<bool> UseDiagnosticHandler(
61 "use-diagnostic-handler", cl::init(false),
62 cl::desc("Use a diagnostic handler to test the handler interface"));
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +000063
Teresa Johnsonf72278f2015-11-02 18:02:11 +000064static cl::opt<bool>
65 ThinLTO("thinlto", cl::init(false),
66 cl::desc("Only write combined global index for ThinLTO backends"));
Teresa Johnson91a88bb2015-10-19 14:30:44 +000067
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000068enum ThinLTOModes {
69 THINLINK,
Teresa Johnson84174c32016-05-10 13:48:23 +000070 THINDISTRIBUTE,
Teresa Johnson8570fe42016-05-10 15:54:09 +000071 THINEMITIMPORTS,
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000072 THINPROMOTE,
73 THINIMPORT,
Mehdi Amini059464f2016-04-24 03:18:01 +000074 THININTERNALIZE,
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000075 THINOPT,
76 THINCODEGEN,
77 THINALL
78};
79
80cl::opt<ThinLTOModes> ThinLTOMode(
81 "thinlto-action", cl::desc("Perform a single ThinLTO stage:"),
82 cl::values(
83 clEnumValN(
84 THINLINK, "thinlink",
85 "ThinLink: produces the index by linking only the summaries."),
Teresa Johnson84174c32016-05-10 13:48:23 +000086 clEnumValN(THINDISTRIBUTE, "distributedindexes",
87 "Produces individual indexes for distributed backends."),
Teresa Johnson8570fe42016-05-10 15:54:09 +000088 clEnumValN(THINEMITIMPORTS, "emitimports",
89 "Emit imports files for distributed backends."),
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000090 clEnumValN(THINPROMOTE, "promote",
91 "Perform pre-import promotion (requires -thinlto-index)."),
92 clEnumValN(THINIMPORT, "import", "Perform both promotion and "
93 "cross-module importing (requires "
94 "-thinlto-index)."),
Mehdi Amini059464f2016-04-24 03:18:01 +000095 clEnumValN(THININTERNALIZE, "internalize",
96 "Perform internalization driven by -exported-symbol "
97 "(requires -thinlto-index)."),
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000098 clEnumValN(THINOPT, "optimize", "Perform ThinLTO optimizations."),
99 clEnumValN(THINCODEGEN, "codegen", "CodeGen (expected to match llc)"),
100 clEnumValN(THINALL, "run", "Perform ThinLTO end-to-end"),
101 clEnumValEnd));
102
103static cl::opt<std::string>
104 ThinLTOIndex("thinlto-index",
105 cl::desc("Provide the index produced by a ThinLink, required "
106 "to perform the promotion and/or importing."));
107
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000108static cl::opt<std::string> ThinLTOPrefixReplace(
109 "thinlto-prefix-replace",
110 cl::desc("Control where files for distributed backends are "
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000111 "created. Expects 'oldprefix;newprefix' and if path "
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000112 "prefix of output file is oldprefix it will be "
113 "replaced with newprefix."));
114
Mehdi Amini03abce92016-05-05 16:33:51 +0000115static cl::opt<std::string> ThinLTOModuleId(
116 "thinlto-module-id",
117 cl::desc("For the module ID for the file to process, useful to "
118 "match what is in the index."));
119
Mehdi Aminiab4a8b62016-05-14 05:16:41 +0000120static cl::opt<std::string>
121 ThinLTOCacheDir("thinlto-cache-dir", cl::desc("Enable ThinLTO caching."));
122
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000123static cl::opt<bool>
Davide Italianob10e8932016-04-13 21:41:35 +0000124 SaveModuleFile("save-merged-module", cl::init(false),
125 cl::desc("Write merged LTO module to file before CodeGen"));
126
127static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
128 cl::desc("<input bitcode files>"));
129
130static cl::opt<std::string> OutputFilename("o", cl::init(""),
131 cl::desc("Override output filename"),
132 cl::value_desc("filename"));
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000133
Mehdi Amini059464f2016-04-24 03:18:01 +0000134static cl::list<std::string> ExportedSymbols(
135 "exported-symbol",
136 cl::desc("List of symbols to export from the resulting object file"),
137 cl::ZeroOrMore);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000138
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000139static cl::list<std::string>
Davide Italianob10e8932016-04-13 21:41:35 +0000140 DSOSymbols("dso-symbol",
141 cl::desc("Symbol to put in the symtab in the resulting dso"),
142 cl::ZeroOrMore);
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000143
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000144static cl::opt<bool> ListSymbolsOnly(
145 "list-symbols-only", cl::init(false),
146 cl::desc("Instead of running LTO, list the symbols in each IR file"));
147
Manman Ren6487ce92015-02-24 00:45:56 +0000148static cl::opt<bool> SetMergedModule(
149 "set-merged-module", cl::init(false),
150 cl::desc("Use the first input module as the merged module"));
151
Peter Collingbournec269ed52015-08-27 23:37:36 +0000152static cl::opt<unsigned> Parallelism("j", cl::Prefix, cl::init(1),
153 cl::desc("Number of backend threads"));
154
Tobias Edler von Koch3f4f6f3e2016-01-18 23:35:24 +0000155static cl::opt<bool> RestoreGlobalsLinkage(
156 "restore-linkage", cl::init(false),
157 cl::desc("Restore original linkage of globals prior to CodeGen"));
158
Mehdi Aminie75aa6f2016-07-11 23:10:18 +0000159static cl::opt<bool> CheckHasObjC(
160 "check-for-objc", cl::init(false),
161 cl::desc("Only check if the module has objective-C defined in it"));
162
Rafael Espindola282a4702013-10-31 20:51:58 +0000163namespace {
164struct ModuleInfo {
165 std::vector<bool> CanBeHidden;
166};
167}
168
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000169static void handleDiagnostics(lto_codegen_diagnostic_severity_t Severity,
170 const char *Msg, void *) {
Yunzhong Gaoef436f02015-11-10 18:52:48 +0000171 errs() << "llvm-lto: ";
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +0000172 switch (Severity) {
173 case LTO_DS_NOTE:
174 errs() << "note: ";
175 break;
176 case LTO_DS_REMARK:
177 errs() << "remark: ";
178 break;
179 case LTO_DS_ERROR:
180 errs() << "error: ";
181 break;
182 case LTO_DS_WARNING:
183 errs() << "warning: ";
184 break;
185 }
186 errs() << Msg << "\n";
187}
188
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000189static std::string CurrentActivity;
Mehdi Amini354f5202015-11-19 05:52:29 +0000190static void diagnosticHandler(const DiagnosticInfo &DI) {
191 raw_ostream &OS = errs();
192 OS << "llvm-lto: ";
193 switch (DI.getSeverity()) {
194 case DS_Error:
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000195 OS << "error";
Mehdi Amini354f5202015-11-19 05:52:29 +0000196 break;
197 case DS_Warning:
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000198 OS << "warning";
Mehdi Amini354f5202015-11-19 05:52:29 +0000199 break;
200 case DS_Remark:
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000201 OS << "remark";
Mehdi Amini354f5202015-11-19 05:52:29 +0000202 break;
203 case DS_Note:
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000204 OS << "note";
Mehdi Amini354f5202015-11-19 05:52:29 +0000205 break;
206 }
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000207 if (!CurrentActivity.empty())
208 OS << ' ' << CurrentActivity;
209 OS << ": ";
Mehdi Amini354f5202015-11-19 05:52:29 +0000210
211 DiagnosticPrinterRawOStream DP(OS);
212 DI.print(DP);
213 OS << '\n';
214
215 if (DI.getSeverity() == DS_Error)
216 exit(1);
217}
218
Petr Pavlu7ad9ec92016-03-01 13:13:49 +0000219static void diagnosticHandlerWithContext(const DiagnosticInfo &DI,
220 void *Context) {
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000221 diagnosticHandler(DI);
222}
223
Rafael Espindola5e128db2015-12-04 00:45:57 +0000224static void error(const Twine &Msg) {
225 errs() << "llvm-lto: " << Msg << '\n';
226 exit(1);
227}
228
229static void error(std::error_code EC, const Twine &Prefix) {
230 if (EC)
231 error(Prefix + ": " + EC.message());
232}
233
234template <typename T>
235static void error(const ErrorOr<T> &V, const Twine &Prefix) {
236 error(V.getError(), Prefix);
237}
238
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000239static void maybeVerifyModule(const Module &Mod) {
240 if (!DisableVerify && verifyModule(Mod))
241 error("Broken Module");
242}
243
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000244static std::unique_ptr<LTOModule>
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000245getLocalLTOModule(StringRef Path, std::unique_ptr<MemoryBuffer> &Buffer,
Rafael Espindola5e128db2015-12-04 00:45:57 +0000246 const TargetOptions &Options) {
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000247 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
248 MemoryBuffer::getFile(Path);
Rafael Espindola5e128db2015-12-04 00:45:57 +0000249 error(BufferOrErr, "error loading file '" + Path + "'");
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000250 Buffer = std::move(BufferOrErr.get());
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000251 CurrentActivity = ("loading file '" + Path + "'").str();
Petr Pavlu7ad9ec92016-03-01 13:13:49 +0000252 std::unique_ptr<LLVMContext> Context = llvm::make_unique<LLVMContext>();
253 Context->setDiagnosticHandler(diagnosticHandlerWithContext, nullptr, true);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000254 ErrorOr<std::unique_ptr<LTOModule>> Ret = LTOModule::createInLocalContext(
Petr Pavlu7ad9ec92016-03-01 13:13:49 +0000255 std::move(Context), Buffer->getBufferStart(), Buffer->getBufferSize(),
256 Options, Path);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000257 CurrentActivity = "";
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000258 maybeVerifyModule((*Ret)->getModule());
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000259 return std::move(*Ret);
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000260}
261
262/// \brief List symbols in each IR file.
263///
264/// The main point here is to provide lit-testable coverage for the LTOModule
265/// functionality that's exposed by the C API to list symbols. Moreover, this
266/// provides testing coverage for modules that have been created in their own
267/// contexts.
Rafael Espindola5e128db2015-12-04 00:45:57 +0000268static void listSymbols(const TargetOptions &Options) {
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000269 for (auto &Filename : InputFilenames) {
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000270 std::unique_ptr<MemoryBuffer> Buffer;
271 std::unique_ptr<LTOModule> Module =
Rafael Espindola5e128db2015-12-04 00:45:57 +0000272 getLocalLTOModule(Filename, Buffer, Options);
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000273
274 // List the symbols.
275 outs() << Filename << ":\n";
276 for (int I = 0, E = Module->getSymbolCount(); I != E; ++I)
277 outs() << Module->getSymbolName(I) << "\n";
278 }
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000279}
280
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000281/// Create a combined index file from the input IR files and write it.
282///
283/// This is meant to enable testing of ThinLTO combined index generation,
284/// currently available via the gold plugin via -thinlto.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000285static void createCombinedModuleSummaryIndex() {
286 ModuleSummaryIndex CombinedIndex;
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000287 uint64_t NextModuleId = 0;
288 for (auto &Filename : InputFilenames) {
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000289 CurrentActivity = "loading file '" + Filename + "'";
Teresa Johnson26ab5772016-03-15 00:04:37 +0000290 ErrorOr<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
291 llvm::getModuleSummaryIndexForFile(Filename, diagnosticHandler);
Mehdi Amini155da5b2016-03-19 00:17:32 +0000292 error(IndexOrErr, "error " + CurrentActivity);
Teresa Johnson26ab5772016-03-15 00:04:37 +0000293 std::unique_ptr<ModuleSummaryIndex> Index = std::move(IndexOrErr.get());
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000294 CurrentActivity = "";
Teresa Johnson26ab5772016-03-15 00:04:37 +0000295 // Skip files without a module summary.
Teresa Johnson6290dbc2015-11-21 21:55:48 +0000296 if (!Index)
297 continue;
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000298 CombinedIndex.mergeFrom(std::move(Index), ++NextModuleId);
299 }
300 std::error_code EC;
301 assert(!OutputFilename.empty());
302 raw_fd_ostream OS(OutputFilename + ".thinlto.bc", EC,
303 sys::fs::OpenFlags::F_None);
Rafael Espindola5e128db2015-12-04 00:45:57 +0000304 error(EC, "error opening the file '" + OutputFilename + ".thinlto.bc'");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000305 WriteIndexToFile(CombinedIndex, OS);
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000306 OS.close();
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000307}
308
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000309/// Parse the thinlto_prefix_replace option into the \p OldPrefix and
310/// \p NewPrefix strings, if it was specified.
311static void getThinLTOOldAndNewPrefix(std::string &OldPrefix,
312 std::string &NewPrefix) {
313 assert(ThinLTOPrefixReplace.empty() ||
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000314 ThinLTOPrefixReplace.find(";") != StringRef::npos);
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000315 StringRef PrefixReplace = ThinLTOPrefixReplace;
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000316 std::pair<StringRef, StringRef> Split = PrefixReplace.split(";");
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000317 OldPrefix = Split.first.str();
318 NewPrefix = Split.second.str();
319}
320
321/// Given the original \p Path to an output file, replace any path
322/// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
323/// resulting directory if it does not yet exist.
324static std::string getThinLTOOutputFile(const std::string &Path,
325 const std::string &OldPrefix,
326 const std::string &NewPrefix) {
327 if (OldPrefix.empty() && NewPrefix.empty())
328 return Path;
329 SmallString<128> NewPath(Path);
330 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
331 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
332 if (!ParentPath.empty()) {
333 // Make sure the new directory exists, creating it if necessary.
334 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
335 error(EC, "error creating the directory '" + ParentPath + "'");
336 }
337 return NewPath.str();
338}
339
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000340namespace thinlto {
341
342std::vector<std::unique_ptr<MemoryBuffer>>
Teresa Johnson26ab5772016-03-15 00:04:37 +0000343loadAllFilesForIndex(const ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000344 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
345
Mehdi Amini385cf282016-03-26 03:35:38 +0000346 for (auto &ModPath : Index.modulePaths()) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000347 const auto &Filename = ModPath.first();
348 auto CurrentActivity = "loading file '" + Filename + "'";
349 auto InputOrErr = MemoryBuffer::getFile(Filename);
350 error(InputOrErr, "error " + CurrentActivity);
351 InputBuffers.push_back(std::move(*InputOrErr));
352 }
353 return InputBuffers;
354}
355
Teresa Johnson26ab5772016-03-15 00:04:37 +0000356std::unique_ptr<ModuleSummaryIndex> loadCombinedIndex() {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000357 if (ThinLTOIndex.empty())
358 report_fatal_error("Missing -thinlto-index for ThinLTO promotion stage");
359 auto CurrentActivity = "loading file '" + ThinLTOIndex + "'";
Teresa Johnson26ab5772016-03-15 00:04:37 +0000360 ErrorOr<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr =
361 llvm::getModuleSummaryIndexForFile(ThinLTOIndex, diagnosticHandler);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000362 error(IndexOrErr, "error " + CurrentActivity);
363 return std::move(IndexOrErr.get());
364}
365
366static std::unique_ptr<Module> loadModule(StringRef Filename,
367 LLVMContext &Ctx) {
368 SMDiagnostic Err;
369 std::unique_ptr<Module> M(parseIRFile(Filename, Err, Ctx));
370 if (!M) {
371 Err.print("llvm-lto", errs());
372 report_fatal_error("Can't load module for file " + Filename);
373 }
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000374 maybeVerifyModule(*M);
Mehdi Amini03abce92016-05-05 16:33:51 +0000375
376 if (ThinLTOModuleId.getNumOccurrences()) {
377 if (InputFilenames.size() != 1)
378 report_fatal_error("Can't override the module id for multiple files");
379 M->setModuleIdentifier(ThinLTOModuleId);
380 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000381 return M;
382}
383
384static void writeModuleToFile(Module &TheModule, StringRef Filename) {
385 std::error_code EC;
386 raw_fd_ostream OS(Filename, EC, sys::fs::OpenFlags::F_None);
387 error(EC, "error opening the file '" + Filename + "'");
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000388 maybeVerifyModule(TheModule);
Teresa Johnson3c35e092016-04-04 21:19:31 +0000389 WriteBitcodeToFile(&TheModule, OS, /* ShouldPreserveUseListOrder */ true);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000390}
391
392class ThinLTOProcessing {
393public:
394 ThinLTOCodeGenerator ThinGenerator;
395
396 ThinLTOProcessing(const TargetOptions &Options) {
Rafael Espindola8c34dd82016-05-18 22:04:49 +0000397 ThinGenerator.setCodePICModel(getRelocModel());
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000398 ThinGenerator.setTargetOptions(Options);
Mehdi Aminiab4a8b62016-05-14 05:16:41 +0000399 ThinGenerator.setCacheDir(ThinLTOCacheDir);
Mehdi Amini059464f2016-04-24 03:18:01 +0000400
401 // Add all the exported symbols to the table of symbols to preserve.
402 for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
403 ThinGenerator.preserveSymbol(ExportedSymbols[i]);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000404 }
405
406 void run() {
407 switch (ThinLTOMode) {
408 case THINLINK:
409 return thinLink();
Teresa Johnson84174c32016-05-10 13:48:23 +0000410 case THINDISTRIBUTE:
411 return distributedIndexes();
Teresa Johnson8570fe42016-05-10 15:54:09 +0000412 case THINEMITIMPORTS:
413 return emitImports();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000414 case THINPROMOTE:
415 return promote();
416 case THINIMPORT:
417 return import();
Mehdi Amini059464f2016-04-24 03:18:01 +0000418 case THININTERNALIZE:
419 return internalize();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000420 case THINOPT:
421 return optimize();
422 case THINCODEGEN:
423 return codegen();
424 case THINALL:
425 return runAll();
426 }
427 }
428
429private:
430 /// Load the input files, create the combined index, and write it out.
431 void thinLink() {
432 // Perform "ThinLink": just produce the index
433 if (OutputFilename.empty())
434 report_fatal_error(
435 "OutputFilename is necessary to store the combined index.\n");
436
437 LLVMContext Ctx;
438 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
439 for (unsigned i = 0; i < InputFilenames.size(); ++i) {
440 auto &Filename = InputFilenames[i];
441 StringRef CurrentActivity = "loading file '" + Filename + "'";
442 auto InputOrErr = MemoryBuffer::getFile(Filename);
443 error(InputOrErr, "error " + CurrentActivity);
444 InputBuffers.push_back(std::move(*InputOrErr));
445 ThinGenerator.addModule(Filename, InputBuffers.back()->getBuffer());
446 }
447
448 auto CombinedIndex = ThinGenerator.linkCombinedIndex();
449 std::error_code EC;
450 raw_fd_ostream OS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
451 error(EC, "error opening the file '" + OutputFilename + "'");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000452 WriteIndexToFile(*CombinedIndex, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000453 return;
454 }
455
Teresa Johnson84174c32016-05-10 13:48:23 +0000456 /// Load the combined index from disk, then compute and generate
457 /// individual index files suitable for ThinLTO distributed backend builds
458 /// on the files mentioned on the command line (these must match the index
459 /// content).
460 void distributedIndexes() {
461 if (InputFilenames.size() != 1 && !OutputFilename.empty())
462 report_fatal_error("Can't handle a single output filename and multiple "
463 "input files, do not provide an output filename and "
464 "the output files will be suffixed from the input "
465 "ones.");
466
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000467 std::string OldPrefix, NewPrefix;
468 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
469
Teresa Johnson84174c32016-05-10 13:48:23 +0000470 auto Index = loadCombinedIndex();
471 for (auto &Filename : InputFilenames) {
472 // Build a map of module to the GUIDs and summary objects that should
473 // be written to its index.
474 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
475 ThinLTOCodeGenerator::gatherImportedSummariesForModule(
476 Filename, *Index, ModuleToSummariesForIndex);
477
478 std::string OutputName = OutputFilename;
479 if (OutputName.empty()) {
480 OutputName = Filename + ".thinlto.bc";
481 }
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000482 OutputName = getThinLTOOutputFile(OutputName, OldPrefix, NewPrefix);
Teresa Johnson84174c32016-05-10 13:48:23 +0000483 std::error_code EC;
484 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::F_None);
485 error(EC, "error opening the file '" + OutputName + "'");
486 WriteIndexToFile(*Index, OS, &ModuleToSummariesForIndex);
487 }
488 }
489
Teresa Johnson8570fe42016-05-10 15:54:09 +0000490 /// Load the combined index from disk, compute the imports, and emit
491 /// the import file lists for each module to disk.
492 void emitImports() {
493 if (InputFilenames.size() != 1 && !OutputFilename.empty())
494 report_fatal_error("Can't handle a single output filename and multiple "
495 "input files, do not provide an output filename and "
496 "the output files will be suffixed from the input "
497 "ones.");
498
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000499 std::string OldPrefix, NewPrefix;
500 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
501
Teresa Johnson8570fe42016-05-10 15:54:09 +0000502 auto Index = loadCombinedIndex();
503 for (auto &Filename : InputFilenames) {
504 std::string OutputName = OutputFilename;
505 if (OutputName.empty()) {
506 OutputName = Filename + ".imports";
507 }
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000508 OutputName = getThinLTOOutputFile(OutputName, OldPrefix, NewPrefix);
Teresa Johnson8570fe42016-05-10 15:54:09 +0000509 ThinLTOCodeGenerator::emitImports(Filename, OutputName, *Index);
510 }
511 }
512
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000513 /// Load the combined index from disk, then load every file referenced by
514 /// the index and add them to the generator, finally perform the promotion
515 /// on the files mentioned on the command line (these must match the index
516 /// content).
517 void promote() {
518 if (InputFilenames.size() != 1 && !OutputFilename.empty())
519 report_fatal_error("Can't handle a single output filename and multiple "
520 "input files, do not provide an output filename and "
521 "the output files will be suffixed from the input "
522 "ones.");
523
524 auto Index = loadCombinedIndex();
525 for (auto &Filename : InputFilenames) {
526 LLVMContext Ctx;
527 auto TheModule = loadModule(Filename, Ctx);
528
529 ThinGenerator.promote(*TheModule, *Index);
530
531 std::string OutputName = OutputFilename;
532 if (OutputName.empty()) {
533 OutputName = Filename + ".thinlto.promoted.bc";
534 }
535 writeModuleToFile(*TheModule, OutputName);
536 }
537 }
538
539 /// Load the combined index from disk, then load every file referenced by
540 /// the index and add them to the generator, then performs the promotion and
541 /// cross module importing on the files mentioned on the command line
542 /// (these must match the index content).
543 void import() {
544 if (InputFilenames.size() != 1 && !OutputFilename.empty())
545 report_fatal_error("Can't handle a single output filename and multiple "
546 "input files, do not provide an output filename and "
547 "the output files will be suffixed from the input "
548 "ones.");
549
550 auto Index = loadCombinedIndex();
551 auto InputBuffers = loadAllFilesForIndex(*Index);
552 for (auto &MemBuffer : InputBuffers)
553 ThinGenerator.addModule(MemBuffer->getBufferIdentifier(),
554 MemBuffer->getBuffer());
555
556 for (auto &Filename : InputFilenames) {
557 LLVMContext Ctx;
558 auto TheModule = loadModule(Filename, Ctx);
559
560 ThinGenerator.crossModuleImport(*TheModule, *Index);
561
562 std::string OutputName = OutputFilename;
563 if (OutputName.empty()) {
564 OutputName = Filename + ".thinlto.imported.bc";
565 }
566 writeModuleToFile(*TheModule, OutputName);
567 }
568 }
569
Mehdi Amini059464f2016-04-24 03:18:01 +0000570 void internalize() {
571 if (InputFilenames.size() != 1 && !OutputFilename.empty())
572 report_fatal_error("Can't handle a single output filename and multiple "
573 "input files, do not provide an output filename and "
574 "the output files will be suffixed from the input "
575 "ones.");
576
577 if (ExportedSymbols.empty())
578 errs() << "Warning: -internalize will not perform without "
579 "-exported-symbol\n";
580
581 auto Index = loadCombinedIndex();
582 auto InputBuffers = loadAllFilesForIndex(*Index);
583 for (auto &MemBuffer : InputBuffers)
584 ThinGenerator.addModule(MemBuffer->getBufferIdentifier(),
585 MemBuffer->getBuffer());
586
587 for (auto &Filename : InputFilenames) {
588 LLVMContext Ctx;
589 auto TheModule = loadModule(Filename, Ctx);
590
591 ThinGenerator.internalize(*TheModule, *Index);
592
593 std::string OutputName = OutputFilename;
594 if (OutputName.empty()) {
595 OutputName = Filename + ".thinlto.internalized.bc";
596 }
597 writeModuleToFile(*TheModule, OutputName);
598 }
599 }
600
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000601 void optimize() {
602 if (InputFilenames.size() != 1 && !OutputFilename.empty())
603 report_fatal_error("Can't handle a single output filename and multiple "
604 "input files, do not provide an output filename and "
605 "the output files will be suffixed from the input "
606 "ones.");
607 if (!ThinLTOIndex.empty())
608 errs() << "Warning: -thinlto-index ignored for optimize stage";
609
610 for (auto &Filename : InputFilenames) {
611 LLVMContext Ctx;
612 auto TheModule = loadModule(Filename, Ctx);
613
614 ThinGenerator.optimize(*TheModule);
615
616 std::string OutputName = OutputFilename;
617 if (OutputName.empty()) {
618 OutputName = Filename + ".thinlto.imported.bc";
619 }
620 writeModuleToFile(*TheModule, OutputName);
621 }
622 }
623
624 void codegen() {
625 if (InputFilenames.size() != 1 && !OutputFilename.empty())
626 report_fatal_error("Can't handle a single output filename and multiple "
627 "input files, do not provide an output filename and "
628 "the output files will be suffixed from the input "
629 "ones.");
630 if (!ThinLTOIndex.empty())
631 errs() << "Warning: -thinlto-index ignored for codegen stage";
632
633 for (auto &Filename : InputFilenames) {
634 LLVMContext Ctx;
635 auto TheModule = loadModule(Filename, Ctx);
636
637 auto Buffer = ThinGenerator.codegen(*TheModule);
638 std::string OutputName = OutputFilename;
639 if (OutputName.empty()) {
640 OutputName = Filename + ".thinlto.o";
641 }
642 if (OutputName == "-") {
643 outs() << Buffer->getBuffer();
644 return;
645 }
646
647 std::error_code EC;
648 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::F_None);
649 error(EC, "error opening the file '" + OutputName + "'");
650 OS << Buffer->getBuffer();
651 }
652 }
653
654 /// Full ThinLTO process
655 void runAll() {
656 if (!OutputFilename.empty())
657 report_fatal_error("Do not provide an output filename for ThinLTO "
658 " processing, the output files will be suffixed from "
659 "the input ones.");
660
661 if (!ThinLTOIndex.empty())
662 errs() << "Warning: -thinlto-index ignored for full ThinLTO process";
663
664 LLVMContext Ctx;
665 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
666 for (unsigned i = 0; i < InputFilenames.size(); ++i) {
667 auto &Filename = InputFilenames[i];
668 StringRef CurrentActivity = "loading file '" + Filename + "'";
669 auto InputOrErr = MemoryBuffer::getFile(Filename);
670 error(InputOrErr, "error " + CurrentActivity);
671 InputBuffers.push_back(std::move(*InputOrErr));
672 ThinGenerator.addModule(Filename, InputBuffers.back()->getBuffer());
673 }
674
675 ThinGenerator.run();
676
677 auto &Binaries = ThinGenerator.getProducedBinaries();
678 if (Binaries.size() != InputFilenames.size())
679 report_fatal_error("Number of output objects does not match the number "
680 "of inputs");
681
682 for (unsigned BufID = 0; BufID < Binaries.size(); ++BufID) {
683 auto OutputName = InputFilenames[BufID] + ".thinlto.o";
684 std::error_code EC;
685 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::F_None);
686 error(EC, "error opening the file '" + OutputName + "'");
687 OS << Binaries[BufID]->getBuffer();
688 }
689 }
690
691 /// Load the combined index from disk, then load every file referenced by
692};
693
694} // namespace thinlto
695
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000696int main(int argc, char **argv) {
697 // Print a stack trace if we signal out.
Richard Smith2ad6d482016-06-09 00:53:21 +0000698 sys::PrintStackTraceOnErrorSignal(argv[0]);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000699 PrettyStackTraceProgram X(argc, argv);
700
701 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
702 cl::ParseCommandLineOptions(argc, argv, "llvm LTO linker\n");
703
Rafael Espindola5e128db2015-12-04 00:45:57 +0000704 if (OptLevel < '0' || OptLevel > '3')
705 error("optimization level must be between 0 and 3");
Peter Collingbourne070843d2015-03-19 22:01:00 +0000706
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000707 // Initialize the configured targets.
708 InitializeAllTargets();
709 InitializeAllTargetMCs();
710 InitializeAllAsmPrinters();
711 InitializeAllAsmParsers();
712
Rafael Espindola0b385c72013-09-30 16:39:19 +0000713 // set up the TargetOptions for the machine
Eli Benderskyf0f21002014-02-19 17:09:35 +0000714 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
Rafael Espindola0b385c72013-09-30 16:39:19 +0000715
Rafael Espindola5e128db2015-12-04 00:45:57 +0000716 if (ListSymbolsOnly) {
717 listSymbols(Options);
718 return 0;
719 }
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000720
Mehdi Aminie75aa6f2016-07-11 23:10:18 +0000721 if (CheckHasObjC) {
722 for (auto &Filename : InputFilenames) {
723 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
724 MemoryBuffer::getFile(Filename);
725 error(BufferOrErr, "error loading file '" + Filename + "'");
726 auto Buffer = std::move(BufferOrErr.get());
727 LLVMContext Ctx;
728 if (llvm::isBitcodeContainingObjCCategory(*Buffer, Ctx))
729 outs() << "Bitcode " << Filename << " contains ObjC\n";
730 else
731 outs() << "Bitcode " << Filename << " does not contain ObjC\n";
732 }
733 return 0;
734 }
735
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000736 if (ThinLTOMode.getNumOccurrences()) {
737 if (ThinLTOMode.getNumOccurrences() > 1)
738 report_fatal_error("You can't specify more than one -thinlto-action");
739 thinlto::ThinLTOProcessing ThinLTOProcessor(Options);
740 ThinLTOProcessor.run();
741 return 0;
742 }
743
Rafael Espindola5e128db2015-12-04 00:45:57 +0000744 if (ThinLTO) {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000745 createCombinedModuleSummaryIndex();
Rafael Espindola5e128db2015-12-04 00:45:57 +0000746 return 0;
747 }
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000748
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000749 unsigned BaseArg = 0;
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000750
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000751 LLVMContext Context;
Petr Pavlu7ad9ec92016-03-01 13:13:49 +0000752 Context.setDiagnosticHandler(diagnosticHandlerWithContext, nullptr, true);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000753
754 LTOCodeGenerator CodeGen(Context);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000755
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +0000756 if (UseDiagnosticHandler)
757 CodeGen.setDiagnosticHandler(handleDiagnostics, nullptr);
758
Rafael Espindola8c34dd82016-05-18 22:04:49 +0000759 CodeGen.setCodePICModel(getRelocModel());
James Molloy951e5292014-04-14 13:54:16 +0000760
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000761 CodeGen.setDebugInfo(LTO_DEBUG_MODEL_DWARF);
Rafael Espindola0b385c72013-09-30 16:39:19 +0000762 CodeGen.setTargetOptions(Options);
Tobias Edler von Koch3f4f6f3e2016-01-18 23:35:24 +0000763 CodeGen.setShouldRestoreGlobalsLinkage(RestoreGlobalsLinkage);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000764
Rafael Espindola282a4702013-10-31 20:51:58 +0000765 llvm::StringSet<llvm::MallocAllocator> DSOSymbolsSet;
766 for (unsigned i = 0; i < DSOSymbols.size(); ++i)
767 DSOSymbolsSet.insert(DSOSymbols[i]);
768
769 std::vector<std::string> KeptDSOSyms;
770
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000771 for (unsigned i = BaseArg; i < InputFilenames.size(); ++i) {
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000772 CurrentActivity = "loading file '" + InputFilenames[i] + "'";
773 ErrorOr<std::unique_ptr<LTOModule>> ModuleOrErr =
774 LTOModule::createFromFile(Context, InputFilenames[i].c_str(), Options);
775 std::unique_ptr<LTOModule> &Module = *ModuleOrErr;
776 CurrentActivity = "";
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000777
Peter Collingbourne552174392015-08-21 19:09:42 +0000778 unsigned NumSyms = Module->getSymbolCount();
779 for (unsigned I = 0; I < NumSyms; ++I) {
780 StringRef Name = Module->getSymbolName(I);
781 if (!DSOSymbolsSet.count(Name))
782 continue;
783 lto_symbol_attributes Attrs = Module->getSymbolAttributes(I);
784 unsigned Scope = Attrs & LTO_SYMBOL_SCOPE_MASK;
785 if (Scope != LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN)
786 KeptDSOSyms.push_back(Name);
787 }
Manman Ren6487ce92015-02-24 00:45:56 +0000788
789 // We use the first input module as the destination module when
790 // SetMergedModule is true.
791 if (SetMergedModule && i == BaseArg) {
792 // Transfer ownership to the code generator.
Peter Collingbourne9c8909d2015-08-24 22:22:53 +0000793 CodeGen.setModule(std::move(Module));
Yunzhong Gao46261a72015-09-11 20:01:53 +0000794 } else if (!CodeGen.addModule(Module.get())) {
795 // Print a message here so that we know addModule() did not abort.
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000796 error("error adding file '" + InputFilenames[i] + "'");
Yunzhong Gao46261a72015-09-11 20:01:53 +0000797 }
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000798 }
799
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000800 // Add all the exported symbols to the table of symbols to preserve.
801 for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
802 CodeGen.addMustPreserveSymbol(ExportedSymbols[i].c_str());
803
Rafael Espindolacda29112013-10-03 18:29:09 +0000804 // Add all the dso symbols to the table of symbols to expose.
Rafael Espindola282a4702013-10-31 20:51:58 +0000805 for (unsigned i = 0; i < KeptDSOSyms.size(); ++i)
806 CodeGen.addMustPreserveSymbol(KeptDSOSyms[i].c_str());
Rafael Espindolacda29112013-10-03 18:29:09 +0000807
Akira Hatanaka23b5f672015-01-30 01:14:28 +0000808 // Set cpu and attrs strings for the default target/subtarget.
809 CodeGen.setCpu(MCPU.c_str());
810
Peter Collingbourne070843d2015-03-19 22:01:00 +0000811 CodeGen.setOptLevel(OptLevel - '0');
812
Tom Roederfd1bc602014-04-25 21:46:51 +0000813 std::string attrs;
814 for (unsigned i = 0; i < MAttrs.size(); ++i) {
815 if (i > 0)
816 attrs.append(",");
817 attrs.append(MAttrs[i]);
818 }
819
820 if (!attrs.empty())
821 CodeGen.setAttr(attrs.c_str());
822
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000823 if (FileType.getNumOccurrences())
824 CodeGen.setFileType(FileType);
825
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000826 if (!OutputFilename.empty()) {
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000827 if (!CodeGen.optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000828 DisableLTOVectorization)) {
829 // Diagnostic messages should have been printed by the handler.
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000830 error("error optimizing the code");
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000831 }
832
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000833 if (SaveModuleFile) {
834 std::string ModuleFilename = OutputFilename;
835 ModuleFilename += ".merged.bc";
836 std::string ErrMsg;
837
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000838 if (!CodeGen.writeMergedModules(ModuleFilename.c_str()))
839 error("writing merged module failed.");
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000840 }
841
Peter Collingbournec269ed52015-08-27 23:37:36 +0000842 std::list<tool_output_file> OSs;
843 std::vector<raw_pwrite_stream *> OSPtrs;
844 for (unsigned I = 0; I != Parallelism; ++I) {
845 std::string PartFilename = OutputFilename;
846 if (Parallelism != 1)
847 PartFilename += "." + utostr(I);
848 std::error_code EC;
849 OSs.emplace_back(PartFilename, EC, sys::fs::F_None);
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000850 if (EC)
851 error("error opening the file '" + PartFilename + "': " + EC.message());
Peter Collingbournec269ed52015-08-27 23:37:36 +0000852 OSPtrs.push_back(&OSs.back().os());
853 }
854
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000855 if (!CodeGen.compileOptimized(OSPtrs))
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000856 // Diagnostic messages should have been printed by the handler.
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000857 error("error compiling the code");
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000858
Peter Collingbournec269ed52015-08-27 23:37:36 +0000859 for (tool_output_file &OS : OSs)
860 OS.keep();
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000861 } else {
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000862 if (Parallelism != 1)
863 error("-j must be specified together with -o");
Peter Collingbournec269ed52015-08-27 23:37:36 +0000864
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000865 if (SaveModuleFile)
866 error(": -save-merged-module must be specified with -o");
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000867
Craig Toppere6cb63e2014-04-25 04:24:47 +0000868 const char *OutputName = nullptr;
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000869 if (!CodeGen.compile_to_file(&OutputName, DisableVerify, DisableInline,
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000870 DisableGVNLoadPRE, DisableLTOVectorization))
871 error("error compiling the code");
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000872 // Diagnostic messages should have been printed by the handler.
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000873
874 outs() << "Wrote native object file '" << OutputName << "'\n";
875 }
876
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000877 return 0;
878}