blob: 87c998c90324ac43b450c8f2e295cf981232365f [file] [log] [blame]
Eugene Zelenko975293f2017-09-07 23:28:24 +00001//===- llvm-lto: a simple command-line program to link modules with LTO ---===//
Peter Collingbourne4e380b02013-09-19 22:15:52 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This program takes in a list of bitcode files, links them, performs link-time
11// optimization, and outputs an object file.
12//
13//===----------------------------------------------------------------------===//
14
Eugene Zelenko975293f2017-09-07 23:28:24 +000015#include "llvm-c/lto.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/STLExtras.h"
18#include "llvm/ADT/SmallString.h"
19#include "llvm/ADT/StringExtras.h"
20#include "llvm/ADT/StringRef.h"
Rafael Espindola282a4702013-10-31 20:51:58 +000021#include "llvm/ADT/StringSet.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000022#include "llvm/ADT/Twine.h"
Teresa Johnsonad176792016-11-11 05:34:58 +000023#include "llvm/Bitcode/BitcodeReader.h"
24#include "llvm/Bitcode/BitcodeWriter.h"
David Blaikiec14bfec2017-11-27 19:43:58 +000025#include "llvm/CodeGen/CommandFlags.def"
Eugene Zelenko975293f2017-09-07 23:28:24 +000026#include "llvm/IR/DiagnosticInfo.h"
Mehdi Amini354f5202015-11-19 05:52:29 +000027#include "llvm/IR/DiagnosticPrinter.h"
Teresa Johnson91a88bb2015-10-19 14:30:44 +000028#include "llvm/IR/LLVMContext.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000029#include "llvm/IR/Module.h"
30#include "llvm/IR/ModuleSummaryIndex.h"
Mehdi Amini3c0e64c2016-04-20 01:04:26 +000031#include "llvm/IR/Verifier.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000032#include "llvm/IRReader/IRReader.h"
Peter Collingbourne5c732202016-07-14 21:21:16 +000033#include "llvm/LTO/legacy/LTOCodeGenerator.h"
34#include "llvm/LTO/legacy/LTOModule.h"
35#include "llvm/LTO/legacy/ThinLTOCodeGenerator.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000036#include "llvm/Support/Allocator.h"
37#include "llvm/Support/Casting.h"
Peter Collingbourne4e380b02013-09-19 22:15:52 +000038#include "llvm/Support/CommandLine.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000039#include "llvm/Support/Error.h"
40#include "llvm/Support/ErrorHandling.h"
41#include "llvm/Support/ErrorOr.h"
Benjamin Kramerd59664f2014-04-29 23:26:49 +000042#include "llvm/Support/FileSystem.h"
Peter Collingbourne4e380b02013-09-19 22:15:52 +000043#include "llvm/Support/ManagedStatic.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000044#include "llvm/Support/MemoryBuffer.h"
Teresa Johnsonbbd10b42016-05-17 14:45:30 +000045#include "llvm/Support/Path.h"
Peter Collingbourne4e380b02013-09-19 22:15:52 +000046#include "llvm/Support/PrettyStackTrace.h"
47#include "llvm/Support/Signals.h"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000048#include "llvm/Support/SourceMgr.h"
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +000049#include "llvm/Support/TargetSelect.h"
Peter Collingbournec269ed52015-08-27 23:37:36 +000050#include "llvm/Support/ToolOutputFile.h"
Chandler Carruth07baed52014-01-13 08:04:33 +000051#include "llvm/Support/raw_ostream.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000052#include "llvm/Target/TargetOptions.h"
53#include <algorithm>
54#include <cassert>
55#include <cstdint>
56#include <cstdlib>
Peter Collingbournec269ed52015-08-27 23:37:36 +000057#include <list>
Eugene Zelenko975293f2017-09-07 23:28:24 +000058#include <map>
59#include <memory>
60#include <string>
61#include <system_error>
62#include <tuple>
63#include <utility>
64#include <vector>
Peter Collingbourne4e380b02013-09-19 22:15:52 +000065
66using namespace llvm;
67
Peter Collingbourne070843d2015-03-19 22:01:00 +000068static cl::opt<char>
Davide Italianob10e8932016-04-13 21:41:35 +000069 OptLevel("O", cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
70 "(default = '-O2')"),
71 cl::Prefix, cl::ZeroOrMore, cl::init('2'));
Peter Collingbourne4e380b02013-09-19 22:15:52 +000072
Mehdi Amini06a47802016-09-14 21:04:59 +000073static cl::opt<bool>
74 IndexStats("thinlto-index-stats",
75 cl::desc("Print statistic for the index in every input files"),
76 cl::init(false));
77
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +000078static cl::opt<bool> DisableVerify(
79 "disable-verify", cl::init(false),
80 cl::desc("Do not run the verifier during the optimization pipeline"));
81
Davide Italianob10e8932016-04-13 21:41:35 +000082static cl::opt<bool> DisableInline("disable-inlining", cl::init(false),
83 cl::desc("Do not run the inliner pass"));
Rafael Espindola0b385c72013-09-30 16:39:19 +000084
85static cl::opt<bool>
Davide Italianob10e8932016-04-13 21:41:35 +000086 DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
87 cl::desc("Do not run the GVN load PRE pass"));
Rafael Espindola0b385c72013-09-30 16:39:19 +000088
Davide Italianob10e8932016-04-13 21:41:35 +000089static cl::opt<bool> DisableLTOVectorization(
90 "disable-lto-vectorization", cl::init(false),
91 cl::desc("Do not run loop or slp vectorization during LTO"));
Arnold Schwaighofereb1a38f2014-10-26 21:50:58 +000092
Mehdi Aminib5a46c12017-03-28 18:55:44 +000093static cl::opt<bool> EnableFreestanding(
94 "lto-freestanding", cl::init(false),
95 cl::desc("Enable Freestanding (disable builtins / TLI) during LTO"));
96
Davide Italianob10e8932016-04-13 21:41:35 +000097static cl::opt<bool> UseDiagnosticHandler(
98 "use-diagnostic-handler", cl::init(false),
99 cl::desc("Use a diagnostic handler to test the handler interface"));
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +0000100
Teresa Johnsonf72278f2015-11-02 18:02:11 +0000101static cl::opt<bool>
102 ThinLTO("thinlto", cl::init(false),
103 cl::desc("Only write combined global index for ThinLTO backends"));
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000104
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000105enum ThinLTOModes {
106 THINLINK,
Teresa Johnson84174c32016-05-10 13:48:23 +0000107 THINDISTRIBUTE,
Teresa Johnson8570fe42016-05-10 15:54:09 +0000108 THINEMITIMPORTS,
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000109 THINPROMOTE,
110 THINIMPORT,
Mehdi Amini059464f2016-04-24 03:18:01 +0000111 THININTERNALIZE,
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000112 THINOPT,
113 THINCODEGEN,
114 THINALL
115};
116
117cl::opt<ThinLTOModes> ThinLTOMode(
118 "thinlto-action", cl::desc("Perform a single ThinLTO stage:"),
119 cl::values(
120 clEnumValN(
121 THINLINK, "thinlink",
122 "ThinLink: produces the index by linking only the summaries."),
Teresa Johnson84174c32016-05-10 13:48:23 +0000123 clEnumValN(THINDISTRIBUTE, "distributedindexes",
124 "Produces individual indexes for distributed backends."),
Teresa Johnson8570fe42016-05-10 15:54:09 +0000125 clEnumValN(THINEMITIMPORTS, "emitimports",
126 "Emit imports files for distributed backends."),
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000127 clEnumValN(THINPROMOTE, "promote",
128 "Perform pre-import promotion (requires -thinlto-index)."),
129 clEnumValN(THINIMPORT, "import", "Perform both promotion and "
130 "cross-module importing (requires "
131 "-thinlto-index)."),
Mehdi Amini059464f2016-04-24 03:18:01 +0000132 clEnumValN(THININTERNALIZE, "internalize",
133 "Perform internalization driven by -exported-symbol "
134 "(requires -thinlto-index)."),
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000135 clEnumValN(THINOPT, "optimize", "Perform ThinLTO optimizations."),
136 clEnumValN(THINCODEGEN, "codegen", "CodeGen (expected to match llc)"),
Mehdi Amini732afdd2016-10-08 19:41:06 +0000137 clEnumValN(THINALL, "run", "Perform ThinLTO end-to-end")));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000138
139static cl::opt<std::string>
140 ThinLTOIndex("thinlto-index",
141 cl::desc("Provide the index produced by a ThinLink, required "
142 "to perform the promotion and/or importing."));
143
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000144static cl::opt<std::string> ThinLTOPrefixReplace(
145 "thinlto-prefix-replace",
146 cl::desc("Control where files for distributed backends are "
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000147 "created. Expects 'oldprefix;newprefix' and if path "
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000148 "prefix of output file is oldprefix it will be "
149 "replaced with newprefix."));
150
Mehdi Amini03abce92016-05-05 16:33:51 +0000151static cl::opt<std::string> ThinLTOModuleId(
152 "thinlto-module-id",
153 cl::desc("For the module ID for the file to process, useful to "
154 "match what is in the index."));
155
Mehdi Aminiab4a8b62016-05-14 05:16:41 +0000156static cl::opt<std::string>
157 ThinLTOCacheDir("thinlto-cache-dir", cl::desc("Enable ThinLTO caching."));
158
Ben Dunbobbin9ecb8b52017-12-19 14:42:38 +0000159static cl::opt<int>
Ekaterina Romanovad345f732018-02-15 23:29:21 +0000160 ThinLTOCachePruningInterval("thinlto-cache-pruning-interval",
161 cl::init(1200), cl::desc("Set ThinLTO cache pruning interval."));
Ben Dunbobbin9ecb8b52017-12-19 14:42:38 +0000162
Ekaterina Romanovab8aeec42018-03-02 03:51:27 +0000163static cl::opt<int>
164 ThinLTOCacheMaxSizeBytes("thinlto-cache-max-size-bytes",
165 cl::desc("Set ThinLTO cache pruning directory maximum size in bytes."));
166
167static cl::opt<int>
168 ThinLTOCacheMaxSizeFiles("thinlto-cache-max-size-files", cl::init(1000000),
169 cl::desc("Set ThinLTO cache pruning directory maximum number of files."));
170
Teresa Johnsonc44a1222016-08-15 23:24:57 +0000171static cl::opt<std::string> ThinLTOSaveTempsPrefix(
172 "thinlto-save-temps",
173 cl::desc("Save ThinLTO temp files using filenames created by adding "
174 "suffixes to the given file path prefix."));
175
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000176static cl::opt<std::string> ThinLTOGeneratedObjectsDir(
177 "thinlto-save-objects",
178 cl::desc("Save ThinLTO generated object files using filenames created in "
179 "the given directory."));
180
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000181static cl::opt<bool>
Davide Italianob10e8932016-04-13 21:41:35 +0000182 SaveModuleFile("save-merged-module", cl::init(false),
183 cl::desc("Write merged LTO module to file before CodeGen"));
184
185static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
186 cl::desc("<input bitcode files>"));
187
188static cl::opt<std::string> OutputFilename("o", cl::init(""),
189 cl::desc("Override output filename"),
190 cl::value_desc("filename"));
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000191
Mehdi Amini059464f2016-04-24 03:18:01 +0000192static cl::list<std::string> ExportedSymbols(
193 "exported-symbol",
194 cl::desc("List of symbols to export from the resulting object file"),
195 cl::ZeroOrMore);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000196
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000197static cl::list<std::string>
Davide Italianob10e8932016-04-13 21:41:35 +0000198 DSOSymbols("dso-symbol",
199 cl::desc("Symbol to put in the symtab in the resulting dso"),
200 cl::ZeroOrMore);
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000201
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000202static cl::opt<bool> ListSymbolsOnly(
203 "list-symbols-only", cl::init(false),
204 cl::desc("Instead of running LTO, list the symbols in each IR file"));
205
Manman Ren6487ce92015-02-24 00:45:56 +0000206static cl::opt<bool> SetMergedModule(
207 "set-merged-module", cl::init(false),
208 cl::desc("Use the first input module as the merged module"));
209
Peter Collingbournec269ed52015-08-27 23:37:36 +0000210static cl::opt<unsigned> Parallelism("j", cl::Prefix, cl::init(1),
211 cl::desc("Number of backend threads"));
212
Tobias Edler von Koch3f4f6f3e2016-01-18 23:35:24 +0000213static cl::opt<bool> RestoreGlobalsLinkage(
214 "restore-linkage", cl::init(false),
215 cl::desc("Restore original linkage of globals prior to CodeGen"));
216
Mehdi Aminie75aa6f2016-07-11 23:10:18 +0000217static cl::opt<bool> CheckHasObjC(
218 "check-for-objc", cl::init(false),
219 cl::desc("Only check if the module has objective-C defined in it"));
220
Rafael Espindola282a4702013-10-31 20:51:58 +0000221namespace {
Eugene Zelenko975293f2017-09-07 23:28:24 +0000222
Rafael Espindola282a4702013-10-31 20:51:58 +0000223struct ModuleInfo {
224 std::vector<bool> CanBeHidden;
225};
Eugene Zelenko975293f2017-09-07 23:28:24 +0000226
227} // end anonymous namespace
Rafael Espindola282a4702013-10-31 20:51:58 +0000228
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000229static void handleDiagnostics(lto_codegen_diagnostic_severity_t Severity,
230 const char *Msg, void *) {
Yunzhong Gaoef436f02015-11-10 18:52:48 +0000231 errs() << "llvm-lto: ";
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +0000232 switch (Severity) {
233 case LTO_DS_NOTE:
234 errs() << "note: ";
235 break;
236 case LTO_DS_REMARK:
237 errs() << "remark: ";
238 break;
239 case LTO_DS_ERROR:
240 errs() << "error: ";
241 break;
242 case LTO_DS_WARNING:
243 errs() << "warning: ";
244 break;
245 }
246 errs() << Msg << "\n";
247}
248
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000249static std::string CurrentActivity;
Vivek Pandyab5ab8952017-09-15 20:10:09 +0000250
251namespace {
252 struct LLVMLTODiagnosticHandler : public DiagnosticHandler {
253 bool handleDiagnostics(const DiagnosticInfo &DI) override {
254 raw_ostream &OS = errs();
255 OS << "llvm-lto: ";
256 switch (DI.getSeverity()) {
257 case DS_Error:
258 OS << "error";
259 break;
260 case DS_Warning:
261 OS << "warning";
262 break;
263 case DS_Remark:
264 OS << "remark";
265 break;
266 case DS_Note:
267 OS << "note";
268 break;
269 }
270 if (!CurrentActivity.empty())
271 OS << ' ' << CurrentActivity;
272 OS << ": ";
273
274 DiagnosticPrinterRawOStream DP(OS);
275 DI.print(DP);
276 OS << '\n';
277
278 if (DI.getSeverity() == DS_Error)
279 exit(1);
280 return true;
281 }
282 };
Mehdi Amini354f5202015-11-19 05:52:29 +0000283 }
Mehdi Amini354f5202015-11-19 05:52:29 +0000284
Rafael Espindola5e128db2015-12-04 00:45:57 +0000285static void error(const Twine &Msg) {
286 errs() << "llvm-lto: " << Msg << '\n';
287 exit(1);
288}
289
290static void error(std::error_code EC, const Twine &Prefix) {
291 if (EC)
292 error(Prefix + ": " + EC.message());
293}
294
295template <typename T>
296static void error(const ErrorOr<T> &V, const Twine &Prefix) {
297 error(V.getError(), Prefix);
298}
299
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000300static void maybeVerifyModule(const Module &Mod) {
Mehdi Amini4c809462016-12-23 23:53:57 +0000301 if (!DisableVerify && verifyModule(Mod, &errs()))
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000302 error("Broken Module");
303}
304
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000305static std::unique_ptr<LTOModule>
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000306getLocalLTOModule(StringRef Path, std::unique_ptr<MemoryBuffer> &Buffer,
Rafael Espindola5e128db2015-12-04 00:45:57 +0000307 const TargetOptions &Options) {
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000308 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
309 MemoryBuffer::getFile(Path);
Rafael Espindola5e128db2015-12-04 00:45:57 +0000310 error(BufferOrErr, "error loading file '" + Path + "'");
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000311 Buffer = std::move(BufferOrErr.get());
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000312 CurrentActivity = ("loading file '" + Path + "'").str();
Petr Pavlu7ad9ec92016-03-01 13:13:49 +0000313 std::unique_ptr<LLVMContext> Context = llvm::make_unique<LLVMContext>();
Vivek Pandyab5ab8952017-09-15 20:10:09 +0000314 Context->setDiagnosticHandler(llvm::make_unique<LLVMLTODiagnosticHandler>(),
315 true);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000316 ErrorOr<std::unique_ptr<LTOModule>> Ret = LTOModule::createInLocalContext(
Petr Pavlu7ad9ec92016-03-01 13:13:49 +0000317 std::move(Context), Buffer->getBufferStart(), Buffer->getBufferSize(),
318 Options, Path);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000319 CurrentActivity = "";
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000320 maybeVerifyModule((*Ret)->getModule());
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000321 return std::move(*Ret);
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000322}
323
Mehdi Amini06a47802016-09-14 21:04:59 +0000324/// Print some statistics on the index for each input files.
325void printIndexStats() {
326 for (auto &Filename : InputFilenames) {
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000327 ExitOnError ExitOnErr("llvm-lto: error loading file '" + Filename + "': ");
328 std::unique_ptr<ModuleSummaryIndex> Index =
Eugene Zelenko975293f2017-09-07 23:28:24 +0000329 ExitOnErr(getModuleSummaryIndexForFile(Filename));
Mehdi Amini06a47802016-09-14 21:04:59 +0000330 // Skip files without a module summary.
331 if (!Index)
332 report_fatal_error(Filename + " does not contain an index");
333
334 unsigned Calls = 0, Refs = 0, Functions = 0, Alias = 0, Globals = 0;
335 for (auto &Summaries : *Index) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000336 for (auto &Summary : Summaries.second.SummaryList) {
Mehdi Amini06a47802016-09-14 21:04:59 +0000337 Refs += Summary->refs().size();
338 if (auto *FuncSummary = dyn_cast<FunctionSummary>(Summary.get())) {
339 Functions++;
340 Calls += FuncSummary->calls().size();
341 } else if (isa<AliasSummary>(Summary.get()))
342 Alias++;
343 else
344 Globals++;
345 }
346 }
347 outs() << "Index " << Filename << " contains "
348 << (Alias + Globals + Functions) << " nodes (" << Functions
349 << " functions, " << Alias << " alias, " << Globals
350 << " globals) and " << (Calls + Refs) << " edges (" << Refs
351 << " refs and " << Calls << " calls)\n";
352 }
353}
354
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000355/// \brief List symbols in each IR file.
356///
357/// The main point here is to provide lit-testable coverage for the LTOModule
358/// functionality that's exposed by the C API to list symbols. Moreover, this
359/// provides testing coverage for modules that have been created in their own
360/// contexts.
Rafael Espindola5e128db2015-12-04 00:45:57 +0000361static void listSymbols(const TargetOptions &Options) {
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000362 for (auto &Filename : InputFilenames) {
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000363 std::unique_ptr<MemoryBuffer> Buffer;
364 std::unique_ptr<LTOModule> Module =
Rafael Espindola5e128db2015-12-04 00:45:57 +0000365 getLocalLTOModule(Filename, Buffer, Options);
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000366
367 // List the symbols.
368 outs() << Filename << ":\n";
369 for (int I = 0, E = Module->getSymbolCount(); I != E; ++I)
370 outs() << Module->getSymbolName(I) << "\n";
371 }
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000372}
373
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000374/// Create a combined index file from the input IR files and write it.
375///
376/// This is meant to enable testing of ThinLTO combined index generation,
377/// currently available via the gold plugin via -thinlto.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000378static void createCombinedModuleSummaryIndex() {
Eugene Leviant28d8a492018-01-22 13:35:40 +0000379 ModuleSummaryIndex CombinedIndex(/*IsPerformingAnalysis=*/false);
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000380 uint64_t NextModuleId = 0;
381 for (auto &Filename : InputFilenames) {
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000382 ExitOnError ExitOnErr("llvm-lto: error loading file '" + Filename + "': ");
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000383 std::unique_ptr<MemoryBuffer> MB =
384 ExitOnErr(errorOrToExpected(MemoryBuffer::getFileOrSTDIN(Filename)));
385 ExitOnErr(readModuleSummaryIndex(*MB, CombinedIndex, ++NextModuleId));
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000386 }
387 std::error_code EC;
388 assert(!OutputFilename.empty());
389 raw_fd_ostream OS(OutputFilename + ".thinlto.bc", EC,
390 sys::fs::OpenFlags::F_None);
Rafael Espindola5e128db2015-12-04 00:45:57 +0000391 error(EC, "error opening the file '" + OutputFilename + ".thinlto.bc'");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000392 WriteIndexToFile(CombinedIndex, OS);
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000393 OS.close();
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000394}
395
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000396/// Parse the thinlto_prefix_replace option into the \p OldPrefix and
397/// \p NewPrefix strings, if it was specified.
398static void getThinLTOOldAndNewPrefix(std::string &OldPrefix,
399 std::string &NewPrefix) {
400 assert(ThinLTOPrefixReplace.empty() ||
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000401 ThinLTOPrefixReplace.find(";") != StringRef::npos);
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000402 StringRef PrefixReplace = ThinLTOPrefixReplace;
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000403 std::pair<StringRef, StringRef> Split = PrefixReplace.split(";");
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000404 OldPrefix = Split.first.str();
405 NewPrefix = Split.second.str();
406}
407
408/// Given the original \p Path to an output file, replace any path
409/// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
410/// resulting directory if it does not yet exist.
411static std::string getThinLTOOutputFile(const std::string &Path,
412 const std::string &OldPrefix,
413 const std::string &NewPrefix) {
414 if (OldPrefix.empty() && NewPrefix.empty())
415 return Path;
416 SmallString<128> NewPath(Path);
417 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
418 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
419 if (!ParentPath.empty()) {
420 // Make sure the new directory exists, creating it if necessary.
421 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
422 error(EC, "error creating the directory '" + ParentPath + "'");
423 }
424 return NewPath.str();
425}
426
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000427namespace thinlto {
428
429std::vector<std::unique_ptr<MemoryBuffer>>
Teresa Johnson26ab5772016-03-15 00:04:37 +0000430loadAllFilesForIndex(const ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000431 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
432
Mehdi Amini385cf282016-03-26 03:35:38 +0000433 for (auto &ModPath : Index.modulePaths()) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000434 const auto &Filename = ModPath.first();
Alexander Kornienko656466e2017-07-04 15:13:02 +0000435 std::string CurrentActivity = ("loading file '" + Filename + "'").str();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000436 auto InputOrErr = MemoryBuffer::getFile(Filename);
437 error(InputOrErr, "error " + CurrentActivity);
438 InputBuffers.push_back(std::move(*InputOrErr));
439 }
440 return InputBuffers;
441}
442
Teresa Johnson26ab5772016-03-15 00:04:37 +0000443std::unique_ptr<ModuleSummaryIndex> loadCombinedIndex() {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000444 if (ThinLTOIndex.empty())
445 report_fatal_error("Missing -thinlto-index for ThinLTO promotion stage");
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000446 ExitOnError ExitOnErr("llvm-lto: error loading file '" + ThinLTOIndex +
447 "': ");
Eugene Zelenko975293f2017-09-07 23:28:24 +0000448 return ExitOnErr(getModuleSummaryIndexForFile(ThinLTOIndex));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000449}
450
451static std::unique_ptr<Module> loadModule(StringRef Filename,
452 LLVMContext &Ctx) {
453 SMDiagnostic Err;
454 std::unique_ptr<Module> M(parseIRFile(Filename, Err, Ctx));
455 if (!M) {
456 Err.print("llvm-lto", errs());
457 report_fatal_error("Can't load module for file " + Filename);
458 }
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000459 maybeVerifyModule(*M);
Mehdi Amini03abce92016-05-05 16:33:51 +0000460
461 if (ThinLTOModuleId.getNumOccurrences()) {
462 if (InputFilenames.size() != 1)
463 report_fatal_error("Can't override the module id for multiple files");
464 M->setModuleIdentifier(ThinLTOModuleId);
465 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000466 return M;
467}
468
469static void writeModuleToFile(Module &TheModule, StringRef Filename) {
470 std::error_code EC;
471 raw_fd_ostream OS(Filename, EC, sys::fs::OpenFlags::F_None);
472 error(EC, "error opening the file '" + Filename + "'");
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000473 maybeVerifyModule(TheModule);
Rafael Espindola6a86e252018-02-14 19:11:32 +0000474 WriteBitcodeToFile(TheModule, OS, /* ShouldPreserveUseListOrder */ true);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000475}
476
477class ThinLTOProcessing {
478public:
479 ThinLTOCodeGenerator ThinGenerator;
480
481 ThinLTOProcessing(const TargetOptions &Options) {
Rafael Espindola8c34dd82016-05-18 22:04:49 +0000482 ThinGenerator.setCodePICModel(getRelocModel());
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000483 ThinGenerator.setTargetOptions(Options);
Mehdi Aminiab4a8b62016-05-14 05:16:41 +0000484 ThinGenerator.setCacheDir(ThinLTOCacheDir);
Ben Dunbobbin9ecb8b52017-12-19 14:42:38 +0000485 ThinGenerator.setCachePruningInterval(ThinLTOCachePruningInterval);
Ekaterina Romanovab8aeec42018-03-02 03:51:27 +0000486 ThinGenerator.setCacheMaxSizeFiles(ThinLTOCacheMaxSizeFiles);
487 ThinGenerator.setCacheMaxSizeBytes(ThinLTOCacheMaxSizeBytes);
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000488 ThinGenerator.setFreestanding(EnableFreestanding);
Mehdi Amini059464f2016-04-24 03:18:01 +0000489
490 // Add all the exported symbols to the table of symbols to preserve.
491 for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
492 ThinGenerator.preserveSymbol(ExportedSymbols[i]);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000493 }
494
495 void run() {
496 switch (ThinLTOMode) {
497 case THINLINK:
498 return thinLink();
Teresa Johnson84174c32016-05-10 13:48:23 +0000499 case THINDISTRIBUTE:
500 return distributedIndexes();
Teresa Johnson8570fe42016-05-10 15:54:09 +0000501 case THINEMITIMPORTS:
502 return emitImports();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000503 case THINPROMOTE:
504 return promote();
505 case THINIMPORT:
506 return import();
Mehdi Amini059464f2016-04-24 03:18:01 +0000507 case THININTERNALIZE:
508 return internalize();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000509 case THINOPT:
510 return optimize();
511 case THINCODEGEN:
512 return codegen();
513 case THINALL:
514 return runAll();
515 }
516 }
517
518private:
519 /// Load the input files, create the combined index, and write it out.
520 void thinLink() {
521 // Perform "ThinLink": just produce the index
522 if (OutputFilename.empty())
523 report_fatal_error(
524 "OutputFilename is necessary to store the combined index.\n");
525
526 LLVMContext Ctx;
527 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
528 for (unsigned i = 0; i < InputFilenames.size(); ++i) {
529 auto &Filename = InputFilenames[i];
Alexander Kornienko656466e2017-07-04 15:13:02 +0000530 std::string CurrentActivity = "loading file '" + Filename + "'";
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000531 auto InputOrErr = MemoryBuffer::getFile(Filename);
532 error(InputOrErr, "error " + CurrentActivity);
533 InputBuffers.push_back(std::move(*InputOrErr));
534 ThinGenerator.addModule(Filename, InputBuffers.back()->getBuffer());
535 }
536
537 auto CombinedIndex = ThinGenerator.linkCombinedIndex();
Mehdi Amini00fa1402016-10-08 04:44:18 +0000538 if (!CombinedIndex)
539 report_fatal_error("ThinLink didn't create an index");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000540 std::error_code EC;
541 raw_fd_ostream OS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
542 error(EC, "error opening the file '" + OutputFilename + "'");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000543 WriteIndexToFile(*CombinedIndex, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000544 }
545
Teresa Johnson84174c32016-05-10 13:48:23 +0000546 /// Load the combined index from disk, then compute and generate
547 /// individual index files suitable for ThinLTO distributed backend builds
548 /// on the files mentioned on the command line (these must match the index
549 /// content).
550 void distributedIndexes() {
551 if (InputFilenames.size() != 1 && !OutputFilename.empty())
552 report_fatal_error("Can't handle a single output filename and multiple "
553 "input files, do not provide an output filename and "
554 "the output files will be suffixed from the input "
555 "ones.");
556
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000557 std::string OldPrefix, NewPrefix;
558 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
559
Teresa Johnson84174c32016-05-10 13:48:23 +0000560 auto Index = loadCombinedIndex();
561 for (auto &Filename : InputFilenames) {
562 // Build a map of module to the GUIDs and summary objects that should
563 // be written to its index.
564 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
565 ThinLTOCodeGenerator::gatherImportedSummariesForModule(
566 Filename, *Index, ModuleToSummariesForIndex);
567
568 std::string OutputName = OutputFilename;
569 if (OutputName.empty()) {
570 OutputName = Filename + ".thinlto.bc";
571 }
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000572 OutputName = getThinLTOOutputFile(OutputName, OldPrefix, NewPrefix);
Teresa Johnson84174c32016-05-10 13:48:23 +0000573 std::error_code EC;
574 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::F_None);
575 error(EC, "error opening the file '" + OutputName + "'");
576 WriteIndexToFile(*Index, OS, &ModuleToSummariesForIndex);
577 }
578 }
579
Teresa Johnson8570fe42016-05-10 15:54:09 +0000580 /// Load the combined index from disk, compute the imports, and emit
581 /// the import file lists for each module to disk.
582 void emitImports() {
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
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000589 std::string OldPrefix, NewPrefix;
590 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
591
Teresa Johnson8570fe42016-05-10 15:54:09 +0000592 auto Index = loadCombinedIndex();
593 for (auto &Filename : InputFilenames) {
594 std::string OutputName = OutputFilename;
595 if (OutputName.empty()) {
596 OutputName = Filename + ".imports";
597 }
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000598 OutputName = getThinLTOOutputFile(OutputName, OldPrefix, NewPrefix);
Teresa Johnson8570fe42016-05-10 15:54:09 +0000599 ThinLTOCodeGenerator::emitImports(Filename, OutputName, *Index);
600 }
601 }
602
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000603 /// Load the combined index from disk, then load every file referenced by
604 /// the index and add them to the generator, finally perform the promotion
605 /// on the files mentioned on the command line (these must match the index
606 /// content).
607 void promote() {
608 if (InputFilenames.size() != 1 && !OutputFilename.empty())
609 report_fatal_error("Can't handle a single output filename and multiple "
610 "input files, do not provide an output filename and "
611 "the output files will be suffixed from the input "
612 "ones.");
613
614 auto Index = loadCombinedIndex();
615 for (auto &Filename : InputFilenames) {
616 LLVMContext Ctx;
617 auto TheModule = loadModule(Filename, Ctx);
618
619 ThinGenerator.promote(*TheModule, *Index);
620
621 std::string OutputName = OutputFilename;
622 if (OutputName.empty()) {
623 OutputName = Filename + ".thinlto.promoted.bc";
624 }
625 writeModuleToFile(*TheModule, OutputName);
626 }
627 }
628
629 /// Load the combined index from disk, then load every file referenced by
630 /// the index and add them to the generator, then performs the promotion and
631 /// cross module importing on the files mentioned on the command line
632 /// (these must match the index content).
633 void import() {
634 if (InputFilenames.size() != 1 && !OutputFilename.empty())
635 report_fatal_error("Can't handle a single output filename and multiple "
636 "input files, do not provide an output filename and "
637 "the output files will be suffixed from the input "
638 "ones.");
639
640 auto Index = loadCombinedIndex();
641 auto InputBuffers = loadAllFilesForIndex(*Index);
642 for (auto &MemBuffer : InputBuffers)
643 ThinGenerator.addModule(MemBuffer->getBufferIdentifier(),
644 MemBuffer->getBuffer());
645
646 for (auto &Filename : InputFilenames) {
647 LLVMContext Ctx;
648 auto TheModule = loadModule(Filename, Ctx);
649
650 ThinGenerator.crossModuleImport(*TheModule, *Index);
651
652 std::string OutputName = OutputFilename;
653 if (OutputName.empty()) {
654 OutputName = Filename + ".thinlto.imported.bc";
655 }
656 writeModuleToFile(*TheModule, OutputName);
657 }
658 }
659
Mehdi Amini059464f2016-04-24 03:18:01 +0000660 void internalize() {
661 if (InputFilenames.size() != 1 && !OutputFilename.empty())
662 report_fatal_error("Can't handle a single output filename and multiple "
663 "input files, do not provide an output filename and "
664 "the output files will be suffixed from the input "
665 "ones.");
666
667 if (ExportedSymbols.empty())
668 errs() << "Warning: -internalize will not perform without "
669 "-exported-symbol\n";
670
671 auto Index = loadCombinedIndex();
672 auto InputBuffers = loadAllFilesForIndex(*Index);
673 for (auto &MemBuffer : InputBuffers)
674 ThinGenerator.addModule(MemBuffer->getBufferIdentifier(),
675 MemBuffer->getBuffer());
676
677 for (auto &Filename : InputFilenames) {
678 LLVMContext Ctx;
679 auto TheModule = loadModule(Filename, Ctx);
680
681 ThinGenerator.internalize(*TheModule, *Index);
682
683 std::string OutputName = OutputFilename;
684 if (OutputName.empty()) {
685 OutputName = Filename + ".thinlto.internalized.bc";
686 }
687 writeModuleToFile(*TheModule, OutputName);
688 }
689 }
690
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000691 void optimize() {
692 if (InputFilenames.size() != 1 && !OutputFilename.empty())
693 report_fatal_error("Can't handle a single output filename and multiple "
694 "input files, do not provide an output filename and "
695 "the output files will be suffixed from the input "
696 "ones.");
697 if (!ThinLTOIndex.empty())
698 errs() << "Warning: -thinlto-index ignored for optimize stage";
699
700 for (auto &Filename : InputFilenames) {
701 LLVMContext Ctx;
702 auto TheModule = loadModule(Filename, Ctx);
703
704 ThinGenerator.optimize(*TheModule);
705
706 std::string OutputName = OutputFilename;
707 if (OutputName.empty()) {
708 OutputName = Filename + ".thinlto.imported.bc";
709 }
710 writeModuleToFile(*TheModule, OutputName);
711 }
712 }
713
714 void codegen() {
715 if (InputFilenames.size() != 1 && !OutputFilename.empty())
716 report_fatal_error("Can't handle a single output filename and multiple "
717 "input files, do not provide an output filename and "
718 "the output files will be suffixed from the input "
719 "ones.");
720 if (!ThinLTOIndex.empty())
721 errs() << "Warning: -thinlto-index ignored for codegen stage";
722
Adrian Prantlcdd785b2017-05-19 17:54:58 +0000723 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000724 for (auto &Filename : InputFilenames) {
725 LLVMContext Ctx;
Adrian Prantlcdd785b2017-05-19 17:54:58 +0000726 auto InputOrErr = MemoryBuffer::getFile(Filename);
727 error(InputOrErr, "error " + CurrentActivity);
728 InputBuffers.push_back(std::move(*InputOrErr));
729 ThinGenerator.addModule(Filename, InputBuffers.back()->getBuffer());
730 }
731 ThinGenerator.setCodeGenOnly(true);
732 ThinGenerator.run();
733 for (auto BinName :
734 zip(ThinGenerator.getProducedBinaries(), InputFilenames)) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000735 std::string OutputName = OutputFilename;
Adrian Prantlcdd785b2017-05-19 17:54:58 +0000736 if (OutputName.empty())
737 OutputName = std::get<1>(BinName) + ".thinlto.o";
738 else if (OutputName == "-") {
739 outs() << std::get<0>(BinName)->getBuffer();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000740 return;
741 }
742
743 std::error_code EC;
744 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::F_None);
745 error(EC, "error opening the file '" + OutputName + "'");
Adrian Prantlcdd785b2017-05-19 17:54:58 +0000746 OS << std::get<0>(BinName)->getBuffer();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000747 }
748 }
749
750 /// Full ThinLTO process
751 void runAll() {
752 if (!OutputFilename.empty())
753 report_fatal_error("Do not provide an output filename for ThinLTO "
754 " processing, the output files will be suffixed from "
755 "the input ones.");
756
757 if (!ThinLTOIndex.empty())
758 errs() << "Warning: -thinlto-index ignored for full ThinLTO process";
759
760 LLVMContext Ctx;
761 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
762 for (unsigned i = 0; i < InputFilenames.size(); ++i) {
763 auto &Filename = InputFilenames[i];
Alexander Kornienko656466e2017-07-04 15:13:02 +0000764 std::string CurrentActivity = "loading file '" + Filename + "'";
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000765 auto InputOrErr = MemoryBuffer::getFile(Filename);
766 error(InputOrErr, "error " + CurrentActivity);
767 InputBuffers.push_back(std::move(*InputOrErr));
768 ThinGenerator.addModule(Filename, InputBuffers.back()->getBuffer());
769 }
770
Teresa Johnsonc44a1222016-08-15 23:24:57 +0000771 if (!ThinLTOSaveTempsPrefix.empty())
772 ThinGenerator.setSaveTempsDir(ThinLTOSaveTempsPrefix);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000773
774 if (!ThinLTOGeneratedObjectsDir.empty()) {
775 ThinGenerator.setGeneratedObjectsDirectory(ThinLTOGeneratedObjectsDir);
776 ThinGenerator.run();
777 return;
778 }
779
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000780 ThinGenerator.run();
781
782 auto &Binaries = ThinGenerator.getProducedBinaries();
783 if (Binaries.size() != InputFilenames.size())
784 report_fatal_error("Number of output objects does not match the number "
785 "of inputs");
786
787 for (unsigned BufID = 0; BufID < Binaries.size(); ++BufID) {
788 auto OutputName = InputFilenames[BufID] + ".thinlto.o";
789 std::error_code EC;
790 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::F_None);
791 error(EC, "error opening the file '" + OutputName + "'");
792 OS << Binaries[BufID]->getBuffer();
793 }
794 }
795
796 /// Load the combined index from disk, then load every file referenced by
797};
798
Eugene Zelenko975293f2017-09-07 23:28:24 +0000799} // end namespace thinlto
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000800
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000801int main(int argc, char **argv) {
802 // Print a stack trace if we signal out.
Richard Smith2ad6d482016-06-09 00:53:21 +0000803 sys::PrintStackTraceOnErrorSignal(argv[0]);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000804 PrettyStackTraceProgram X(argc, argv);
805
806 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
807 cl::ParseCommandLineOptions(argc, argv, "llvm LTO linker\n");
808
Rafael Espindola5e128db2015-12-04 00:45:57 +0000809 if (OptLevel < '0' || OptLevel > '3')
810 error("optimization level must be between 0 and 3");
Peter Collingbourne070843d2015-03-19 22:01:00 +0000811
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000812 // Initialize the configured targets.
813 InitializeAllTargets();
814 InitializeAllTargetMCs();
815 InitializeAllAsmPrinters();
816 InitializeAllAsmParsers();
817
Rafael Espindola0b385c72013-09-30 16:39:19 +0000818 // set up the TargetOptions for the machine
Eli Benderskyf0f21002014-02-19 17:09:35 +0000819 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
Rafael Espindola0b385c72013-09-30 16:39:19 +0000820
Rafael Espindola5e128db2015-12-04 00:45:57 +0000821 if (ListSymbolsOnly) {
822 listSymbols(Options);
823 return 0;
824 }
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000825
Mehdi Amini06a47802016-09-14 21:04:59 +0000826 if (IndexStats) {
827 printIndexStats();
828 return 0;
829 }
830
Mehdi Aminie75aa6f2016-07-11 23:10:18 +0000831 if (CheckHasObjC) {
832 for (auto &Filename : InputFilenames) {
Peter Collingbournecd513a42016-11-11 19:50:24 +0000833 ExitOnError ExitOnErr(std::string(*argv) + ": error loading file '" +
834 Filename + "': ");
835 std::unique_ptr<MemoryBuffer> BufferOrErr =
836 ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(Filename)));
Mehdi Aminie75aa6f2016-07-11 23:10:18 +0000837 auto Buffer = std::move(BufferOrErr.get());
Eugene Zelenko975293f2017-09-07 23:28:24 +0000838 if (ExitOnErr(isBitcodeContainingObjCCategory(*Buffer)))
Mehdi Aminie75aa6f2016-07-11 23:10:18 +0000839 outs() << "Bitcode " << Filename << " contains ObjC\n";
840 else
841 outs() << "Bitcode " << Filename << " does not contain ObjC\n";
842 }
843 return 0;
844 }
845
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000846 if (ThinLTOMode.getNumOccurrences()) {
847 if (ThinLTOMode.getNumOccurrences() > 1)
848 report_fatal_error("You can't specify more than one -thinlto-action");
849 thinlto::ThinLTOProcessing ThinLTOProcessor(Options);
850 ThinLTOProcessor.run();
851 return 0;
852 }
853
Rafael Espindola5e128db2015-12-04 00:45:57 +0000854 if (ThinLTO) {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000855 createCombinedModuleSummaryIndex();
Rafael Espindola5e128db2015-12-04 00:45:57 +0000856 return 0;
857 }
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000858
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000859 unsigned BaseArg = 0;
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000860
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000861 LLVMContext Context;
Vivek Pandyab5ab8952017-09-15 20:10:09 +0000862 Context.setDiagnosticHandler(llvm::make_unique<LLVMLTODiagnosticHandler>(),
863 true);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000864
865 LTOCodeGenerator CodeGen(Context);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000866
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +0000867 if (UseDiagnosticHandler)
868 CodeGen.setDiagnosticHandler(handleDiagnostics, nullptr);
869
Rafael Espindola8c34dd82016-05-18 22:04:49 +0000870 CodeGen.setCodePICModel(getRelocModel());
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000871 CodeGen.setFreestanding(EnableFreestanding);
James Molloy951e5292014-04-14 13:54:16 +0000872
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000873 CodeGen.setDebugInfo(LTO_DEBUG_MODEL_DWARF);
Rafael Espindola0b385c72013-09-30 16:39:19 +0000874 CodeGen.setTargetOptions(Options);
Tobias Edler von Koch3f4f6f3e2016-01-18 23:35:24 +0000875 CodeGen.setShouldRestoreGlobalsLinkage(RestoreGlobalsLinkage);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000876
Eugene Zelenko975293f2017-09-07 23:28:24 +0000877 StringSet<MallocAllocator> DSOSymbolsSet;
Rafael Espindola282a4702013-10-31 20:51:58 +0000878 for (unsigned i = 0; i < DSOSymbols.size(); ++i)
879 DSOSymbolsSet.insert(DSOSymbols[i]);
880
881 std::vector<std::string> KeptDSOSyms;
882
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000883 for (unsigned i = BaseArg; i < InputFilenames.size(); ++i) {
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000884 CurrentActivity = "loading file '" + InputFilenames[i] + "'";
885 ErrorOr<std::unique_ptr<LTOModule>> ModuleOrErr =
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000886 LTOModule::createFromFile(Context, InputFilenames[i], Options);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000887 std::unique_ptr<LTOModule> &Module = *ModuleOrErr;
888 CurrentActivity = "";
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000889
Peter Collingbourne552174392015-08-21 19:09:42 +0000890 unsigned NumSyms = Module->getSymbolCount();
891 for (unsigned I = 0; I < NumSyms; ++I) {
892 StringRef Name = Module->getSymbolName(I);
893 if (!DSOSymbolsSet.count(Name))
894 continue;
895 lto_symbol_attributes Attrs = Module->getSymbolAttributes(I);
896 unsigned Scope = Attrs & LTO_SYMBOL_SCOPE_MASK;
897 if (Scope != LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN)
898 KeptDSOSyms.push_back(Name);
899 }
Manman Ren6487ce92015-02-24 00:45:56 +0000900
901 // We use the first input module as the destination module when
902 // SetMergedModule is true.
903 if (SetMergedModule && i == BaseArg) {
904 // Transfer ownership to the code generator.
Peter Collingbourne9c8909d2015-08-24 22:22:53 +0000905 CodeGen.setModule(std::move(Module));
Yunzhong Gao46261a72015-09-11 20:01:53 +0000906 } else if (!CodeGen.addModule(Module.get())) {
907 // Print a message here so that we know addModule() did not abort.
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000908 error("error adding file '" + InputFilenames[i] + "'");
Yunzhong Gao46261a72015-09-11 20:01:53 +0000909 }
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000910 }
911
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000912 // Add all the exported symbols to the table of symbols to preserve.
913 for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000914 CodeGen.addMustPreserveSymbol(ExportedSymbols[i]);
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000915
Rafael Espindolacda29112013-10-03 18:29:09 +0000916 // Add all the dso symbols to the table of symbols to expose.
Rafael Espindola282a4702013-10-31 20:51:58 +0000917 for (unsigned i = 0; i < KeptDSOSyms.size(); ++i)
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000918 CodeGen.addMustPreserveSymbol(KeptDSOSyms[i]);
Rafael Espindolacda29112013-10-03 18:29:09 +0000919
Akira Hatanaka23b5f672015-01-30 01:14:28 +0000920 // Set cpu and attrs strings for the default target/subtarget.
921 CodeGen.setCpu(MCPU.c_str());
922
Peter Collingbourne070843d2015-03-19 22:01:00 +0000923 CodeGen.setOptLevel(OptLevel - '0');
924
Tom Roederfd1bc602014-04-25 21:46:51 +0000925 std::string attrs;
926 for (unsigned i = 0; i < MAttrs.size(); ++i) {
927 if (i > 0)
928 attrs.append(",");
929 attrs.append(MAttrs[i]);
930 }
931
932 if (!attrs.empty())
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000933 CodeGen.setAttr(attrs);
Tom Roederfd1bc602014-04-25 21:46:51 +0000934
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000935 if (FileType.getNumOccurrences())
936 CodeGen.setFileType(FileType);
937
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000938 if (!OutputFilename.empty()) {
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000939 if (!CodeGen.optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000940 DisableLTOVectorization)) {
941 // Diagnostic messages should have been printed by the handler.
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000942 error("error optimizing the code");
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000943 }
944
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000945 if (SaveModuleFile) {
946 std::string ModuleFilename = OutputFilename;
947 ModuleFilename += ".merged.bc";
948 std::string ErrMsg;
949
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000950 if (!CodeGen.writeMergedModules(ModuleFilename))
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000951 error("writing merged module failed.");
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000952 }
953
Reid Kleckner3fc649c2017-09-23 01:03:17 +0000954 std::list<ToolOutputFile> OSs;
Peter Collingbournec269ed52015-08-27 23:37:36 +0000955 std::vector<raw_pwrite_stream *> OSPtrs;
956 for (unsigned I = 0; I != Parallelism; ++I) {
957 std::string PartFilename = OutputFilename;
958 if (Parallelism != 1)
959 PartFilename += "." + utostr(I);
960 std::error_code EC;
961 OSs.emplace_back(PartFilename, EC, sys::fs::F_None);
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000962 if (EC)
963 error("error opening the file '" + PartFilename + "': " + EC.message());
Peter Collingbournec269ed52015-08-27 23:37:36 +0000964 OSPtrs.push_back(&OSs.back().os());
965 }
966
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000967 if (!CodeGen.compileOptimized(OSPtrs))
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000968 // Diagnostic messages should have been printed by the handler.
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000969 error("error compiling the code");
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000970
Reid Kleckner3fc649c2017-09-23 01:03:17 +0000971 for (ToolOutputFile &OS : OSs)
Peter Collingbournec269ed52015-08-27 23:37:36 +0000972 OS.keep();
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000973 } else {
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000974 if (Parallelism != 1)
975 error("-j must be specified together with -o");
Peter Collingbournec269ed52015-08-27 23:37:36 +0000976
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000977 if (SaveModuleFile)
978 error(": -save-merged-module must be specified with -o");
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000979
Craig Toppere6cb63e2014-04-25 04:24:47 +0000980 const char *OutputName = nullptr;
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000981 if (!CodeGen.compile_to_file(&OutputName, DisableVerify, DisableInline,
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000982 DisableGVNLoadPRE, DisableLTOVectorization))
983 error("error compiling the code");
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000984 // Diagnostic messages should have been printed by the handler.
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000985
986 outs() << "Wrote native object file '" << OutputName << "'\n";
987 }
988
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000989 return 0;
990}