blob: a41ee607415381965fb131d243d6420ce37d6d9a [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 };
Peter Collingbourne54a52b72017-03-03 20:25:30 +000087 auto AddUint64 = [&](uint64_t I) {
88 uint8_t Data[8];
89 Data[0] = I;
90 Data[1] = I >> 8;
91 Data[2] = I >> 16;
92 Data[3] = I >> 24;
93 Data[4] = I >> 32;
94 Data[5] = I >> 40;
95 Data[6] = I >> 48;
96 Data[7] = I >> 56;
97 Hasher.update(ArrayRef<uint8_t>{Data, 8});
98 };
Peter Collingbournef4257522016-12-08 05:28:30 +000099 AddString(Conf.CPU);
100 // FIXME: Hash more of Options. For now all clients initialize Options from
101 // command-line flags (which is unsupported in production), but may set
102 // RelaxELFRelocations. The clang driver can also pass FunctionSections,
103 // DataSections and DebuggerTuning via command line flags.
104 AddUnsigned(Conf.Options.RelaxELFRelocations);
105 AddUnsigned(Conf.Options.FunctionSections);
106 AddUnsigned(Conf.Options.DataSections);
107 AddUnsigned((unsigned)Conf.Options.DebuggerTuning);
108 for (auto &A : Conf.MAttrs)
109 AddString(A);
110 AddUnsigned(Conf.RelocModel);
111 AddUnsigned(Conf.CodeModel);
112 AddUnsigned(Conf.CGOptLevel);
Tobias Edler von Kochf454b9e2017-02-15 20:36:36 +0000113 AddUnsigned(Conf.CGFileType);
Peter Collingbournef4257522016-12-08 05:28:30 +0000114 AddUnsigned(Conf.OptLevel);
115 AddString(Conf.OptPipeline);
116 AddString(Conf.AAPipeline);
117 AddString(Conf.OverrideTriple);
118 AddString(Conf.DefaultTriple);
119
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000120 // Include the hash for the current module
121 auto ModHash = Index.getModuleHash(ModuleID);
122 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
123 for (auto F : ExportList)
124 // The export list can impact the internalization, be conservative here
125 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
126
Peter Collingbourne54a52b72017-03-03 20:25:30 +0000127 // Include the hash for every module we import functions from. The set of
128 // imported symbols for each module may affect code generation and is
129 // sensitive to link order, so include that as well.
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000130 for (auto &Entry : ImportList) {
131 auto ModHash = Index.getModuleHash(Entry.first());
132 Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
Peter Collingbourne54a52b72017-03-03 20:25:30 +0000133
134 AddUint64(Entry.second.size());
135 for (auto &Fn : Entry.second)
136 AddUint64(Fn.first);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000137 }
138
139 // Include the hash for the resolved ODR.
140 for (auto &Entry : ResolvedODR) {
141 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
142 sizeof(GlobalValue::GUID)));
143 Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
144 sizeof(GlobalValue::LinkageTypes)));
145 }
146
147 // Include the hash for the linkage type to reflect internalization and weak
148 // resolution.
149 for (auto &GS : DefinedGlobals) {
150 GlobalValue::LinkageTypes Linkage = GS.second->linkage();
151 Hasher.update(
152 ArrayRef<uint8_t>((const uint8_t *)&Linkage, sizeof(Linkage)));
153 }
154
Dehao Chen27978002016-12-16 16:48:46 +0000155 if (!Conf.SampleProfile.empty()) {
156 auto FileOrErr = MemoryBuffer::getFile(Conf.SampleProfile);
157 if (FileOrErr)
158 Hasher.update(FileOrErr.get()->getBuffer());
159 }
160
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000161 Key = toHex(Hasher.result());
162}
163
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000164static void thinLTOResolveWeakForLinkerGUID(
165 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
166 DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000167 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000168 isPrevailing,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000169 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000170 recordNewLinkage) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000171 for (auto &S : GVSummaryList) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000172 GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
173 if (!GlobalValue::isWeakForLinker(OriginalLinkage))
174 continue;
Peter Collingbourne73589f32016-07-07 18:31:51 +0000175 // We need to emit only one of these. The prevailing module will keep it,
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000176 // but turned into a weak, while the others will drop it when possible.
Teresa Johnson3bc8abd2016-10-30 05:15:23 +0000177 // This is both a compile-time optimization and a correctness
178 // transformation. This is necessary for correctness when we have exported
179 // a reference - we need to convert the linkonce to weak to
180 // ensure a copy is kept to satisfy the exported reference.
181 // FIXME: We may want to split the compile time and correctness
182 // aspects into separate routines.
Peter Collingbourne73589f32016-07-07 18:31:51 +0000183 if (isPrevailing(GUID, S.get())) {
Teresa Johnson28c03b52016-05-26 14:16:52 +0000184 if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
185 S->setLinkage(GlobalValue::getWeakLinkage(
186 GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000187 }
Teresa Johnson3bc8abd2016-10-30 05:15:23 +0000188 // Alias and aliasee can't be turned into available_externally.
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000189 else if (!isa<AliasSummary>(S.get()) &&
Teresa Johnson4566c6d2017-01-20 21:54:58 +0000190 !GlobalInvolvedWithAlias.count(S.get()))
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000191 S->setLinkage(GlobalValue::AvailableExternallyLinkage);
192 if (S->linkage() != OriginalLinkage)
193 recordNewLinkage(S->modulePath(), GUID, S->linkage());
194 }
195}
196
197// Resolve Weak and LinkOnce values in the \p Index.
198//
199// We'd like to drop these functions if they are no longer referenced in the
200// current module. However there is a chance that another module is still
201// referencing them because of the import. We make sure we always emit at least
202// one copy.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000203void llvm::thinLTOResolveWeakForLinkerInIndex(
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000204 ModuleSummaryIndex &Index,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000205 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000206 isPrevailing,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000207 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000208 recordNewLinkage) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000209 // We won't optimize the globals that are referenced by an alias for now
210 // Ideally we should turn the alias into a global and duplicate the definition
211 // when needed.
212 DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
213 for (auto &I : Index)
214 for (auto &S : I.second)
215 if (auto AS = dyn_cast<AliasSummary>(S.get()))
216 GlobalInvolvedWithAlias.insert(&AS->getAliasee());
217
218 for (auto &I : Index)
219 thinLTOResolveWeakForLinkerGUID(I.second, I.first, GlobalInvolvedWithAlias,
Peter Collingbourne73589f32016-07-07 18:31:51 +0000220 isPrevailing, recordNewLinkage);
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000221}
222
223static void thinLTOInternalizeAndPromoteGUID(
224 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
Mehdi Amini1380edf2017-02-03 07:41:43 +0000225 function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000226 for (auto &S : GVSummaryList) {
Mehdi Amini1380edf2017-02-03 07:41:43 +0000227 if (isExported(S->modulePath(), GUID)) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000228 if (GlobalValue::isLocalLinkage(S->linkage()))
229 S->setLinkage(GlobalValue::ExternalLinkage);
230 } else if (!GlobalValue::isLocalLinkage(S->linkage()))
231 S->setLinkage(GlobalValue::InternalLinkage);
232 }
233}
234
235// Update the linkages in the given \p Index to mark exported values
236// as external and non-exported values as internal.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000237void llvm::thinLTOInternalizeAndPromoteInIndex(
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000238 ModuleSummaryIndex &Index,
Mehdi Amini1380edf2017-02-03 07:41:43 +0000239 function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000240 for (auto &I : Index)
241 thinLTOInternalizeAndPromoteGUID(I.second, I.first, isExported);
242}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000243
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000244struct InputFile::InputModule {
245 BitcodeModule BM;
246 std::unique_ptr<Module> Mod;
247
248 // The range of ModuleSymbolTable entries for this input module.
249 size_t SymBegin, SymEnd;
250};
251
252// Requires a destructor for std::vector<InputModule>.
253InputFile::~InputFile() = default;
254
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000255Expected<std::unique_ptr<InputFile>> InputFile::create(MemoryBufferRef Object) {
256 std::unique_ptr<InputFile> File(new InputFile);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000257
Peter Collingbournead903692016-12-13 19:43:49 +0000258 ErrorOr<MemoryBufferRef> BCOrErr =
259 IRObjectFile::findBitcodeInMemBuffer(Object);
260 if (!BCOrErr)
261 return errorCodeToError(BCOrErr.getError());
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000262
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000263 Expected<std::vector<BitcodeModule>> BMsOrErr =
264 getBitcodeModuleList(*BCOrErr);
265 if (!BMsOrErr)
266 return BMsOrErr.takeError();
Peter Collingbournead903692016-12-13 19:43:49 +0000267
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000268 if (BMsOrErr->empty())
269 return make_error<StringError>("Bitcode file does not contain any modules",
270 inconvertibleErrorCode());
Peter Collingbournead903692016-12-13 19:43:49 +0000271
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000272 // Create an InputModule for each module in the InputFile, and add it to the
273 // ModuleSymbolTable.
274 for (auto BM : *BMsOrErr) {
275 Expected<std::unique_ptr<Module>> MOrErr =
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000276 BM.getLazyModule(File->Ctx, /*ShouldLazyLoadMetadata*/ true,
277 /*IsImporting*/ false);
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000278 if (!MOrErr)
279 return MOrErr.takeError();
280
281 size_t SymBegin = File->SymTab.symbols().size();
282 File->SymTab.addModule(MOrErr->get());
283 size_t SymEnd = File->SymTab.symbols().size();
284
285 for (const auto &C : (*MOrErr)->getComdatSymbolTable()) {
286 auto P = File->ComdatMap.insert(
287 std::make_pair(&C.second, File->Comdats.size()));
288 assert(P.second);
289 (void)P;
290 File->Comdats.push_back(C.first());
291 }
292
293 File->Mods.push_back({BM, std::move(*MOrErr), SymBegin, SymEnd});
Rafael Espindola79121102016-10-25 12:02:03 +0000294 }
295
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000296 return std::move(File);
297}
298
Rafael Espindola79121102016-10-25 12:02:03 +0000299Expected<int> InputFile::Symbol::getComdatIndex() const {
Peter Collingbournead903692016-12-13 19:43:49 +0000300 if (!isGV())
Rafael Espindola79121102016-10-25 12:02:03 +0000301 return -1;
Peter Collingbournead903692016-12-13 19:43:49 +0000302 const GlobalObject *GO = getGV()->getBaseObject();
303 if (!GO)
304 return make_error<StringError>("Unable to determine comdat of alias!",
305 inconvertibleErrorCode());
Rafael Espindola79121102016-10-25 12:02:03 +0000306 if (const Comdat *C = GO->getComdat()) {
307 auto I = File->ComdatMap.find(C);
308 assert(I != File->ComdatMap.end());
309 return I->second;
310 }
311 return -1;
312}
313
Bob Haarmandd4ebc12017-02-02 23:00:49 +0000314Expected<std::string> InputFile::getLinkerOpts() {
315 std::string LinkerOpts;
316 raw_string_ostream LOS(LinkerOpts);
317 // Extract linker options from module metadata.
318 for (InputModule &Mod : Mods) {
319 std::unique_ptr<Module> &M = Mod.Mod;
320 if (auto E = M->materializeMetadata())
321 return std::move(E);
322 if (Metadata *Val = M->getModuleFlag("Linker Options")) {
323 MDNode *LinkerOptions = cast<MDNode>(Val);
324 for (const MDOperand &MDOptions : LinkerOptions->operands())
325 for (const MDOperand &MDOption : cast<MDNode>(MDOptions)->operands())
326 LOS << " " << cast<MDString>(MDOption)->getString();
327 }
328 }
329
330 // Synthesize export flags for symbols with dllexport storage.
331 const Triple TT(Mods[0].Mod->getTargetTriple());
332 Mangler M;
333 for (const ModuleSymbolTable::Symbol &Sym : SymTab.symbols())
334 if (auto *GV = Sym.dyn_cast<GlobalValue*>())
335 emitLinkerFlagsForGlobalCOFF(LOS, GV, TT, M);
336 LOS.flush();
337 return LinkerOpts;
338}
339
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000340StringRef InputFile::getName() const {
341 return Mods[0].BM.getModuleIdentifier();
342}
343
344StringRef InputFile::getSourceFileName() const {
345 return Mods[0].Mod->getSourceFileName();
346}
347
348iterator_range<InputFile::symbol_iterator>
349InputFile::module_symbols(InputModule &IM) {
350 return llvm::make_range(
351 symbol_iterator(SymTab.symbols().data() + IM.SymBegin, SymTab, this),
352 symbol_iterator(SymTab.symbols().data() + IM.SymEnd, SymTab, this));
353}
354
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000355LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
356 Config &Conf)
357 : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
Mehdi Aminie7494532016-08-23 18:39:12 +0000358 Ctx(Conf) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000359
360LTO::ThinLTOState::ThinLTOState(ThinBackend Backend) : Backend(Backend) {
361 if (!Backend)
Teresa Johnsonec544c52016-10-19 17:35:01 +0000362 this->Backend =
363 createInProcessThinBackend(llvm::heavyweight_hardware_concurrency());
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000364}
365
366LTO::LTO(Config Conf, ThinBackend Backend,
367 unsigned ParallelCodeGenParallelismLevel)
368 : Conf(std::move(Conf)),
369 RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
Mehdi Amini026ddbb2016-08-19 05:56:37 +0000370 ThinLTO(std::move(Backend)) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000371
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000372// Requires a destructor for MapVector<BitcodeModule>.
373LTO::~LTO() = default;
374
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000375// Add the given symbol to the GlobalResolutions map, and resolve its partition.
Peter Collingbournead903692016-12-13 19:43:49 +0000376void LTO::addSymbolToGlobalRes(SmallPtrSet<GlobalValue *, 8> &Used,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000377 const InputFile::Symbol &Sym,
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000378 SymbolResolution Res, unsigned Partition) {
Peter Collingbournead903692016-12-13 19:43:49 +0000379 GlobalValue *GV = Sym.isGV() ? Sym.getGV() : nullptr;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000380
381 auto &GlobalRes = GlobalResolutions[Sym.getName()];
382 if (GV) {
383 GlobalRes.UnnamedAddr &= GV->hasGlobalUnnamedAddr();
384 if (Res.Prevailing)
385 GlobalRes.IRName = GV->getName();
386 }
Teresa Johnson6c475a72017-01-05 21:34:18 +0000387 // Set the partition to external if we know it is used elsewhere, e.g.
388 // it is visible to a regular object, is referenced from llvm.compiler_used,
389 // or was already recorded as being referenced from a different partition.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000390 if (Res.VisibleToRegularObj || (GV && Used.count(GV)) ||
391 (GlobalRes.Partition != GlobalResolution::Unknown &&
Teresa Johnson6c475a72017-01-05 21:34:18 +0000392 GlobalRes.Partition != Partition)) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000393 GlobalRes.Partition = GlobalResolution::External;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000394 } else
395 // First recorded reference, save the current partition.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000396 GlobalRes.Partition = Partition;
Teresa Johnson6c475a72017-01-05 21:34:18 +0000397
398 // Flag as visible outside of ThinLTO if visible from a regular object or
399 // if this is a reference in the regular LTO partition.
400 GlobalRes.VisibleOutsideThinLTO |=
401 (Res.VisibleToRegularObj || (Partition == GlobalResolution::RegularLTO));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000402}
403
Rafael Espindola7775c332016-08-26 20:19:35 +0000404static void writeToResolutionFile(raw_ostream &OS, InputFile *Input,
405 ArrayRef<SymbolResolution> Res) {
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000406 StringRef Path = Input->getName();
Rafael Espindola7775c332016-08-26 20:19:35 +0000407 OS << Path << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000408 auto ResI = Res.begin();
409 for (const InputFile::Symbol &Sym : Input->symbols()) {
410 assert(ResI != Res.end());
411 SymbolResolution Res = *ResI++;
412
Rafael Espindola7775c332016-08-26 20:19:35 +0000413 OS << "-r=" << Path << ',' << Sym.getName() << ',';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000414 if (Res.Prevailing)
Rafael Espindola7775c332016-08-26 20:19:35 +0000415 OS << 'p';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000416 if (Res.FinalDefinitionInLinkageUnit)
Rafael Espindola7775c332016-08-26 20:19:35 +0000417 OS << 'l';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000418 if (Res.VisibleToRegularObj)
Rafael Espindola7775c332016-08-26 20:19:35 +0000419 OS << 'x';
420 OS << '\n';
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000421 }
Peter Collingbourne58ffcfb2017-01-19 23:10:14 +0000422 OS.flush();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000423 assert(ResI == Res.end());
424}
425
426Error LTO::add(std::unique_ptr<InputFile> Input,
427 ArrayRef<SymbolResolution> Res) {
428 assert(!CalledGetMaxTasks);
429
430 if (Conf.ResolutionFile)
Rafael Espindola7775c332016-08-26 20:19:35 +0000431 writeToResolutionFile(*Conf.ResolutionFile, Input.get(), Res);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000432
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000433 const SymbolResolution *ResI = Res.begin();
434 for (InputFile::InputModule &IM : Input->Mods)
435 if (Error Err = addModule(*Input, IM, ResI, Res.end()))
436 return Err;
437
438 assert(ResI == Res.end());
439 return Error::success();
440}
441
442Error LTO::addModule(InputFile &Input, InputFile::InputModule &IM,
443 const SymbolResolution *&ResI,
444 const SymbolResolution *ResE) {
Mehdi Amini9989f802016-08-19 15:35:44 +0000445 // FIXME: move to backend
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000446 Module &M = *IM.Mod;
Davide Italiano2ceb6282016-12-14 21:57:04 +0000447
448 if (M.getDataLayoutStr().empty())
449 return make_error<StringError>("input module has no datalayout",
450 inconvertibleErrorCode());
451
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000452 if (!Conf.OverrideTriple.empty())
453 M.setTargetTriple(Conf.OverrideTriple);
454 else if (M.getTargetTriple().empty())
455 M.setTargetTriple(Conf.DefaultTriple);
456
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000457 Expected<bool> HasThinLTOSummary = IM.BM.hasSummary();
Peter Collingbournecd513a42016-11-11 19:50:24 +0000458 if (!HasThinLTOSummary)
459 return HasThinLTOSummary.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000460
Peter Collingbournecd513a42016-11-11 19:50:24 +0000461 if (*HasThinLTOSummary)
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000462 return addThinLTO(IM.BM, M, Input.module_symbols(IM), ResI, ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000463 else
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000464 return addRegularLTO(IM.BM, ResI, ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000465}
466
467// Add a regular LTO object to the link.
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000468Error LTO::addRegularLTO(BitcodeModule BM, const SymbolResolution *&ResI,
469 const SymbolResolution *ResE) {
Mehdi Aminie7494532016-08-23 18:39:12 +0000470 if (!RegularLTO.CombinedModule) {
471 RegularLTO.CombinedModule =
472 llvm::make_unique<Module>("ld-temp.o", RegularLTO.Ctx);
473 RegularLTO.Mover = llvm::make_unique<IRMover>(*RegularLTO.CombinedModule);
474 }
Peter Collingbournead903692016-12-13 19:43:49 +0000475 Expected<std::unique_ptr<Module>> MOrErr =
Teresa Johnsona61f5e32016-12-16 21:25:01 +0000476 BM.getLazyModule(RegularLTO.Ctx, /*ShouldLazyLoadMetadata*/ true,
477 /*IsImporting*/ false);
Peter Collingbournead903692016-12-13 19:43:49 +0000478 if (!MOrErr)
479 return MOrErr.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000480
Peter Collingbournead903692016-12-13 19:43:49 +0000481 Module &M = **MOrErr;
Peter Collingbourne7f00d0a2016-11-09 17:49:19 +0000482 if (Error Err = M.materializeMetadata())
483 return Err;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000484 UpgradeDebugInfo(M);
485
Peter Collingbournead903692016-12-13 19:43:49 +0000486 ModuleSymbolTable SymTab;
487 SymTab.addModule(&M);
488
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000489 SmallPtrSet<GlobalValue *, 8> Used;
490 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
491
492 std::vector<GlobalValue *> Keep;
493
494 for (GlobalVariable &GV : M.globals())
495 if (GV.hasAppendingLinkage())
496 Keep.push_back(&GV);
497
Peter Collingbourne46136262017-02-02 05:22:42 +0000498 DenseSet<GlobalObject *> AliasedGlobals;
499 for (auto &GA : M.aliases())
500 if (GlobalObject *GO = GA.getBaseObject())
501 AliasedGlobals.insert(GO);
502
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000503 for (const InputFile::Symbol &Sym :
Peter Collingbournead903692016-12-13 19:43:49 +0000504 make_range(InputFile::symbol_iterator(SymTab.symbols().begin(), SymTab,
505 nullptr),
506 InputFile::symbol_iterator(SymTab.symbols().end(), SymTab,
507 nullptr))) {
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000508 assert(ResI != ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000509 SymbolResolution Res = *ResI++;
Peter Collingbournead903692016-12-13 19:43:49 +0000510 addSymbolToGlobalRes(Used, Sym, Res, 0);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000511
Peter Collingbournec387e702017-02-02 05:12:15 +0000512 if (Sym.isGV()) {
Peter Collingbournead903692016-12-13 19:43:49 +0000513 GlobalValue *GV = Sym.getGV();
Peter Collingbournec387e702017-02-02 05:12:15 +0000514 if (Res.Prevailing) {
515 if (Sym.getFlags() & object::BasicSymbolRef::SF_Undefined)
516 continue;
517 Keep.push_back(GV);
518 switch (GV->getLinkage()) {
519 default:
520 break;
521 case GlobalValue::LinkOnceAnyLinkage:
522 GV->setLinkage(GlobalValue::WeakAnyLinkage);
523 break;
524 case GlobalValue::LinkOnceODRLinkage:
525 GV->setLinkage(GlobalValue::WeakODRLinkage);
526 break;
527 }
Peter Collingbourne46136262017-02-02 05:22:42 +0000528 } else if (isa<GlobalObject>(GV) &&
529 (GV->hasLinkOnceODRLinkage() || GV->hasWeakODRLinkage() ||
530 GV->hasAvailableExternallyLinkage()) &&
531 !AliasedGlobals.count(cast<GlobalObject>(GV))) {
532 // Either of the above three types of linkage indicates that the
533 // chosen prevailing symbol will have the same semantics as this copy of
534 // the symbol, so we can link it with available_externally linkage. We
535 // only need to do this if the symbol is undefined.
Peter Collingbournec387e702017-02-02 05:12:15 +0000536 GlobalValue *CombinedGV =
537 RegularLTO.CombinedModule->getNamedValue(GV->getName());
Peter Collingbourne46136262017-02-02 05:22:42 +0000538 if (!CombinedGV || CombinedGV->isDeclaration()) {
Peter Collingbournec387e702017-02-02 05:12:15 +0000539 Keep.push_back(GV);
Peter Collingbourne46136262017-02-02 05:22:42 +0000540 GV->setLinkage(GlobalValue::AvailableExternallyLinkage);
541 cast<GlobalObject>(GV)->setComdat(nullptr);
542 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000543 }
544 }
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000545 // Common resolution: collect the maximum size/alignment over all commons.
546 // We also record if we see an instance of a common as prevailing, so that
547 // if none is prevailing we can ignore it later.
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000548 if (Sym.getFlags() & object::BasicSymbolRef::SF_Common) {
Peter Collingbournefb8c2a42016-12-01 02:51:12 +0000549 // FIXME: We should figure out what to do about commons defined by asm.
550 // For now they aren't reported correctly by ModuleSymbolTable.
Peter Collingbournead903692016-12-13 19:43:49 +0000551 auto &CommonRes = RegularLTO.Commons[Sym.getGV()->getName()];
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000552 CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
553 CommonRes.Align = std::max(CommonRes.Align, Sym.getCommonAlignment());
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000554 CommonRes.Prevailing |= Res.Prevailing;
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000555 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000556
557 // FIXME: use proposed local attribute for FinalDefinitionInLinkageUnit.
558 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000559
Peter Collingbournead903692016-12-13 19:43:49 +0000560 return RegularLTO.Mover->move(std::move(*MOrErr), Keep,
Teresa Johnson4b9b3792016-10-12 18:39:29 +0000561 [](GlobalValue &, IRMover::ValueAdder) {},
Teresa Johnson040cc162016-12-12 16:09:30 +0000562 /* IsPerformingImport */ false);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000563}
564
565// Add a ThinLTO object to the link.
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000566// FIXME: This function should not need to take as many parameters once we have
567// a bitcode symbol table.
568Error LTO::addThinLTO(BitcodeModule BM, Module &M,
569 iterator_range<InputFile::symbol_iterator> Syms,
570 const SymbolResolution *&ResI,
571 const SymbolResolution *ResE) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000572 SmallPtrSet<GlobalValue *, 8> Used;
573 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
574
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000575 Expected<std::unique_ptr<ModuleSummaryIndex>> SummaryOrErr = BM.getSummary();
576 if (!SummaryOrErr)
577 return SummaryOrErr.takeError();
578 ThinLTO.CombinedIndex.mergeFrom(std::move(*SummaryOrErr),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000579 ThinLTO.ModuleMap.size());
580
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000581 for (const InputFile::Symbol &Sym : Syms) {
582 assert(ResI != ResE);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000583 SymbolResolution Res = *ResI++;
Peter Collingbournead903692016-12-13 19:43:49 +0000584 addSymbolToGlobalRes(Used, Sym, Res, ThinLTO.ModuleMap.size() + 1);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000585
Peter Collingbournead903692016-12-13 19:43:49 +0000586 if (Res.Prevailing && Sym.isGV())
587 ThinLTO.PrevailingModuleForGUID[Sym.getGV()->getGUID()] =
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000588 BM.getModuleIdentifier();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000589 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000590
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000591 if (!ThinLTO.ModuleMap.insert({BM.getModuleIdentifier(), BM}).second)
592 return make_error<StringError>(
593 "Expected at most one ThinLTO module per bitcode file",
594 inconvertibleErrorCode());
595
Mehdi Amini41af4302016-11-11 04:28:40 +0000596 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000597}
598
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000599unsigned LTO::getMaxTasks() const {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000600 CalledGetMaxTasks = true;
601 return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
602}
603
Peter Collingbourne80186a52016-09-23 21:33:43 +0000604Error LTO::run(AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000605 // Save the status of having a regularLTO combined module, as
606 // this is needed for generating the ThinLTO Task ID, and
607 // the CombinedModule will be moved at the end of runRegularLTO.
608 bool HasRegularLTO = RegularLTO.CombinedModule != nullptr;
Mehdi Aminie7494532016-08-23 18:39:12 +0000609 // Invoke regular LTO if there was a regular LTO module to start with.
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000610 if (HasRegularLTO)
Peter Collingbourne80186a52016-09-23 21:33:43 +0000611 if (auto E = runRegularLTO(AddStream))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000612 return E;
Peter Collingbourne80186a52016-09-23 21:33:43 +0000613 return runThinLTO(AddStream, Cache, HasRegularLTO);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000614}
615
Peter Collingbourne80186a52016-09-23 21:33:43 +0000616Error LTO::runRegularLTO(AddStreamFn AddStream) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000617 // Make sure commons have the right size/alignment: we kept the largest from
618 // all the prevailing when adding the inputs, and we apply it here.
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000619 const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000620 for (auto &I : RegularLTO.Commons) {
Mehdi Aminib2f46d1d2016-09-14 21:05:04 +0000621 if (!I.second.Prevailing)
622 // Don't do anything if no instance of this common was prevailing.
623 continue;
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000624 GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000625 if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000626 // Don't create a new global if the type is already correct, just make
627 // sure the alignment is correct.
628 OldGV->setAlignment(I.second.Align);
629 continue;
630 }
Teresa Johnsone2e621a2016-08-27 04:41:22 +0000631 ArrayType *Ty =
632 ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000633 auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
634 GlobalValue::CommonLinkage,
635 ConstantAggregateZero::get(Ty), "");
636 GV->setAlignment(I.second.Align);
637 if (OldGV) {
638 OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
639 GV->takeName(OldGV);
640 OldGV->eraseFromParent();
641 } else {
642 GV->setName(I.first);
643 }
644 }
645
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000646 if (Conf.PreOptModuleHook &&
647 !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
Mehdi Amini41af4302016-11-11 04:28:40 +0000648 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000649
Mehdi Aminid310b472016-08-22 06:25:41 +0000650 if (!Conf.CodeGenOnly) {
651 for (const auto &R : GlobalResolutions) {
652 if (R.second.IRName.empty())
653 continue;
654 if (R.second.Partition != 0 &&
655 R.second.Partition != GlobalResolution::External)
656 continue;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000657
Mehdi Aminid310b472016-08-22 06:25:41 +0000658 GlobalValue *GV =
659 RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
660 // Ignore symbols defined in other partitions.
661 if (!GV || GV->hasLocalLinkage())
662 continue;
663 GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
664 : GlobalValue::UnnamedAddr::None);
665 if (R.second.Partition == 0)
666 GV->setLinkage(GlobalValue::InternalLinkage);
667 }
668
669 if (Conf.PostInternalizeModuleHook &&
670 !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
Mehdi Amini41af4302016-11-11 04:28:40 +0000671 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000672 }
Peter Collingbourne80186a52016-09-23 21:33:43 +0000673 return backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
Peter Collingbournee02b74e2017-01-20 22:18:52 +0000674 std::move(RegularLTO.CombinedModule), ThinLTO.CombinedIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000675}
676
677/// This class defines the interface to the ThinLTO backend.
678class lto::ThinBackendProc {
679protected:
680 Config &Conf;
681 ModuleSummaryIndex &CombinedIndex;
Mehdi Amini767e1452016-09-06 03:23:45 +0000682 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000683
684public:
685 ThinBackendProc(Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000686 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
Mehdi Amini18b91112016-08-19 06:10:03 +0000687 : Conf(Conf), CombinedIndex(CombinedIndex),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000688 ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
689
690 virtual ~ThinBackendProc() {}
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000691 virtual Error start(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000692 unsigned Task, BitcodeModule BM,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000693 const FunctionImporter::ImportMapTy &ImportList,
694 const FunctionImporter::ExportSetTy &ExportList,
695 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000696 MapVector<StringRef, BitcodeModule> &ModuleMap) = 0;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000697 virtual Error wait() = 0;
698};
699
Benjamin Kramerffd37152016-11-19 20:44:26 +0000700namespace {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000701class InProcessThinBackend : public ThinBackendProc {
702 ThreadPool BackendThreadPool;
Peter Collingbourne80186a52016-09-23 21:33:43 +0000703 AddStreamFn AddStream;
704 NativeObjectCache Cache;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000705
706 Optional<Error> Err;
707 std::mutex ErrMu;
708
709public:
Mehdi Amini767e1452016-09-06 03:23:45 +0000710 InProcessThinBackend(
711 Config &Conf, ModuleSummaryIndex &CombinedIndex,
712 unsigned ThinLTOParallelismLevel,
713 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000714 AddStreamFn AddStream, NativeObjectCache Cache)
Mehdi Amini18b91112016-08-19 06:10:03 +0000715 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
716 BackendThreadPool(ThinLTOParallelismLevel),
Peter Collingbourne80186a52016-09-23 21:33:43 +0000717 AddStream(std::move(AddStream)), Cache(std::move(Cache)) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000718
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000719 Error runThinLTOBackendThread(
Peter Collingbourne80186a52016-09-23 21:33:43 +0000720 AddStreamFn AddStream, NativeObjectCache Cache, unsigned Task,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000721 BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000722 const FunctionImporter::ImportMapTy &ImportList,
723 const FunctionImporter::ExportSetTy &ExportList,
724 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
725 const GVSummaryMapTy &DefinedGlobals,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000726 MapVector<StringRef, BitcodeModule> &ModuleMap) {
Peter Collingbourne80186a52016-09-23 21:33:43 +0000727 auto RunThinBackend = [&](AddStreamFn AddStream) {
728 LTOLLVMContext BackendContext(Conf);
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000729 Expected<std::unique_ptr<Module>> MOrErr = BM.parseModule(BackendContext);
Peter Collingbourned9445c42016-11-13 07:00:17 +0000730 if (!MOrErr)
731 return MOrErr.takeError();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000732
Peter Collingbourne80186a52016-09-23 21:33:43 +0000733 return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
734 ImportList, DefinedGlobals, ModuleMap);
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000735 };
Peter Collingbourne80186a52016-09-23 21:33:43 +0000736
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000737 auto ModuleID = BM.getModuleIdentifier();
Mehdi Aminif82bda02016-10-08 04:44:23 +0000738
739 if (!Cache || !CombinedIndex.modulePaths().count(ModuleID) ||
740 all_of(CombinedIndex.getModuleHash(ModuleID),
741 [](uint32_t V) { return V == 0; }))
742 // Cache disabled or no entry for this module in the combined index or
743 // no module hash.
Peter Collingbourne80186a52016-09-23 21:33:43 +0000744 return RunThinBackend(AddStream);
745
746 SmallString<40> Key;
747 // The module may be cached, this helps handling it.
Peter Collingbournef4257522016-12-08 05:28:30 +0000748 computeCacheKey(Key, Conf, CombinedIndex, ModuleID, ImportList, ExportList,
Mehdi Amini00fa1402016-10-08 04:44:18 +0000749 ResolvedODR, DefinedGlobals);
Peter Collingbourne80186a52016-09-23 21:33:43 +0000750 if (AddStreamFn CacheAddStream = Cache(Task, Key))
751 return RunThinBackend(CacheAddStream);
752
Mehdi Amini41af4302016-11-11 04:28:40 +0000753 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000754 }
755
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000756 Error start(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000757 unsigned Task, BitcodeModule BM,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000758 const FunctionImporter::ImportMapTy &ImportList,
759 const FunctionImporter::ExportSetTy &ExportList,
760 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000761 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
762 StringRef ModulePath = BM.getModuleIdentifier();
Mehdi Amini767e1452016-09-06 03:23:45 +0000763 assert(ModuleToDefinedGVSummaries.count(ModulePath));
764 const GVSummaryMapTy &DefinedGlobals =
765 ModuleToDefinedGVSummaries.find(ModulePath)->second;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000766 BackendThreadPool.async(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000767 [=](BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000768 const FunctionImporter::ImportMapTy &ImportList,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000769 const FunctionImporter::ExportSetTy &ExportList,
770 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
771 &ResolvedODR,
Mehdi Amini767e1452016-09-06 03:23:45 +0000772 const GVSummaryMapTy &DefinedGlobals,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000773 MapVector<StringRef, BitcodeModule> &ModuleMap) {
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000774 Error E = runThinLTOBackendThread(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000775 AddStream, Cache, Task, BM, CombinedIndex, ImportList,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000776 ExportList, ResolvedODR, DefinedGlobals, ModuleMap);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000777 if (E) {
778 std::unique_lock<std::mutex> L(ErrMu);
779 if (Err)
780 Err = joinErrors(std::move(*Err), std::move(E));
781 else
782 Err = std::move(E);
783 }
784 },
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000785 BM, std::ref(CombinedIndex), std::ref(ImportList),
Mehdi Amini767e1452016-09-06 03:23:45 +0000786 std::ref(ExportList), std::ref(ResolvedODR), std::ref(DefinedGlobals),
787 std::ref(ModuleMap));
Mehdi Amini41af4302016-11-11 04:28:40 +0000788 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000789 }
790
791 Error wait() override {
792 BackendThreadPool.wait();
793 if (Err)
794 return std::move(*Err);
795 else
Mehdi Amini41af4302016-11-11 04:28:40 +0000796 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000797 }
798};
Benjamin Kramerffd37152016-11-19 20:44:26 +0000799} // end anonymous namespace
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000800
801ThinBackend lto::createInProcessThinBackend(unsigned ParallelismLevel) {
802 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000803 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000804 AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000805 return llvm::make_unique<InProcessThinBackend>(
806 Conf, CombinedIndex, ParallelismLevel, ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000807 AddStream, Cache);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000808 };
809}
810
Teresa Johnson3f212b82016-09-21 19:12:05 +0000811// Given the original \p Path to an output file, replace any path
812// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
813// resulting directory if it does not yet exist.
814std::string lto::getThinLTOOutputFile(const std::string &Path,
815 const std::string &OldPrefix,
816 const std::string &NewPrefix) {
817 if (OldPrefix.empty() && NewPrefix.empty())
818 return Path;
819 SmallString<128> NewPath(Path);
820 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
821 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
822 if (!ParentPath.empty()) {
823 // Make sure the new directory exists, creating it if necessary.
824 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
825 llvm::errs() << "warning: could not create directory '" << ParentPath
826 << "': " << EC.message() << '\n';
827 }
828 return NewPath.str();
829}
830
Benjamin Kramerffd37152016-11-19 20:44:26 +0000831namespace {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000832class WriteIndexesThinBackend : public ThinBackendProc {
833 std::string OldPrefix, NewPrefix;
834 bool ShouldEmitImportsFiles;
835
836 std::string LinkedObjectsFileName;
837 std::unique_ptr<llvm::raw_fd_ostream> LinkedObjectsFile;
838
839public:
Mehdi Amini767e1452016-09-06 03:23:45 +0000840 WriteIndexesThinBackend(
841 Config &Conf, ModuleSummaryIndex &CombinedIndex,
842 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
843 std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
844 std::string LinkedObjectsFileName)
Mehdi Amini18b91112016-08-19 06:10:03 +0000845 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000846 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
847 ShouldEmitImportsFiles(ShouldEmitImportsFiles),
848 LinkedObjectsFileName(LinkedObjectsFileName) {}
849
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000850 Error start(
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000851 unsigned Task, BitcodeModule BM,
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000852 const FunctionImporter::ImportMapTy &ImportList,
853 const FunctionImporter::ExportSetTy &ExportList,
854 const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
Peter Collingbourne1a0720e2016-12-14 01:17:59 +0000855 MapVector<StringRef, BitcodeModule> &ModuleMap) override {
856 StringRef ModulePath = BM.getModuleIdentifier();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000857 std::string NewModulePath =
858 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
859
860 std::error_code EC;
861 if (!LinkedObjectsFileName.empty()) {
862 if (!LinkedObjectsFile) {
863 LinkedObjectsFile = llvm::make_unique<raw_fd_ostream>(
864 LinkedObjectsFileName, EC, sys::fs::OpenFlags::F_None);
865 if (EC)
866 return errorCodeToError(EC);
867 }
868 *LinkedObjectsFile << NewModulePath << '\n';
869 }
870
871 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
872 gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000873 ImportList, ModuleToSummariesForIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000874
875 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
876 sys::fs::OpenFlags::F_None);
877 if (EC)
878 return errorCodeToError(EC);
879 WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
880
881 if (ShouldEmitImportsFiles)
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000882 return errorCodeToError(
883 EmitImportsFiles(ModulePath, NewModulePath + ".imports", ImportList));
Mehdi Amini41af4302016-11-11 04:28:40 +0000884 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000885 }
886
Mehdi Amini41af4302016-11-11 04:28:40 +0000887 Error wait() override { return Error::success(); }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000888};
Benjamin Kramerffd37152016-11-19 20:44:26 +0000889} // end anonymous namespace
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000890
891ThinBackend lto::createWriteIndexesThinBackend(std::string OldPrefix,
892 std::string NewPrefix,
893 bool ShouldEmitImportsFiles,
894 std::string LinkedObjectsFile) {
895 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
Mehdi Amini767e1452016-09-06 03:23:45 +0000896 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Peter Collingbourne80186a52016-09-23 21:33:43 +0000897 AddStreamFn AddStream, NativeObjectCache Cache) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000898 return llvm::make_unique<WriteIndexesThinBackend>(
Mehdi Amini18b91112016-08-19 06:10:03 +0000899 Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
900 ShouldEmitImportsFiles, LinkedObjectsFile);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000901 };
902}
903
Peter Collingbourne80186a52016-09-23 21:33:43 +0000904Error LTO::runThinLTO(AddStreamFn AddStream, NativeObjectCache Cache,
905 bool HasRegularLTO) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000906 if (ThinLTO.ModuleMap.empty())
Mehdi Amini41af4302016-11-11 04:28:40 +0000907 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000908
909 if (Conf.CombinedIndexHook && !Conf.CombinedIndexHook(ThinLTO.CombinedIndex))
Mehdi Amini41af4302016-11-11 04:28:40 +0000910 return Error::success();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000911
912 // Collect for each module the list of function it defines (GUID ->
913 // Summary).
914 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
915 ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
916 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
917 ModuleToDefinedGVSummaries);
Teresa Johnson620c1402016-09-20 23:07:17 +0000918 // Create entries for any modules that didn't have any GV summaries
919 // (either they didn't have any GVs to start with, or we suppressed
920 // generation of the summaries because they e.g. had inline assembly
921 // uses that couldn't be promoted/renamed on export). This is so
922 // InProcessThinBackend::start can still launch a backend thread, which
923 // is passed the map of summaries for the module, without any special
924 // handling for this case.
925 for (auto &Mod : ThinLTO.ModuleMap)
926 if (!ModuleToDefinedGVSummaries.count(Mod.first))
927 ModuleToDefinedGVSummaries.try_emplace(Mod.first);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000928
929 StringMap<FunctionImporter::ImportMapTy> ImportLists(
930 ThinLTO.ModuleMap.size());
931 StringMap<FunctionImporter::ExportSetTy> ExportLists(
932 ThinLTO.ModuleMap.size());
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000933 StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
Mehdi Aminiadc0e262016-08-23 21:30:12 +0000934
Teresa Johnson002af9b2016-10-31 22:12:21 +0000935 if (Conf.OptLevel > 0) {
Mehdi Aminif39ce992017-01-20 23:34:12 +0000936 // Compute "dead" symbols, we don't want to import/export these!
937 DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
938 for (auto &Res : GlobalResolutions) {
939 if (Res.second.VisibleOutsideThinLTO &&
940 // IRName will be defined if we have seen the prevailing copy of
941 // this value. If not, no need to preserve any ThinLTO copies.
942 !Res.second.IRName.empty())
943 GUIDPreservedSymbols.insert(GlobalValue::getGUID(Res.second.IRName));
944 }
945
946 auto DeadSymbols =
947 computeDeadSymbols(ThinLTO.CombinedIndex, GUIDPreservedSymbols);
948
Teresa Johnson002af9b2016-10-31 22:12:21 +0000949 ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
Teresa Johnson6c475a72017-01-05 21:34:18 +0000950 ImportLists, ExportLists, &DeadSymbols);
Teresa Johnson002af9b2016-10-31 22:12:21 +0000951
952 std::set<GlobalValue::GUID> ExportedGUIDs;
953 for (auto &Res : GlobalResolutions) {
Teresa Johnson6c475a72017-01-05 21:34:18 +0000954 // First check if the symbol was flagged as having external references.
955 if (Res.second.Partition != GlobalResolution::External)
956 continue;
957 // IRName will be defined if we have seen the prevailing copy of
958 // this value. If not, no need to mark as exported from a ThinLTO
959 // partition (and we can't get the GUID).
960 if (Res.second.IRName.empty())
961 continue;
962 auto GUID = GlobalValue::getGUID(Res.second.IRName);
963 // Mark exported unless index-based analysis determined it to be dead.
964 if (!DeadSymbols.count(GUID))
Teresa Johnson002af9b2016-10-31 22:12:21 +0000965 ExportedGUIDs.insert(GlobalValue::getGUID(Res.second.IRName));
966 }
967
968 auto isPrevailing = [&](GlobalValue::GUID GUID,
969 const GlobalValueSummary *S) {
970 return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
971 };
Mehdi Amini1380edf2017-02-03 07:41:43 +0000972 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
Teresa Johnson002af9b2016-10-31 22:12:21 +0000973 const auto &ExportList = ExportLists.find(ModuleIdentifier);
Mehdi Amini1380edf2017-02-03 07:41:43 +0000974 return (ExportList != ExportLists.end() &&
975 ExportList->second.count(GUID)) ||
976 ExportedGUIDs.count(GUID);
Teresa Johnson002af9b2016-10-31 22:12:21 +0000977 };
978 thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported);
979
980 auto recordNewLinkage = [&](StringRef ModuleIdentifier,
981 GlobalValue::GUID GUID,
982 GlobalValue::LinkageTypes NewLinkage) {
983 ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
984 };
985
986 thinLTOResolveWeakForLinkerInIndex(ThinLTO.CombinedIndex, isPrevailing,
987 recordNewLinkage);
988 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000989
Peter Collingbourne80186a52016-09-23 21:33:43 +0000990 std::unique_ptr<ThinBackendProc> BackendProc =
991 ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
992 AddStream, Cache);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000993
Davide Italiano63098952017-01-04 20:37:57 +0000994 // Task numbers start at ParallelCodeGenParallelismLevel if an LTO
995 // module is present, as tasks 0 through ParallelCodeGenParallelismLevel-1
996 // are reserved for parallel code generation partitions.
Teresa Johnson8dd61ae2016-09-16 13:54:19 +0000997 unsigned Task =
998 HasRegularLTO ? RegularLTO.ParallelCodeGenParallelismLevel : 0;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000999 for (auto &Mod : ThinLTO.ModuleMap) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +00001000 if (Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
Mehdi Aminiadc0e262016-08-23 21:30:12 +00001001 ExportLists[Mod.first],
1002 ResolvedODR[Mod.first], ThinLTO.ModuleMap))
Teresa Johnson9ba95f92016-08-11 14:58:12 +00001003 return E;
Teresa Johnson9ba95f92016-08-11 14:58:12 +00001004 ++Task;
Teresa Johnson9ba95f92016-08-11 14:58:12 +00001005 }
1006
1007 return BackendProc->wait();
Teresa Johnsondf6edc52016-05-23 22:54:06 +00001008}
Davide Italiano690ed9d2017-02-10 23:49:38 +00001009
1010Expected<std::unique_ptr<tool_output_file>>
1011lto::setupOptimizationRemarks(LLVMContext &Context,
1012 StringRef LTORemarksFilename,
1013 bool LTOPassRemarksWithHotness, int Count) {
1014 if (LTORemarksFilename.empty())
1015 return nullptr;
1016
1017 std::string Filename = LTORemarksFilename;
1018 if (Count != -1)
1019 Filename += ".thin." + llvm::utostr(Count) + ".yaml";
1020
1021 std::error_code EC;
1022 auto DiagnosticFile =
1023 llvm::make_unique<tool_output_file>(Filename, EC, sys::fs::F_None);
1024 if (EC)
1025 return errorCodeToError(EC);
1026 Context.setDiagnosticsOutputFile(
1027 llvm::make_unique<yaml::Output>(DiagnosticFile->os()));
1028 if (LTOPassRemarksWithHotness)
1029 Context.setDiagnosticHotnessRequested(true);
1030 DiagnosticFile->keep();
1031 return std::move(DiagnosticFile);
1032}