blob: c97ff4d247675fa27b9b7cb71c4bf665020df679 [file] [log] [blame]
Rui Ueyama25992482016-03-22 20:52:10 +00001//===- LTO.cpp ------------------------------------------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Rui Ueyama25992482016-03-22 20:52:10 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "LTO.h"
10#include "Config.h"
Rui Ueyama25992482016-03-22 20:52:10 +000011#include "InputFiles.h"
Rui Ueyama3f851702017-10-02 21:00:41 +000012#include "LinkerScript.h"
Rafael Espindola4b075bb2017-07-26 23:39:10 +000013#include "SymbolTable.h"
Rui Ueyama25992482016-03-22 20:52:10 +000014#include "Symbols.h"
Sam Clegg5cdc91d2019-01-30 20:46:18 +000015#include "lld/Common/Args.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
Peter Collingbourne82a7f142018-08-06 20:12:12 +000070 // LLD supports the new relocations and address-significance tables.
Sam Cleggdfbd1902019-02-01 02:24:50 +000071 C.Options = initTargetOptionsFromCodeGenFlags();
Rui Ueyama397dffd2018-05-07 23:24:07 +000072 C.Options.RelaxELFRelocations = true;
Peter Collingbourne82a7f142018-08-06 20:12:12 +000073 C.Options.EmitAddrsig = true;
Davide Italianodf24d5b2016-06-02 22:58:11 +000074
Davide Italiano957f1202017-07-24 20:15:07 +000075 // Always emit a section per function/datum with LTO.
Rui Ueyama397dffd2018-05-07 23:24:07 +000076 C.Options.FunctionSections = true;
77 C.Options.DataSections = true;
Davide Italiano1f4e29c2017-07-24 19:38:13 +000078
Evgeniy Stepanovf12ac5b2017-05-22 21:11:44 +000079 if (Config->Relocatable)
Rui Ueyama397dffd2018-05-07 23:24:07 +000080 C.RelocModel = None;
Evgeniy Stepanovf12ac5b2017-05-22 21:11:44 +000081 else if (Config->Pic)
Rui Ueyama397dffd2018-05-07 23:24:07 +000082 C.RelocModel = Reloc::PIC_;
Evgeniy Stepanovf12ac5b2017-05-22 21:11:44 +000083 else
Rui Ueyama397dffd2018-05-07 23:24:07 +000084 C.RelocModel = Reloc::Static;
85
Sam Cleggdfbd1902019-02-01 02:24:50 +000086 C.CodeModel = getCodeModelFromCMModel();
Rui Ueyama397dffd2018-05-07 23:24:07 +000087 C.DisableVerify = Config->DisableVerify;
88 C.DiagHandler = diagnosticHandler;
89 C.OptLevel = Config->LTOO;
Sam Cleggdfbd1902019-02-01 02:24:50 +000090 C.CPU = getCPUStr();
91 C.MAttrs = getMAttrs();
Sam Clegg5cdc91d2019-01-30 20:46:18 +000092 C.CGOptLevel = args::getCGOptLevel(Config->LTOO);
Davide Italianodf24d5b2016-06-02 22:58:11 +000093
Davide Italiano786d8e32016-09-29 00:40:08 +000094 // Set up a custom pipeline if we've been asked to.
Rui Ueyama397dffd2018-05-07 23:24:07 +000095 C.OptPipeline = Config->LTONewPmPasses;
96 C.AAPipeline = Config->LTOAAPipeline;
Rui Ueyama25992482016-03-22 20:52:10 +000097
Davide Italianodb4b0a72017-02-13 17:49:18 +000098 // Set up optimization remarks if we've been asked to.
Rui Ueyama397dffd2018-05-07 23:24:07 +000099 C.RemarksFilename = Config->OptRemarksFilename;
Francis Visoiu Mistrih20fff322019-03-12 20:28:50 +0000100 C.RemarksPasses = Config->OptRemarksPasses;
Rui Ueyama397dffd2018-05-07 23:24:07 +0000101 C.RemarksWithHotness = Config->OptRemarksWithHotness;
102
103 C.SampleProfile = Config->LTOSampleProfile;
104 C.UseNewPM = Config->LTONewPassManager;
105 C.DebugPassManager = Config->LTODebugPassManager;
Yunlian Jiang496fb3e2018-07-16 17:55:48 +0000106 C.DwoDir = Config->DwoDir;
Davide Italianodb4b0a72017-02-13 17:49:18 +0000107
Rong Xuf92e59c2019-03-11 22:51:38 +0000108 C.CSIRProfile = Config->LTOCSProfileFile;
109 C.RunCSIRInstr = Config->LTOCSProfileGenerate;
110
Rui Ueyama9f499902018-12-14 21:58:49 +0000111 if (Config->EmitLLVM) {
112 C.PostInternalizeModuleHook = [](size_t Task, const Module &M) {
113 if (std::unique_ptr<raw_fd_ostream> OS = openFile(Config->OutputFile))
114 WriteBitcodeToFile(M, *OS, false);
115 return false;
116 };
117 }
118
Rui Ueyama25992482016-03-22 20:52:10 +0000119 if (Config->SaveTemps)
Rui Ueyama397dffd2018-05-07 23:24:07 +0000120 checkError(C.addSaveTemps(Config->OutputFile.str() + ".",
121 /*UseInputModulePath*/ true));
122 return C;
123}
Davide Italiano786d8e32016-09-29 00:40:08 +0000124
Rui Ueyama397dffd2018-05-07 23:24:07 +0000125BitcodeCompiler::BitcodeCompiler() {
Rui Ueyama98e4a5c2018-09-11 14:37:27 +0000126 // Initialize IndexFile.
127 if (!Config->ThinLTOIndexOnlyArg.empty())
128 IndexFile = openFile(Config->ThinLTOIndexOnlyArg);
129
Rui Ueyama397dffd2018-05-07 23:24:07 +0000130 // Initialize LTOObj.
Davide Italiano7a7b35a2016-10-10 18:12:53 +0000131 lto::ThinBackend Backend;
Rumeet Dhindsad366e362018-05-02 21:40:07 +0000132 if (Config->ThinLTOIndexOnly) {
Rui Ueyama98e4a5c2018-09-11 14:37:27 +0000133 auto OnIndexWrite = [&](StringRef S) { ThinIndices.erase(S); };
Rui Ueyama4454b3d2018-05-07 17:59:43 +0000134 Backend = lto::createWriteIndexesThinBackend(
135 Config->ThinLTOPrefixReplace.first, Config->ThinLTOPrefixReplace.second,
Rumeet Dhindsa18883262018-05-08 20:12:07 +0000136 Config->ThinLTOEmitImportsFiles, IndexFile.get(), OnIndexWrite);
Rui Ueyama397dffd2018-05-07 23:24:07 +0000137 } else if (Config->ThinLTOJobs != -1U) {
138 Backend = lto::createInProcessThinBackend(Config->ThinLTOJobs);
Rumeet Dhindsad366e362018-05-02 21:40:07 +0000139 }
140
Rui Ueyama397dffd2018-05-07 23:24:07 +0000141 LTOObj = llvm::make_unique<lto::LTO>(createConfig(), Backend,
Rui Ueyama66a9f252018-05-07 17:46:28 +0000142 Config->LTOPartitions);
Rui Ueyama25992482016-03-22 20:52:10 +0000143
Rui Ueyama397dffd2018-05-07 23:24:07 +0000144 // Initialize UsedStartStop.
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000145 for (Symbol *Sym : Symtab->getSymbols()) {
Rui Ueyama98e4a5c2018-09-11 14:37:27 +0000146 StringRef S = Sym->getName();
Rafael Espindola4b075bb2017-07-26 23:39:10 +0000147 for (StringRef Prefix : {"__start_", "__stop_"})
Rui Ueyama98e4a5c2018-09-11 14:37:27 +0000148 if (S.startswith(Prefix))
149 UsedStartStop.insert(S.substr(Prefix.size()));
Rafael Espindola4b075bb2017-07-26 23:39:10 +0000150 }
151}
Rafael Espindolaae605c12016-04-21 20:35:25 +0000152
Eugene Zelenko22886a22016-11-05 01:00:56 +0000153BitcodeCompiler::~BitcodeCompiler() = default;
Rui Ueyama412c8022016-04-22 21:16:18 +0000154
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000155static void undefine(Symbol *S) {
Rafael Espindolabec37652017-11-17 01:37:50 +0000156 replaceSymbol<Undefined>(S, nullptr, S->getName(), STB_GLOBAL, STV_DEFAULT,
157 S->Type);
Peter Collingbourne0ef38742016-05-12 19:46:14 +0000158}
159
Peter Smith3a52eb02017-02-01 10:26:03 +0000160void BitcodeCompiler::add(BitcodeFile &F) {
Davide Italiano786d8e32016-09-29 00:40:08 +0000161 lto::InputFile &Obj = *F.Obj;
Rui Ueyamad31b54b2018-05-08 17:50:54 +0000162 bool IsExec = !Config->Shared && !Config->Relocatable;
Rumeet Dhindsad366e362018-05-02 21:40:07 +0000163
Rumeet Dhindsa18883262018-05-08 20:12:07 +0000164 if (Config->ThinLTOIndexOnly)
Rui Ueyama98e4a5c2018-09-11 14:37:27 +0000165 ThinIndices.insert(Obj.getName());
Rumeet Dhindsad366e362018-05-02 21:40:07 +0000166
Rui Ueyama2f9fa422018-05-08 17:50:43 +0000167 ArrayRef<Symbol *> Syms = F.getSymbols();
Rui Ueyamad31b54b2018-05-08 17:50:54 +0000168 ArrayRef<lto::InputFile::Symbol> ObjSyms = Obj.symbols();
Davide Italiano786d8e32016-09-29 00:40:08 +0000169 std::vector<lto::SymbolResolution> Resols(Syms.size());
Davide Italiano334fce92016-05-11 01:07:22 +0000170
Davide Italiano786d8e32016-09-29 00:40:08 +0000171 // Provide a resolution to the LTO API for each symbol.
Rui Ueyamad31b54b2018-05-08 17:50:54 +0000172 for (size_t I = 0, E = Syms.size(); I != E; ++I) {
173 Symbol *Sym = Syms[I];
174 const lto::InputFile::Symbol &ObjSym = ObjSyms[I];
175 lto::SymbolResolution &R = Resols[I];
Davide Italiano86f2bd52016-03-29 21:46:35 +0000176
Davide Italiano786d8e32016-09-29 00:40:08 +0000177 // Ideally we shouldn't check for SF_Undefined but currently IRObjectFile
178 // reports two symbols for module ASM defined. Without this check, lld
179 // flags an undefined in IR with a definition in ASM as prevailing.
180 // Once IRObjectFile is fixed to report only one symbol this hack can
181 // be removed.
Rafael Espindoladfebd362017-11-29 22:47:35 +0000182 R.Prevailing = !ObjSym.isUndefined() && Sym->File == &F;
Peter Collingbourne3ad1c1e2016-05-05 17:13:49 +0000183
George Rimar3a1af222017-08-22 08:36:54 +0000184 // We ask LTO to preserve following global symbols:
185 // 1) All symbols when doing relocatable link, so that them can be used
186 // for doing final link.
187 // 2) Symbols that are used in regular objects.
188 // 3) C named sections if we have corresponding __start_/__stop_ symbol.
189 // 4) Symbols that are defined in bitcode files and used for dynamic linking.
190 R.VisibleToRegularObj = Config->Relocatable || Sym->IsUsedInRegularObj ||
Rafael Espindolaaffe7202017-07-25 22:51:05 +0000191 (R.Prevailing && Sym->includeInDynsym()) ||
Rafael Espindola4b075bb2017-07-26 23:39:10 +0000192 UsedStartStop.count(ObjSym.getSectionName());
Dmitry Mikulinc84e0ee2018-02-07 00:49:51 +0000193 const auto *DR = dyn_cast<Defined>(Sym);
Rafael Espindolac6df38c2018-01-16 16:49:05 +0000194 R.FinalDefinitionInLinkageUnit =
Rui Ueyamad31b54b2018-05-08 17:50:54 +0000195 (IsExec || Sym->Visibility != STV_DEFAULT) && DR &&
Dmitry Mikulinc84e0ee2018-02-07 00:49:51 +0000196 // Skip absolute symbols from ELF objects, otherwise PC-rel relocations
197 // will be generated by for them, triggering linker errors.
198 // Symbol section is always null for bitcode symbols, hence the check
Dmitry Mikulin8ddd9222018-02-08 04:25:52 +0000199 // for isElf(). Skip linker script defined symbols as well: they have
200 // no File defined.
201 !(DR->Section == nullptr && (!Sym->File || Sym->File->isElf()));
Rafael Espindolac6df38c2018-01-16 16:49:05 +0000202
Davide Italiano786d8e32016-09-29 00:40:08 +0000203 if (R.Prevailing)
Peter Smith3a52eb02017-02-01 10:26:03 +0000204 undefine(Sym);
George Rimard28c26b2017-09-25 09:31:43 +0000205
George Rimarc4ccfb52018-01-30 09:04:27 +0000206 // We tell LTO to not apply interprocedural optimization for wrapped
207 // (with --wrap) symbols because otherwise LTO would inline them while
208 // their values are still not final.
209 R.LinkerRedefined = !Sym->CanInline;
Rui Ueyama25992482016-03-22 20:52:10 +0000210 }
Davide Italiano3bfa0812016-11-26 05:37:04 +0000211 checkError(LTOObj->add(std::move(F.Obj), Resols));
Davide Italianobc176632016-04-15 22:38:10 +0000212}
213
Rui Ueyamaf06d4942018-05-17 18:27:12 +0000214static void createEmptyIndex(StringRef ModulePath) {
215 std::string Path = replaceThinLTOSuffix(getThinLTOOutputFile(ModulePath));
Rui Ueyamaf06d4942018-05-17 18:27:12 +0000216 std::unique_ptr<raw_fd_ostream> OS = openFile(Path + ".thinlto.bc");
217 if (!OS)
218 return;
219
Teresa Johnson566b4022018-06-06 22:22:13 +0000220 ModuleSummaryIndex M(/*HaveGVs*/ false);
Rui Ueyamaf06d4942018-05-17 18:27:12 +0000221 M.setSkipModuleByDistributedBackend();
222 WriteIndexToFile(M, *OS);
223
224 if (Config->ThinLTOEmitImportsFiles)
225 openFile(Path + ".imports");
226}
227
Rui Ueyama25992482016-03-22 20:52:10 +0000228// Merge all the bitcode files we have seen, codegen the result
Davide Italiano786d8e32016-09-29 00:40:08 +0000229// and return the resulting ObjectFile(s).
Rui Ueyama38dbd3e2016-09-14 00:05:51 +0000230std::vector<InputFile *> BitcodeCompiler::compile() {
Davide Italiano3bfa0812016-11-26 05:37:04 +0000231 unsigned MaxTasks = LTOObj->getMaxTasks();
Rui Ueyamaf06d4942018-05-17 18:27:12 +0000232 Buf.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>(
Rui Ueyamaf06d4942018-05-17 18:27:12 +0000249 llvm::make_unique<raw_svector_ostream>(Buf[Task]));
Peter Collingbournee02775f2017-03-01 23:00:10 +0000250 },
251 Cache));
Rafael Espindolaabf6c652016-04-17 23:20:08 +0000252
Rumeet Dhindsa18883262018-05-08 20:12:07 +0000253 // Emit empty index files for non-indexed files
Rui Ueyama98e4a5c2018-09-11 14:37:27 +0000254 for (StringRef S : ThinIndices) {
255 std::string Path = getThinLTOOutputFile(S);
256 openFile(Path + ".thinlto.bc");
257 if (Config->ThinLTOEmitImportsFiles)
258 openFile(Path + ".imports");
Davide Italiano786d8e32016-09-29 00:40:08 +0000259 }
Peter Collingbournee02775f2017-03-01 23:00:10 +0000260
Rui Ueyamad54f1c22018-05-07 22:11:24 +0000261 // If LazyObjFile has not been added to link, emit empty index files.
262 // This is needed because this is what GNU gold plugin does and we have a
263 // distributed build system that depends on that behavior.
264 if (Config->ThinLTOIndexOnly) {
Rui Ueyamaf06d4942018-05-17 18:27:12 +0000265 for (LazyObjFile *F : LazyObjFiles)
266 if (!F->AddedToLink && isBitcode(F->MB))
267 createEmptyIndex(F->getName());
Rui Ueyamad54f1c22018-05-07 22:11:24 +0000268
Rumeet Dhindsab5b7d6e2018-05-08 22:37:57 +0000269 if (!Config->LTOObjPath.empty())
Rui Ueyamaf06d4942018-05-17 18:27:12 +0000270 saveBuffer(Buf[0], Config->LTOObjPath);
Rumeet Dhindsa18883262018-05-08 20:12:07 +0000271
Rui Ueyamad54f1c22018-05-07 22:11:24 +0000272 // ThinLTO with index only option is required to generate only the index
273 // files. After that, we exit from linker and ThinLTO backend runs in a
274 // distributed environment.
Rui Ueyama554adb22018-05-07 22:11:34 +0000275 if (IndexFile)
276 IndexFile->close();
277 return {};
Rui Ueyamad54f1c22018-05-07 22:11:24 +0000278 }
Rui Ueyamaf06d4942018-05-17 18:27:12 +0000279
Rumeet Dhindsa18883262018-05-08 20:12:07 +0000280 if (!Config->ThinLTOCacheDir.empty())
281 pruneCache(Config->ThinLTOCacheDir, Config->ThinLTOCachePolicy);
282
Bill Wendling01706bd2019-02-26 19:29:14 +0000283 if (!Config->LTOObjPath.empty()) {
284 saveBuffer(Buf[0], Config->LTOObjPath);
285 for (unsigned I = 1; I != MaxTasks; ++I)
286 saveBuffer(Buf[I], Config->LTOObjPath + Twine(I));
Rumeet Dhindsa18883262018-05-08 20:12:07 +0000287 }
Rumeet Dhindsad366e362018-05-02 21:40:07 +0000288
Bill Wendling01706bd2019-02-26 19:29:14 +0000289 if (Config->SaveTemps) {
290 saveBuffer(Buf[0], Config->OutputFile + ".lto.o");
291 for (unsigned I = 1; I != MaxTasks; ++I)
292 saveBuffer(Buf[I], Config->OutputFile + Twine(I) + ".lto.o");
293 }
294
295 std::vector<InputFile *> Ret;
296 for (unsigned I = 0; I != MaxTasks; ++I)
297 if (!Buf[I].empty())
298 Ret.push_back(createObjectFile(MemoryBufferRef(Buf[I], "lto.tmp")));
299
Peter Collingbournee02775f2017-03-01 23:00:10 +0000300 for (std::unique_ptr<MemoryBuffer> &File : Files)
301 if (File)
302 Ret.push_back(createObjectFile(*File));
Davide Italiano786d8e32016-09-29 00:40:08 +0000303 return Ret;
Rui Ueyama961f2ff2016-03-23 21:19:27 +0000304}