blob: 9e5458f4ad91869f58c55d228bdada9a0d44a8af [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
Teresa Johnsonc44a1222016-08-15 23:24:57 +0000163static cl::opt<std::string> ThinLTOSaveTempsPrefix(
164 "thinlto-save-temps",
165 cl::desc("Save ThinLTO temp files using filenames created by adding "
166 "suffixes to the given file path prefix."));
167
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000168static cl::opt<std::string> ThinLTOGeneratedObjectsDir(
169 "thinlto-save-objects",
170 cl::desc("Save ThinLTO generated object files using filenames created in "
171 "the given directory."));
172
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000173static cl::opt<bool>
Davide Italianob10e8932016-04-13 21:41:35 +0000174 SaveModuleFile("save-merged-module", cl::init(false),
175 cl::desc("Write merged LTO module to file before CodeGen"));
176
177static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore,
178 cl::desc("<input bitcode files>"));
179
180static cl::opt<std::string> OutputFilename("o", cl::init(""),
181 cl::desc("Override output filename"),
182 cl::value_desc("filename"));
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000183
Mehdi Amini059464f2016-04-24 03:18:01 +0000184static cl::list<std::string> ExportedSymbols(
185 "exported-symbol",
186 cl::desc("List of symbols to export from the resulting object file"),
187 cl::ZeroOrMore);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000188
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000189static cl::list<std::string>
Davide Italianob10e8932016-04-13 21:41:35 +0000190 DSOSymbols("dso-symbol",
191 cl::desc("Symbol to put in the symtab in the resulting dso"),
192 cl::ZeroOrMore);
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000193
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000194static cl::opt<bool> ListSymbolsOnly(
195 "list-symbols-only", cl::init(false),
196 cl::desc("Instead of running LTO, list the symbols in each IR file"));
197
Manman Ren6487ce92015-02-24 00:45:56 +0000198static cl::opt<bool> SetMergedModule(
199 "set-merged-module", cl::init(false),
200 cl::desc("Use the first input module as the merged module"));
201
Peter Collingbournec269ed52015-08-27 23:37:36 +0000202static cl::opt<unsigned> Parallelism("j", cl::Prefix, cl::init(1),
203 cl::desc("Number of backend threads"));
204
Tobias Edler von Koch3f4f6f3e2016-01-18 23:35:24 +0000205static cl::opt<bool> RestoreGlobalsLinkage(
206 "restore-linkage", cl::init(false),
207 cl::desc("Restore original linkage of globals prior to CodeGen"));
208
Mehdi Aminie75aa6f2016-07-11 23:10:18 +0000209static cl::opt<bool> CheckHasObjC(
210 "check-for-objc", cl::init(false),
211 cl::desc("Only check if the module has objective-C defined in it"));
212
Rafael Espindola282a4702013-10-31 20:51:58 +0000213namespace {
Eugene Zelenko975293f2017-09-07 23:28:24 +0000214
Rafael Espindola282a4702013-10-31 20:51:58 +0000215struct ModuleInfo {
216 std::vector<bool> CanBeHidden;
217};
Eugene Zelenko975293f2017-09-07 23:28:24 +0000218
219} // end anonymous namespace
Rafael Espindola282a4702013-10-31 20:51:58 +0000220
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000221static void handleDiagnostics(lto_codegen_diagnostic_severity_t Severity,
222 const char *Msg, void *) {
Yunzhong Gaoef436f02015-11-10 18:52:48 +0000223 errs() << "llvm-lto: ";
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +0000224 switch (Severity) {
225 case LTO_DS_NOTE:
226 errs() << "note: ";
227 break;
228 case LTO_DS_REMARK:
229 errs() << "remark: ";
230 break;
231 case LTO_DS_ERROR:
232 errs() << "error: ";
233 break;
234 case LTO_DS_WARNING:
235 errs() << "warning: ";
236 break;
237 }
238 errs() << Msg << "\n";
239}
240
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000241static std::string CurrentActivity;
Vivek Pandyab5ab8952017-09-15 20:10:09 +0000242
243namespace {
244 struct LLVMLTODiagnosticHandler : public DiagnosticHandler {
245 bool handleDiagnostics(const DiagnosticInfo &DI) override {
246 raw_ostream &OS = errs();
247 OS << "llvm-lto: ";
248 switch (DI.getSeverity()) {
249 case DS_Error:
250 OS << "error";
251 break;
252 case DS_Warning:
253 OS << "warning";
254 break;
255 case DS_Remark:
256 OS << "remark";
257 break;
258 case DS_Note:
259 OS << "note";
260 break;
261 }
262 if (!CurrentActivity.empty())
263 OS << ' ' << CurrentActivity;
264 OS << ": ";
265
266 DiagnosticPrinterRawOStream DP(OS);
267 DI.print(DP);
268 OS << '\n';
269
270 if (DI.getSeverity() == DS_Error)
271 exit(1);
272 return true;
273 }
274 };
Mehdi Amini354f5202015-11-19 05:52:29 +0000275 }
Mehdi Amini354f5202015-11-19 05:52:29 +0000276
Rafael Espindola5e128db2015-12-04 00:45:57 +0000277static void error(const Twine &Msg) {
278 errs() << "llvm-lto: " << Msg << '\n';
279 exit(1);
280}
281
282static void error(std::error_code EC, const Twine &Prefix) {
283 if (EC)
284 error(Prefix + ": " + EC.message());
285}
286
287template <typename T>
288static void error(const ErrorOr<T> &V, const Twine &Prefix) {
289 error(V.getError(), Prefix);
290}
291
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000292static void maybeVerifyModule(const Module &Mod) {
Mehdi Amini4c809462016-12-23 23:53:57 +0000293 if (!DisableVerify && verifyModule(Mod, &errs()))
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000294 error("Broken Module");
295}
296
Benjamin Kramerf044d3f2015-03-09 16:23:46 +0000297static std::unique_ptr<LTOModule>
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000298getLocalLTOModule(StringRef Path, std::unique_ptr<MemoryBuffer> &Buffer,
Rafael Espindola5e128db2015-12-04 00:45:57 +0000299 const TargetOptions &Options) {
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000300 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
301 MemoryBuffer::getFile(Path);
Rafael Espindola5e128db2015-12-04 00:45:57 +0000302 error(BufferOrErr, "error loading file '" + Path + "'");
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000303 Buffer = std::move(BufferOrErr.get());
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000304 CurrentActivity = ("loading file '" + Path + "'").str();
Petr Pavlu7ad9ec92016-03-01 13:13:49 +0000305 std::unique_ptr<LLVMContext> Context = llvm::make_unique<LLVMContext>();
Vivek Pandyab5ab8952017-09-15 20:10:09 +0000306 Context->setDiagnosticHandler(llvm::make_unique<LLVMLTODiagnosticHandler>(),
307 true);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000308 ErrorOr<std::unique_ptr<LTOModule>> Ret = LTOModule::createInLocalContext(
Petr Pavlu7ad9ec92016-03-01 13:13:49 +0000309 std::move(Context), Buffer->getBufferStart(), Buffer->getBufferSize(),
310 Options, Path);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000311 CurrentActivity = "";
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000312 maybeVerifyModule((*Ret)->getModule());
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000313 return std::move(*Ret);
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000314}
315
Mehdi Amini06a47802016-09-14 21:04:59 +0000316/// Print some statistics on the index for each input files.
317void printIndexStats() {
318 for (auto &Filename : InputFilenames) {
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000319 ExitOnError ExitOnErr("llvm-lto: error loading file '" + Filename + "': ");
320 std::unique_ptr<ModuleSummaryIndex> Index =
Eugene Zelenko975293f2017-09-07 23:28:24 +0000321 ExitOnErr(getModuleSummaryIndexForFile(Filename));
Mehdi Amini06a47802016-09-14 21:04:59 +0000322 // Skip files without a module summary.
323 if (!Index)
324 report_fatal_error(Filename + " does not contain an index");
325
326 unsigned Calls = 0, Refs = 0, Functions = 0, Alias = 0, Globals = 0;
327 for (auto &Summaries : *Index) {
Peter Collingbourne9667b912017-05-04 18:03:25 +0000328 for (auto &Summary : Summaries.second.SummaryList) {
Mehdi Amini06a47802016-09-14 21:04:59 +0000329 Refs += Summary->refs().size();
330 if (auto *FuncSummary = dyn_cast<FunctionSummary>(Summary.get())) {
331 Functions++;
332 Calls += FuncSummary->calls().size();
333 } else if (isa<AliasSummary>(Summary.get()))
334 Alias++;
335 else
336 Globals++;
337 }
338 }
339 outs() << "Index " << Filename << " contains "
340 << (Alias + Globals + Functions) << " nodes (" << Functions
341 << " functions, " << Alias << " alias, " << Globals
342 << " globals) and " << (Calls + Refs) << " edges (" << Refs
343 << " refs and " << Calls << " calls)\n";
344 }
345}
346
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000347/// \brief List symbols in each IR file.
348///
349/// The main point here is to provide lit-testable coverage for the LTOModule
350/// functionality that's exposed by the C API to list symbols. Moreover, this
351/// provides testing coverage for modules that have been created in their own
352/// contexts.
Rafael Espindola5e128db2015-12-04 00:45:57 +0000353static void listSymbols(const TargetOptions &Options) {
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000354 for (auto &Filename : InputFilenames) {
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000355 std::unique_ptr<MemoryBuffer> Buffer;
356 std::unique_ptr<LTOModule> Module =
Rafael Espindola5e128db2015-12-04 00:45:57 +0000357 getLocalLTOModule(Filename, Buffer, Options);
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000358
359 // List the symbols.
360 outs() << Filename << ":\n";
361 for (int I = 0, E = Module->getSymbolCount(); I != E; ++I)
362 outs() << Module->getSymbolName(I) << "\n";
363 }
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000364}
365
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000366/// Create a combined index file from the input IR files and write it.
367///
368/// This is meant to enable testing of ThinLTO combined index generation,
369/// currently available via the gold plugin via -thinlto.
Teresa Johnson26ab5772016-03-15 00:04:37 +0000370static void createCombinedModuleSummaryIndex() {
Eugene Leviant28d8a492018-01-22 13:35:40 +0000371 ModuleSummaryIndex CombinedIndex(/*IsPerformingAnalysis=*/false);
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000372 uint64_t NextModuleId = 0;
373 for (auto &Filename : InputFilenames) {
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000374 ExitOnError ExitOnErr("llvm-lto: error loading file '" + Filename + "': ");
Peter Collingbourne74d22dd2017-05-01 22:04:36 +0000375 std::unique_ptr<MemoryBuffer> MB =
376 ExitOnErr(errorOrToExpected(MemoryBuffer::getFileOrSTDIN(Filename)));
377 ExitOnErr(readModuleSummaryIndex(*MB, CombinedIndex, ++NextModuleId));
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000378 }
379 std::error_code EC;
380 assert(!OutputFilename.empty());
381 raw_fd_ostream OS(OutputFilename + ".thinlto.bc", EC,
382 sys::fs::OpenFlags::F_None);
Rafael Espindola5e128db2015-12-04 00:45:57 +0000383 error(EC, "error opening the file '" + OutputFilename + ".thinlto.bc'");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000384 WriteIndexToFile(CombinedIndex, OS);
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000385 OS.close();
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000386}
387
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000388/// Parse the thinlto_prefix_replace option into the \p OldPrefix and
389/// \p NewPrefix strings, if it was specified.
390static void getThinLTOOldAndNewPrefix(std::string &OldPrefix,
391 std::string &NewPrefix) {
392 assert(ThinLTOPrefixReplace.empty() ||
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000393 ThinLTOPrefixReplace.find(";") != StringRef::npos);
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000394 StringRef PrefixReplace = ThinLTOPrefixReplace;
Reid Kleckner8e96c3e2016-05-17 18:43:22 +0000395 std::pair<StringRef, StringRef> Split = PrefixReplace.split(";");
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000396 OldPrefix = Split.first.str();
397 NewPrefix = Split.second.str();
398}
399
400/// Given the original \p Path to an output file, replace any path
401/// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
402/// resulting directory if it does not yet exist.
403static std::string getThinLTOOutputFile(const std::string &Path,
404 const std::string &OldPrefix,
405 const std::string &NewPrefix) {
406 if (OldPrefix.empty() && NewPrefix.empty())
407 return Path;
408 SmallString<128> NewPath(Path);
409 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
410 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
411 if (!ParentPath.empty()) {
412 // Make sure the new directory exists, creating it if necessary.
413 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
414 error(EC, "error creating the directory '" + ParentPath + "'");
415 }
416 return NewPath.str();
417}
418
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000419namespace thinlto {
420
421std::vector<std::unique_ptr<MemoryBuffer>>
Teresa Johnson26ab5772016-03-15 00:04:37 +0000422loadAllFilesForIndex(const ModuleSummaryIndex &Index) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000423 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
424
Mehdi Amini385cf282016-03-26 03:35:38 +0000425 for (auto &ModPath : Index.modulePaths()) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000426 const auto &Filename = ModPath.first();
Alexander Kornienko656466e2017-07-04 15:13:02 +0000427 std::string CurrentActivity = ("loading file '" + Filename + "'").str();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000428 auto InputOrErr = MemoryBuffer::getFile(Filename);
429 error(InputOrErr, "error " + CurrentActivity);
430 InputBuffers.push_back(std::move(*InputOrErr));
431 }
432 return InputBuffers;
433}
434
Teresa Johnson26ab5772016-03-15 00:04:37 +0000435std::unique_ptr<ModuleSummaryIndex> loadCombinedIndex() {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000436 if (ThinLTOIndex.empty())
437 report_fatal_error("Missing -thinlto-index for ThinLTO promotion stage");
Peter Collingbourne6de481a2016-11-11 19:50:39 +0000438 ExitOnError ExitOnErr("llvm-lto: error loading file '" + ThinLTOIndex +
439 "': ");
Eugene Zelenko975293f2017-09-07 23:28:24 +0000440 return ExitOnErr(getModuleSummaryIndexForFile(ThinLTOIndex));
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000441}
442
443static std::unique_ptr<Module> loadModule(StringRef Filename,
444 LLVMContext &Ctx) {
445 SMDiagnostic Err;
446 std::unique_ptr<Module> M(parseIRFile(Filename, Err, Ctx));
447 if (!M) {
448 Err.print("llvm-lto", errs());
449 report_fatal_error("Can't load module for file " + Filename);
450 }
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000451 maybeVerifyModule(*M);
Mehdi Amini03abce92016-05-05 16:33:51 +0000452
453 if (ThinLTOModuleId.getNumOccurrences()) {
454 if (InputFilenames.size() != 1)
455 report_fatal_error("Can't override the module id for multiple files");
456 M->setModuleIdentifier(ThinLTOModuleId);
457 }
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000458 return M;
459}
460
461static void writeModuleToFile(Module &TheModule, StringRef Filename) {
462 std::error_code EC;
463 raw_fd_ostream OS(Filename, EC, sys::fs::OpenFlags::F_None);
464 error(EC, "error opening the file '" + Filename + "'");
Mehdi Amini3c0e64c2016-04-20 01:04:26 +0000465 maybeVerifyModule(TheModule);
Rafael Espindola6a86e252018-02-14 19:11:32 +0000466 WriteBitcodeToFile(TheModule, OS, /* ShouldPreserveUseListOrder */ true);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000467}
468
469class ThinLTOProcessing {
470public:
471 ThinLTOCodeGenerator ThinGenerator;
472
473 ThinLTOProcessing(const TargetOptions &Options) {
Rafael Espindola8c34dd82016-05-18 22:04:49 +0000474 ThinGenerator.setCodePICModel(getRelocModel());
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000475 ThinGenerator.setTargetOptions(Options);
Mehdi Aminiab4a8b62016-05-14 05:16:41 +0000476 ThinGenerator.setCacheDir(ThinLTOCacheDir);
Ben Dunbobbin9ecb8b52017-12-19 14:42:38 +0000477 ThinGenerator.setCachePruningInterval(ThinLTOCachePruningInterval);
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000478 ThinGenerator.setFreestanding(EnableFreestanding);
Mehdi Amini059464f2016-04-24 03:18:01 +0000479
480 // Add all the exported symbols to the table of symbols to preserve.
481 for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
482 ThinGenerator.preserveSymbol(ExportedSymbols[i]);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000483 }
484
485 void run() {
486 switch (ThinLTOMode) {
487 case THINLINK:
488 return thinLink();
Teresa Johnson84174c32016-05-10 13:48:23 +0000489 case THINDISTRIBUTE:
490 return distributedIndexes();
Teresa Johnson8570fe42016-05-10 15:54:09 +0000491 case THINEMITIMPORTS:
492 return emitImports();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000493 case THINPROMOTE:
494 return promote();
495 case THINIMPORT:
496 return import();
Mehdi Amini059464f2016-04-24 03:18:01 +0000497 case THININTERNALIZE:
498 return internalize();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000499 case THINOPT:
500 return optimize();
501 case THINCODEGEN:
502 return codegen();
503 case THINALL:
504 return runAll();
505 }
506 }
507
508private:
509 /// Load the input files, create the combined index, and write it out.
510 void thinLink() {
511 // Perform "ThinLink": just produce the index
512 if (OutputFilename.empty())
513 report_fatal_error(
514 "OutputFilename is necessary to store the combined index.\n");
515
516 LLVMContext Ctx;
517 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
518 for (unsigned i = 0; i < InputFilenames.size(); ++i) {
519 auto &Filename = InputFilenames[i];
Alexander Kornienko656466e2017-07-04 15:13:02 +0000520 std::string CurrentActivity = "loading file '" + Filename + "'";
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000521 auto InputOrErr = MemoryBuffer::getFile(Filename);
522 error(InputOrErr, "error " + CurrentActivity);
523 InputBuffers.push_back(std::move(*InputOrErr));
524 ThinGenerator.addModule(Filename, InputBuffers.back()->getBuffer());
525 }
526
527 auto CombinedIndex = ThinGenerator.linkCombinedIndex();
Mehdi Amini00fa1402016-10-08 04:44:18 +0000528 if (!CombinedIndex)
529 report_fatal_error("ThinLink didn't create an index");
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000530 std::error_code EC;
531 raw_fd_ostream OS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
532 error(EC, "error opening the file '" + OutputFilename + "'");
Teresa Johnson76a1c1d2016-03-11 18:52:24 +0000533 WriteIndexToFile(*CombinedIndex, OS);
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000534 }
535
Teresa Johnson84174c32016-05-10 13:48:23 +0000536 /// Load the combined index from disk, then compute and generate
537 /// individual index files suitable for ThinLTO distributed backend builds
538 /// on the files mentioned on the command line (these must match the index
539 /// content).
540 void distributedIndexes() {
541 if (InputFilenames.size() != 1 && !OutputFilename.empty())
542 report_fatal_error("Can't handle a single output filename and multiple "
543 "input files, do not provide an output filename and "
544 "the output files will be suffixed from the input "
545 "ones.");
546
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000547 std::string OldPrefix, NewPrefix;
548 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
549
Teresa Johnson84174c32016-05-10 13:48:23 +0000550 auto Index = loadCombinedIndex();
551 for (auto &Filename : InputFilenames) {
552 // Build a map of module to the GUIDs and summary objects that should
553 // be written to its index.
554 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
555 ThinLTOCodeGenerator::gatherImportedSummariesForModule(
556 Filename, *Index, ModuleToSummariesForIndex);
557
558 std::string OutputName = OutputFilename;
559 if (OutputName.empty()) {
560 OutputName = Filename + ".thinlto.bc";
561 }
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000562 OutputName = getThinLTOOutputFile(OutputName, OldPrefix, NewPrefix);
Teresa Johnson84174c32016-05-10 13:48:23 +0000563 std::error_code EC;
564 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::F_None);
565 error(EC, "error opening the file '" + OutputName + "'");
566 WriteIndexToFile(*Index, OS, &ModuleToSummariesForIndex);
567 }
568 }
569
Teresa Johnson8570fe42016-05-10 15:54:09 +0000570 /// Load the combined index from disk, compute the imports, and emit
571 /// the import file lists for each module to disk.
572 void emitImports() {
573 if (InputFilenames.size() != 1 && !OutputFilename.empty())
574 report_fatal_error("Can't handle a single output filename and multiple "
575 "input files, do not provide an output filename and "
576 "the output files will be suffixed from the input "
577 "ones.");
578
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000579 std::string OldPrefix, NewPrefix;
580 getThinLTOOldAndNewPrefix(OldPrefix, NewPrefix);
581
Teresa Johnson8570fe42016-05-10 15:54:09 +0000582 auto Index = loadCombinedIndex();
583 for (auto &Filename : InputFilenames) {
584 std::string OutputName = OutputFilename;
585 if (OutputName.empty()) {
586 OutputName = Filename + ".imports";
587 }
Teresa Johnsonbbd10b42016-05-17 14:45:30 +0000588 OutputName = getThinLTOOutputFile(OutputName, OldPrefix, NewPrefix);
Teresa Johnson8570fe42016-05-10 15:54:09 +0000589 ThinLTOCodeGenerator::emitImports(Filename, OutputName, *Index);
590 }
591 }
592
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000593 /// Load the combined index from disk, then load every file referenced by
594 /// the index and add them to the generator, finally perform the promotion
595 /// on the files mentioned on the command line (these must match the index
596 /// content).
597 void promote() {
598 if (InputFilenames.size() != 1 && !OutputFilename.empty())
599 report_fatal_error("Can't handle a single output filename and multiple "
600 "input files, do not provide an output filename and "
601 "the output files will be suffixed from the input "
602 "ones.");
603
604 auto Index = loadCombinedIndex();
605 for (auto &Filename : InputFilenames) {
606 LLVMContext Ctx;
607 auto TheModule = loadModule(Filename, Ctx);
608
609 ThinGenerator.promote(*TheModule, *Index);
610
611 std::string OutputName = OutputFilename;
612 if (OutputName.empty()) {
613 OutputName = Filename + ".thinlto.promoted.bc";
614 }
615 writeModuleToFile(*TheModule, OutputName);
616 }
617 }
618
619 /// Load the combined index from disk, then load every file referenced by
620 /// the index and add them to the generator, then performs the promotion and
621 /// cross module importing on the files mentioned on the command line
622 /// (these must match the index content).
623 void import() {
624 if (InputFilenames.size() != 1 && !OutputFilename.empty())
625 report_fatal_error("Can't handle a single output filename and multiple "
626 "input files, do not provide an output filename and "
627 "the output files will be suffixed from the input "
628 "ones.");
629
630 auto Index = loadCombinedIndex();
631 auto InputBuffers = loadAllFilesForIndex(*Index);
632 for (auto &MemBuffer : InputBuffers)
633 ThinGenerator.addModule(MemBuffer->getBufferIdentifier(),
634 MemBuffer->getBuffer());
635
636 for (auto &Filename : InputFilenames) {
637 LLVMContext Ctx;
638 auto TheModule = loadModule(Filename, Ctx);
639
640 ThinGenerator.crossModuleImport(*TheModule, *Index);
641
642 std::string OutputName = OutputFilename;
643 if (OutputName.empty()) {
644 OutputName = Filename + ".thinlto.imported.bc";
645 }
646 writeModuleToFile(*TheModule, OutputName);
647 }
648 }
649
Mehdi Amini059464f2016-04-24 03:18:01 +0000650 void internalize() {
651 if (InputFilenames.size() != 1 && !OutputFilename.empty())
652 report_fatal_error("Can't handle a single output filename and multiple "
653 "input files, do not provide an output filename and "
654 "the output files will be suffixed from the input "
655 "ones.");
656
657 if (ExportedSymbols.empty())
658 errs() << "Warning: -internalize will not perform without "
659 "-exported-symbol\n";
660
661 auto Index = loadCombinedIndex();
662 auto InputBuffers = loadAllFilesForIndex(*Index);
663 for (auto &MemBuffer : InputBuffers)
664 ThinGenerator.addModule(MemBuffer->getBufferIdentifier(),
665 MemBuffer->getBuffer());
666
667 for (auto &Filename : InputFilenames) {
668 LLVMContext Ctx;
669 auto TheModule = loadModule(Filename, Ctx);
670
671 ThinGenerator.internalize(*TheModule, *Index);
672
673 std::string OutputName = OutputFilename;
674 if (OutputName.empty()) {
675 OutputName = Filename + ".thinlto.internalized.bc";
676 }
677 writeModuleToFile(*TheModule, OutputName);
678 }
679 }
680
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000681 void optimize() {
682 if (InputFilenames.size() != 1 && !OutputFilename.empty())
683 report_fatal_error("Can't handle a single output filename and multiple "
684 "input files, do not provide an output filename and "
685 "the output files will be suffixed from the input "
686 "ones.");
687 if (!ThinLTOIndex.empty())
688 errs() << "Warning: -thinlto-index ignored for optimize stage";
689
690 for (auto &Filename : InputFilenames) {
691 LLVMContext Ctx;
692 auto TheModule = loadModule(Filename, Ctx);
693
694 ThinGenerator.optimize(*TheModule);
695
696 std::string OutputName = OutputFilename;
697 if (OutputName.empty()) {
698 OutputName = Filename + ".thinlto.imported.bc";
699 }
700 writeModuleToFile(*TheModule, OutputName);
701 }
702 }
703
704 void codegen() {
705 if (InputFilenames.size() != 1 && !OutputFilename.empty())
706 report_fatal_error("Can't handle a single output filename and multiple "
707 "input files, do not provide an output filename and "
708 "the output files will be suffixed from the input "
709 "ones.");
710 if (!ThinLTOIndex.empty())
711 errs() << "Warning: -thinlto-index ignored for codegen stage";
712
Adrian Prantlcdd785b2017-05-19 17:54:58 +0000713 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000714 for (auto &Filename : InputFilenames) {
715 LLVMContext Ctx;
Adrian Prantlcdd785b2017-05-19 17:54:58 +0000716 auto InputOrErr = MemoryBuffer::getFile(Filename);
717 error(InputOrErr, "error " + CurrentActivity);
718 InputBuffers.push_back(std::move(*InputOrErr));
719 ThinGenerator.addModule(Filename, InputBuffers.back()->getBuffer());
720 }
721 ThinGenerator.setCodeGenOnly(true);
722 ThinGenerator.run();
723 for (auto BinName :
724 zip(ThinGenerator.getProducedBinaries(), InputFilenames)) {
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000725 std::string OutputName = OutputFilename;
Adrian Prantlcdd785b2017-05-19 17:54:58 +0000726 if (OutputName.empty())
727 OutputName = std::get<1>(BinName) + ".thinlto.o";
728 else if (OutputName == "-") {
729 outs() << std::get<0>(BinName)->getBuffer();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000730 return;
731 }
732
733 std::error_code EC;
734 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::F_None);
735 error(EC, "error opening the file '" + OutputName + "'");
Adrian Prantlcdd785b2017-05-19 17:54:58 +0000736 OS << std::get<0>(BinName)->getBuffer();
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000737 }
738 }
739
740 /// Full ThinLTO process
741 void runAll() {
742 if (!OutputFilename.empty())
743 report_fatal_error("Do not provide an output filename for ThinLTO "
744 " processing, the output files will be suffixed from "
745 "the input ones.");
746
747 if (!ThinLTOIndex.empty())
748 errs() << "Warning: -thinlto-index ignored for full ThinLTO process";
749
750 LLVMContext Ctx;
751 std::vector<std::unique_ptr<MemoryBuffer>> InputBuffers;
752 for (unsigned i = 0; i < InputFilenames.size(); ++i) {
753 auto &Filename = InputFilenames[i];
Alexander Kornienko656466e2017-07-04 15:13:02 +0000754 std::string CurrentActivity = "loading file '" + Filename + "'";
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000755 auto InputOrErr = MemoryBuffer::getFile(Filename);
756 error(InputOrErr, "error " + CurrentActivity);
757 InputBuffers.push_back(std::move(*InputOrErr));
758 ThinGenerator.addModule(Filename, InputBuffers.back()->getBuffer());
759 }
760
Teresa Johnsonc44a1222016-08-15 23:24:57 +0000761 if (!ThinLTOSaveTempsPrefix.empty())
762 ThinGenerator.setSaveTempsDir(ThinLTOSaveTempsPrefix);
Mehdi Amini8e13bc42016-12-14 04:56:42 +0000763
764 if (!ThinLTOGeneratedObjectsDir.empty()) {
765 ThinGenerator.setGeneratedObjectsDirectory(ThinLTOGeneratedObjectsDir);
766 ThinGenerator.run();
767 return;
768 }
769
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000770 ThinGenerator.run();
771
772 auto &Binaries = ThinGenerator.getProducedBinaries();
773 if (Binaries.size() != InputFilenames.size())
774 report_fatal_error("Number of output objects does not match the number "
775 "of inputs");
776
777 for (unsigned BufID = 0; BufID < Binaries.size(); ++BufID) {
778 auto OutputName = InputFilenames[BufID] + ".thinlto.o";
779 std::error_code EC;
780 raw_fd_ostream OS(OutputName, EC, sys::fs::OpenFlags::F_None);
781 error(EC, "error opening the file '" + OutputName + "'");
782 OS << Binaries[BufID]->getBuffer();
783 }
784 }
785
786 /// Load the combined index from disk, then load every file referenced by
787};
788
Eugene Zelenko975293f2017-09-07 23:28:24 +0000789} // end namespace thinlto
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000790
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000791int main(int argc, char **argv) {
792 // Print a stack trace if we signal out.
Richard Smith2ad6d482016-06-09 00:53:21 +0000793 sys::PrintStackTraceOnErrorSignal(argv[0]);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000794 PrettyStackTraceProgram X(argc, argv);
795
796 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
797 cl::ParseCommandLineOptions(argc, argv, "llvm LTO linker\n");
798
Rafael Espindola5e128db2015-12-04 00:45:57 +0000799 if (OptLevel < '0' || OptLevel > '3')
800 error("optimization level must be between 0 and 3");
Peter Collingbourne070843d2015-03-19 22:01:00 +0000801
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000802 // Initialize the configured targets.
803 InitializeAllTargets();
804 InitializeAllTargetMCs();
805 InitializeAllAsmPrinters();
806 InitializeAllAsmParsers();
807
Rafael Espindola0b385c72013-09-30 16:39:19 +0000808 // set up the TargetOptions for the machine
Eli Benderskyf0f21002014-02-19 17:09:35 +0000809 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
Rafael Espindola0b385c72013-09-30 16:39:19 +0000810
Rafael Espindola5e128db2015-12-04 00:45:57 +0000811 if (ListSymbolsOnly) {
812 listSymbols(Options);
813 return 0;
814 }
Duncan P. N. Exon Smithf9abf4f2014-12-17 02:00:38 +0000815
Mehdi Amini06a47802016-09-14 21:04:59 +0000816 if (IndexStats) {
817 printIndexStats();
818 return 0;
819 }
820
Mehdi Aminie75aa6f2016-07-11 23:10:18 +0000821 if (CheckHasObjC) {
822 for (auto &Filename : InputFilenames) {
Peter Collingbournecd513a42016-11-11 19:50:24 +0000823 ExitOnError ExitOnErr(std::string(*argv) + ": error loading file '" +
824 Filename + "': ");
825 std::unique_ptr<MemoryBuffer> BufferOrErr =
826 ExitOnErr(errorOrToExpected(MemoryBuffer::getFile(Filename)));
Mehdi Aminie75aa6f2016-07-11 23:10:18 +0000827 auto Buffer = std::move(BufferOrErr.get());
Eugene Zelenko975293f2017-09-07 23:28:24 +0000828 if (ExitOnErr(isBitcodeContainingObjCCategory(*Buffer)))
Mehdi Aminie75aa6f2016-07-11 23:10:18 +0000829 outs() << "Bitcode " << Filename << " contains ObjC\n";
830 else
831 outs() << "Bitcode " << Filename << " does not contain ObjC\n";
832 }
833 return 0;
834 }
835
Mehdi Amini7c4a1a82016-03-09 01:37:22 +0000836 if (ThinLTOMode.getNumOccurrences()) {
837 if (ThinLTOMode.getNumOccurrences() > 1)
838 report_fatal_error("You can't specify more than one -thinlto-action");
839 thinlto::ThinLTOProcessing ThinLTOProcessor(Options);
840 ThinLTOProcessor.run();
841 return 0;
842 }
843
Rafael Espindola5e128db2015-12-04 00:45:57 +0000844 if (ThinLTO) {
Teresa Johnson26ab5772016-03-15 00:04:37 +0000845 createCombinedModuleSummaryIndex();
Rafael Espindola5e128db2015-12-04 00:45:57 +0000846 return 0;
847 }
Teresa Johnson91a88bb2015-10-19 14:30:44 +0000848
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000849 unsigned BaseArg = 0;
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000850
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000851 LLVMContext Context;
Vivek Pandyab5ab8952017-09-15 20:10:09 +0000852 Context.setDiagnosticHandler(llvm::make_unique<LLVMLTODiagnosticHandler>(),
853 true);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000854
855 LTOCodeGenerator CodeGen(Context);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000856
Duncan P. N. Exon Smith30c92422014-10-01 18:36:03 +0000857 if (UseDiagnosticHandler)
858 CodeGen.setDiagnosticHandler(handleDiagnostics, nullptr);
859
Rafael Espindola8c34dd82016-05-18 22:04:49 +0000860 CodeGen.setCodePICModel(getRelocModel());
Mehdi Aminib5a46c12017-03-28 18:55:44 +0000861 CodeGen.setFreestanding(EnableFreestanding);
James Molloy951e5292014-04-14 13:54:16 +0000862
Peter Collingbourne4ccf0f12013-09-24 23:52:22 +0000863 CodeGen.setDebugInfo(LTO_DEBUG_MODEL_DWARF);
Rafael Espindola0b385c72013-09-30 16:39:19 +0000864 CodeGen.setTargetOptions(Options);
Tobias Edler von Koch3f4f6f3e2016-01-18 23:35:24 +0000865 CodeGen.setShouldRestoreGlobalsLinkage(RestoreGlobalsLinkage);
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000866
Eugene Zelenko975293f2017-09-07 23:28:24 +0000867 StringSet<MallocAllocator> DSOSymbolsSet;
Rafael Espindola282a4702013-10-31 20:51:58 +0000868 for (unsigned i = 0; i < DSOSymbols.size(); ++i)
869 DSOSymbolsSet.insert(DSOSymbols[i]);
870
871 std::vector<std::string> KeptDSOSyms;
872
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000873 for (unsigned i = BaseArg; i < InputFilenames.size(); ++i) {
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000874 CurrentActivity = "loading file '" + InputFilenames[i] + "'";
875 ErrorOr<std::unique_ptr<LTOModule>> ModuleOrErr =
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000876 LTOModule::createFromFile(Context, InputFilenames[i], Options);
Rafael Espindolaa7612b42015-12-04 16:14:31 +0000877 std::unique_ptr<LTOModule> &Module = *ModuleOrErr;
878 CurrentActivity = "";
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000879
Peter Collingbourne552174392015-08-21 19:09:42 +0000880 unsigned NumSyms = Module->getSymbolCount();
881 for (unsigned I = 0; I < NumSyms; ++I) {
882 StringRef Name = Module->getSymbolName(I);
883 if (!DSOSymbolsSet.count(Name))
884 continue;
885 lto_symbol_attributes Attrs = Module->getSymbolAttributes(I);
886 unsigned Scope = Attrs & LTO_SYMBOL_SCOPE_MASK;
887 if (Scope != LTO_SYMBOL_SCOPE_DEFAULT_CAN_BE_HIDDEN)
888 KeptDSOSyms.push_back(Name);
889 }
Manman Ren6487ce92015-02-24 00:45:56 +0000890
891 // We use the first input module as the destination module when
892 // SetMergedModule is true.
893 if (SetMergedModule && i == BaseArg) {
894 // Transfer ownership to the code generator.
Peter Collingbourne9c8909d2015-08-24 22:22:53 +0000895 CodeGen.setModule(std::move(Module));
Yunzhong Gao46261a72015-09-11 20:01:53 +0000896 } else if (!CodeGen.addModule(Module.get())) {
897 // Print a message here so that we know addModule() did not abort.
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000898 error("error adding file '" + InputFilenames[i] + "'");
Yunzhong Gao46261a72015-09-11 20:01:53 +0000899 }
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000900 }
901
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000902 // Add all the exported symbols to the table of symbols to preserve.
903 for (unsigned i = 0; i < ExportedSymbols.size(); ++i)
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000904 CodeGen.addMustPreserveSymbol(ExportedSymbols[i]);
Rafael Espindoladafc53d2013-10-02 14:12:56 +0000905
Rafael Espindolacda29112013-10-03 18:29:09 +0000906 // Add all the dso symbols to the table of symbols to expose.
Rafael Espindola282a4702013-10-31 20:51:58 +0000907 for (unsigned i = 0; i < KeptDSOSyms.size(); ++i)
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000908 CodeGen.addMustPreserveSymbol(KeptDSOSyms[i]);
Rafael Espindolacda29112013-10-03 18:29:09 +0000909
Akira Hatanaka23b5f672015-01-30 01:14:28 +0000910 // Set cpu and attrs strings for the default target/subtarget.
911 CodeGen.setCpu(MCPU.c_str());
912
Peter Collingbourne070843d2015-03-19 22:01:00 +0000913 CodeGen.setOptLevel(OptLevel - '0');
914
Tom Roederfd1bc602014-04-25 21:46:51 +0000915 std::string attrs;
916 for (unsigned i = 0; i < MAttrs.size(); ++i) {
917 if (i > 0)
918 attrs.append(",");
919 attrs.append(MAttrs[i]);
920 }
921
922 if (!attrs.empty())
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000923 CodeGen.setAttr(attrs);
Tom Roederfd1bc602014-04-25 21:46:51 +0000924
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000925 if (FileType.getNumOccurrences())
926 CodeGen.setFileType(FileType);
927
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000928 if (!OutputFilename.empty()) {
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000929 if (!CodeGen.optimize(DisableVerify, DisableInline, DisableGVNLoadPRE,
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000930 DisableLTOVectorization)) {
931 // Diagnostic messages should have been printed by the handler.
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000932 error("error optimizing the code");
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000933 }
934
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000935 if (SaveModuleFile) {
936 std::string ModuleFilename = OutputFilename;
937 ModuleFilename += ".merged.bc";
938 std::string ErrMsg;
939
Malcolm Parsons06ac79c2016-11-02 16:43:50 +0000940 if (!CodeGen.writeMergedModules(ModuleFilename))
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000941 error("writing merged module failed.");
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000942 }
943
Reid Kleckner3fc649c2017-09-23 01:03:17 +0000944 std::list<ToolOutputFile> OSs;
Peter Collingbournec269ed52015-08-27 23:37:36 +0000945 std::vector<raw_pwrite_stream *> OSPtrs;
946 for (unsigned I = 0; I != Parallelism; ++I) {
947 std::string PartFilename = OutputFilename;
948 if (Parallelism != 1)
949 PartFilename += "." + utostr(I);
950 std::error_code EC;
951 OSs.emplace_back(PartFilename, EC, sys::fs::F_None);
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000952 if (EC)
953 error("error opening the file '" + PartFilename + "': " + EC.message());
Peter Collingbournec269ed52015-08-27 23:37:36 +0000954 OSPtrs.push_back(&OSs.back().os());
955 }
956
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000957 if (!CodeGen.compileOptimized(OSPtrs))
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000958 // Diagnostic messages should have been printed by the handler.
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000959 error("error compiling the code");
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000960
Reid Kleckner3fc649c2017-09-23 01:03:17 +0000961 for (ToolOutputFile &OS : OSs)
Peter Collingbournec269ed52015-08-27 23:37:36 +0000962 OS.keep();
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000963 } else {
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000964 if (Parallelism != 1)
965 error("-j must be specified together with -o");
Peter Collingbournec269ed52015-08-27 23:37:36 +0000966
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000967 if (SaveModuleFile)
968 error(": -save-merged-module must be specified with -o");
Tobias Edler von Koch49c9a6e2015-11-20 00:13:05 +0000969
Craig Toppere6cb63e2014-04-25 04:24:47 +0000970 const char *OutputName = nullptr;
Duncan P. N. Exon Smithcff5fef2015-09-15 23:05:59 +0000971 if (!CodeGen.compile_to_file(&OutputName, DisableVerify, DisableInline,
Davide Italiano1eea9bd2016-04-13 22:08:26 +0000972 DisableGVNLoadPRE, DisableLTOVectorization))
973 error("error compiling the code");
Yunzhong Gao8e348cc2015-11-17 19:48:12 +0000974 // Diagnostic messages should have been printed by the handler.
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000975
976 outs() << "Wrote native object file '" << OutputName << "'\n";
977 }
978
Peter Collingbourne4e380b02013-09-19 22:15:52 +0000979 return 0;
980}