blob: dd19424157c9edc2bb94dc3c7c06f0403d5667c9 [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 Blaikie4333f972018-04-11 18:49:37 +000025#include "llvm/CodeGen/CommandFlags.inc"
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"
Rui Ueyama197194b2018-04-13 18:26:06 +000043#include "llvm/Support/InitLLVM.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"
Mehdi Amini7c4a1a82016-03-09 01:37:22 +000046#include "llvm/Support/SourceMgr.h"
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +000047#include "llvm/Support/TargetSelect.h"
Peter Collingbournec269ed52015-08-27 23:37:36 +000048#include "llvm/Support/ToolOutputFile.h"
Chandler Carruth07baed52014-01-13 08:04:33 +000049#include "llvm/Support/raw_ostream.h"
Eugene Zelenko975293f2017-09-07 23:28:24 +000050#include "llvm/Target/TargetOptions.h"
51#include <algorithm>
52#include <cassert>
53#include <cstdint>
54#include <cstdlib>
Peter Collingbournec269ed52015-08-27 23:37:36 +000055#include <list>
Eugene Zelenko975293f2017-09-07 23:28:24 +000056#include <map>
57#include <memory>
58#include <string>
59#include <system_error>
60#include <tuple>
61#include <utility>
62#include <vector>
Peter Collingbourne4e380b02013-09-19 22:15:52 +000063
64using namespace llvm;
65
Peter Collingbourne070843d2015-03-19 22:01:00 +000066static cl::opt<char>
Davide Italianob10e8932016-04-13 21:41:35 +000067 OptLevel("O", cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
68 "(default = '-O2')"),
69 cl::Prefix, cl::ZeroOrMore, cl::init('2'));
Peter Collingbourne4e380b02013-09-19 22:15:52 +000070
Mehdi Amini06a47802016-09-14 21:04:59 +000071static cl::opt<bool>
72 IndexStats("thinlto-index-stats",
73 cl::desc("Print statistic for the index in every input files"),
74 cl::init(false));
75
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +000076static cl::opt<bool> DisableVerify(
77 "disable-verify", cl::init(false),
78 cl::desc("Do not run the verifier during the optimization pipeline"));
79
Davide Italianob10e8932016-04-13 21:41:35 +000080static cl::opt<bool> DisableInline("disable-inlining", cl::init(false),
81 cl::desc("Do not run the inliner pass"));
Rafael Espindola0b385c72013-09-30 16:39:19 +000082
83static cl::opt<bool>
Davide Italianob10e8932016-04-13 21:41:35 +000084 DisableGVNLoadPRE("disable-gvn-loadpre", cl::init(false),
85 cl::desc("Do not run the GVN load PRE pass"));
Rafael Espindola0b385c72013-09-30 16:39:19 +000086
Davide Italianob10e8932016-04-13 21:41:35 +000087static cl::opt<bool> DisableLTOVectorization(
88 "disable-lto-vectorization", cl::init(false),
89 cl::desc("Do not run loop or slp vectorization during LTO"));
Arnold Schwaighofereb1a38f2014-10-26 21:50:58 +000090
Mehdi Aminib5a46c12017-03-28 18:55:44 +000091static cl::opt<bool> EnableFreestanding(
92 "lto-freestanding", cl::init(false),
93 cl::desc("Enable Freestanding (disable builtins / TLI) during LTO"));
94
Davide Italianob10e8932016-04-13 21:41:35 +000095static cl::opt<bool> UseDiagnosticHandler(
96 "use-diagnostic-handler", cl::init(false),
97 cl::desc("Use a diagnostic handler to test the handler interface"));
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +000098
Teresa Johnsonf72278f2015-11-02 18:02:11 +000099static cl::opt<bool>
100 ThinLTO("thinlto", cl::init(false),
101 cl::desc("Only write combined global index for ThinLTO backends"));
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000102
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000103enum ThinLTOModes {
104 THINLINK,
Teresa Johnson84174c32016-05-10 13:48:23 +0000105 THINDISTRIBUTE,
Teresa Johnson8570fe42016-05-10 15:54:09 +0000106 THINEMITIMPORTS,
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000107 THINPROMOTE,
108 THINIMPORT,
Mehdi Amini059464f2016-04-24 03:18:01 +0000109 THININTERNALIZE,
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000110 THINOPT,
111 THINCODEGEN,
112 THINALL
113};
114
115cl::opt<ThinLTOModes> ThinLTOMode(
116 "thinlto-action", cl::desc("Perform a single ThinLTO stage:"),
117 cl::values(
118 clEnumValN(
119 THINLINK, "thinlink",
120 "ThinLink: produces the index by linking only the summaries."),
Teresa Johnson84174c32016-05-10 13:48:23 +0000121 clEnumValN(THINDISTRIBUTE, "distributedindexes",
122 "Produces individual indexes for distributed backends."),
Teresa Johnson8570fe42016-05-10 15:54:09 +0000123 clEnumValN(THINEMITIMPORTS, "emitimports",
124 "Emit imports files for distributed backends."),
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000125 clEnumValN(THINPROMOTE, "promote",
126 "Perform pre-import promotion (requires -thinlto-index)."),
127 clEnumValN(THINIMPORT, "import", "Perform both promotion and "
128 "cross-module importing (requires "
129 "-thinlto-index)."),
Mehdi Amini059464f2016-04-24 03:18:01 +0000130 clEnumValN(THININTERNALIZE, "internalize",
131 "Perform internalization driven by -exported-symbol "
132 "(requires -thinlto-index)."),
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000133 clEnumValN(THINOPT, "optimize", "Perform ThinLTO optimizations."),
134 clEnumValN(THINCODEGEN, "codegen", "CodeGen (expected to match llc)"),
Mehdi Amini732afdd2016-10-08 19:41:06 +0000135 clEnumValN(THINALL, "run", "Perform ThinLTO end-to-end")));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000136
137static cl::opt<std::string>
138 ThinLTOIndex("thinlto-index",
139 cl::desc("Provide the index produced by a ThinLink, required "
140 "to perform the promotion and/or importing."));
141
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000142static cl::opt<std::string> ThinLTOPrefixReplace(
143 "thinlto-prefix-replace",
144 cl::desc("Control where files for distributed backends are "
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000145 "created. Expects 'oldprefix;newprefix' and if path "
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000146 "prefix of output file is oldprefix it will be "
147 "replaced with newprefix."));
148
Mehdi Amini03abce92016-05-05 16:33:51 +0000149static cl::opt<std::string> ThinLTOModuleId(
150 "thinlto-module-id",
151 cl::desc("For the module ID for the file to process, useful to "
152 "match what is in the index."));
153
Mehdi Aminiab4a8b62016-05-14 05:16:41 +0000154static cl::opt<std::string>
155 ThinLTOCacheDir("thinlto-cache-dir", cl::desc("Enable ThinLTO caching."));
156
Ben Dunbobbin9ecb8b52017-12-19 14:42:38 +0000157static cl::opt<int>
Ekaterina Romanovad345f732018-02-15 23:29:21 +0000158 ThinLTOCachePruningInterval("thinlto-cache-pruning-interval",
159 cl::init(1200), cl::desc("Set ThinLTO cache pruning interval."));
Ben Dunbobbin9ecb8b52017-12-19 14:42:38 +0000160
James Hendersone29e4082018-09-17 10:21:26 +0000161static cl::opt<unsigned long long>
Ekaterina Romanovab8aeec42018-03-02 03:51:27 +0000162 ThinLTOCacheMaxSizeBytes("thinlto-cache-max-size-bytes",
163 cl::desc("Set ThinLTO cache pruning directory maximum size in bytes."));
164
165static cl::opt<int>
166 ThinLTOCacheMaxSizeFiles("thinlto-cache-max-size-files", cl::init(1000000),
167 cl::desc("Set ThinLTO cache pruning directory maximum number of files."));
168
James Henderson99031b72018-10-03 13:00:20 +0000169static cl::opt<unsigned>
170 ThinLTOCacheEntryExpiration("thinlto-cache-entry-expiration", cl::init(604800) /* 1w */,
171 cl::desc("Set ThinLTO cache entry expiration time."));
172
Teresa Johnsonc44a1222016-08-15 23:24:57 +0000173static cl::opt<std::string> ThinLTOSaveTempsPrefix(
174 "thinlto-save-temps",
175 cl::desc("Save ThinLTO temp files using filenames created by adding "
176 "suffixes to the given file path prefix."));
177
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000178static cl::opt<std::string> ThinLTOGeneratedObjectsDir(
179 "thinlto-save-objects",
180 cl::desc("Save ThinLTO generated object files using filenames created in "
181 "the given directory."));
182
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000183static cl::opt<bool>
Davide Italianob10e8932016-04-13 21:41:35 +0000184 SaveModuleFile("save-merged-module", cl::init(false),
185 cl::desc("Write merged LTO module to file before CodeGen"));
186
187static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
188 cl::desc("<input bitcode files>"));
189
190static cl::opt<std::string> OutputFilename("o", cl::init(""),
191 cl::desc("Override output filename"),
192 cl::value_desc("filename"));
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000193
Mehdi Amini059464f2016-04-24 03:18:01 +0000194static cl::list<std::string> ExportedSymbols(
195 "exported-symbol",
196 cl::desc("List of symbols to export from the resulting object file"),
197 cl::ZeroOrMore);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000198
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000199static cl::list<std::string>
Davide Italianob10e8932016-04-13 21:41:35 +0000200 DSOSymbols("dso-symbol",
201 cl::desc("Symbol to put in the symtab in the resulting dso"),
202 cl::ZeroOrMore);
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000203
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000204static cl::opt<bool> ListSymbolsOnly(
205 "list-symbols-only", cl::init(false),
206 cl::desc("Instead of running LTO, list the symbols in each IR file"));
207
Manman Ren6487ce92015-02-24 00:45:56 +0000208static cl::opt<bool> SetMergedModule(
209 "set-merged-module", cl::init(false),
210 cl::desc("Use the first input module as the merged module"));
211
Peter Collingbournec269ed52015-08-27 23:37:36 +0000212static cl::opt<unsigned> Parallelism("j", cl::Prefix, cl::init(1),
213 cl::desc("Number of backend threads"));
214
Tobias Edler von Koch3f4f6f3e2016-01-18 23:35:24 +0000215static cl::opt<bool> RestoreGlobalsLinkage(
216 "restore-linkage", cl::init(false),
217 cl::desc("Restore original linkage of globals prior to CodeGen"));
218
Mehdi Aminie75aa6f2016-07-11 23:10:18 +0000219static cl::opt<bool> CheckHasObjC(
220 "check-for-objc", cl::init(false),
221 cl::desc("Only check if the module has objective-C defined in it"));
222
Rafael Espindola282a4702013-10-31 20:51:58 +0000223namespace {
Eugene Zelenko975293f2017-09-07 23:28:24 +0000224
Rafael Espindola282a4702013-10-31 20:51:58 +0000225struct ModuleInfo {
226 std::vector<bool> CanBeHidden;
227};
Eugene Zelenko975293f2017-09-07 23:28:24 +0000228
229} // end anonymous namespace
Rafael Espindola282a4702013-10-31 20:51:58 +0000230
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000231static void handleDiagnostics(lto_codegen_diagnostic_severity_t Severity,
232 const char *Msg, void *) {
Yunzhong Gaoef436f02015-11-10 18:52:48 +0000233 errs() << "llvm-lto: ";
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +0000234 switch (Severity) {
235 case LTO_DS_NOTE:
236 errs() << "note: ";
237 break;
238 case LTO_DS_REMARK:
239 errs() << "remark: ";
240 break;
241 case LTO_DS_ERROR:
242 errs() << "error: ";
243 break;
244 case LTO_DS_WARNING:
245 errs() << "warning: ";
246 break;
247 }
248 errs() << Msg << "\n";
249}
250
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000251static std::string CurrentActivity;
Vivek Pandyab5ab8952017-09-15 20:10:09 +0000252
253namespace {
254 struct LLVMLTODiagnosticHandler : public DiagnosticHandler {
255 bool handleDiagnostics(const DiagnosticInfo &DI) override {
256 raw_ostream &OS = errs();
257 OS << "llvm-lto: ";
258 switch (DI.getSeverity()) {
259 case DS_Error:
260 OS << "error";
261 break;
262 case DS_Warning:
263 OS << "warning";
264 break;
265 case DS_Remark:
266 OS << "remark";
267 break;
268 case DS_Note:
269 OS << "note";
270 break;
271 }
272 if (!CurrentActivity.empty())
273 OS << ' ' << CurrentActivity;
274 OS << ": ";
275
276 DiagnosticPrinterRawOStream DP(OS);
277 DI.print(DP);
278 OS << '\n';
279
280 if (DI.getSeverity() == DS_Error)
281 exit(1);
282 return true;
283 }
284 };
Mehdi Amini354f5202015-11-19 05:52:29 +0000285 }
Mehdi Amini354f5202015-11-19 05:52:29 +0000286
Rafael Espindola5e128db2015-12-04 00:45:57 +0000287static void error(const Twine &Msg) {
288 errs() << "llvm-lto: " << Msg << '\n';
289 exit(1);
290}
291
292static void error(std::error_code EC, const Twine &Prefix) {
293 if (EC)
294 error(Prefix + ": " + EC.message());
295}
296
297template <typename T>
298static void error(const ErrorOr<T> &V, const Twine &Prefix) {
299 error(V.getError(), Prefix);
300}
301
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000302static void maybeVerifyModule(const Module &Mod) {
Mehdi Amini4c809462016-12-23 23:53:57 +0000303 if (!DisableVerify && verifyModule(Mod, &errs()))
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000304 error("Broken Module");
305}
306
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000307static std::unique_ptr<LTOModule>
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000308getLocalLTOModule(StringRef Path, std::unique_ptr<MemoryBuffer> &Buffer,
Rafael Espindola5e128db2015-12-04 00:45:57 +0000309 const TargetOptions &Options) {
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000310 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
311 MemoryBuffer::getFile(Path);
Rafael Espindola5e128db2015-12-04 00:45:57 +0000312 error(BufferOrErr, "error loading file '" + Path + "'");
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000313 Buffer = std::move(BufferOrErr.get());
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000314 CurrentActivity = ("loading file '" + Path + "'").str();
Petr Pavlu7ad9ec92016-03-01 13:13:49 +0000315 std::unique_ptr<LLVMContext> Context = llvm::make_unique<LLVMContext>();
Vivek Pandyab5ab8952017-09-15 20:10:09 +0000316 Context->setDiagnosticHandler(llvm::make_unique<LLVMLTODiagnosticHandler>(),
317 true);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000318 ErrorOr<std::unique_ptr<LTOModule>> Ret = LTOModule::createInLocalContext(
Petr Pavlu7ad9ec92016-03-01 13:13:49 +0000319 std::move(Context), Buffer->getBufferStart(), Buffer->getBufferSize(),
320 Options, Path);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000321 CurrentActivity = "";
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000322 maybeVerifyModule((*Ret)->getModule());
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000323 return std::move(*Ret);
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000324}
325
Mehdi Amini06a47802016-09-14 21:04:59 +0000326/// Print some statistics on the index for each input files.
327void printIndexStats() {
328 for (auto &Filename : InputFilenames) {
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000329 ExitOnError ExitOnErr("llvm-lto: error loading file '" + Filename + "': ");
330 std::unique_ptr<ModuleSummaryIndex> Index =
Eugene Zelenko975293f2017-09-07 23:28:24 +0000331 ExitOnErr(getModuleSummaryIndexForFile(Filename));
Mehdi Amini06a47802016-09-14 21:04:59 +0000332 // Skip files without a module summary.
333 if (!Index)
334 report_fatal_error(Filename + " does not contain an index");
335
336 unsigned Calls = 0, Refs = 0, Functions = 0, Alias = 0, Globals = 0;
337 for (auto &Summaries : *Index) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000338 for (auto &Summary : Summaries.second.SummaryList) {
Mehdi Amini06a47802016-09-14 21:04:59 +0000339 Refs += Summary->refs().size();
340 if (auto *FuncSummary = dyn_cast<FunctionSummary>(Summary.get())) {
341 Functions++;
342 Calls += FuncSummary->calls().size();
343 } else if (isa<AliasSummary>(Summary.get()))
344 Alias++;
345 else
346 Globals++;
347 }
348 }
349 outs() << "Index " << Filename << " contains "
350 << (Alias + Globals + Functions) << " nodes (" << Functions
351 << " functions, " << Alias << " alias, " << Globals
352 << " globals) and " << (Calls + Refs) << " edges (" << Refs
353 << " refs and " << Calls << " calls)\n";
354 }
355}
356
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000357/// List symbols in each IR file.
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000358///
359/// The main point here is to provide lit-testable coverage for the LTOModule
360/// functionality that's exposed by the C API to list symbols. Moreover, this
361/// provides testing coverage for modules that have been created in their own
362/// contexts.
Rafael Espindola5e128db2015-12-04 00:45:57 +0000363static void listSymbols(const TargetOptions &Options) {
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000364 for (auto &Filename : InputFilenames) {
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000365 std::unique_ptr<MemoryBuffer> Buffer;
366 std::unique_ptr<LTOModule> Module =
Rafael Espindola5e128db2015-12-04 00:45:57 +0000367 getLocalLTOModule(Filename, Buffer, Options);
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000368
369 // List the symbols.
370 outs() << Filename << ":\n";
371 for (int I = 0, E = Module->getSymbolCount(); I != E; ++I)
372 outs() << Module->getSymbolName(I) << "\n";
373 }
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000374}
375
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000376/// Create a combined index file from the input IR files and write it.
377///
378/// This is meant to enable testing of ThinLTO combined index generation,
379/// currently available via the gold plugin via -thinlto.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000380static void createCombinedModuleSummaryIndex() {
Teresa Johnson4ffc3e72018-06-06 22:22:01 +0000381 ModuleSummaryIndex CombinedIndex(/*HaveGVs=*/false);
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000382 uint64_t NextModuleId = 0;
383 for (auto &Filename : InputFilenames) {
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000384 ExitOnError ExitOnErr("llvm-lto: error loading file '" + Filename + "': ");
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000385 std::unique_ptr<MemoryBuffer> MB =
386 ExitOnErr(errorOrToExpected(MemoryBuffer::getFileOrSTDIN(Filename)));
Teresa Johnson43e71ec42018-05-16 14:58:14 +0000387 ExitOnErr(readModuleSummaryIndex(*MB, CombinedIndex, NextModuleId++));
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000388 }
389 std::error_code EC;
390 assert(!OutputFilename.empty());
391 raw_fd_ostream OS(OutputFilename + ".thinlto.bc", EC,
392 sys::fs::OpenFlags::F_None);
Rafael Espindola5e128db2015-12-04 00:45:57 +0000393 error(EC, "error opening the file '" + OutputFilename + ".thinlto.bc'");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000394 WriteIndexToFile(CombinedIndex, OS);
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000395 OS.close();
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000396}
397
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000398/// Parse the thinlto_prefix_replace option into the \p OldPrefix and
399/// \p NewPrefix strings, if it was specified.
400static void getThinLTOOldAndNewPrefix(std::string &OldPrefix,
401 std::string &NewPrefix) {
402 assert(ThinLTOPrefixReplace.empty() ||
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000403 ThinLTOPrefixReplace.find(";") != StringRef::npos);
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000404 StringRef PrefixReplace = ThinLTOPrefixReplace;
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000405 std::pair<StringRef, StringRef> Split = PrefixReplace.split(";");
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000406 OldPrefix = Split.first.str();
407 NewPrefix = Split.second.str();
408}
409
410/// Given the original \p Path to an output file, replace any path
411/// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
412/// resulting directory if it does not yet exist.
413static std::string getThinLTOOutputFile(const std::string &Path,
414 const std::string &OldPrefix,
415 const std::string &NewPrefix) {
416 if (OldPrefix.empty() && NewPrefix.empty())
417 return Path;
418 SmallString<128> NewPath(Path);
419 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
420 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
421 if (!ParentPath.empty()) {
422 // Make sure the new directory exists, creating it if necessary.
423 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
424 error(EC, "error creating the directory '" + ParentPath + "'");
425 }
426 return NewPath.str();
427}
428
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000429namespace thinlto {
430
431std::vector<std::unique_ptr<MemoryBuffer>>
Teresa Johnson26ab5772016-03-15 00:04:37 +0000432loadAllFilesForIndex(const ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000433 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
434
Mehdi Amini385cf282016-03-26 03:35:38 +0000435 for (auto &ModPath : Index.modulePaths()) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000436 const auto &Filename = ModPath.first();
Alexander Kornienko656466e2017-07-04 15:13:02 +0000437 std::string CurrentActivity = ("loading file '" + Filename + "'").str();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000438 auto InputOrErr = MemoryBuffer::getFile(Filename);
439 error(InputOrErr, "error " + CurrentActivity);
440 InputBuffers.push_back(std::move(*InputOrErr));
441 }
442 return InputBuffers;
443}
444
Teresa Johnson26ab5772016-03-15 00:04:37 +0000445std::unique_ptr<ModuleSummaryIndex> loadCombinedIndex() {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000446 if (ThinLTOIndex.empty())
447 report_fatal_error("Missing -thinlto-index for ThinLTO promotion stage");
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000448 ExitOnError ExitOnErr("llvm-lto: error loading file '" + ThinLTOIndex +
449 "': ");
Eugene Zelenko975293f2017-09-07 23:28:24 +0000450 return ExitOnErr(getModuleSummaryIndexForFile(ThinLTOIndex));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000451}
452
453static std::unique_ptr<Module> loadModule(StringRef Filename,
454 LLVMContext &Ctx) {
455 SMDiagnostic Err;
456 std::unique_ptr<Module> M(parseIRFile(Filename, Err, Ctx));
457 if (!M) {
458 Err.print("llvm-lto", errs());
459 report_fatal_error("Can't load module for file " + Filename);
460 }
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000461 maybeVerifyModule(*M);
Mehdi Amini03abce92016-05-05 16:33:51 +0000462
463 if (ThinLTOModuleId.getNumOccurrences()) {
464 if (InputFilenames.size() != 1)
465 report_fatal_error("Can't override the module id for multiple files");
466 M->setModuleIdentifier(ThinLTOModuleId);
467 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000468 return M;
469}
470
471static void writeModuleToFile(Module &TheModule, StringRef Filename) {
472 std::error_code EC;
473 raw_fd_ostream OS(Filename, EC, sys::fs::OpenFlags::F_None);
474 error(EC, "error opening the file '" + Filename + "'");
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000475 maybeVerifyModule(TheModule);
Rafael Espindola6a86e252018-02-14 19:11:32 +0000476 WriteBitcodeToFile(TheModule, OS, /* ShouldPreserveUseListOrder */ true);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000477}
478
479class ThinLTOProcessing {
480public:
481 ThinLTOCodeGenerator ThinGenerator;
482
483 ThinLTOProcessing(const TargetOptions &Options) {
Rafael Espindola8c34dd82016-05-18 22:04:49 +0000484 ThinGenerator.setCodePICModel(getRelocModel());
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000485 ThinGenerator.setTargetOptions(Options);
Mehdi Aminiab4a8b62016-05-14 05:16:41 +0000486 ThinGenerator.setCacheDir(ThinLTOCacheDir);
Ben Dunbobbin9ecb8b52017-12-19 14:42:38 +0000487 ThinGenerator.setCachePruningInterval(ThinLTOCachePruningInterval);
James Henderson99031b72018-10-03 13:00:20 +0000488 ThinGenerator.setCacheEntryExpiration(ThinLTOCacheEntryExpiration);
Ekaterina Romanovab8aeec42018-03-02 03:51:27 +0000489 ThinGenerator.setCacheMaxSizeFiles(ThinLTOCacheMaxSizeFiles);
490 ThinGenerator.setCacheMaxSizeBytes(ThinLTOCacheMaxSizeBytes);
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000491 ThinGenerator.setFreestanding(EnableFreestanding);
Mehdi Amini059464f2016-04-24 03:18:01 +0000492
493 // Add all the exported symbols to the table of symbols to preserve.
494 for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
495 ThinGenerator.preserveSymbol(ExportedSymbols[i]);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000496 }
497
498 void run() {
499 switch (ThinLTOMode) {
500 case THINLINK:
501 return thinLink();
Teresa Johnson84174c32016-05-10 13:48:23 +0000502 case THINDISTRIBUTE:
503 return distributedIndexes();
Teresa Johnson8570fe42016-05-10 15:54:09 +0000504 case THINEMITIMPORTS:
505 return emitImports();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000506 case THINPROMOTE:
507 return promote();
508 case THINIMPORT:
509 return import();
Mehdi Amini059464f2016-04-24 03:18:01 +0000510 case THININTERNALIZE:
511 return internalize();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000512 case THINOPT:
513 return optimize();
514 case THINCODEGEN:
515 return codegen();
516 case THINALL:
517 return runAll();
518 }
519 }
520
521private:
522 /// Load the input files, create the combined index, and write it out.
523 void thinLink() {
524 // Perform "ThinLink": just produce the index
525 if (OutputFilename.empty())
526 report_fatal_error(
527 "OutputFilename is necessary to store the combined index.\n");
528
529 LLVMContext Ctx;
530 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
531 for (unsigned i = 0; i < InputFilenames.size(); ++i) {
532 auto &Filename = InputFilenames[i];
Alexander Kornienko656466e2017-07-04 15:13:02 +0000533 std::string CurrentActivity = "loading file '" + Filename + "'";
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000534 auto InputOrErr = MemoryBuffer::getFile(Filename);
535 error(InputOrErr, "error " + CurrentActivity);
536 InputBuffers.push_back(std::move(*InputOrErr));
537 ThinGenerator.addModule(Filename, InputBuffers.back()->getBuffer());
538 }
539
540 auto CombinedIndex = ThinGenerator.linkCombinedIndex();
Mehdi Amini00fa1402016-10-08 04:44:18 +0000541 if (!CombinedIndex)
542 report_fatal_error("ThinLink didn't create an index");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000543 std::error_code EC;
544 raw_fd_ostream OS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
545 error(EC, "error opening the file '" + OutputFilename + "'");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000546 WriteIndexToFile(*CombinedIndex, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000547 }
548
Teresa Johnson84174c32016-05-10 13:48:23 +0000549 /// Load the combined index from disk, then compute and generate
550 /// individual index files suitable for ThinLTO distributed backend builds
551 /// on the files mentioned on the command line (these must match the index
552 /// content).
553 void distributedIndexes() {
554 if (InputFilenames.size() != 1 && !OutputFilename.empty())
555 report_fatal_error("Can't handle a single output filename and multiple "
556 "input files, do not provide an output filename and "
557 "the output files will be suffixed from the input "
558 "ones.");
559
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000560 std::string OldPrefix, NewPrefix;
561 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
562
Teresa Johnson84174c32016-05-10 13:48:23 +0000563 auto Index = loadCombinedIndex();
564 for (auto &Filename : InputFilenames) {
565 // Build a map of module to the GUIDs and summary objects that should
566 // be written to its index.
567 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
568 ThinLTOCodeGenerator::gatherImportedSummariesForModule(
569 Filename, *Index, ModuleToSummariesForIndex);
570
571 std::string OutputName = OutputFilename;
572 if (OutputName.empty()) {
573 OutputName = Filename + ".thinlto.bc";
574 }
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000575 OutputName = getThinLTOOutputFile(OutputName, OldPrefix, NewPrefix);
Teresa Johnson84174c32016-05-10 13:48:23 +0000576 std::error_code EC;
577 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::F_None);
578 error(EC, "error opening the file '" + OutputName + "'");
579 WriteIndexToFile(*Index, OS, &ModuleToSummariesForIndex);
580 }
581 }
582
Teresa Johnson8570fe42016-05-10 15:54:09 +0000583 /// Load the combined index from disk, compute the imports, and emit
584 /// the import file lists for each module to disk.
585 void emitImports() {
586 if (InputFilenames.size() != 1 && !OutputFilename.empty())
587 report_fatal_error("Can't handle a single output filename and multiple "
588 "input files, do not provide an output filename and "
589 "the output files will be suffixed from the input "
590 "ones.");
591
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000592 std::string OldPrefix, NewPrefix;
593 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
594
Teresa Johnson8570fe42016-05-10 15:54:09 +0000595 auto Index = loadCombinedIndex();
596 for (auto &Filename : InputFilenames) {
597 std::string OutputName = OutputFilename;
598 if (OutputName.empty()) {
599 OutputName = Filename + ".imports";
600 }
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000601 OutputName = getThinLTOOutputFile(OutputName, OldPrefix, NewPrefix);
Teresa Johnson8570fe42016-05-10 15:54:09 +0000602 ThinLTOCodeGenerator::emitImports(Filename, OutputName, *Index);
603 }
604 }
605
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000606 /// Load the combined index from disk, then load every file referenced by
607 /// the index and add them to the generator, finally perform the promotion
608 /// on the files mentioned on the command line (these must match the index
609 /// content).
610 void promote() {
611 if (InputFilenames.size() != 1 && !OutputFilename.empty())
612 report_fatal_error("Can't handle a single output filename and multiple "
613 "input files, do not provide an output filename and "
614 "the output files will be suffixed from the input "
615 "ones.");
616
617 auto Index = loadCombinedIndex();
618 for (auto &Filename : InputFilenames) {
619 LLVMContext Ctx;
620 auto TheModule = loadModule(Filename, Ctx);
621
622 ThinGenerator.promote(*TheModule, *Index);
623
624 std::string OutputName = OutputFilename;
625 if (OutputName.empty()) {
626 OutputName = Filename + ".thinlto.promoted.bc";
627 }
628 writeModuleToFile(*TheModule, OutputName);
629 }
630 }
631
632 /// Load the combined index from disk, then load every file referenced by
633 /// the index and add them to the generator, then performs the promotion and
634 /// cross module importing on the files mentioned on the command line
635 /// (these must match the index content).
636 void import() {
637 if (InputFilenames.size() != 1 && !OutputFilename.empty())
638 report_fatal_error("Can't handle a single output filename and multiple "
639 "input files, do not provide an output filename and "
640 "the output files will be suffixed from the input "
641 "ones.");
642
643 auto Index = loadCombinedIndex();
644 auto InputBuffers = loadAllFilesForIndex(*Index);
645 for (auto &MemBuffer : InputBuffers)
646 ThinGenerator.addModule(MemBuffer->getBufferIdentifier(),
647 MemBuffer->getBuffer());
648
649 for (auto &Filename : InputFilenames) {
650 LLVMContext Ctx;
651 auto TheModule = loadModule(Filename, Ctx);
652
653 ThinGenerator.crossModuleImport(*TheModule, *Index);
654
655 std::string OutputName = OutputFilename;
656 if (OutputName.empty()) {
657 OutputName = Filename + ".thinlto.imported.bc";
658 }
659 writeModuleToFile(*TheModule, OutputName);
660 }
661 }
662
Mehdi Amini059464f2016-04-24 03:18:01 +0000663 void internalize() {
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
670 if (ExportedSymbols.empty())
671 errs() << "Warning: -internalize will not perform without "
672 "-exported-symbol\n";
673
674 auto Index = loadCombinedIndex();
675 auto InputBuffers = loadAllFilesForIndex(*Index);
676 for (auto &MemBuffer : InputBuffers)
677 ThinGenerator.addModule(MemBuffer->getBufferIdentifier(),
678 MemBuffer->getBuffer());
679
680 for (auto &Filename : InputFilenames) {
681 LLVMContext Ctx;
682 auto TheModule = loadModule(Filename, Ctx);
683
684 ThinGenerator.internalize(*TheModule, *Index);
685
686 std::string OutputName = OutputFilename;
687 if (OutputName.empty()) {
688 OutputName = Filename + ".thinlto.internalized.bc";
689 }
690 writeModuleToFile(*TheModule, OutputName);
691 }
692 }
693
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000694 void optimize() {
695 if (InputFilenames.size() != 1 && !OutputFilename.empty())
696 report_fatal_error("Can't handle a single output filename and multiple "
697 "input files, do not provide an output filename and "
698 "the output files will be suffixed from the input "
699 "ones.");
700 if (!ThinLTOIndex.empty())
701 errs() << "Warning: -thinlto-index ignored for optimize stage";
702
703 for (auto &Filename : InputFilenames) {
704 LLVMContext Ctx;
705 auto TheModule = loadModule(Filename, Ctx);
706
707 ThinGenerator.optimize(*TheModule);
708
709 std::string OutputName = OutputFilename;
710 if (OutputName.empty()) {
711 OutputName = Filename + ".thinlto.imported.bc";
712 }
713 writeModuleToFile(*TheModule, OutputName);
714 }
715 }
716
717 void codegen() {
718 if (InputFilenames.size() != 1 && !OutputFilename.empty())
719 report_fatal_error("Can't handle a single output filename and multiple "
720 "input files, do not provide an output filename and "
721 "the output files will be suffixed from the input "
722 "ones.");
723 if (!ThinLTOIndex.empty())
724 errs() << "Warning: -thinlto-index ignored for codegen stage";
725
Adrian Prantlcdd785b2017-05-19 17:54:58 +0000726 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000727 for (auto &Filename : InputFilenames) {
728 LLVMContext Ctx;
Adrian Prantlcdd785b2017-05-19 17:54:58 +0000729 auto InputOrErr = MemoryBuffer::getFile(Filename);
730 error(InputOrErr, "error " + CurrentActivity);
731 InputBuffers.push_back(std::move(*InputOrErr));
732 ThinGenerator.addModule(Filename, InputBuffers.back()->getBuffer());
733 }
734 ThinGenerator.setCodeGenOnly(true);
735 ThinGenerator.run();
736 for (auto BinName :
737 zip(ThinGenerator.getProducedBinaries(), InputFilenames)) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000738 std::string OutputName = OutputFilename;
Adrian Prantlcdd785b2017-05-19 17:54:58 +0000739 if (OutputName.empty())
740 OutputName = std::get<1>(BinName) + ".thinlto.o";
741 else if (OutputName == "-") {
742 outs() << std::get<0>(BinName)->getBuffer();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000743 return;
744 }
745
746 std::error_code EC;
747 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::F_None);
748 error(EC, "error opening the file '" + OutputName + "'");
Adrian Prantlcdd785b2017-05-19 17:54:58 +0000749 OS << std::get<0>(BinName)->getBuffer();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000750 }
751 }
752
753 /// Full ThinLTO process
754 void runAll() {
755 if (!OutputFilename.empty())
756 report_fatal_error("Do not provide an output filename for ThinLTO "
757 " processing, the output files will be suffixed from "
758 "the input ones.");
759
760 if (!ThinLTOIndex.empty())
761 errs() << "Warning: -thinlto-index ignored for full ThinLTO process";
762
763 LLVMContext Ctx;
764 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
765 for (unsigned i = 0; i < InputFilenames.size(); ++i) {
766 auto &Filename = InputFilenames[i];
Alexander Kornienko656466e2017-07-04 15:13:02 +0000767 std::string CurrentActivity = "loading file '" + Filename + "'";
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000768 auto InputOrErr = MemoryBuffer::getFile(Filename);
769 error(InputOrErr, "error " + CurrentActivity);
770 InputBuffers.push_back(std::move(*InputOrErr));
771 ThinGenerator.addModule(Filename, InputBuffers.back()->getBuffer());
772 }
773
Teresa Johnsonc44a1222016-08-15 23:24:57 +0000774 if (!ThinLTOSaveTempsPrefix.empty())
775 ThinGenerator.setSaveTempsDir(ThinLTOSaveTempsPrefix);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000776
777 if (!ThinLTOGeneratedObjectsDir.empty()) {
778 ThinGenerator.setGeneratedObjectsDirectory(ThinLTOGeneratedObjectsDir);
779 ThinGenerator.run();
780 return;
781 }
782
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000783 ThinGenerator.run();
784
785 auto &Binaries = ThinGenerator.getProducedBinaries();
786 if (Binaries.size() != InputFilenames.size())
787 report_fatal_error("Number of output objects does not match the number "
788 "of inputs");
789
790 for (unsigned BufID = 0; BufID < Binaries.size(); ++BufID) {
791 auto OutputName = InputFilenames[BufID] + ".thinlto.o";
792 std::error_code EC;
793 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::F_None);
794 error(EC, "error opening the file '" + OutputName + "'");
795 OS << Binaries[BufID]->getBuffer();
796 }
797 }
798
799 /// Load the combined index from disk, then load every file referenced by
800};
801
Eugene Zelenko975293f2017-09-07 23:28:24 +0000802} // end namespace thinlto
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000803
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000804int main(int argc, char **argv) {
Rui Ueyama197194b2018-04-13 18:26:06 +0000805 InitLLVM X(argc, argv);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000806 cl::ParseCommandLineOptions(argc, argv, "llvm LTO linker\n");
807
Rafael Espindola5e128db2015-12-04 00:45:57 +0000808 if (OptLevel < '0' || OptLevel > '3')
809 error("optimization level must be between 0 and 3");
Peter Collingbourne070843d2015-03-19 22:01:00 +0000810
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000811 // Initialize the configured targets.
812 InitializeAllTargets();
813 InitializeAllTargetMCs();
814 InitializeAllAsmPrinters();
815 InitializeAllAsmParsers();
816
Rafael Espindola0b385c72013-09-30 16:39:19 +0000817 // set up the TargetOptions for the machine
Eli Benderskyf0f21002014-02-19 17:09:35 +0000818 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
Rafael Espindola0b385c72013-09-30 16:39:19 +0000819
Rafael Espindola5e128db2015-12-04 00:45:57 +0000820 if (ListSymbolsOnly) {
821 listSymbols(Options);
822 return 0;
823 }
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000824
Mehdi Amini06a47802016-09-14 21:04:59 +0000825 if (IndexStats) {
826 printIndexStats();
827 return 0;
828 }
829
Mehdi Aminie75aa6f2016-07-11 23:10:18 +0000830 if (CheckHasObjC) {
831 for (auto &Filename : InputFilenames) {
Peter Collingbournecd513a42016-11-11 19:50:24 +0000832 ExitOnError ExitOnErr(std::string(*argv) + ": error loading file '" +
833 Filename + "': ");
834 std::unique_ptr<MemoryBuffer> BufferOrErr =
835 ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(Filename)));
Mehdi Aminie75aa6f2016-07-11 23:10:18 +0000836 auto Buffer = std::move(BufferOrErr.get());
Eugene Zelenko975293f2017-09-07 23:28:24 +0000837 if (ExitOnErr(isBitcodeContainingObjCCategory(*Buffer)))
Mehdi Aminie75aa6f2016-07-11 23:10:18 +0000838 outs() << "Bitcode " << Filename << " contains ObjC\n";
839 else
840 outs() << "Bitcode " << Filename << " does not contain ObjC\n";
841 }
842 return 0;
843 }
844
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000845 if (ThinLTOMode.getNumOccurrences()) {
846 if (ThinLTOMode.getNumOccurrences() > 1)
847 report_fatal_error("You can't specify more than one -thinlto-action");
848 thinlto::ThinLTOProcessing ThinLTOProcessor(Options);
849 ThinLTOProcessor.run();
850 return 0;
851 }
852
Rafael Espindola5e128db2015-12-04 00:45:57 +0000853 if (ThinLTO) {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000854 createCombinedModuleSummaryIndex();
Rafael Espindola5e128db2015-12-04 00:45:57 +0000855 return 0;
856 }
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000857
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000858 unsigned BaseArg = 0;
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000859
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000860 LLVMContext Context;
Vivek Pandyab5ab8952017-09-15 20:10:09 +0000861 Context.setDiagnosticHandler(llvm::make_unique<LLVMLTODiagnosticHandler>(),
862 true);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000863
864 LTOCodeGenerator CodeGen(Context);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000865
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +0000866 if (UseDiagnosticHandler)
867 CodeGen.setDiagnosticHandler(handleDiagnostics, nullptr);
868
Rafael Espindola8c34dd82016-05-18 22:04:49 +0000869 CodeGen.setCodePICModel(getRelocModel());
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000870 CodeGen.setFreestanding(EnableFreestanding);
James Molloy951e5292014-04-14 13:54:16 +0000871
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000872 CodeGen.setDebugInfo(LTO_DEBUG_MODEL_DWARF);
Rafael Espindola0b385c72013-09-30 16:39:19 +0000873 CodeGen.setTargetOptions(Options);
Tobias Edler von Koch3f4f6f3e2016-01-18 23:35:24 +0000874 CodeGen.setShouldRestoreGlobalsLinkage(RestoreGlobalsLinkage);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000875
Eugene Zelenko975293f2017-09-07 23:28:24 +0000876 StringSet<MallocAllocator> DSOSymbolsSet;
Rafael Espindola282a4702013-10-31 20:51:58 +0000877 for (unsigned i = 0; i < DSOSymbols.size(); ++i)
878 DSOSymbolsSet.insert(DSOSymbols[i]);
879
880 std::vector<std::string> KeptDSOSyms;
881
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000882 for (unsigned i = BaseArg; i < InputFilenames.size(); ++i) {
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000883 CurrentActivity = "loading file '" + InputFilenames[i] + "'";
884 ErrorOr<std::unique_ptr<LTOModule>> ModuleOrErr =
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000885 LTOModule::createFromFile(Context, InputFilenames[i], Options);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000886 std::unique_ptr<LTOModule> &Module = *ModuleOrErr;
887 CurrentActivity = "";
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000888
Peter Collingbourne552174392015-08-21 19:09:42 +0000889 unsigned NumSyms = Module->getSymbolCount();
890 for (unsigned I = 0; I < NumSyms; ++I) {
891 StringRef Name = Module->getSymbolName(I);
892 if (!DSOSymbolsSet.count(Name))
893 continue;
894 lto_symbol_attributes Attrs = Module->getSymbolAttributes(I);
895 unsigned Scope = Attrs & LTO_SYMBOL_SCOPE_MASK;
896 if (Scope != LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN)
897 KeptDSOSyms.push_back(Name);
898 }
Manman Ren6487ce92015-02-24 00:45:56 +0000899
900 // We use the first input module as the destination module when
901 // SetMergedModule is true.
902 if (SetMergedModule && i == BaseArg) {
903 // Transfer ownership to the code generator.
Peter Collingbourne9c8909d2015-08-24 22:22:53 +0000904 CodeGen.setModule(std::move(Module));
Yunzhong Gao46261a72015-09-11 20:01:53 +0000905 } else if (!CodeGen.addModule(Module.get())) {
906 // Print a message here so that we know addModule() did not abort.
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000907 error("error adding file '" + InputFilenames[i] + "'");
Yunzhong Gao46261a72015-09-11 20:01:53 +0000908 }
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000909 }
910
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000911 // Add all the exported symbols to the table of symbols to preserve.
912 for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000913 CodeGen.addMustPreserveSymbol(ExportedSymbols[i]);
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000914
Rafael Espindolacda29112013-10-03 18:29:09 +0000915 // Add all the dso symbols to the table of symbols to expose.
Rafael Espindola282a4702013-10-31 20:51:58 +0000916 for (unsigned i = 0; i < KeptDSOSyms.size(); ++i)
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000917 CodeGen.addMustPreserveSymbol(KeptDSOSyms[i]);
Rafael Espindolacda29112013-10-03 18:29:09 +0000918
Akira Hatanaka23b5f672015-01-30 01:14:28 +0000919 // Set cpu and attrs strings for the default target/subtarget.
920 CodeGen.setCpu(MCPU.c_str());
921
Peter Collingbourne070843d2015-03-19 22:01:00 +0000922 CodeGen.setOptLevel(OptLevel - '0');
923
Tom Roederfd1bc602014-04-25 21:46:51 +0000924 std::string attrs;
925 for (unsigned i = 0; i < MAttrs.size(); ++i) {
926 if (i > 0)
927 attrs.append(",");
928 attrs.append(MAttrs[i]);
929 }
930
931 if (!attrs.empty())
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000932 CodeGen.setAttr(attrs);
Tom Roederfd1bc602014-04-25 21:46:51 +0000933
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000934 if (FileType.getNumOccurrences())
935 CodeGen.setFileType(FileType);
936
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000937 if (!OutputFilename.empty()) {
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000938 if (!CodeGen.optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000939 DisableLTOVectorization)) {
940 // Diagnostic messages should have been printed by the handler.
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000941 error("error optimizing the code");
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000942 }
943
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000944 if (SaveModuleFile) {
945 std::string ModuleFilename = OutputFilename;
946 ModuleFilename += ".merged.bc";
947 std::string ErrMsg;
948
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000949 if (!CodeGen.writeMergedModules(ModuleFilename))
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000950 error("writing merged module failed.");
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000951 }
952
Reid Kleckner3fc649c2017-09-23 01:03:17 +0000953 std::list<ToolOutputFile> OSs;
Peter Collingbournec269ed52015-08-27 23:37:36 +0000954 std::vector<raw_pwrite_stream *> OSPtrs;
955 for (unsigned I = 0; I != Parallelism; ++I) {
956 std::string PartFilename = OutputFilename;
957 if (Parallelism != 1)
958 PartFilename += "." + utostr(I);
959 std::error_code EC;
960 OSs.emplace_back(PartFilename, EC, sys::fs::F_None);
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000961 if (EC)
962 error("error opening the file '" + PartFilename + "': " + EC.message());
Peter Collingbournec269ed52015-08-27 23:37:36 +0000963 OSPtrs.push_back(&OSs.back().os());
964 }
965
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000966 if (!CodeGen.compileOptimized(OSPtrs))
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000967 // Diagnostic messages should have been printed by the handler.
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000968 error("error compiling the code");
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000969
Reid Kleckner3fc649c2017-09-23 01:03:17 +0000970 for (ToolOutputFile &OS : OSs)
Peter Collingbournec269ed52015-08-27 23:37:36 +0000971 OS.keep();
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000972 } else {
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000973 if (Parallelism != 1)
974 error("-j must be specified together with -o");
Peter Collingbournec269ed52015-08-27 23:37:36 +0000975
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000976 if (SaveModuleFile)
977 error(": -save-merged-module must be specified with -o");
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000978
Craig Toppere6cb63e2014-04-25 04:24:47 +0000979 const char *OutputName = nullptr;
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000980 if (!CodeGen.compile_to_file(&OutputName, DisableVerify, DisableInline,
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000981 DisableGVNLoadPRE, DisableLTOVectorization))
982 error("error compiling the code");
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000983 // Diagnostic messages should have been printed by the handler.
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000984
985 outs() << "Wrote native object file '" << OutputName << "'\n";
986 }
987
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000988 return 0;
989}