blob: 3d94e064d2db05f174ae2ba17499eb8d36af5f25 [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) {
Rui Ueyamacdf8d062018-05-07 23:43:48 +000058 SmallString<128> S;
59 raw_svector_ostream OS(S);
Davide Italiano786d8e32016-09-29 00:40:08 +000060 DiagnosticPrinterRawOStream DP(OS);
61 DI.print(DP);
Rui Ueyamacdf8d062018-05-07 23:43:48 +000062 warn(S);
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) {
Rumeet Dhindsad366e362018-05-02 21:40:07 +000073 std::error_code EC;
Rui Ueyama66a9f252018-05-07 17:46:28 +000074 auto Ret =
75 llvm::make_unique<raw_fd_ostream>(File, EC, sys::fs::OpenFlags::F_None);
Rui Ueyamad54f1c22018-05-07 22:11:24 +000076 if (EC) {
77 error("cannot open " + File + ": " + EC.message());
78 return nullptr;
79 }
Rui Ueyama66a9f252018-05-07 17:46:28 +000080 return Ret;
Rumeet Dhindsad366e362018-05-02 21:40:07 +000081}
82
Rui Ueyamad54f1c22018-05-07 22:11:24 +000083static std::string getThinLTOOutputFile(StringRef ModulePath) {
84 return lto::getThinLTOOutputFile(ModulePath,
85 Config->ThinLTOPrefixReplace.first,
Rumeet Dhindsa4fb51192018-05-07 23:14:12 +000086 Config->ThinLTOPrefixReplace.second);
Rui Ueyamad54f1c22018-05-07 22:11:24 +000087}
88
Rui Ueyama397dffd2018-05-07 23:24:07 +000089static lto::Config createConfig() {
90 lto::Config C;
Davide Italianod26c4a12016-05-15 19:29:38 +000091
Davide Italiano786d8e32016-09-29 00:40:08 +000092 // LLD supports the new relocations.
Rui Ueyama397dffd2018-05-07 23:24:07 +000093 C.Options = InitTargetOptionsFromCodeGenFlags();
94 C.Options.RelaxELFRelocations = true;
Davide Italianodf24d5b2016-06-02 22:58:11 +000095
Davide Italiano957f1202017-07-24 20:15:07 +000096 // Always emit a section per function/datum with LTO.
Rui Ueyama397dffd2018-05-07 23:24:07 +000097 C.Options.FunctionSections = true;
98 C.Options.DataSections = true;
Davide Italiano1f4e29c2017-07-24 19:38:13 +000099
Evgeniy Stepanovf12ac5b2017-05-22 21:11:44 +0000100 if (Config->Relocatable)
Rui Ueyama397dffd2018-05-07 23:24:07 +0000101 C.RelocModel = None;
Evgeniy Stepanovf12ac5b2017-05-22 21:11:44 +0000102 else if (Config->Pic)
Rui Ueyama397dffd2018-05-07 23:24:07 +0000103 C.RelocModel = Reloc::PIC_;
Evgeniy Stepanovf12ac5b2017-05-22 21:11:44 +0000104 else
Rui Ueyama397dffd2018-05-07 23:24:07 +0000105 C.RelocModel = Reloc::Static;
106
107 C.CodeModel = GetCodeModelFromCMModel();
108 C.DisableVerify = Config->DisableVerify;
109 C.DiagHandler = diagnosticHandler;
110 C.OptLevel = Config->LTOO;
111 C.CPU = GetCPUStr();
Davide Italianodf24d5b2016-06-02 22:58:11 +0000112
Davide Italiano786d8e32016-09-29 00:40:08 +0000113 // Set up a custom pipeline if we've been asked to.
Rui Ueyama397dffd2018-05-07 23:24:07 +0000114 C.OptPipeline = Config->LTONewPmPasses;
115 C.AAPipeline = Config->LTOAAPipeline;
Rui Ueyama25992482016-03-22 20:52:10 +0000116
Davide Italianodb4b0a72017-02-13 17:49:18 +0000117 // Set up optimization remarks if we've been asked to.
Rui Ueyama397dffd2018-05-07 23:24:07 +0000118 C.RemarksFilename = Config->OptRemarksFilename;
119 C.RemarksWithHotness = Config->OptRemarksWithHotness;
120
121 C.SampleProfile = Config->LTOSampleProfile;
122 C.UseNewPM = Config->LTONewPassManager;
123 C.DebugPassManager = Config->LTODebugPassManager;
Davide Italianodb4b0a72017-02-13 17:49:18 +0000124
Rui Ueyama25992482016-03-22 20:52:10 +0000125 if (Config->SaveTemps)
Rui Ueyama397dffd2018-05-07 23:24:07 +0000126 checkError(C.addSaveTemps(Config->OutputFile.str() + ".",
127 /*UseInputModulePath*/ true));
128 return C;
129}
Davide Italiano786d8e32016-09-29 00:40:08 +0000130
Rui Ueyama397dffd2018-05-07 23:24:07 +0000131BitcodeCompiler::BitcodeCompiler() {
132 // Initialize LTOObj.
Davide Italiano7a7b35a2016-10-10 18:12:53 +0000133 lto::ThinBackend Backend;
Rumeet Dhindsa682a4172018-04-09 17:56:07 +0000134
Rumeet Dhindsad366e362018-05-02 21:40:07 +0000135 if (Config->ThinLTOIndexOnly) {
Rui Ueyamad432f212018-05-07 23:24:16 +0000136 StringRef Path = Config->ThinLTOIndexOnlyArg;
137 if (!Path.empty())
138 IndexFile = openFile(Path);
139
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;
Rui Ueyamad31b54b2018-05-08 17:50:54 +0000168 bool IsExec = !Config->Shared && !Config->Relocatable;
Rumeet Dhindsad366e362018-05-02 21:40:07 +0000169
Rumeet Dhindsad366e362018-05-02 21:40:07 +0000170 // Create the empty files which, if indexed, will be overwritten later.
Rumeet Dhindsa4fb51192018-05-07 23:14:12 +0000171 if (Config->ThinLTOIndexOnly) {
172 std::string Path = getThinLTOOutputFile(Obj.getName());
173 openFile(Path + ".thinlto.bc");
174
175 if (Config->ThinLTOEmitImportsFiles)
176 openFile(Path + ".imports");
177 }
Rumeet Dhindsad366e362018-05-02 21:40:07 +0000178
Rui Ueyama2f9fa422018-05-08 17:50:43 +0000179 ArrayRef<Symbol *> Syms = F.getSymbols();
Rui Ueyamad31b54b2018-05-08 17:50:54 +0000180 ArrayRef<lto::InputFile::Symbol> ObjSyms = Obj.symbols();
Davide Italiano786d8e32016-09-29 00:40:08 +0000181 std::vector<lto::SymbolResolution> Resols(Syms.size());
Davide Italiano334fce92016-05-11 01:07:22 +0000182
Davide Italiano786d8e32016-09-29 00:40:08 +0000183 // Provide a resolution to the LTO API for each symbol.
Rui Ueyamad31b54b2018-05-08 17:50:54 +0000184 for (size_t I = 0, E = Syms.size(); I != E; ++I) {
185 Symbol *Sym = Syms[I];
186 const lto::InputFile::Symbol &ObjSym = ObjSyms[I];
187 lto::SymbolResolution &R = Resols[I];
Davide Italiano86f2bd52016-03-29 21:46:35 +0000188
Davide Italiano786d8e32016-09-29 00:40:08 +0000189 // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile
190 // reports two symbols for module ASM defined. Without this check, lld
191 // flags an undefined in IR with a definition in ASM as prevailing.
192 // Once IRObjectFile is fixed to report only one symbol this hack can
193 // be removed.
Rafael Espindoladfebd362017-11-29 22:47:35 +0000194 R.Prevailing = !ObjSym.isUndefined() && Sym->File == &F;
Peter Collingbourne3ad1c1e2016-05-05 17:13:49 +0000195
George Rimar3a1af222017-08-22 08:36:54 +0000196 // We ask LTO to preserve following global symbols:
197 // 1) All symbols when doing relocatable link, so that them can be used
198 // for doing final link.
199 // 2) Symbols that are used in regular objects.
200 // 3) C named sections if we have corresponding __start_/__stop_ symbol.
201 // 4) Symbols that are defined in bitcode files and used for dynamic linking.
202 R.VisibleToRegularObj = Config->Relocatable || Sym->IsUsedInRegularObj ||
Rafael Espindolaaffe7202017-07-25 22:51:05 +0000203 (R.Prevailing && Sym->includeInDynsym()) ||
Rafael Espindola4b075bb2017-07-26 23:39:10 +0000204 UsedStartStop.count(ObjSym.getSectionName());
Dmitry Mikulinc84e0ee2018-02-07 00:49:51 +0000205 const auto *DR = dyn_cast<Defined>(Sym);
Rafael Espindolac6df38c2018-01-16 16:49:05 +0000206 R.FinalDefinitionInLinkageUnit =
Rui Ueyamad31b54b2018-05-08 17:50:54 +0000207 (IsExec || Sym->Visibility != STV_DEFAULT) && DR &&
Dmitry Mikulinc84e0ee2018-02-07 00:49:51 +0000208 // Skip absolute symbols from ELF objects, otherwise PC-rel relocations
209 // will be generated by for them, triggering linker errors.
210 // Symbol section is always null for bitcode symbols, hence the check
Dmitry Mikulin8ddd9222018-02-08 04:25:52 +0000211 // for isElf(). Skip linker script defined symbols as well: they have
212 // no File defined.
213 !(DR->Section == nullptr && (!Sym->File || Sym->File->isElf()));
Rafael Espindolac6df38c2018-01-16 16:49:05 +0000214
Davide Italiano786d8e32016-09-29 00:40:08 +0000215 if (R.Prevailing)
Peter Smith3a52eb02017-02-01 10:26:03 +0000216 undefine(Sym);
George Rimard28c26b2017-09-25 09:31:43 +0000217
George Rimarc4ccfb52018-01-30 09:04:27 +0000218 // We tell LTO to not apply interprocedural optimization for wrapped
219 // (with --wrap) symbols because otherwise LTO would inline them while
220 // their values are still not final.
221 R.LinkerRedefined = !Sym->CanInline;
Rui Ueyama25992482016-03-22 20:52:10 +0000222 }
Davide Italiano3bfa0812016-11-26 05:37:04 +0000223 checkError(LTOObj->add(std::move(F.Obj), Resols));
Davide Italianobc176632016-04-15 22:38:10 +0000224}
225
Rui Ueyama25992482016-03-22 20:52:10 +0000226// Merge all the bitcode files we have seen, codegen the result
Davide Italiano786d8e32016-09-29 00:40:08 +0000227// and return the resulting ObjectFile(s).
Rui Ueyama38dbd3e2016-09-14 00:05:51 +0000228std::vector<InputFile *> BitcodeCompiler::compile() {
Davide Italiano786d8e32016-09-29 00:40:08 +0000229 std::vector<InputFile *> Ret;
Davide Italiano3bfa0812016-11-26 05:37:04 +0000230 unsigned MaxTasks = LTOObj->getMaxTasks();
Davide Italiano786d8e32016-09-29 00:40:08 +0000231 Buff.resize(MaxTasks);
Peter Collingbournee02775f2017-03-01 23:00:10 +0000232 Files.resize(MaxTasks);
Davide Italiano828ac5412016-03-28 15:44:21 +0000233
Peter Collingbournee02775f2017-03-01 23:00:10 +0000234 // The --thinlto-cache-dir option specifies the path to a directory in which
235 // to cache native object files for ThinLTO incremental builds. If a path was
236 // specified, configure LTO to use it as the cache directory.
237 lto::NativeObjectCache Cache;
238 if (!Config->ThinLTOCacheDir.empty())
Peter Collingbourne128423f2017-03-17 00:34:07 +0000239 Cache = check(
240 lto::localCache(Config->ThinLTOCacheDir,
Teresa Johnson2c2ed3c2018-02-20 20:21:59 +0000241 [&](size_t Task, std::unique_ptr<MemoryBuffer> MB) {
242 Files[Task] = std::move(MB);
243 }));
Peter Collingbournee02775f2017-03-01 23:00:10 +0000244
245 checkError(LTOObj->run(
246 [&](size_t Task) {
247 return llvm::make_unique<lto::NativeObjectStream>(
248 llvm::make_unique<raw_svector_ostream>(Buff[Task]));
249 },
250 Cache));
Rafael Espindolaabf6c652016-04-17 23:20:08 +0000251
Peter Collingbourneee59e432017-03-17 02:24:16 +0000252 if (!Config->ThinLTOCacheDir.empty())
253 pruneCache(Config->ThinLTOCacheDir, Config->ThinLTOCachePolicy);
254
Davide Italiano786d8e32016-09-29 00:40:08 +0000255 for (unsigned I = 0; I != MaxTasks; ++I) {
256 if (Buff[I].empty())
257 continue;
258 if (Config->SaveTemps) {
Peter Collingbourned22ec642017-01-26 02:18:28 +0000259 if (I == 0)
Davide Italiano786d8e32016-09-29 00:40:08 +0000260 saveBuffer(Buff[I], Config->OutputFile + ".lto.o");
261 else
262 saveBuffer(Buff[I], Config->OutputFile + Twine(I) + ".lto.o");
263 }
Rui Ueyama55518e72016-10-28 20:57:25 +0000264 InputFile *Obj = createObjectFile(MemoryBufferRef(Buff[I], "lto.tmp"));
Davide Italiano786d8e32016-09-29 00:40:08 +0000265 Ret.push_back(Obj);
266 }
Peter Collingbournee02775f2017-03-01 23:00:10 +0000267
Rui Ueyamad54f1c22018-05-07 22:11:24 +0000268 // If LazyObjFile has not been added to link, emit empty index files.
269 // This is needed because this is what GNU gold plugin does and we have a
270 // distributed build system that depends on that behavior.
271 if (Config->ThinLTOIndexOnly) {
272 for (LazyObjFile *F : LazyObjFiles) {
273 if (F->AddedToLink || !isBitcode(F->MB))
274 continue;
275
Rumeet Dhindsa4fb51192018-05-07 23:14:12 +0000276 std::string Path = getThinLTOOutputFile(F->getName());
277 std::unique_ptr<raw_fd_ostream> OS = openFile(Path + ".thinlto.bc");
Rui Ueyamad54f1c22018-05-07 22:11:24 +0000278 if (!OS)
279 continue;
280
281 ModuleSummaryIndex M(false);
282 M.setSkipModuleByDistributedBackend();
283 WriteIndexToFile(M, *OS);
Rumeet Dhindsa4fb51192018-05-07 23:14:12 +0000284
285 if (Config->ThinLTOEmitImportsFiles)
286 openFile(Path + ".imports");
Rui Ueyamad54f1c22018-05-07 22:11:24 +0000287 }
288
289 // ThinLTO with index only option is required to generate only the index
290 // files. After that, we exit from linker and ThinLTO backend runs in a
291 // distributed environment.
Rui Ueyama554adb22018-05-07 22:11:34 +0000292 if (IndexFile)
293 IndexFile->close();
294 return {};
Rui Ueyamad54f1c22018-05-07 22:11:24 +0000295 }
Rumeet Dhindsad366e362018-05-02 21:40:07 +0000296
Peter Collingbournee02775f2017-03-01 23:00:10 +0000297 for (std::unique_ptr<MemoryBuffer> &File : Files)
298 if (File)
299 Ret.push_back(createObjectFile(*File));
Davide Italiano786d8e32016-09-29 00:40:08 +0000300 return Ret;
Rui Ueyama961f2ff2016-03-23 21:19:27 +0000301}