blob: db0253161b8d11282275dda07650045c07676c64 [file] [log] [blame]
Teresa Johnsondf6edc52016-05-23 22:54:06 +00001//===-LTO.cpp - LLVM Link Time Optimizer ----------------------------------===//
2//
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 file implements functions and classes used to support LTO.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/LTO/LTO.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000015#include "llvm/Analysis/TargetLibraryInfo.h"
16#include "llvm/Analysis/TargetTransformInfo.h"
Teresa Johnsonad176792016-11-11 05:34:58 +000017#include "llvm/Bitcode/BitcodeReader.h"
18#include "llvm/Bitcode/BitcodeWriter.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000019#include "llvm/CodeGen/Analysis.h"
Bob Haarmandd4ebc12017-02-02 23:00:49 +000020#include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000021#include "llvm/IR/AutoUpgrade.h"
22#include "llvm/IR/DiagnosticPrinter.h"
23#include "llvm/IR/LegacyPassManager.h"
Bob Haarmandd4ebc12017-02-02 23:00:49 +000024#include "llvm/IR/Mangler.h"
25#include "llvm/IR/Metadata.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000026#include "llvm/LTO/LTOBackend.h"
27#include "llvm/Linker/IRMover.h"
28#include "llvm/Object/ModuleSummaryIndexObjectFile.h"
Bob Haarmandd4ebc12017-02-02 23:00:49 +000029#include "llvm/Support/Error.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000030#include "llvm/Support/ManagedStatic.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000031#include "llvm/Support/MemoryBuffer.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000032#include "llvm/Support/Path.h"
Mehdi Aminiadc0e262016-08-23 21:30:12 +000033#include "llvm/Support/SHA1.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000034#include "llvm/Support/SourceMgr.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000035#include "llvm/Support/TargetRegistry.h"
36#include "llvm/Support/ThreadPool.h"
Teresa Johnsonec544c52016-10-19 17:35:01 +000037#include "llvm/Support/Threading.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000038#include "llvm/Support/raw_ostream.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000039#include "llvm/Target/TargetMachine.h"
40#include "llvm/Target/TargetOptions.h"
41#include "llvm/Transforms/IPO.h"
42#include "llvm/Transforms/IPO/PassManagerBuilder.h"
43#include "llvm/Transforms/Utils/SplitModule.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000044
Teresa Johnson9ba95f92016-08-11 14:58:12 +000045#include <set>
46
47using namespace llvm;
48using namespace lto;
49using namespace object;
Teresa Johnsondf6edc52016-05-23 22:54:06 +000050
Mehdi Aminiadc0e262016-08-23 21:30:12 +000051#define DEBUG_TYPE "lto"
52
53// Returns a unique hash for the Module considering the current list of
54// export/import and other global analysis results.
55// The hash is produced in \p Key.
56static void computeCacheKey(
Peter Collingbournef4257522016-12-08 05:28:30 +000057 SmallString<40> &Key, const Config &Conf, const ModuleSummaryIndex &Index,
58 StringRef ModuleID, const FunctionImporter::ImportMapTy &ImportList,
Mehdi Aminiadc0e262016-08-23 21:30:12 +000059 const FunctionImporter::ExportSetTy &ExportList,
60 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
61 const GVSummaryMapTy &DefinedGlobals) {
62 // Compute the unique hash for this entry.
63 // This is based on the current compiler version, the module itself, the
64 // export list, the hash for every single module in the import list, the
65 // list of ResolvedODR for the module, and the list of preserved symbols.
66 SHA1 Hasher;
67
68 // Start with the compiler revision
69 Hasher.update(LLVM_VERSION_STRING);
70#ifdef HAVE_LLVM_REVISION
71 Hasher.update(LLVM_REVISION);
72#endif
73
Peter Collingbournef4257522016-12-08 05:28:30 +000074 // Include the parts of the LTO configuration that affect code generation.
75 auto AddString = [&](StringRef Str) {
76 Hasher.update(Str);
77 Hasher.update(ArrayRef<uint8_t>{0});
78 };
79 auto AddUnsigned = [&](unsigned I) {
80 uint8_t Data[4];
81 Data[0] = I;
82 Data[1] = I >> 8;
83 Data[2] = I >> 16;
84 Data[3] = I >> 24;
85 Hasher.update(ArrayRef<uint8_t>{Data, 4});
86 };
87 AddString(Conf.CPU);
88 // FIXME: Hash more of Options. For now all clients initialize Options from
89 // command-line flags (which is unsupported in production), but may set
90 // RelaxELFRelocations. The clang driver can also pass FunctionSections,
91 // DataSections and DebuggerTuning via command line flags.
92 AddUnsigned(Conf.Options.RelaxELFRelocations);
93 AddUnsigned(Conf.Options.FunctionSections);
94 AddUnsigned(Conf.Options.DataSections);
95 AddUnsigned((unsigned)Conf.Options.DebuggerTuning);
96 for (auto &A : Conf.MAttrs)
97 AddString(A);
98 AddUnsigned(Conf.RelocModel);
99 AddUnsigned(Conf.CodeModel);
100 AddUnsigned(Conf.CGOptLevel);
101 AddUnsigned(Conf.OptLevel);
102 AddString(Conf.OptPipeline);
103 AddString(Conf.AAPipeline);
104 AddString(Conf.OverrideTriple);
105 AddString(Conf.DefaultTriple);
106
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000107 // Include the hash for the current module
108 auto ModHash = Index.getModuleHash(ModuleID);
109 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
110 for (auto F : ExportList)
111 // The export list can impact the internalization, be conservative here
112 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
113
114 // Include the hash for every module we import functions from
115 for (auto &Entry : ImportList) {
116 auto ModHash = Index.getModuleHash(Entry.first());
117 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
118 }
119
120 // Include the hash for the resolved ODR.
121 for (auto &Entry : ResolvedODR) {
122 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
123 sizeof(GlobalValue::GUID)));
124 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
125 sizeof(GlobalValue::LinkageTypes)));
126 }
127
128 // Include the hash for the linkage type to reflect internalization and weak
129 // resolution.
130 for (auto &GS : DefinedGlobals) {
131 GlobalValue::LinkageTypes Linkage = GS.second->linkage();
132 Hasher.update(
133 ArrayRef<uint8_t>((const uint8_t *)&Linkage, sizeof(Linkage)));
134 }
135
Dehao Chen27978002016-12-16 16:48:46 +0000136 if (!Conf.SampleProfile.empty()) {
137 auto FileOrErr = MemoryBuffer::getFile(Conf.SampleProfile);
138 if (FileOrErr)
139 Hasher.update(FileOrErr.get()->getBuffer());
140 }
141
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000142 Key = toHex(Hasher.result());
143}
144
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000145static void thinLTOResolveWeakForLinkerGUID(
146 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
147 DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000148 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000149 isPrevailing,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000150 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000151 recordNewLinkage) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000152 for (auto &S : GVSummaryList) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000153 GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
154 if (!GlobalValue::isWeakForLinker(OriginalLinkage))
155 continue;
Peter Collingbourne73589f32016-07-07 18:31:51 +0000156 // We need to emit only one of these. The prevailing module will keep it,
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000157 // but turned into a weak, while the others will drop it when possible.
Teresa Johnson3bc8abd2016-10-30 05:15:23 +0000158 // This is both a compile-time optimization and a correctness
159 // transformation. This is necessary for correctness when we have exported
160 // a reference - we need to convert the linkonce to weak to
161 // ensure a copy is kept to satisfy the exported reference.
162 // FIXME: We may want to split the compile time and correctness
163 // aspects into separate routines.
Peter Collingbourne73589f32016-07-07 18:31:51 +0000164 if (isPrevailing(GUID, S.get())) {
Teresa Johnson28c03b52016-05-26 14:16:52 +0000165 if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
166 S->setLinkage(GlobalValue::getWeakLinkage(
167 GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000168 }
Teresa Johnson3bc8abd2016-10-30 05:15:23 +0000169 // Alias and aliasee can't be turned into available_externally.
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000170 else if (!isa<AliasSummary>(S.get()) &&
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000171 !GlobalInvolvedWithAlias.count(S.get()))
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000172 S->setLinkage(GlobalValue::AvailableExternallyLinkage);
173 if (S->linkage() != OriginalLinkage)
174 recordNewLinkage(S->modulePath(), GUID, S->linkage());
175 }
176}
177
178// Resolve Weak and LinkOnce values in the \p Index.
179//
180// We'd like to drop these functions if they are no longer referenced in the
181// current module. However there is a chance that another module is still
182// referencing them because of the import. We make sure we always emit at least
183// one copy.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000184void llvm::thinLTOResolveWeakForLinkerInIndex(
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000185 ModuleSummaryIndex &Index,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000186 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000187 isPrevailing,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000188 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000189 recordNewLinkage) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000190 // We won't optimize the globals that are referenced by an alias for now
191 // Ideally we should turn the alias into a global and duplicate the definition
192 // when needed.
193 DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
194 for (auto &I : Index)
195 for (auto &S : I.second)
196 if (auto AS = dyn_cast<AliasSummary>(S.get()))
197 GlobalInvolvedWithAlias.insert(&AS->getAliasee());
198
199 for (auto &I : Index)
200 thinLTOResolveWeakForLinkerGUID(I.second, I.first, GlobalInvolvedWithAlias,
Peter Collingbourne73589f32016-07-07 18:31:51 +0000201 isPrevailing, recordNewLinkage);
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000202}
203
204static void thinLTOInternalizeAndPromoteGUID(
205 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
Mehdi Amini97624fb2017-02-02 18:31:35 +0000206 function_ref<SummaryResolution(StringRef, GlobalValue::GUID)> isExported) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000207 for (auto &S : GVSummaryList) {
Mehdi Amini97624fb2017-02-02 18:31:35 +0000208 auto ExportResolution = isExported(S->modulePath(), GUID);
209 if (ExportResolution != Internal) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000210 if (GlobalValue::isLocalLinkage(S->linkage()))
211 S->setLinkage(GlobalValue::ExternalLinkage);
Mehdi Amini97624fb2017-02-02 18:31:35 +0000212 if (ExportResolution == Hidden)
213 S->setAutoHide();
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000214 } else if (!GlobalValue::isLocalLinkage(S->linkage()))
215 S->setLinkage(GlobalValue::InternalLinkage);
216 }
217}
218
219// Update the linkages in the given \p Index to mark exported values
220// as external and non-exported values as internal.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000221void llvm::thinLTOInternalizeAndPromoteInIndex(
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000222 ModuleSummaryIndex &Index,
Mehdi Amini97624fb2017-02-02 18:31:35 +0000223 function_ref<SummaryResolution(StringRef, GlobalValue::GUID)> isExported) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000224 for (auto &I : Index)
225 thinLTOInternalizeAndPromoteGUID(I.second, I.first, isExported);
226}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000227
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000228struct InputFile::InputModule {
229 BitcodeModule BM;
230 std::unique_ptr<Module> Mod;
231
232 // The range of ModuleSymbolTable entries for this input module.
233 size_t SymBegin, SymEnd;
234};
235
236// Requires a destructor for std::vector<InputModule>.
237InputFile::~InputFile() = default;
238
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000239Expected<std::unique_ptr<InputFile>> InputFile::create(MemoryBufferRef Object) {
240 std::unique_ptr<InputFile> File(new InputFile);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000241
Peter Collingbournead903692016-12-13 19:43:49 +0000242 ErrorOr<MemoryBufferRef> BCOrErr =
243 IRObjectFile::findBitcodeInMemBuffer(Object);
244 if (!BCOrErr)
245 return errorCodeToError(BCOrErr.getError());
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000246
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000247 Expected<std::vector<BitcodeModule>> BMsOrErr =
248 getBitcodeModuleList(*BCOrErr);
249 if (!BMsOrErr)
250 return BMsOrErr.takeError();
Peter Collingbournead903692016-12-13 19:43:49 +0000251
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000252 if (BMsOrErr->empty())
253 return make_error<StringError>("Bitcode file does not contain any modules",
254 inconvertibleErrorCode());
Peter Collingbournead903692016-12-13 19:43:49 +0000255
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000256 // Create an InputModule for each module in the InputFile, and add it to the
257 // ModuleSymbolTable.
258 for (auto BM : *BMsOrErr) {
259 Expected<std::unique_ptr<Module>> MOrErr =
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000260 BM.getLazyModule(File->Ctx, /*ShouldLazyLoadMetadata*/ true,
261 /*IsImporting*/ false);
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000262 if (!MOrErr)
263 return MOrErr.takeError();
264
265 size_t SymBegin = File->SymTab.symbols().size();
266 File->SymTab.addModule(MOrErr->get());
267 size_t SymEnd = File->SymTab.symbols().size();
268
269 for (const auto &C : (*MOrErr)->getComdatSymbolTable()) {
270 auto P = File->ComdatMap.insert(
271 std::make_pair(&C.second, File->Comdats.size()));
272 assert(P.second);
273 (void)P;
274 File->Comdats.push_back(C.first());
275 }
276
277 File->Mods.push_back({BM, std::move(*MOrErr), SymBegin, SymEnd});
Rafael Espindola79121102016-10-25 12:02:03 +0000278 }
279
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000280 return std::move(File);
281}
282
Rafael Espindola79121102016-10-25 12:02:03 +0000283Expected<int> InputFile::Symbol::getComdatIndex() const {
Peter Collingbournead903692016-12-13 19:43:49 +0000284 if (!isGV())
Rafael Espindola79121102016-10-25 12:02:03 +0000285 return -1;
Peter Collingbournead903692016-12-13 19:43:49 +0000286 const GlobalObject *GO = getGV()->getBaseObject();
287 if (!GO)
288 return make_error<StringError>("Unable to determine comdat of alias!",
289 inconvertibleErrorCode());
Rafael Espindola79121102016-10-25 12:02:03 +0000290 if (const Comdat *C = GO->getComdat()) {
291 auto I = File->ComdatMap.find(C);
292 assert(I != File->ComdatMap.end());
293 return I->second;
294 }
295 return -1;
296}
297
Bob Haarmandd4ebc12017-02-02 23:00:49 +0000298Expected<std::string> InputFile::getLinkerOpts() {
299 std::string LinkerOpts;
300 raw_string_ostream LOS(LinkerOpts);
301 // Extract linker options from module metadata.
302 for (InputModule &Mod : Mods) {
303 std::unique_ptr<Module> &M = Mod.Mod;
304 if (auto E = M->materializeMetadata())
305 return std::move(E);
306 if (Metadata *Val = M->getModuleFlag("Linker Options")) {
307 MDNode *LinkerOptions = cast<MDNode>(Val);
308 for (const MDOperand &MDOptions : LinkerOptions->operands())
309 for (const MDOperand &MDOption : cast<MDNode>(MDOptions)->operands())
310 LOS << " " << cast<MDString>(MDOption)->getString();
311 }
312 }
313
314 // Synthesize export flags for symbols with dllexport storage.
315 const Triple TT(Mods[0].Mod->getTargetTriple());
316 Mangler M;
317 for (const ModuleSymbolTable::Symbol &Sym : SymTab.symbols())
318 if (auto *GV = Sym.dyn_cast<GlobalValue*>())
319 emitLinkerFlagsForGlobalCOFF(LOS, GV, TT, M);
320 LOS.flush();
321 return LinkerOpts;
322}
323
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000324StringRef InputFile::getName() const {
325 return Mods[0].BM.getModuleIdentifier();
326}
327
328StringRef InputFile::getSourceFileName() const {
329 return Mods[0].Mod->getSourceFileName();
330}
331
332iterator_range<InputFile::symbol_iterator>
333InputFile::module_symbols(InputModule &IM) {
334 return llvm::make_range(
335 symbol_iterator(SymTab.symbols().data() + IM.SymBegin, SymTab, this),
336 symbol_iterator(SymTab.symbols().data() + IM.SymEnd, SymTab, this));
337}
338
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000339LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
340 Config &Conf)
341 : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
Mehdi Aminie7494532016-08-23 18:39:12 +0000342 Ctx(Conf) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000343
344LTO::ThinLTOState::ThinLTOState(ThinBackend Backend) : Backend(Backend) {
345 if (!Backend)
Teresa Johnsonec544c52016-10-19 17:35:01 +0000346 this->Backend =
347 createInProcessThinBackend(llvm::heavyweight_hardware_concurrency());
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000348}
349
350LTO::LTO(Config Conf, ThinBackend Backend,
351 unsigned ParallelCodeGenParallelismLevel)
352 : Conf(std::move(Conf)),
353 RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
Mehdi Amini026ddbb2016-08-19 05:56:37 +0000354 ThinLTO(std::move(Backend)) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000355
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000356// Requires a destructor for MapVector<BitcodeModule>.
357LTO::~LTO() = default;
358
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000359// Add the given symbol to the GlobalResolutions map, and resolve its partition.
Peter Collingbournead903692016-12-13 19:43:49 +0000360void LTO::addSymbolToGlobalRes(SmallPtrSet<GlobalValue *, 8> &Used,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000361 const InputFile::Symbol &Sym,
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000362 SymbolResolution Res, unsigned Partition) {
Peter Collingbournead903692016-12-13 19:43:49 +0000363 GlobalValue *GV = Sym.isGV() ? Sym.getGV() : nullptr;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000364
365 auto &GlobalRes = GlobalResolutions[Sym.getName()];
366 if (GV) {
367 GlobalRes.UnnamedAddr &= GV->hasGlobalUnnamedAddr();
368 if (Res.Prevailing)
369 GlobalRes.IRName = GV->getName();
370 }
Teresa Johnson6c475a72017-01-05 21:34:18 +0000371 // Set the partition to external if we know it is used elsewhere, e.g.
372 // it is visible to a regular object, is referenced from llvm.compiler_used,
373 // or was already recorded as being referenced from a different partition.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000374 if (Res.VisibleToRegularObj || (GV && Used.count(GV)) ||
375 (GlobalRes.Partition != GlobalResolution::Unknown &&
Teresa Johnson6c475a72017-01-05 21:34:18 +0000376 GlobalRes.Partition != Partition)) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000377 GlobalRes.Partition = GlobalResolution::External;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000378 } else
379 // First recorded reference, save the current partition.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000380 GlobalRes.Partition = Partition;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000381
382 // Flag as visible outside of ThinLTO if visible from a regular object or
383 // if this is a reference in the regular LTO partition.
384 GlobalRes.VisibleOutsideThinLTO |=
385 (Res.VisibleToRegularObj || (Partition == GlobalResolution::RegularLTO));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000386}
387
Rafael Espindola7775c332016-08-26 20:19:35 +0000388static void writeToResolutionFile(raw_ostream &OS, InputFile *Input,
389 ArrayRef<SymbolResolution> Res) {
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000390 StringRef Path = Input->getName();
Rafael Espindola7775c332016-08-26 20:19:35 +0000391 OS << Path << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000392 auto ResI = Res.begin();
393 for (const InputFile::Symbol &Sym : Input->symbols()) {
394 assert(ResI != Res.end());
395 SymbolResolution Res = *ResI++;
396
Rafael Espindola7775c332016-08-26 20:19:35 +0000397 OS << "-r=" << Path << ',' << Sym.getName() << ',';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000398 if (Res.Prevailing)
Rafael Espindola7775c332016-08-26 20:19:35 +0000399 OS << 'p';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000400 if (Res.FinalDefinitionInLinkageUnit)
Rafael Espindola7775c332016-08-26 20:19:35 +0000401 OS << 'l';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000402 if (Res.VisibleToRegularObj)
Rafael Espindola7775c332016-08-26 20:19:35 +0000403 OS << 'x';
404 OS << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000405 }
Peter Collingbourne58ffcfb2017-01-19 23:10:14 +0000406 OS.flush();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000407 assert(ResI == Res.end());
408}
409
410Error LTO::add(std::unique_ptr<InputFile> Input,
411 ArrayRef<SymbolResolution> Res) {
412 assert(!CalledGetMaxTasks);
413
414 if (Conf.ResolutionFile)
Rafael Espindola7775c332016-08-26 20:19:35 +0000415 writeToResolutionFile(*Conf.ResolutionFile, Input.get(), Res);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000416
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000417 const SymbolResolution *ResI = Res.begin();
418 for (InputFile::InputModule &IM : Input->Mods)
419 if (Error Err = addModule(*Input, IM, ResI, Res.end()))
420 return Err;
421
422 assert(ResI == Res.end());
423 return Error::success();
424}
425
426Error LTO::addModule(InputFile &Input, InputFile::InputModule &IM,
427 const SymbolResolution *&ResI,
428 const SymbolResolution *ResE) {
Mehdi Amini9989f802016-08-19 15:35:44 +0000429 // FIXME: move to backend
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000430 Module &M = *IM.Mod;
Davide Italiano2ceb6282016-12-14 21:57:04 +0000431
432 if (M.getDataLayoutStr().empty())
433 return make_error<StringError>("input module has no datalayout",
434 inconvertibleErrorCode());
435
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000436 if (!Conf.OverrideTriple.empty())
437 M.setTargetTriple(Conf.OverrideTriple);
438 else if (M.getTargetTriple().empty())
439 M.setTargetTriple(Conf.DefaultTriple);
440
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000441 Expected<bool> HasThinLTOSummary = IM.BM.hasSummary();
Peter Collingbournecd513a42016-11-11 19:50:24 +0000442 if (!HasThinLTOSummary)
443 return HasThinLTOSummary.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000444
Peter Collingbournecd513a42016-11-11 19:50:24 +0000445 if (*HasThinLTOSummary)
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000446 return addThinLTO(IM.BM, M, Input.module_symbols(IM), ResI, ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000447 else
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000448 return addRegularLTO(IM.BM, ResI, ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000449}
450
451// Add a regular LTO object to the link.
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000452Error LTO::addRegularLTO(BitcodeModule BM, const SymbolResolution *&ResI,
453 const SymbolResolution *ResE) {
Mehdi Aminie7494532016-08-23 18:39:12 +0000454 if (!RegularLTO.CombinedModule) {
455 RegularLTO.CombinedModule =
456 llvm::make_unique<Module>("ld-temp.o", RegularLTO.Ctx);
457 RegularLTO.Mover = llvm::make_unique<IRMover>(*RegularLTO.CombinedModule);
458 }
Peter Collingbournead903692016-12-13 19:43:49 +0000459 Expected<std::unique_ptr<Module>> MOrErr =
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000460 BM.getLazyModule(RegularLTO.Ctx, /*ShouldLazyLoadMetadata*/ true,
461 /*IsImporting*/ false);
Peter Collingbournead903692016-12-13 19:43:49 +0000462 if (!MOrErr)
463 return MOrErr.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000464
Peter Collingbournead903692016-12-13 19:43:49 +0000465 Module &M = **MOrErr;
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000466 if (Error Err = M.materializeMetadata())
467 return Err;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000468 UpgradeDebugInfo(M);
469
Peter Collingbournead903692016-12-13 19:43:49 +0000470 ModuleSymbolTable SymTab;
471 SymTab.addModule(&M);
472
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000473 SmallPtrSet<GlobalValue *, 8> Used;
474 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
475
476 std::vector<GlobalValue *> Keep;
477
478 for (GlobalVariable &GV : M.globals())
479 if (GV.hasAppendingLinkage())
480 Keep.push_back(&GV);
481
Peter Collingbourne46136262017-02-02 05:22:42 +0000482 DenseSet<GlobalObject *> AliasedGlobals;
483 for (auto &GA : M.aliases())
484 if (GlobalObject *GO = GA.getBaseObject())
485 AliasedGlobals.insert(GO);
486
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000487 for (const InputFile::Symbol &Sym :
Peter Collingbournead903692016-12-13 19:43:49 +0000488 make_range(InputFile::symbol_iterator(SymTab.symbols().begin(), SymTab,
489 nullptr),
490 InputFile::symbol_iterator(SymTab.symbols().end(), SymTab,
491 nullptr))) {
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000492 assert(ResI != ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000493 SymbolResolution Res = *ResI++;
Peter Collingbournead903692016-12-13 19:43:49 +0000494 addSymbolToGlobalRes(Used, Sym, Res, 0);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000495
Peter Collingbournec387e702017-02-02 05:12:15 +0000496 if (Sym.isGV()) {
Peter Collingbournead903692016-12-13 19:43:49 +0000497 GlobalValue *GV = Sym.getGV();
Peter Collingbournec387e702017-02-02 05:12:15 +0000498 if (Res.Prevailing) {
499 if (Sym.getFlags() & object::BasicSymbolRef::SF_Undefined)
500 continue;
501 Keep.push_back(GV);
502 switch (GV->getLinkage()) {
503 default:
504 break;
505 case GlobalValue::LinkOnceAnyLinkage:
506 GV->setLinkage(GlobalValue::WeakAnyLinkage);
507 break;
508 case GlobalValue::LinkOnceODRLinkage:
509 GV->setLinkage(GlobalValue::WeakODRLinkage);
510 break;
511 }
Peter Collingbourne46136262017-02-02 05:22:42 +0000512 } else if (isa<GlobalObject>(GV) &&
513 (GV->hasLinkOnceODRLinkage() || GV->hasWeakODRLinkage() ||
514 GV->hasAvailableExternallyLinkage()) &&
515 !AliasedGlobals.count(cast<GlobalObject>(GV))) {
516 // Either of the above three types of linkage indicates that the
517 // chosen prevailing symbol will have the same semantics as this copy of
518 // the symbol, so we can link it with available_externally linkage. We
519 // only need to do this if the symbol is undefined.
Peter Collingbournec387e702017-02-02 05:12:15 +0000520 GlobalValue *CombinedGV =
521 RegularLTO.CombinedModule->getNamedValue(GV->getName());
Peter Collingbourne46136262017-02-02 05:22:42 +0000522 if (!CombinedGV || CombinedGV->isDeclaration()) {
Peter Collingbournec387e702017-02-02 05:12:15 +0000523 Keep.push_back(GV);
Peter Collingbourne46136262017-02-02 05:22:42 +0000524 GV->setLinkage(GlobalValue::AvailableExternallyLinkage);
525 cast<GlobalObject>(GV)->setComdat(nullptr);
526 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000527 }
528 }
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000529 // Common resolution: collect the maximum size/alignment over all commons.
530 // We also record if we see an instance of a common as prevailing, so that
531 // if none is prevailing we can ignore it later.
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000532 if (Sym.getFlags() & object::BasicSymbolRef::SF_Common) {
Peter Collingbournefb8c2a42016-12-01 02:51:12 +0000533 // FIXME: We should figure out what to do about commons defined by asm.
534 // For now they aren't reported correctly by ModuleSymbolTable.
Peter Collingbournead903692016-12-13 19:43:49 +0000535 auto &CommonRes = RegularLTO.Commons[Sym.getGV()->getName()];
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000536 CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
537 CommonRes.Align = std::max(CommonRes.Align, Sym.getCommonAlignment());
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000538 CommonRes.Prevailing |= Res.Prevailing;
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000539 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000540
541 // FIXME: use proposed local attribute for FinalDefinitionInLinkageUnit.
542 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000543
Peter Collingbournead903692016-12-13 19:43:49 +0000544 return RegularLTO.Mover->move(std::move(*MOrErr), Keep,
Teresa Johnson4b9b3792016-10-12 18:39:29 +0000545 [](GlobalValue &, IRMover::ValueAdder) {},
Teresa Johnson040cc162016-12-12 16:09:30 +0000546 /* LinkModuleInlineAsm */ true,
547 /* IsPerformingImport */ false);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000548}
549
550// Add a ThinLTO object to the link.
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000551// FIXME: This function should not need to take as many parameters once we have
552// a bitcode symbol table.
553Error LTO::addThinLTO(BitcodeModule BM, Module &M,
554 iterator_range<InputFile::symbol_iterator> Syms,
555 const SymbolResolution *&ResI,
556 const SymbolResolution *ResE) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000557 SmallPtrSet<GlobalValue *, 8> Used;
558 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
559
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000560 Expected<std::unique_ptr<ModuleSummaryIndex>> SummaryOrErr = BM.getSummary();
561 if (!SummaryOrErr)
562 return SummaryOrErr.takeError();
563 ThinLTO.CombinedIndex.mergeFrom(std::move(*SummaryOrErr),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000564 ThinLTO.ModuleMap.size());
565
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000566 for (const InputFile::Symbol &Sym : Syms) {
567 assert(ResI != ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000568 SymbolResolution Res = *ResI++;
Peter Collingbournead903692016-12-13 19:43:49 +0000569 addSymbolToGlobalRes(Used, Sym, Res, ThinLTO.ModuleMap.size() + 1);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000570
Peter Collingbournead903692016-12-13 19:43:49 +0000571 if (Res.Prevailing && Sym.isGV())
572 ThinLTO.PrevailingModuleForGUID[Sym.getGV()->getGUID()] =
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000573 BM.getModuleIdentifier();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000574 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000575
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000576 if (!ThinLTO.ModuleMap.insert({BM.getModuleIdentifier(), BM}).second)
577 return make_error<StringError>(
578 "Expected at most one ThinLTO module per bitcode file",
579 inconvertibleErrorCode());
580
Mehdi Amini41af4302016-11-11 04:28:40 +0000581 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000582}
583
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000584unsigned LTO::getMaxTasks() const {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000585 CalledGetMaxTasks = true;
586 return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
587}
588
Peter Collingbourne80186a52016-09-23 21:33:43 +0000589Error LTO::run(AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000590 // Save the status of having a regularLTO combined module, as
591 // this is needed for generating the ThinLTO Task ID, and
592 // the CombinedModule will be moved at the end of runRegularLTO.
593 bool HasRegularLTO = RegularLTO.CombinedModule != nullptr;
Mehdi Aminie7494532016-08-23 18:39:12 +0000594 // Invoke regular LTO if there was a regular LTO module to start with.
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000595 if (HasRegularLTO)
Peter Collingbourne80186a52016-09-23 21:33:43 +0000596 if (auto E = runRegularLTO(AddStream))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000597 return E;
Peter Collingbourne80186a52016-09-23 21:33:43 +0000598 return runThinLTO(AddStream, Cache, HasRegularLTO);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000599}
600
Peter Collingbourne80186a52016-09-23 21:33:43 +0000601Error LTO::runRegularLTO(AddStreamFn AddStream) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000602 // Make sure commons have the right size/alignment: we kept the largest from
603 // all the prevailing when adding the inputs, and we apply it here.
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000604 const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000605 for (auto &I : RegularLTO.Commons) {
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000606 if (!I.second.Prevailing)
607 // Don't do anything if no instance of this common was prevailing.
608 continue;
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000609 GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000610 if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000611 // Don't create a new global if the type is already correct, just make
612 // sure the alignment is correct.
613 OldGV->setAlignment(I.second.Align);
614 continue;
615 }
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000616 ArrayType *Ty =
617 ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000618 auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
619 GlobalValue::CommonLinkage,
620 ConstantAggregateZero::get(Ty), "");
621 GV->setAlignment(I.second.Align);
622 if (OldGV) {
623 OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
624 GV->takeName(OldGV);
625 OldGV->eraseFromParent();
626 } else {
627 GV->setName(I.first);
628 }
629 }
630
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000631 if (Conf.PreOptModuleHook &&
632 !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
Mehdi Amini41af4302016-11-11 04:28:40 +0000633 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000634
Mehdi Aminid310b472016-08-22 06:25:41 +0000635 if (!Conf.CodeGenOnly) {
636 for (const auto &R : GlobalResolutions) {
637 if (R.second.IRName.empty())
638 continue;
639 if (R.second.Partition != 0 &&
640 R.second.Partition != GlobalResolution::External)
641 continue;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000642
Mehdi Aminid310b472016-08-22 06:25:41 +0000643 GlobalValue *GV =
644 RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
645 // Ignore symbols defined in other partitions.
646 if (!GV || GV->hasLocalLinkage())
647 continue;
648 GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
649 : GlobalValue::UnnamedAddr::None);
650 if (R.second.Partition == 0)
651 GV->setLinkage(GlobalValue::InternalLinkage);
652 }
653
654 if (Conf.PostInternalizeModuleHook &&
655 !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
Mehdi Amini41af4302016-11-11 04:28:40 +0000656 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000657 }
Peter Collingbourne80186a52016-09-23 21:33:43 +0000658 return backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
Peter Collingbournee02b74e2017-01-20 22:18:52 +0000659 std::move(RegularLTO.CombinedModule), ThinLTO.CombinedIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000660}
661
662/// This class defines the interface to the ThinLTO backend.
663class lto::ThinBackendProc {
664protected:
665 Config &Conf;
666 ModuleSummaryIndex &CombinedIndex;
Mehdi Amini767e1452016-09-06 03:23:45 +0000667 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000668
669public:
670 ThinBackendProc(Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000671 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
Mehdi Amini18b91112016-08-19 06:10:03 +0000672 : Conf(Conf), CombinedIndex(CombinedIndex),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000673 ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
674
675 virtual ~ThinBackendProc() {}
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000676 virtual Error start(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000677 unsigned Task, BitcodeModule BM,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000678 const FunctionImporter::ImportMapTy &ImportList,
679 const FunctionImporter::ExportSetTy &ExportList,
680 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000681 MapVector<StringRef, BitcodeModule> &ModuleMap) = 0;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000682 virtual Error wait() = 0;
683};
684
Benjamin Kramerffd37152016-11-19 20:44:26 +0000685namespace {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000686class InProcessThinBackend : public ThinBackendProc {
687 ThreadPool BackendThreadPool;
Peter Collingbourne80186a52016-09-23 21:33:43 +0000688 AddStreamFn AddStream;
689 NativeObjectCache Cache;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000690
691 Optional<Error> Err;
692 std::mutex ErrMu;
693
694public:
Mehdi Amini767e1452016-09-06 03:23:45 +0000695 InProcessThinBackend(
696 Config &Conf, ModuleSummaryIndex &CombinedIndex,
697 unsigned ThinLTOParallelismLevel,
698 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000699 AddStreamFn AddStream, NativeObjectCache Cache)
Mehdi Amini18b91112016-08-19 06:10:03 +0000700 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
701 BackendThreadPool(ThinLTOParallelismLevel),
Peter Collingbourne80186a52016-09-23 21:33:43 +0000702 AddStream(std::move(AddStream)), Cache(std::move(Cache)) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000703
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000704 Error runThinLTOBackendThread(
Peter Collingbourne80186a52016-09-23 21:33:43 +0000705 AddStreamFn AddStream, NativeObjectCache Cache, unsigned Task,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000706 BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000707 const FunctionImporter::ImportMapTy &ImportList,
708 const FunctionImporter::ExportSetTy &ExportList,
709 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
710 const GVSummaryMapTy &DefinedGlobals,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000711 MapVector<StringRef, BitcodeModule> &ModuleMap) {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000712 auto RunThinBackend = [&](AddStreamFn AddStream) {
713 LTOLLVMContext BackendContext(Conf);
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000714 Expected<std::unique_ptr<Module>> MOrErr = BM.parseModule(BackendContext);
Peter Collingbourned9445c42016-11-13 07:00:17 +0000715 if (!MOrErr)
716 return MOrErr.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000717
Peter Collingbourne80186a52016-09-23 21:33:43 +0000718 return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
719 ImportList, DefinedGlobals, ModuleMap);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000720 };
Peter Collingbourne80186a52016-09-23 21:33:43 +0000721
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000722 auto ModuleID = BM.getModuleIdentifier();
Mehdi Aminif82bda02016-10-08 04:44:23 +0000723
724 if (!Cache || !CombinedIndex.modulePaths().count(ModuleID) ||
725 all_of(CombinedIndex.getModuleHash(ModuleID),
726 [](uint32_t V) { return V == 0; }))
727 // Cache disabled or no entry for this module in the combined index or
728 // no module hash.
Peter Collingbourne80186a52016-09-23 21:33:43 +0000729 return RunThinBackend(AddStream);
730
731 SmallString<40> Key;
732 // The module may be cached, this helps handling it.
Peter Collingbournef4257522016-12-08 05:28:30 +0000733 computeCacheKey(Key, Conf, CombinedIndex, ModuleID, ImportList, ExportList,
Mehdi Amini00fa1402016-10-08 04:44:18 +0000734 ResolvedODR, DefinedGlobals);
Peter Collingbourne80186a52016-09-23 21:33:43 +0000735 if (AddStreamFn CacheAddStream = Cache(Task, Key))
736 return RunThinBackend(CacheAddStream);
737
Mehdi Amini41af4302016-11-11 04:28:40 +0000738 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000739 }
740
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000741 Error start(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000742 unsigned Task, BitcodeModule BM,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000743 const FunctionImporter::ImportMapTy &ImportList,
744 const FunctionImporter::ExportSetTy &ExportList,
745 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000746 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
747 StringRef ModulePath = BM.getModuleIdentifier();
Mehdi Amini767e1452016-09-06 03:23:45 +0000748 assert(ModuleToDefinedGVSummaries.count(ModulePath));
749 const GVSummaryMapTy &DefinedGlobals =
750 ModuleToDefinedGVSummaries.find(ModulePath)->second;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000751 BackendThreadPool.async(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000752 [=](BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000753 const FunctionImporter::ImportMapTy &ImportList,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000754 const FunctionImporter::ExportSetTy &ExportList,
755 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
756 &ResolvedODR,
Mehdi Amini767e1452016-09-06 03:23:45 +0000757 const GVSummaryMapTy &DefinedGlobals,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000758 MapVector<StringRef, BitcodeModule> &ModuleMap) {
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000759 Error E = runThinLTOBackendThread(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000760 AddStream, Cache, Task, BM, CombinedIndex, ImportList,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000761 ExportList, ResolvedODR, DefinedGlobals, ModuleMap);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000762 if (E) {
763 std::unique_lock<std::mutex> L(ErrMu);
764 if (Err)
765 Err = joinErrors(std::move(*Err), std::move(E));
766 else
767 Err = std::move(E);
768 }
769 },
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000770 BM, std::ref(CombinedIndex), std::ref(ImportList),
Mehdi Amini767e1452016-09-06 03:23:45 +0000771 std::ref(ExportList), std::ref(ResolvedODR), std::ref(DefinedGlobals),
772 std::ref(ModuleMap));
Mehdi Amini41af4302016-11-11 04:28:40 +0000773 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000774 }
775
776 Error wait() override {
777 BackendThreadPool.wait();
778 if (Err)
779 return std::move(*Err);
780 else
Mehdi Amini41af4302016-11-11 04:28:40 +0000781 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000782 }
783};
Benjamin Kramerffd37152016-11-19 20:44:26 +0000784} // end anonymous namespace
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000785
786ThinBackend lto::createInProcessThinBackend(unsigned ParallelismLevel) {
787 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000788 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000789 AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000790 return llvm::make_unique<InProcessThinBackend>(
791 Conf, CombinedIndex, ParallelismLevel, ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000792 AddStream, Cache);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000793 };
794}
795
Teresa Johnson3f212b82016-09-21 19:12:05 +0000796// Given the original \p Path to an output file, replace any path
797// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
798// resulting directory if it does not yet exist.
799std::string lto::getThinLTOOutputFile(const std::string &Path,
800 const std::string &OldPrefix,
801 const std::string &NewPrefix) {
802 if (OldPrefix.empty() && NewPrefix.empty())
803 return Path;
804 SmallString<128> NewPath(Path);
805 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
806 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
807 if (!ParentPath.empty()) {
808 // Make sure the new directory exists, creating it if necessary.
809 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
810 llvm::errs() << "warning: could not create directory '" << ParentPath
811 << "': " << EC.message() << '\n';
812 }
813 return NewPath.str();
814}
815
Benjamin Kramerffd37152016-11-19 20:44:26 +0000816namespace {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000817class WriteIndexesThinBackend : public ThinBackendProc {
818 std::string OldPrefix, NewPrefix;
819 bool ShouldEmitImportsFiles;
820
821 std::string LinkedObjectsFileName;
822 std::unique_ptr<llvm::raw_fd_ostream> LinkedObjectsFile;
823
824public:
Mehdi Amini767e1452016-09-06 03:23:45 +0000825 WriteIndexesThinBackend(
826 Config &Conf, ModuleSummaryIndex &CombinedIndex,
827 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
828 std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
829 std::string LinkedObjectsFileName)
Mehdi Amini18b91112016-08-19 06:10:03 +0000830 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000831 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
832 ShouldEmitImportsFiles(ShouldEmitImportsFiles),
833 LinkedObjectsFileName(LinkedObjectsFileName) {}
834
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000835 Error start(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000836 unsigned Task, BitcodeModule BM,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000837 const FunctionImporter::ImportMapTy &ImportList,
838 const FunctionImporter::ExportSetTy &ExportList,
839 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000840 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
841 StringRef ModulePath = BM.getModuleIdentifier();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000842 std::string NewModulePath =
843 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
844
845 std::error_code EC;
846 if (!LinkedObjectsFileName.empty()) {
847 if (!LinkedObjectsFile) {
848 LinkedObjectsFile = llvm::make_unique<raw_fd_ostream>(
849 LinkedObjectsFileName, EC, sys::fs::OpenFlags::F_None);
850 if (EC)
851 return errorCodeToError(EC);
852 }
853 *LinkedObjectsFile << NewModulePath << '\n';
854 }
855
856 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
857 gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000858 ImportList, ModuleToSummariesForIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000859
860 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
861 sys::fs::OpenFlags::F_None);
862 if (EC)
863 return errorCodeToError(EC);
864 WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
865
866 if (ShouldEmitImportsFiles)
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000867 return errorCodeToError(
868 EmitImportsFiles(ModulePath, NewModulePath + ".imports", ImportList));
Mehdi Amini41af4302016-11-11 04:28:40 +0000869 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000870 }
871
Mehdi Amini41af4302016-11-11 04:28:40 +0000872 Error wait() override { return Error::success(); }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000873};
Benjamin Kramerffd37152016-11-19 20:44:26 +0000874} // end anonymous namespace
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000875
876ThinBackend lto::createWriteIndexesThinBackend(std::string OldPrefix,
877 std::string NewPrefix,
878 bool ShouldEmitImportsFiles,
879 std::string LinkedObjectsFile) {
880 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000881 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000882 AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000883 return llvm::make_unique<WriteIndexesThinBackend>(
Mehdi Amini18b91112016-08-19 06:10:03 +0000884 Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
885 ShouldEmitImportsFiles, LinkedObjectsFile);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000886 };
887}
888
Peter Collingbourne80186a52016-09-23 21:33:43 +0000889Error LTO::runThinLTO(AddStreamFn AddStream, NativeObjectCache Cache,
890 bool HasRegularLTO) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000891 if (ThinLTO.ModuleMap.empty())
Mehdi Amini41af4302016-11-11 04:28:40 +0000892 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000893
894 if (Conf.CombinedIndexHook && !Conf.CombinedIndexHook(ThinLTO.CombinedIndex))
Mehdi Amini41af4302016-11-11 04:28:40 +0000895 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000896
897 // Collect for each module the list of function it defines (GUID ->
898 // Summary).
899 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
900 ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
901 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
902 ModuleToDefinedGVSummaries);
Teresa Johnson620c1402016-09-20 23:07:17 +0000903 // Create entries for any modules that didn't have any GV summaries
904 // (either they didn't have any GVs to start with, or we suppressed
905 // generation of the summaries because they e.g. had inline assembly
906 // uses that couldn't be promoted/renamed on export). This is so
907 // InProcessThinBackend::start can still launch a backend thread, which
908 // is passed the map of summaries for the module, without any special
909 // handling for this case.
910 for (auto &Mod : ThinLTO.ModuleMap)
911 if (!ModuleToDefinedGVSummaries.count(Mod.first))
912 ModuleToDefinedGVSummaries.try_emplace(Mod.first);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000913
914 StringMap<FunctionImporter::ImportMapTy> ImportLists(
915 ThinLTO.ModuleMap.size());
916 StringMap<FunctionImporter::ExportSetTy> ExportLists(
917 ThinLTO.ModuleMap.size());
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000918 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000919
Teresa Johnson002af9b2016-10-31 22:12:21 +0000920 if (Conf.OptLevel > 0) {
Mehdi Aminif39ce992017-01-20 23:34:12 +0000921 // Compute "dead" symbols, we don't want to import/export these!
922 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
923 for (auto &Res : GlobalResolutions) {
924 if (Res.second.VisibleOutsideThinLTO &&
925 // IRName will be defined if we have seen the prevailing copy of
926 // this value. If not, no need to preserve any ThinLTO copies.
927 !Res.second.IRName.empty())
928 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Res.second.IRName));
929 }
930
931 auto DeadSymbols =
932 computeDeadSymbols(ThinLTO.CombinedIndex, GUIDPreservedSymbols);
933
Teresa Johnson002af9b2016-10-31 22:12:21 +0000934 ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000935 ImportLists, ExportLists, &DeadSymbols);
Teresa Johnson002af9b2016-10-31 22:12:21 +0000936
937 std::set<GlobalValue::GUID> ExportedGUIDs;
938 for (auto &Res : GlobalResolutions) {
Teresa Johnson6c475a72017-01-05 21:34:18 +0000939 // First check if the symbol was flagged as having external references.
940 if (Res.second.Partition != GlobalResolution::External)
941 continue;
942 // IRName will be defined if we have seen the prevailing copy of
943 // this value. If not, no need to mark as exported from a ThinLTO
944 // partition (and we can't get the GUID).
945 if (Res.second.IRName.empty())
946 continue;
947 auto GUID = GlobalValue::getGUID(Res.second.IRName);
948 // Mark exported unless index-based analysis determined it to be dead.
949 if (!DeadSymbols.count(GUID))
Teresa Johnson002af9b2016-10-31 22:12:21 +0000950 ExportedGUIDs.insert(GlobalValue::getGUID(Res.second.IRName));
951 }
952
953 auto isPrevailing = [&](GlobalValue::GUID GUID,
954 const GlobalValueSummary *S) {
955 return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
956 };
Mehdi Amini97624fb2017-02-02 18:31:35 +0000957 auto isExported = [&](StringRef ModuleIdentifier,
958 GlobalValue::GUID GUID) -> SummaryResolution {
Teresa Johnson002af9b2016-10-31 22:12:21 +0000959 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Mehdi Amini97624fb2017-02-02 18:31:35 +0000960 if ((ExportList != ExportLists.end() && ExportList->second.count(GUID)) ||
961 ExportedGUIDs.count(GUID)) {
962 // We could do better by hiding when a symbol is in
963 // GUIDPreservedSymbols because it is only referenced from regular LTO
964 // or from native files and not outside the final binary, but that's
965 // something the native linker could do as gwell.
966 if (GUIDPreservedSymbols.count(GUID))
967 return Exported;
968 return Hidden;
969 }
970 return Internal;
Teresa Johnson002af9b2016-10-31 22:12:21 +0000971 };
972 thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported);
973
974 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
975 GlobalValue::GUID GUID,
976 GlobalValue::LinkageTypes NewLinkage) {
977 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
978 };
979
980 thinLTOResolveWeakForLinkerInIndex(ThinLTO.CombinedIndex, isPrevailing,
981 recordNewLinkage);
982 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000983
Peter Collingbourne80186a52016-09-23 21:33:43 +0000984 std::unique_ptr<ThinBackendProc> BackendProc =
985 ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
986 AddStream, Cache);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000987
Davide Italiano63098952017-01-04 20:37:57 +0000988 // Task numbers start at ParallelCodeGenParallelismLevel if an LTO
989 // module is present, as tasks 0 through ParallelCodeGenParallelismLevel-1
990 // are reserved for parallel code generation partitions.
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000991 unsigned Task =
992 HasRegularLTO ? RegularLTO.ParallelCodeGenParallelismLevel : 0;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000993 for (auto &Mod : ThinLTO.ModuleMap) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000994 if (Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000995 ExportLists[Mod.first],
996 ResolvedODR[Mod.first], ThinLTO.ModuleMap))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000997 return E;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000998 ++Task;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000999 }
1000
1001 return BackendProc->wait();
Teresa Johnsondf6edc52016-05-23 22:54:06 +00001002}