blob: b1e1b03cbc1985811720218dfac0773428be56cb [file] [log] [blame]
Rui Ueyama25992482016-03-22 20:52:10 +00001//===- LTO.cpp ------------------------------------------------------------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "LTO.h"
11#include "Config.h"
Rui Ueyama25992482016-03-22 20:52:10 +000012#include "InputFiles.h"
Rui Ueyama3f851702017-10-02 21:00:41 +000013#include "LinkerScript.h"
Rafael Espindola4b075bb2017-07-26 23:39:10 +000014#include "SymbolTable.h"
Rui Ueyama25992482016-03-22 20:52:10 +000015#include "Symbols.h"
Bob Haarmanb8a59c82017-10-25 22:28:38 +000016#include "lld/Common/ErrorHandler.h"
Rui Ueyama3f851702017-10-02 21:00:41 +000017#include "lld/Common/TargetOptionsCommandFlags.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000018#include "llvm/ADT/STLExtras.h"
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +000019#include "llvm/ADT/SmallString.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000020#include "llvm/ADT/StringRef.h"
21#include "llvm/ADT/Twine.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000022#include "llvm/BinaryFormat/ELF.h"
Rumeet Dhindsad366e362018-05-02 21:40:07 +000023#include "llvm/Bitcode/BitcodeReader.h"
24#include "llvm/Bitcode/BitcodeWriter.h"
Davide Italiano786d8e32016-09-29 00:40:08 +000025#include "llvm/IR/DiagnosticPrinter.h"
Peter Collingbournee02775f2017-03-01 23:00:10 +000026#include "llvm/LTO/Caching.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000027#include "llvm/LTO/Config.h"
Davide Italiano786d8e32016-09-29 00:40:08 +000028#include "llvm/LTO/LTO.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000029#include "llvm/Object/SymbolicFile.h"
30#include "llvm/Support/CodeGen.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000031#include "llvm/Support/Error.h"
32#include "llvm/Support/FileSystem.h"
33#include "llvm/Support/MemoryBuffer.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000034#include <algorithm>
35#include <cstddef>
36#include <memory>
37#include <string>
38#include <system_error>
39#include <vector>
Rui Ueyama25992482016-03-22 20:52:10 +000040
41using namespace llvm;
42using namespace llvm::object;
43using namespace llvm::ELF;
44
45using namespace lld;
46using namespace lld::elf;
47
48// This is for use when debugging LTO.
Rui Ueyama48da5cf2016-07-15 02:17:13 +000049static void saveBuffer(StringRef Buffer, const Twine &Path) {
Rui Ueyama25992482016-03-22 20:52:10 +000050 std::error_code EC;
Rui Ueyama48da5cf2016-07-15 02:17:13 +000051 raw_fd_ostream OS(Path.str(), EC, sys::fs::OpenFlags::F_None);
Rui Ueyamaf8292e92016-07-15 02:01:03 +000052 if (EC)
Rui Ueyamac8d3a832017-01-12 22:18:04 +000053 error("cannot create " + Path + ": " + EC.message());
Rui Ueyama25992482016-03-22 20:52:10 +000054 OS << Buffer;
55}
56
Davide Italiano786d8e32016-09-29 00:40:08 +000057static void diagnosticHandler(const DiagnosticInfo &DI) {
58 SmallString<128> ErrStorage;
59 raw_svector_ostream OS(ErrStorage);
60 DiagnosticPrinterRawOStream DP(OS);
61 DI.print(DP);
Rui Ueyamad31e13f2016-09-29 21:00:23 +000062 warn(ErrStorage);
Rui Ueyama25992482016-03-22 20:52:10 +000063}
64
Rui Ueyama6c5cbff2016-09-29 21:00:26 +000065static void checkError(Error E) {
Rafael Espindola5329c752017-09-21 22:50:52 +000066 handleAllErrors(std::move(E),
67 [&](ErrorInfoBase &EIB) { error(EIB.message()); });
Rui Ueyama6c5cbff2016-09-29 21:00:26 +000068}
69
Rui Ueyama66a9f252018-05-07 17:46:28 +000070// Creates an empty file to store a list of object files for final
Rumeet Dhindsad366e362018-05-02 21:40:07 +000071// linking of distributed ThinLTO.
Rui Ueyama66a9f252018-05-07 17:46:28 +000072static std::unique_ptr<raw_fd_ostream> openFile(StringRef File) {
73 if (File.empty())
Rumeet Dhindsad366e362018-05-02 21:40:07 +000074 return nullptr;
Rui Ueyama66a9f252018-05-07 17:46:28 +000075
Rumeet Dhindsad366e362018-05-02 21:40:07 +000076 std::error_code EC;
Rui Ueyama66a9f252018-05-07 17:46:28 +000077 auto Ret =
78 llvm::make_unique<raw_fd_ostream>(File, EC, sys::fs::OpenFlags::F_None);
Rui Ueyamad54f1c22018-05-07 22:11:24 +000079 if (EC) {
80 error("cannot open " + File + ": " + EC.message());
81 return nullptr;
82 }
Rui Ueyama66a9f252018-05-07 17:46:28 +000083 return Ret;
Rumeet Dhindsad366e362018-05-02 21:40:07 +000084}
85
Rui Ueyamad54f1c22018-05-07 22:11:24 +000086static std::string getThinLTOOutputFile(StringRef ModulePath) {
87 return lto::getThinLTOOutputFile(ModulePath,
88 Config->ThinLTOPrefixReplace.first,
Rumeet Dhindsa4fb51192018-05-07 23:14:12 +000089 Config->ThinLTOPrefixReplace.second);
Rui Ueyamad54f1c22018-05-07 22:11:24 +000090}
91
Rui Ueyama397dffd2018-05-07 23:24:07 +000092static lto::Config createConfig() {
93 lto::Config C;
Davide Italianod26c4a12016-05-15 19:29:38 +000094
Davide Italiano786d8e32016-09-29 00:40:08 +000095 // LLD supports the new relocations.
Rui Ueyama397dffd2018-05-07 23:24:07 +000096 C.Options = InitTargetOptionsFromCodeGenFlags();
97 C.Options.RelaxELFRelocations = true;
Davide Italianodf24d5b2016-06-02 22:58:11 +000098
Davide Italiano957f1202017-07-24 20:15:07 +000099 // Always emit a section per function/datum with LTO.
Rui Ueyama397dffd2018-05-07 23:24:07 +0000100 C.Options.FunctionSections = true;
101 C.Options.DataSections = true;
Davide Italiano1f4e29c2017-07-24 19:38:13 +0000102
Evgeniy Stepanovf12ac5b2017-05-22 21:11:44 +0000103 if (Config->Relocatable)
Rui Ueyama397dffd2018-05-07 23:24:07 +0000104 C.RelocModel = None;
Evgeniy Stepanovf12ac5b2017-05-22 21:11:44 +0000105 else if (Config->Pic)
Rui Ueyama397dffd2018-05-07 23:24:07 +0000106 C.RelocModel = Reloc::PIC_;
Evgeniy Stepanovf12ac5b2017-05-22 21:11:44 +0000107 else
Rui Ueyama397dffd2018-05-07 23:24:07 +0000108 C.RelocModel = Reloc::Static;
109
110 C.CodeModel = GetCodeModelFromCMModel();
111 C.DisableVerify = Config->DisableVerify;
112 C.DiagHandler = diagnosticHandler;
113 C.OptLevel = Config->LTOO;
114 C.CPU = GetCPUStr();
Davide Italianodf24d5b2016-06-02 22:58:11 +0000115
Davide Italiano786d8e32016-09-29 00:40:08 +0000116 // Set up a custom pipeline if we've been asked to.
Rui Ueyama397dffd2018-05-07 23:24:07 +0000117 C.OptPipeline = Config->LTONewPmPasses;
118 C.AAPipeline = Config->LTOAAPipeline;
Rui Ueyama25992482016-03-22 20:52:10 +0000119
Davide Italianodb4b0a72017-02-13 17:49:18 +0000120 // Set up optimization remarks if we've been asked to.
Rui Ueyama397dffd2018-05-07 23:24:07 +0000121 C.RemarksFilename = Config->OptRemarksFilename;
122 C.RemarksWithHotness = Config->OptRemarksWithHotness;
123
124 C.SampleProfile = Config->LTOSampleProfile;
125 C.UseNewPM = Config->LTONewPassManager;
126 C.DebugPassManager = Config->LTODebugPassManager;
Davide Italianodb4b0a72017-02-13 17:49:18 +0000127
Rui Ueyama25992482016-03-22 20:52:10 +0000128 if (Config->SaveTemps)
Rui Ueyama397dffd2018-05-07 23:24:07 +0000129 checkError(C.addSaveTemps(Config->OutputFile.str() + ".",
130 /*UseInputModulePath*/ true));
131 return C;
132}
Davide Italiano786d8e32016-09-29 00:40:08 +0000133
Rui Ueyama397dffd2018-05-07 23:24:07 +0000134BitcodeCompiler::BitcodeCompiler() {
135 // Initialize LTOObj.
Davide Italiano7a7b35a2016-10-10 18:12:53 +0000136 lto::ThinBackend Backend;
Rumeet Dhindsa682a4172018-04-09 17:56:07 +0000137
Rumeet Dhindsad366e362018-05-02 21:40:07 +0000138 if (Config->ThinLTOIndexOnly) {
Rui Ueyama66a9f252018-05-07 17:46:28 +0000139 IndexFile = openFile(Config->ThinLTOIndexOnlyObjectsFile);
Rui Ueyama4454b3d2018-05-07 17:59:43 +0000140 Backend = lto::createWriteIndexesThinBackend(
141 Config->ThinLTOPrefixReplace.first, Config->ThinLTOPrefixReplace.second,
Rumeet Dhindsa4fb51192018-05-07 23:14:12 +0000142 Config->ThinLTOEmitImportsFiles, IndexFile.get(), nullptr);
Rui Ueyama397dffd2018-05-07 23:24:07 +0000143 } else if (Config->ThinLTOJobs != -1U) {
144 Backend = lto::createInProcessThinBackend(Config->ThinLTOJobs);
Rumeet Dhindsad366e362018-05-02 21:40:07 +0000145 }
146
Rui Ueyama397dffd2018-05-07 23:24:07 +0000147 LTOObj = llvm::make_unique<lto::LTO>(createConfig(), Backend,
Rui Ueyama66a9f252018-05-07 17:46:28 +0000148 Config->LTOPartitions);
Rui Ueyama25992482016-03-22 20:52:10 +0000149
Rui Ueyama397dffd2018-05-07 23:24:07 +0000150 // Initialize UsedStartStop.
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000151 for (Symbol *Sym : Symtab->getSymbols()) {
Rui Ueyamaf1f00842017-10-31 16:07:41 +0000152 StringRef Name = Sym->getName();
Rafael Espindola4b075bb2017-07-26 23:39:10 +0000153 for (StringRef Prefix : {"__start_", "__stop_"})
154 if (Name.startswith(Prefix))
155 UsedStartStop.insert(Name.substr(Prefix.size()));
156 }
157}
Rafael Espindolaae605c12016-04-21 20:35:25 +0000158
Eugene Zelenko22886a22016-11-05 01:00:56 +0000159BitcodeCompiler::~BitcodeCompiler() = default;
Rui Ueyama412c8022016-04-22 21:16:18 +0000160
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000161static void undefine(Symbol *S) {
Rafael Espindolabec37652017-11-17 01:37:50 +0000162 replaceSymbol<Undefined>(S, nullptr, S->getName(), STB_GLOBAL, STV_DEFAULT,
163 S->Type);
Peter Collingbourne0ef38742016-05-12 19:46:14 +0000164}
165
Peter Smith3a52eb02017-02-01 10:26:03 +0000166void BitcodeCompiler::add(BitcodeFile &F) {
Davide Italiano786d8e32016-09-29 00:40:08 +0000167 lto::InputFile &Obj = *F.Obj;
Rumeet Dhindsad366e362018-05-02 21:40:07 +0000168
Rumeet Dhindsad366e362018-05-02 21:40:07 +0000169 // Create the empty files which, if indexed, will be overwritten later.
Rumeet Dhindsa4fb51192018-05-07 23:14:12 +0000170 if (Config->ThinLTOIndexOnly) {
171 std::string Path = getThinLTOOutputFile(Obj.getName());
172 openFile(Path + ".thinlto.bc");
173
174 if (Config->ThinLTOEmitImportsFiles)
175 openFile(Path + ".imports");
176 }
Rumeet Dhindsad366e362018-05-02 21:40:07 +0000177
Davide Italiano786d8e32016-09-29 00:40:08 +0000178 unsigned SymNum = 0;
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000179 std::vector<Symbol *> Syms = F.getSymbols();
Davide Italiano786d8e32016-09-29 00:40:08 +0000180 std::vector<lto::SymbolResolution> Resols(Syms.size());
Davide Italiano334fce92016-05-11 01:07:22 +0000181
Rafael Espindolac6df38c2018-01-16 16:49:05 +0000182 bool IsExecutable = !Config->Shared && !Config->Relocatable;
183
Davide Italiano786d8e32016-09-29 00:40:08 +0000184 // Provide a resolution to the LTO API for each symbol.
185 for (const lto::InputFile::Symbol &ObjSym : Obj.symbols()) {
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000186 Symbol *Sym = Syms[SymNum];
Davide Italiano786d8e32016-09-29 00:40:08 +0000187 lto::SymbolResolution &R = Resols[SymNum];
188 ++SymNum;
Davide Italiano86f2bd52016-03-29 21:46:35 +0000189
Davide Italiano786d8e32016-09-29 00:40:08 +0000190 // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile
191 // reports two symbols for module ASM defined. Without this check, lld
192 // flags an undefined in IR with a definition in ASM as prevailing.
193 // Once IRObjectFile is fixed to report only one symbol this hack can
194 // be removed.
Rafael Espindoladfebd362017-11-29 22:47:35 +0000195 R.Prevailing = !ObjSym.isUndefined() && Sym->File == &F;
Peter Collingbourne3ad1c1e2016-05-05 17:13:49 +0000196
George Rimar3a1af222017-08-22 08:36:54 +0000197 // We ask LTO to preserve following global symbols:
198 // 1) All symbols when doing relocatable link, so that them can be used
199 // for doing final link.
200 // 2) Symbols that are used in regular objects.
201 // 3) C named sections if we have corresponding __start_/__stop_ symbol.
202 // 4) Symbols that are defined in bitcode files and used for dynamic linking.
203 R.VisibleToRegularObj = Config->Relocatable || Sym->IsUsedInRegularObj ||
Rafael Espindolaaffe7202017-07-25 22:51:05 +0000204 (R.Prevailing && Sym->includeInDynsym()) ||
Rafael Espindola4b075bb2017-07-26 23:39:10 +0000205 UsedStartStop.count(ObjSym.getSectionName());
Dmitry Mikulinc84e0ee2018-02-07 00:49:51 +0000206 const auto *DR = dyn_cast<Defined>(Sym);
Rafael Espindolac6df38c2018-01-16 16:49:05 +0000207 R.FinalDefinitionInLinkageUnit =
Dmitry Mikulinc84e0ee2018-02-07 00:49:51 +0000208 (IsExecutable || Sym->Visibility != STV_DEFAULT) && DR &&
209 // Skip absolute symbols from ELF objects, otherwise PC-rel relocations
210 // will be generated by for them, triggering linker errors.
211 // Symbol section is always null for bitcode symbols, hence the check
Dmitry Mikulin8ddd9222018-02-08 04:25:52 +0000212 // for isElf(). Skip linker script defined symbols as well: they have
213 // no File defined.
214 !(DR->Section == nullptr && (!Sym->File || Sym->File->isElf()));
Rafael Espindolac6df38c2018-01-16 16:49:05 +0000215
Davide Italiano786d8e32016-09-29 00:40:08 +0000216 if (R.Prevailing)
Peter Smith3a52eb02017-02-01 10:26:03 +0000217 undefine(Sym);
George Rimard28c26b2017-09-25 09:31:43 +0000218
George Rimarc4ccfb52018-01-30 09:04:27 +0000219 // We tell LTO to not apply interprocedural optimization for wrapped
220 // (with --wrap) symbols because otherwise LTO would inline them while
221 // their values are still not final.
222 R.LinkerRedefined = !Sym->CanInline;
Rui Ueyama25992482016-03-22 20:52:10 +0000223 }
Davide Italiano3bfa0812016-11-26 05:37:04 +0000224 checkError(LTOObj->add(std::move(F.Obj), Resols));
Davide Italianobc176632016-04-15 22:38:10 +0000225}
226
Rui Ueyama25992482016-03-22 20:52:10 +0000227// Merge all the bitcode files we have seen, codegen the result
Davide Italiano786d8e32016-09-29 00:40:08 +0000228// and return the resulting ObjectFile(s).
Rui Ueyama38dbd3e2016-09-14 00:05:51 +0000229std::vector<InputFile *> BitcodeCompiler::compile() {
Davide Italiano786d8e32016-09-29 00:40:08 +0000230 std::vector<InputFile *> Ret;
Davide Italiano3bfa0812016-11-26 05:37:04 +0000231 unsigned MaxTasks = LTOObj->getMaxTasks();
Davide Italiano786d8e32016-09-29 00:40:08 +0000232 Buff.resize(MaxTasks);
Peter Collingbournee02775f2017-03-01 23:00:10 +0000233 Files.resize(MaxTasks);
Davide Italiano828ac5412016-03-28 15:44:21 +0000234
Peter Collingbournee02775f2017-03-01 23:00:10 +0000235 // The --thinlto-cache-dir option specifies the path to a directory in which
236 // to cache native object files for ThinLTO incremental builds. If a path was
237 // specified, configure LTO to use it as the cache directory.
238 lto::NativeObjectCache Cache;
239 if (!Config->ThinLTOCacheDir.empty())
Peter Collingbourne128423f2017-03-17 00:34:07 +0000240 Cache = check(
241 lto::localCache(Config->ThinLTOCacheDir,
Teresa Johnson2c2ed3c2018-02-20 20:21:59 +0000242 [&](size_t Task, std::unique_ptr<MemoryBuffer> MB) {
243 Files[Task] = std::move(MB);
244 }));
Peter Collingbournee02775f2017-03-01 23:00:10 +0000245
246 checkError(LTOObj->run(
247 [&](size_t Task) {
248 return llvm::make_unique<lto::NativeObjectStream>(
249 llvm::make_unique<raw_svector_ostream>(Buff[Task]));
250 },
251 Cache));
Rafael Espindolaabf6c652016-04-17 23:20:08 +0000252
Peter Collingbourneee59e432017-03-17 02:24:16 +0000253 if (!Config->ThinLTOCacheDir.empty())
254 pruneCache(Config->ThinLTOCacheDir, Config->ThinLTOCachePolicy);
255
Davide Italiano786d8e32016-09-29 00:40:08 +0000256 for (unsigned I = 0; I != MaxTasks; ++I) {
257 if (Buff[I].empty())
258 continue;
259 if (Config->SaveTemps) {
Peter Collingbourned22ec642017-01-26 02:18:28 +0000260 if (I == 0)
Davide Italiano786d8e32016-09-29 00:40:08 +0000261 saveBuffer(Buff[I], Config->OutputFile + ".lto.o");
262 else
263 saveBuffer(Buff[I], Config->OutputFile + Twine(I) + ".lto.o");
264 }
Rui Ueyama55518e72016-10-28 20:57:25 +0000265 InputFile *Obj = createObjectFile(MemoryBufferRef(Buff[I], "lto.tmp"));
Davide Italiano786d8e32016-09-29 00:40:08 +0000266 Ret.push_back(Obj);
267 }
Peter Collingbournee02775f2017-03-01 23:00:10 +0000268
Rui Ueyamad54f1c22018-05-07 22:11:24 +0000269 // If LazyObjFile has not been added to link, emit empty index files.
270 // This is needed because this is what GNU gold plugin does and we have a
271 // distributed build system that depends on that behavior.
272 if (Config->ThinLTOIndexOnly) {
273 for (LazyObjFile *F : LazyObjFiles) {
274 if (F->AddedToLink || !isBitcode(F->MB))
275 continue;
276
Rumeet Dhindsa4fb51192018-05-07 23:14:12 +0000277 std::string Path = getThinLTOOutputFile(F->getName());
278 std::unique_ptr<raw_fd_ostream> OS = openFile(Path + ".thinlto.bc");
Rui Ueyamad54f1c22018-05-07 22:11:24 +0000279 if (!OS)
280 continue;
281
282 ModuleSummaryIndex M(false);
283 M.setSkipModuleByDistributedBackend();
284 WriteIndexToFile(M, *OS);
Rumeet Dhindsa4fb51192018-05-07 23:14:12 +0000285
286 if (Config->ThinLTOEmitImportsFiles)
287 openFile(Path + ".imports");
Rui Ueyamad54f1c22018-05-07 22:11:24 +0000288 }
289
290 // ThinLTO with index only option is required to generate only the index
291 // files. After that, we exit from linker and ThinLTO backend runs in a
292 // distributed environment.
Rui Ueyama554adb22018-05-07 22:11:34 +0000293 if (IndexFile)
294 IndexFile->close();
295 return {};
Rui Ueyamad54f1c22018-05-07 22:11:24 +0000296 }
Rumeet Dhindsad366e362018-05-02 21:40:07 +0000297
Peter Collingbournee02775f2017-03-01 23:00:10 +0000298 for (std::unique_ptr<MemoryBuffer> &File : Files)
299 if (File)
300 Ret.push_back(createObjectFile(*File));
Davide Italiano786d8e32016-09-29 00:40:08 +0000301 return Ret;
Rui Ueyama961f2ff2016-03-23 21:19:27 +0000302}