blob: ef58932e86cc7be4dbbbabdff726bcf183ea8f6b [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
Rui Ueyama66a9f252018-05-07 17:46:28 +000048// Creates an empty file to store a list of object files for final
Rumeet Dhindsad366e362018-05-02 21:40:07 +000049// linking of distributed ThinLTO.
Rui Ueyama66a9f252018-05-07 17:46:28 +000050static std::unique_ptr<raw_fd_ostream> openFile(StringRef File) {
Rumeet Dhindsad366e362018-05-02 21:40:07 +000051 std::error_code EC;
Rui Ueyama66a9f252018-05-07 17:46:28 +000052 auto Ret =
53 llvm::make_unique<raw_fd_ostream>(File, EC, sys::fs::OpenFlags::F_None);
Rui Ueyamad54f1c22018-05-07 22:11:24 +000054 if (EC) {
55 error("cannot open " + File + ": " + EC.message());
56 return nullptr;
57 }
Rui Ueyama66a9f252018-05-07 17:46:28 +000058 return Ret;
Rumeet Dhindsad366e362018-05-02 21:40:07 +000059}
60
Rui Ueyamad54f1c22018-05-07 22:11:24 +000061static std::string getThinLTOOutputFile(StringRef ModulePath) {
62 return lto::getThinLTOOutputFile(ModulePath,
63 Config->ThinLTOPrefixReplace.first,
Rumeet Dhindsa4fb51192018-05-07 23:14:12 +000064 Config->ThinLTOPrefixReplace.second);
Rui Ueyamad54f1c22018-05-07 22:11:24 +000065}
66
Rui Ueyama397dffd2018-05-07 23:24:07 +000067static lto::Config createConfig() {
68 lto::Config C;
Davide Italianod26c4a12016-05-15 19:29:38 +000069
Davide Italiano786d8e32016-09-29 00:40:08 +000070 // LLD supports the new relocations.
Rui Ueyama397dffd2018-05-07 23:24:07 +000071 C.Options = InitTargetOptionsFromCodeGenFlags();
72 C.Options.RelaxELFRelocations = true;
Davide Italianodf24d5b2016-06-02 22:58:11 +000073
Davide Italiano957f1202017-07-24 20:15:07 +000074 // Always emit a section per function/datum with LTO.
Rui Ueyama397dffd2018-05-07 23:24:07 +000075 C.Options.FunctionSections = true;
76 C.Options.DataSections = true;
Davide Italiano1f4e29c2017-07-24 19:38:13 +000077
Evgeniy Stepanovf12ac5b2017-05-22 21:11:44 +000078 if (Config->Relocatable)
Rui Ueyama397dffd2018-05-07 23:24:07 +000079 C.RelocModel = None;
Evgeniy Stepanovf12ac5b2017-05-22 21:11:44 +000080 else if (Config->Pic)
Rui Ueyama397dffd2018-05-07 23:24:07 +000081 C.RelocModel = Reloc::PIC_;
Evgeniy Stepanovf12ac5b2017-05-22 21:11:44 +000082 else
Rui Ueyama397dffd2018-05-07 23:24:07 +000083 C.RelocModel = Reloc::Static;
84
85 C.CodeModel = GetCodeModelFromCMModel();
86 C.DisableVerify = Config->DisableVerify;
87 C.DiagHandler = diagnosticHandler;
88 C.OptLevel = Config->LTOO;
89 C.CPU = GetCPUStr();
Davide Italianodf24d5b2016-06-02 22:58:11 +000090
Davide Italiano786d8e32016-09-29 00:40:08 +000091 // Set up a custom pipeline if we've been asked to.
Rui Ueyama397dffd2018-05-07 23:24:07 +000092 C.OptPipeline = Config->LTONewPmPasses;
93 C.AAPipeline = Config->LTOAAPipeline;
Rui Ueyama25992482016-03-22 20:52:10 +000094
Davide Italianodb4b0a72017-02-13 17:49:18 +000095 // Set up optimization remarks if we've been asked to.
Rui Ueyama397dffd2018-05-07 23:24:07 +000096 C.RemarksFilename = Config->OptRemarksFilename;
97 C.RemarksWithHotness = Config->OptRemarksWithHotness;
98
99 C.SampleProfile = Config->LTOSampleProfile;
100 C.UseNewPM = Config->LTONewPassManager;
101 C.DebugPassManager = Config->LTODebugPassManager;
Yunlian Jiang496fb3e2018-07-16 17:55:48 +0000102 C.DwoDir = Config->DwoDir;
Davide Italianodb4b0a72017-02-13 17:49:18 +0000103
Rui Ueyama25992482016-03-22 20:52:10 +0000104 if (Config->SaveTemps)
Rui Ueyama397dffd2018-05-07 23:24:07 +0000105 checkError(C.addSaveTemps(Config->OutputFile.str() + ".",
106 /*UseInputModulePath*/ true));
107 return C;
108}
Davide Italiano786d8e32016-09-29 00:40:08 +0000109
Rui Ueyama397dffd2018-05-07 23:24:07 +0000110BitcodeCompiler::BitcodeCompiler() {
111 // Initialize LTOObj.
Davide Italiano7a7b35a2016-10-10 18:12:53 +0000112 lto::ThinBackend Backend;
Rumeet Dhindsa682a4172018-04-09 17:56:07 +0000113
Rumeet Dhindsad366e362018-05-02 21:40:07 +0000114 if (Config->ThinLTOIndexOnly) {
Rui Ueyamad432f212018-05-07 23:24:16 +0000115 StringRef Path = Config->ThinLTOIndexOnlyArg;
116 if (!Path.empty())
117 IndexFile = openFile(Path);
118
Rumeet Dhindsa18883262018-05-08 20:12:07 +0000119 auto OnIndexWrite = [&](const std::string &Identifier) {
120 ObjectToIndexFileState[Identifier] = true;
121 };
122
Rui Ueyama4454b3d2018-05-07 17:59:43 +0000123 Backend = lto::createWriteIndexesThinBackend(
124 Config->ThinLTOPrefixReplace.first, Config->ThinLTOPrefixReplace.second,
Rumeet Dhindsa18883262018-05-08 20:12:07 +0000125 Config->ThinLTOEmitImportsFiles, IndexFile.get(), OnIndexWrite);
Rui Ueyama397dffd2018-05-07 23:24:07 +0000126 } else if (Config->ThinLTOJobs != -1U) {
127 Backend = lto::createInProcessThinBackend(Config->ThinLTOJobs);
Rumeet Dhindsad366e362018-05-02 21:40:07 +0000128 }
129
Rui Ueyama397dffd2018-05-07 23:24:07 +0000130 LTOObj = llvm::make_unique<lto::LTO>(createConfig(), Backend,
Rui Ueyama66a9f252018-05-07 17:46:28 +0000131 Config->LTOPartitions);
Rui Ueyama25992482016-03-22 20:52:10 +0000132
Rui Ueyama397dffd2018-05-07 23:24:07 +0000133 // Initialize UsedStartStop.
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000134 for (Symbol *Sym : Symtab->getSymbols()) {
Rui Ueyamaf1f00842017-10-31 16:07:41 +0000135 StringRef Name = Sym->getName();
Rafael Espindola4b075bb2017-07-26 23:39:10 +0000136 for (StringRef Prefix : {"__start_", "__stop_"})
Fangrui Songbdbe5d82018-05-23 16:51:23 +0000137 if (Name.startswith(Prefix))
138 UsedStartStop.insert(Name.substr(Prefix.size()));
Rafael Espindola4b075bb2017-07-26 23:39:10 +0000139 }
140}
Rafael Espindolaae605c12016-04-21 20:35:25 +0000141
Eugene Zelenko22886a22016-11-05 01:00:56 +0000142BitcodeCompiler::~BitcodeCompiler() = default;
Rui Ueyama412c8022016-04-22 21:16:18 +0000143
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000144static void undefine(Symbol *S) {
Rafael Espindolabec37652017-11-17 01:37:50 +0000145 replaceSymbol<Undefined>(S, nullptr, S->getName(), STB_GLOBAL, STV_DEFAULT,
146 S->Type);
Peter Collingbourne0ef38742016-05-12 19:46:14 +0000147}
148
Peter Smith3a52eb02017-02-01 10:26:03 +0000149void BitcodeCompiler::add(BitcodeFile &F) {
Davide Italiano786d8e32016-09-29 00:40:08 +0000150 lto::InputFile &Obj = *F.Obj;
Rui Ueyamad31b54b2018-05-08 17:50:54 +0000151 bool IsExec = !Config->Shared && !Config->Relocatable;
Rumeet Dhindsad366e362018-05-02 21:40:07 +0000152
Rumeet Dhindsa18883262018-05-08 20:12:07 +0000153 if (Config->ThinLTOIndexOnly)
154 ObjectToIndexFileState.insert({Obj.getName(), false});
Rumeet Dhindsad366e362018-05-02 21:40:07 +0000155
Rui Ueyama2f9fa422018-05-08 17:50:43 +0000156 ArrayRef<Symbol *> Syms = F.getSymbols();
Rui Ueyamad31b54b2018-05-08 17:50:54 +0000157 ArrayRef<lto::InputFile::Symbol> ObjSyms = Obj.symbols();
Davide Italiano786d8e32016-09-29 00:40:08 +0000158 std::vector<lto::SymbolResolution> Resols(Syms.size());
Davide Italiano334fce92016-05-11 01:07:22 +0000159
Davide Italiano786d8e32016-09-29 00:40:08 +0000160 // Provide a resolution to the LTO API for each symbol.
Rui Ueyamad31b54b2018-05-08 17:50:54 +0000161 for (size_t I = 0, E = Syms.size(); I != E; ++I) {
162 Symbol *Sym = Syms[I];
163 const lto::InputFile::Symbol &ObjSym = ObjSyms[I];
164 lto::SymbolResolution &R = Resols[I];
Davide Italiano86f2bd52016-03-29 21:46:35 +0000165
Davide Italiano786d8e32016-09-29 00:40:08 +0000166 // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile
167 // reports two symbols for module ASM defined. Without this check, lld
168 // flags an undefined in IR with a definition in ASM as prevailing.
169 // Once IRObjectFile is fixed to report only one symbol this hack can
170 // be removed.
Rafael Espindoladfebd362017-11-29 22:47:35 +0000171 R.Prevailing = !ObjSym.isUndefined() && Sym->File == &F;
Peter Collingbourne3ad1c1e2016-05-05 17:13:49 +0000172
George Rimar3a1af222017-08-22 08:36:54 +0000173 // We ask LTO to preserve following global symbols:
174 // 1) All symbols when doing relocatable link, so that them can be used
175 // for doing final link.
176 // 2) Symbols that are used in regular objects.
177 // 3) C named sections if we have corresponding __start_/__stop_ symbol.
178 // 4) Symbols that are defined in bitcode files and used for dynamic linking.
179 R.VisibleToRegularObj = Config->Relocatable || Sym->IsUsedInRegularObj ||
Rafael Espindolaaffe7202017-07-25 22:51:05 +0000180 (R.Prevailing && Sym->includeInDynsym()) ||
Rafael Espindola4b075bb2017-07-26 23:39:10 +0000181 UsedStartStop.count(ObjSym.getSectionName());
Dmitry Mikulinc84e0ee2018-02-07 00:49:51 +0000182 const auto *DR = dyn_cast<Defined>(Sym);
Rafael Espindolac6df38c2018-01-16 16:49:05 +0000183 R.FinalDefinitionInLinkageUnit =
Rui Ueyamad31b54b2018-05-08 17:50:54 +0000184 (IsExec || Sym->Visibility != STV_DEFAULT) && DR &&
Dmitry Mikulinc84e0ee2018-02-07 00:49:51 +0000185 // Skip absolute symbols from ELF objects, otherwise PC-rel relocations
186 // will be generated by for them, triggering linker errors.
187 // Symbol section is always null for bitcode symbols, hence the check
Dmitry Mikulin8ddd9222018-02-08 04:25:52 +0000188 // for isElf(). Skip linker script defined symbols as well: they have
189 // no File defined.
190 !(DR->Section == nullptr && (!Sym->File || Sym->File->isElf()));
Rafael Espindolac6df38c2018-01-16 16:49:05 +0000191
Davide Italiano786d8e32016-09-29 00:40:08 +0000192 if (R.Prevailing)
Peter Smith3a52eb02017-02-01 10:26:03 +0000193 undefine(Sym);
George Rimard28c26b2017-09-25 09:31:43 +0000194
George Rimarc4ccfb52018-01-30 09:04:27 +0000195 // We tell LTO to not apply interprocedural optimization for wrapped
196 // (with --wrap) symbols because otherwise LTO would inline them while
197 // their values are still not final.
198 R.LinkerRedefined = !Sym->CanInline;
Rui Ueyama25992482016-03-22 20:52:10 +0000199 }
Davide Italiano3bfa0812016-11-26 05:37:04 +0000200 checkError(LTOObj->add(std::move(F.Obj), Resols));
Davide Italianobc176632016-04-15 22:38:10 +0000201}
202
Rui Ueyamaf06d4942018-05-17 18:27:12 +0000203static void createEmptyIndex(StringRef ModulePath) {
204 std::string Path = replaceThinLTOSuffix(getThinLTOOutputFile(ModulePath));
Rui Ueyamaf06d4942018-05-17 18:27:12 +0000205 std::unique_ptr<raw_fd_ostream> OS = openFile(Path + ".thinlto.bc");
206 if (!OS)
207 return;
208
Teresa Johnson566b4022018-06-06 22:22:13 +0000209 ModuleSummaryIndex M(/*HaveGVs*/ false);
Rui Ueyamaf06d4942018-05-17 18:27:12 +0000210 M.setSkipModuleByDistributedBackend();
211 WriteIndexToFile(M, *OS);
212
213 if (Config->ThinLTOEmitImportsFiles)
214 openFile(Path + ".imports");
215}
216
Rui Ueyama25992482016-03-22 20:52:10 +0000217// Merge all the bitcode files we have seen, codegen the result
Davide Italiano786d8e32016-09-29 00:40:08 +0000218// and return the resulting ObjectFile(s).
Rui Ueyama38dbd3e2016-09-14 00:05:51 +0000219std::vector<InputFile *> BitcodeCompiler::compile() {
Davide Italiano3bfa0812016-11-26 05:37:04 +0000220 unsigned MaxTasks = LTOObj->getMaxTasks();
Rui Ueyamaf06d4942018-05-17 18:27:12 +0000221 Buf.resize(MaxTasks);
Peter Collingbournee02775f2017-03-01 23:00:10 +0000222 Files.resize(MaxTasks);
Davide Italiano828ac5412016-03-28 15:44:21 +0000223
Peter Collingbournee02775f2017-03-01 23:00:10 +0000224 // The --thinlto-cache-dir option specifies the path to a directory in which
225 // to cache native object files for ThinLTO incremental builds. If a path was
226 // specified, configure LTO to use it as the cache directory.
227 lto::NativeObjectCache Cache;
228 if (!Config->ThinLTOCacheDir.empty())
Peter Collingbourne128423f2017-03-17 00:34:07 +0000229 Cache = check(
230 lto::localCache(Config->ThinLTOCacheDir,
Teresa Johnson2c2ed3c2018-02-20 20:21:59 +0000231 [&](size_t Task, std::unique_ptr<MemoryBuffer> MB) {
232 Files[Task] = std::move(MB);
233 }));
Peter Collingbournee02775f2017-03-01 23:00:10 +0000234
235 checkError(LTOObj->run(
236 [&](size_t Task) {
237 return llvm::make_unique<lto::NativeObjectStream>(
Rui Ueyamaf06d4942018-05-17 18:27:12 +0000238 llvm::make_unique<raw_svector_ostream>(Buf[Task]));
Peter Collingbournee02775f2017-03-01 23:00:10 +0000239 },
240 Cache));
Rafael Espindolaabf6c652016-04-17 23:20:08 +0000241
Rumeet Dhindsa18883262018-05-08 20:12:07 +0000242 // Emit empty index files for non-indexed files
243 if (Config->ThinLTOIndexOnly) {
244 for (auto &Identifier : ObjectToIndexFileState)
245 if (!Identifier.getValue()) {
246 std::string Path = getThinLTOOutputFile(Identifier.getKey());
247 openFile(Path + ".thinlto.bc");
Peter Collingbourneee59e432017-03-17 02:24:16 +0000248
Rumeet Dhindsa18883262018-05-08 20:12:07 +0000249 if (Config->ThinLTOEmitImportsFiles)
250 openFile(Path + ".imports");
251 }
Davide Italiano786d8e32016-09-29 00:40:08 +0000252 }
Peter Collingbournee02775f2017-03-01 23:00:10 +0000253
Rui Ueyamad54f1c22018-05-07 22:11:24 +0000254 // If LazyObjFile has not been added to link, emit empty index files.
255 // This is needed because this is what GNU gold plugin does and we have a
256 // distributed build system that depends on that behavior.
257 if (Config->ThinLTOIndexOnly) {
Rui Ueyamaf06d4942018-05-17 18:27:12 +0000258 for (LazyObjFile *F : LazyObjFiles)
259 if (!F->AddedToLink && isBitcode(F->MB))
260 createEmptyIndex(F->getName());
Rui Ueyamad54f1c22018-05-07 22:11:24 +0000261
Rumeet Dhindsab5b7d6e2018-05-08 22:37:57 +0000262 if (!Config->LTOObjPath.empty())
Rui Ueyamaf06d4942018-05-17 18:27:12 +0000263 saveBuffer(Buf[0], Config->LTOObjPath);
Rumeet Dhindsa18883262018-05-08 20:12:07 +0000264
Rui Ueyamad54f1c22018-05-07 22:11:24 +0000265 // ThinLTO with index only option is required to generate only the index
266 // files. After that, we exit from linker and ThinLTO backend runs in a
267 // distributed environment.
Rui Ueyama554adb22018-05-07 22:11:34 +0000268 if (IndexFile)
269 IndexFile->close();
270 return {};
Rui Ueyamad54f1c22018-05-07 22:11:24 +0000271 }
Rui Ueyamaf06d4942018-05-17 18:27:12 +0000272
Rumeet Dhindsa18883262018-05-08 20:12:07 +0000273 if (!Config->ThinLTOCacheDir.empty())
274 pruneCache(Config->ThinLTOCacheDir, Config->ThinLTOCachePolicy);
275
276 std::vector<InputFile *> Ret;
277 for (unsigned I = 0; I != MaxTasks; ++I) {
Rui Ueyamaf06d4942018-05-17 18:27:12 +0000278 if (Buf[I].empty())
Rumeet Dhindsa18883262018-05-08 20:12:07 +0000279 continue;
280 if (Config->SaveTemps) {
281 if (I == 0)
Rui Ueyamaf06d4942018-05-17 18:27:12 +0000282 saveBuffer(Buf[I], Config->OutputFile + ".lto.o");
Rumeet Dhindsa18883262018-05-08 20:12:07 +0000283 else
Rui Ueyamaf06d4942018-05-17 18:27:12 +0000284 saveBuffer(Buf[I], Config->OutputFile + Twine(I) + ".lto.o");
Rumeet Dhindsa18883262018-05-08 20:12:07 +0000285 }
Rui Ueyamaf06d4942018-05-17 18:27:12 +0000286 InputFile *Obj = createObjectFile(MemoryBufferRef(Buf[I], "lto.tmp"));
Rumeet Dhindsa18883262018-05-08 20:12:07 +0000287 Ret.push_back(Obj);
288 }
Rumeet Dhindsad366e362018-05-02 21:40:07 +0000289
Peter Collingbournee02775f2017-03-01 23:00:10 +0000290 for (std::unique_ptr<MemoryBuffer> &File : Files)
291 if (File)
292 Ret.push_back(createObjectFile(*File));
Davide Italiano786d8e32016-09-29 00:40:08 +0000293 return Ret;
Rui Ueyama961f2ff2016-03-23 21:19:27 +0000294}