blob: 04c5ac79aeb0ac619588cf1366a6aa9d9eb0b0f0 [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 Johnsondf6edc52016-05-23 22:54:06 +000017#include "llvm/Bitcode/ReaderWriter.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000018#include "llvm/CodeGen/Analysis.h"
19#include "llvm/IR/AutoUpgrade.h"
20#include "llvm/IR/DiagnosticPrinter.h"
21#include "llvm/IR/LegacyPassManager.h"
22#include "llvm/LTO/LTOBackend.h"
23#include "llvm/Linker/IRMover.h"
24#include "llvm/Object/ModuleSummaryIndexObjectFile.h"
25#include "llvm/Support/ManagedStatic.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000026#include "llvm/Support/MemoryBuffer.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000027#include "llvm/Support/Path.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000028#include "llvm/Support/SourceMgr.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000029#include "llvm/Support/TargetRegistry.h"
30#include "llvm/Support/ThreadPool.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000031#include "llvm/Support/raw_ostream.h"
Teresa Johnson9ba95f92016-08-11 14:58:12 +000032#include "llvm/Target/TargetMachine.h"
33#include "llvm/Target/TargetOptions.h"
34#include "llvm/Transforms/IPO.h"
35#include "llvm/Transforms/IPO/PassManagerBuilder.h"
36#include "llvm/Transforms/Utils/SplitModule.h"
Teresa Johnsondf6edc52016-05-23 22:54:06 +000037
Teresa Johnson9ba95f92016-08-11 14:58:12 +000038#include <set>
39
40using namespace llvm;
41using namespace lto;
42using namespace object;
Teresa Johnsondf6edc52016-05-23 22:54:06 +000043
44// Simple helper to load a module from bitcode
Teresa Johnson9ba95f92016-08-11 14:58:12 +000045std::unique_ptr<Module>
46llvm::loadModuleFromBuffer(const MemoryBufferRef &Buffer, LLVMContext &Context,
47 bool Lazy) {
Teresa Johnsondf6edc52016-05-23 22:54:06 +000048 SMDiagnostic Err;
49 ErrorOr<std::unique_ptr<Module>> ModuleOrErr(nullptr);
50 if (Lazy) {
51 ModuleOrErr =
52 getLazyBitcodeModule(MemoryBuffer::getMemBuffer(Buffer, false), Context,
53 /* ShouldLazyLoadMetadata */ Lazy);
54 } else {
55 ModuleOrErr = parseBitcodeFile(Buffer, Context);
56 }
57 if (std::error_code EC = ModuleOrErr.getError()) {
58 Err = SMDiagnostic(Buffer.getBufferIdentifier(), SourceMgr::DK_Error,
59 EC.message());
60 Err.print("ThinLTO", errs());
61 report_fatal_error("Can't load module, abort.");
62 }
63 return std::move(ModuleOrErr.get());
64}
Teresa Johnson04c9a2d2016-05-25 14:03:11 +000065
66static void thinLTOResolveWeakForLinkerGUID(
67 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
68 DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +000069 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +000070 isPrevailing,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +000071 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +000072 recordNewLinkage) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +000073 for (auto &S : GVSummaryList) {
74 if (GlobalInvolvedWithAlias.count(S.get()))
75 continue;
76 GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
77 if (!GlobalValue::isWeakForLinker(OriginalLinkage))
78 continue;
Peter Collingbourne73589f32016-07-07 18:31:51 +000079 // We need to emit only one of these. The prevailing module will keep it,
Teresa Johnson04c9a2d2016-05-25 14:03:11 +000080 // but turned into a weak, while the others will drop it when possible.
Peter Collingbourne73589f32016-07-07 18:31:51 +000081 if (isPrevailing(GUID, S.get())) {
Teresa Johnson28c03b52016-05-26 14:16:52 +000082 if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
83 S->setLinkage(GlobalValue::getWeakLinkage(
84 GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
Teresa Johnson04c9a2d2016-05-25 14:03:11 +000085 }
86 // Alias can't be turned into available_externally.
87 else if (!isa<AliasSummary>(S.get()) &&
88 (GlobalValue::isLinkOnceODRLinkage(OriginalLinkage) ||
89 GlobalValue::isWeakODRLinkage(OriginalLinkage)))
90 S->setLinkage(GlobalValue::AvailableExternallyLinkage);
91 if (S->linkage() != OriginalLinkage)
92 recordNewLinkage(S->modulePath(), GUID, S->linkage());
93 }
94}
95
96// Resolve Weak and LinkOnce values in the \p Index.
97//
98// We'd like to drop these functions if they are no longer referenced in the
99// current module. However there is a chance that another module is still
100// referencing them because of the import. We make sure we always emit at least
101// one copy.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000102void llvm::thinLTOResolveWeakForLinkerInIndex(
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000103 ModuleSummaryIndex &Index,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000104 function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000105 isPrevailing,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000106 function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000107 recordNewLinkage) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000108 // We won't optimize the globals that are referenced by an alias for now
109 // Ideally we should turn the alias into a global and duplicate the definition
110 // when needed.
111 DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
112 for (auto &I : Index)
113 for (auto &S : I.second)
114 if (auto AS = dyn_cast<AliasSummary>(S.get()))
115 GlobalInvolvedWithAlias.insert(&AS->getAliasee());
116
117 for (auto &I : Index)
118 thinLTOResolveWeakForLinkerGUID(I.second, I.first, GlobalInvolvedWithAlias,
Peter Collingbourne73589f32016-07-07 18:31:51 +0000119 isPrevailing, recordNewLinkage);
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000120}
121
122static void thinLTOInternalizeAndPromoteGUID(
123 GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000124 function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000125 for (auto &S : GVSummaryList) {
126 if (isExported(S->modulePath(), GUID)) {
127 if (GlobalValue::isLocalLinkage(S->linkage()))
128 S->setLinkage(GlobalValue::ExternalLinkage);
129 } else if (!GlobalValue::isLocalLinkage(S->linkage()))
130 S->setLinkage(GlobalValue::InternalLinkage);
131 }
132}
133
134// Update the linkages in the given \p Index to mark exported values
135// as external and non-exported values as internal.
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000136void llvm::thinLTOInternalizeAndPromoteInIndex(
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000137 ModuleSummaryIndex &Index,
Benjamin Kramerd3f4c052016-06-12 16:13:55 +0000138 function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
Teresa Johnson04c9a2d2016-05-25 14:03:11 +0000139 for (auto &I : Index)
140 thinLTOInternalizeAndPromoteGUID(I.second, I.first, isExported);
141}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000142
143Expected<std::unique_ptr<InputFile>> InputFile::create(MemoryBufferRef Object) {
144 std::unique_ptr<InputFile> File(new InputFile);
145 std::string Msg;
146 auto DiagHandler = [](const DiagnosticInfo &DI, void *MsgP) {
147 auto *Msg = reinterpret_cast<std::string *>(MsgP);
148 raw_string_ostream OS(*Msg);
149 DiagnosticPrinterRawOStream DP(OS);
150 DI.print(DP);
151 };
152 File->Ctx.setDiagnosticHandler(DiagHandler, static_cast<void *>(&Msg));
153
154 ErrorOr<std::unique_ptr<object::IRObjectFile>> IRObj =
155 IRObjectFile::create(Object, File->Ctx);
156 if (!Msg.empty())
157 return make_error<StringError>(Msg, inconvertibleErrorCode());
158 if (!IRObj)
159 return errorCodeToError(IRObj.getError());
160 File->Obj = std::move(*IRObj);
161
162 File->Ctx.setDiagnosticHandler(nullptr, nullptr);
163
164 return std::move(File);
165}
166
167LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
168 Config &Conf)
169 : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
Mehdi Aminie7494532016-08-23 18:39:12 +0000170 Ctx(Conf) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000171
172LTO::ThinLTOState::ThinLTOState(ThinBackend Backend) : Backend(Backend) {
173 if (!Backend)
174 this->Backend = createInProcessThinBackend(thread::hardware_concurrency());
175}
176
177LTO::LTO(Config Conf, ThinBackend Backend,
178 unsigned ParallelCodeGenParallelismLevel)
179 : Conf(std::move(Conf)),
180 RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
Mehdi Amini026ddbb2016-08-19 05:56:37 +0000181 ThinLTO(std::move(Backend)) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000182
183// Add the given symbol to the GlobalResolutions map, and resolve its partition.
184void LTO::addSymbolToGlobalRes(IRObjectFile *Obj,
185 SmallPtrSet<GlobalValue *, 8> &Used,
186 const InputFile::Symbol &Sym,
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000187 SymbolResolution Res, unsigned Partition) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000188 GlobalValue *GV = Obj->getSymbolGV(Sym.I->getRawDataRefImpl());
189
190 auto &GlobalRes = GlobalResolutions[Sym.getName()];
191 if (GV) {
192 GlobalRes.UnnamedAddr &= GV->hasGlobalUnnamedAddr();
193 if (Res.Prevailing)
194 GlobalRes.IRName = GV->getName();
195 }
196 if (Res.VisibleToRegularObj || (GV && Used.count(GV)) ||
197 (GlobalRes.Partition != GlobalResolution::Unknown &&
198 GlobalRes.Partition != Partition))
199 GlobalRes.Partition = GlobalResolution::External;
200 else
201 GlobalRes.Partition = Partition;
202}
203
204void LTO::writeToResolutionFile(InputFile *Input,
205 ArrayRef<SymbolResolution> Res) {
206 StringRef Path = Input->Obj->getMemoryBufferRef().getBufferIdentifier();
207 *Conf.ResolutionFile << Path << '\n';
208 auto ResI = Res.begin();
209 for (const InputFile::Symbol &Sym : Input->symbols()) {
210 assert(ResI != Res.end());
211 SymbolResolution Res = *ResI++;
212
213 *Conf.ResolutionFile << "-r=" << Path << ',' << Sym.getName() << ',';
214 if (Res.Prevailing)
215 *Conf.ResolutionFile << 'p';
216 if (Res.FinalDefinitionInLinkageUnit)
217 *Conf.ResolutionFile << 'l';
218 if (Res.VisibleToRegularObj)
219 *Conf.ResolutionFile << 'x';
220 *Conf.ResolutionFile << '\n';
221 }
222 assert(ResI == Res.end());
223}
224
225Error LTO::add(std::unique_ptr<InputFile> Input,
226 ArrayRef<SymbolResolution> Res) {
227 assert(!CalledGetMaxTasks);
228
229 if (Conf.ResolutionFile)
230 writeToResolutionFile(Input.get(), Res);
231
Mehdi Amini9989f802016-08-19 15:35:44 +0000232 // FIXME: move to backend
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000233 Module &M = Input->Obj->getModule();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000234 if (!Conf.OverrideTriple.empty())
235 M.setTargetTriple(Conf.OverrideTriple);
236 else if (M.getTargetTriple().empty())
237 M.setTargetTriple(Conf.DefaultTriple);
238
239 MemoryBufferRef MBRef = Input->Obj->getMemoryBufferRef();
240 bool HasThinLTOSummary = hasGlobalValueSummary(MBRef, Conf.DiagHandler);
241
242 if (HasThinLTOSummary)
243 return addThinLTO(std::move(Input), Res);
244 else
245 return addRegularLTO(std::move(Input), Res);
246}
247
248// Add a regular LTO object to the link.
249Error LTO::addRegularLTO(std::unique_ptr<InputFile> Input,
250 ArrayRef<SymbolResolution> Res) {
Mehdi Aminie7494532016-08-23 18:39:12 +0000251 if (!RegularLTO.CombinedModule) {
252 RegularLTO.CombinedModule =
253 llvm::make_unique<Module>("ld-temp.o", RegularLTO.Ctx);
254 RegularLTO.Mover = llvm::make_unique<IRMover>(*RegularLTO.CombinedModule);
255 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000256 ErrorOr<std::unique_ptr<object::IRObjectFile>> ObjOrErr =
257 IRObjectFile::create(Input->Obj->getMemoryBufferRef(), RegularLTO.Ctx);
258 if (!ObjOrErr)
259 return errorCodeToError(ObjOrErr.getError());
260 std::unique_ptr<object::IRObjectFile> Obj = std::move(*ObjOrErr);
261
262 Module &M = Obj->getModule();
263 M.materializeMetadata();
264 UpgradeDebugInfo(M);
265
266 SmallPtrSet<GlobalValue *, 8> Used;
267 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
268
269 std::vector<GlobalValue *> Keep;
270
271 for (GlobalVariable &GV : M.globals())
272 if (GV.hasAppendingLinkage())
273 Keep.push_back(&GV);
274
275 auto ResI = Res.begin();
276 for (const InputFile::Symbol &Sym :
277 make_range(InputFile::symbol_iterator(Obj->symbol_begin()),
278 InputFile::symbol_iterator(Obj->symbol_end()))) {
279 assert(ResI != Res.end());
280 SymbolResolution Res = *ResI++;
281 addSymbolToGlobalRes(Obj.get(), Used, Sym, Res, 0);
282
283 GlobalValue *GV = Obj->getSymbolGV(Sym.I->getRawDataRefImpl());
284 if (Res.Prevailing && GV) {
285 Keep.push_back(GV);
286 switch (GV->getLinkage()) {
287 default:
288 break;
289 case GlobalValue::LinkOnceAnyLinkage:
290 GV->setLinkage(GlobalValue::WeakAnyLinkage);
291 break;
292 case GlobalValue::LinkOnceODRLinkage:
293 GV->setLinkage(GlobalValue::WeakODRLinkage);
294 break;
295 }
296 }
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000297 // Common resolution: collect the maximum size/alignment.
298 // FIXME: right now we ignore the prevailing information, it is not clear
299 // what is the "right" behavior here.
300 if (Sym.getFlags() & object::BasicSymbolRef::SF_Common) {
301 auto &CommonRes = RegularLTO.Commons[Sym.getIRName()];
302 CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
303 CommonRes.Align = std::max(CommonRes.Align, Sym.getCommonAlignment());
304 }
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000305
306 // FIXME: use proposed local attribute for FinalDefinitionInLinkageUnit.
307 }
308 assert(ResI == Res.end());
309
Mehdi Aminie7494532016-08-23 18:39:12 +0000310 return RegularLTO.Mover->move(Obj->takeModule(), Keep,
311 [](GlobalValue &, IRMover::ValueAdder) {});
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000312}
313
314// Add a ThinLTO object to the link.
315Error LTO::addThinLTO(std::unique_ptr<InputFile> Input,
316 ArrayRef<SymbolResolution> Res) {
317 Module &M = Input->Obj->getModule();
318 SmallPtrSet<GlobalValue *, 8> Used;
319 collectUsedGlobalVariables(M, Used, /*CompilerUsed*/ false);
320
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000321 MemoryBufferRef MBRef = Input->Obj->getMemoryBufferRef();
322 ErrorOr<std::unique_ptr<object::ModuleSummaryIndexObjectFile>>
323 SummaryObjOrErr =
324 object::ModuleSummaryIndexObjectFile::create(MBRef, Conf.DiagHandler);
325 if (!SummaryObjOrErr)
326 return errorCodeToError(SummaryObjOrErr.getError());
327 ThinLTO.CombinedIndex.mergeFrom((*SummaryObjOrErr)->takeIndex(),
328 ThinLTO.ModuleMap.size());
329
330 auto ResI = Res.begin();
331 for (const InputFile::Symbol &Sym : Input->symbols()) {
332 assert(ResI != Res.end());
333 SymbolResolution Res = *ResI++;
334 addSymbolToGlobalRes(Input->Obj.get(), Used, Sym, Res,
335 ThinLTO.ModuleMap.size() + 1);
336
337 GlobalValue *GV = Input->Obj->getSymbolGV(Sym.I->getRawDataRefImpl());
338 if (Res.Prevailing && GV)
339 ThinLTO.PrevailingModuleForGUID[GV->getGUID()] =
340 MBRef.getBufferIdentifier();
341 }
342 assert(ResI == Res.end());
343
344 ThinLTO.ModuleMap[MBRef.getBufferIdentifier()] = MBRef;
345 return Error();
346}
347
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000348unsigned LTO::getMaxTasks() const {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000349 CalledGetMaxTasks = true;
350 return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
351}
352
Mehdi Amini970800e2016-08-17 06:23:09 +0000353Error LTO::run(AddOutputFn AddOutput) {
Mehdi Aminie7494532016-08-23 18:39:12 +0000354 // Invoke regular LTO if there was a regular LTO module to start with.
355 if (RegularLTO.CombinedModule)
Mehdi Amini970800e2016-08-17 06:23:09 +0000356 if (auto E = runRegularLTO(AddOutput))
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000357 return E;
Mehdi Amini970800e2016-08-17 06:23:09 +0000358 return runThinLTO(AddOutput);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000359}
360
Mehdi Amini970800e2016-08-17 06:23:09 +0000361Error LTO::runRegularLTO(AddOutputFn AddOutput) {
Mehdi Aminidc4c8cf2016-08-22 06:25:46 +0000362 // Make sure commons have the right size/alignment: we kept the largest from
363 // all the prevailing when adding the inputs, and we apply it here.
364 for (auto &I : RegularLTO.Commons) {
365 ArrayType *Ty =
366 ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
367 GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
368 if (OldGV && OldGV->getType()->getElementType() == Ty) {
369 // Don't create a new global if the type is already correct, just make
370 // sure the alignment is correct.
371 OldGV->setAlignment(I.second.Align);
372 continue;
373 }
374 auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
375 GlobalValue::CommonLinkage,
376 ConstantAggregateZero::get(Ty), "");
377 GV->setAlignment(I.second.Align);
378 if (OldGV) {
379 OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
380 GV->takeName(OldGV);
381 OldGV->eraseFromParent();
382 } else {
383 GV->setName(I.first);
384 }
385 }
386
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000387 if (Conf.PreOptModuleHook &&
388 !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
389 return Error();
390
Mehdi Aminid310b472016-08-22 06:25:41 +0000391 if (!Conf.CodeGenOnly) {
392 for (const auto &R : GlobalResolutions) {
393 if (R.second.IRName.empty())
394 continue;
395 if (R.second.Partition != 0 &&
396 R.second.Partition != GlobalResolution::External)
397 continue;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000398
Mehdi Aminid310b472016-08-22 06:25:41 +0000399 GlobalValue *GV =
400 RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
401 // Ignore symbols defined in other partitions.
402 if (!GV || GV->hasLocalLinkage())
403 continue;
404 GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
405 : GlobalValue::UnnamedAddr::None);
406 if (R.second.Partition == 0)
407 GV->setLinkage(GlobalValue::InternalLinkage);
408 }
409
410 if (Conf.PostInternalizeModuleHook &&
411 !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
412 return Error();
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000413 }
Mehdi Amini970800e2016-08-17 06:23:09 +0000414 return backend(Conf, AddOutput, RegularLTO.ParallelCodeGenParallelismLevel,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000415 std::move(RegularLTO.CombinedModule));
416}
417
418/// This class defines the interface to the ThinLTO backend.
419class lto::ThinBackendProc {
420protected:
421 Config &Conf;
422 ModuleSummaryIndex &CombinedIndex;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000423 StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
424
425public:
426 ThinBackendProc(Config &Conf, ModuleSummaryIndex &CombinedIndex,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000427 StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
Mehdi Amini18b91112016-08-19 06:10:03 +0000428 : Conf(Conf), CombinedIndex(CombinedIndex),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000429 ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
430
431 virtual ~ThinBackendProc() {}
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000432 virtual Error start(unsigned Task, MemoryBufferRef MBRef,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000433 const FunctionImporter::ImportMapTy &ImportList,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000434 MapVector<StringRef, MemoryBufferRef> &ModuleMap) = 0;
435 virtual Error wait() = 0;
436};
437
438class InProcessThinBackend : public ThinBackendProc {
439 ThreadPool BackendThreadPool;
Mehdi Amini18b91112016-08-19 06:10:03 +0000440 AddOutputFn AddOutput;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000441
442 Optional<Error> Err;
443 std::mutex ErrMu;
444
445public:
446 InProcessThinBackend(Config &Conf, ModuleSummaryIndex &CombinedIndex,
447 unsigned ThinLTOParallelismLevel,
448 StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Amini970800e2016-08-17 06:23:09 +0000449 AddOutputFn AddOutput)
Mehdi Amini18b91112016-08-19 06:10:03 +0000450 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
451 BackendThreadPool(ThinLTOParallelismLevel),
452 AddOutput(std::move(AddOutput)) {}
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000453
454 Error
Mehdi Amini970800e2016-08-17 06:23:09 +0000455 runThinLTOBackendThread(AddOutputFn AddOutput, unsigned Task,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000456 MemoryBufferRef MBRef,
457 ModuleSummaryIndex &CombinedIndex,
458 const FunctionImporter::ImportMapTy &ImportList,
459 const GVSummaryMapTy &DefinedGlobals,
460 MapVector<StringRef, MemoryBufferRef> &ModuleMap) {
Mehdi Amini9ec5a612016-08-23 16:53:34 +0000461 LTOLLVMContext BackendContext(Conf);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000462
463 ErrorOr<std::unique_ptr<Module>> MOrErr =
464 parseBitcodeFile(MBRef, BackendContext);
465 assert(MOrErr && "Unable to load module in thread?");
466
Mehdi Amini970800e2016-08-17 06:23:09 +0000467 return thinBackend(Conf, Task, AddOutput, **MOrErr, CombinedIndex,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000468 ImportList, DefinedGlobals, ModuleMap);
469 }
470
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000471 Error start(unsigned Task, MemoryBufferRef MBRef,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000472 const FunctionImporter::ImportMapTy &ImportList,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000473 MapVector<StringRef, MemoryBufferRef> &ModuleMap) override {
474 StringRef ModulePath = MBRef.getBufferIdentifier();
475 BackendThreadPool.async(
476 [=](MemoryBufferRef MBRef, ModuleSummaryIndex &CombinedIndex,
477 const FunctionImporter::ImportMapTy &ImportList,
478 GVSummaryMapTy &DefinedGlobals,
479 MapVector<StringRef, MemoryBufferRef> &ModuleMap) {
480 Error E =
Mehdi Amini970800e2016-08-17 06:23:09 +0000481 runThinLTOBackendThread(AddOutput, Task, MBRef, CombinedIndex,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000482 ImportList, DefinedGlobals, ModuleMap);
483 if (E) {
484 std::unique_lock<std::mutex> L(ErrMu);
485 if (Err)
486 Err = joinErrors(std::move(*Err), std::move(E));
487 else
488 Err = std::move(E);
489 }
490 },
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000491 MBRef, std::ref(CombinedIndex), std::ref(ImportList),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000492 std::ref(ModuleToDefinedGVSummaries[ModulePath]), std::ref(ModuleMap));
493 return Error();
494 }
495
496 Error wait() override {
497 BackendThreadPool.wait();
498 if (Err)
499 return std::move(*Err);
500 else
501 return Error();
502 }
503};
504
505ThinBackend lto::createInProcessThinBackend(unsigned ParallelismLevel) {
506 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
507 StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Amini970800e2016-08-17 06:23:09 +0000508 AddOutputFn AddOutput) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000509 return llvm::make_unique<InProcessThinBackend>(
510 Conf, CombinedIndex, ParallelismLevel, ModuleToDefinedGVSummaries,
Mehdi Amini970800e2016-08-17 06:23:09 +0000511 AddOutput);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000512 };
513}
514
515class WriteIndexesThinBackend : public ThinBackendProc {
516 std::string OldPrefix, NewPrefix;
517 bool ShouldEmitImportsFiles;
518
519 std::string LinkedObjectsFileName;
520 std::unique_ptr<llvm::raw_fd_ostream> LinkedObjectsFile;
521
522public:
523 WriteIndexesThinBackend(Config &Conf, ModuleSummaryIndex &CombinedIndex,
524 StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Amini18b91112016-08-19 06:10:03 +0000525 std::string OldPrefix, std::string NewPrefix,
526 bool ShouldEmitImportsFiles,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000527 std::string LinkedObjectsFileName)
Mehdi Amini18b91112016-08-19 06:10:03 +0000528 : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000529 OldPrefix(OldPrefix), NewPrefix(NewPrefix),
530 ShouldEmitImportsFiles(ShouldEmitImportsFiles),
531 LinkedObjectsFileName(LinkedObjectsFileName) {}
532
533 /// Given the original \p Path to an output file, replace any path
534 /// prefix matching \p OldPrefix with \p NewPrefix. Also, create the
535 /// resulting directory if it does not yet exist.
536 std::string getThinLTOOutputFile(const std::string &Path,
537 const std::string &OldPrefix,
538 const std::string &NewPrefix) {
539 if (OldPrefix.empty() && NewPrefix.empty())
540 return Path;
541 SmallString<128> NewPath(Path);
542 llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
543 StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
544 if (!ParentPath.empty()) {
545 // Make sure the new directory exists, creating it if necessary.
546 if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
547 llvm::errs() << "warning: could not create directory '" << ParentPath
548 << "': " << EC.message() << '\n';
549 }
550 return NewPath.str();
551 }
552
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000553 Error start(unsigned Task, MemoryBufferRef MBRef,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000554 const FunctionImporter::ImportMapTy &ImportList,
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000555 MapVector<StringRef, MemoryBufferRef> &ModuleMap) override {
556 StringRef ModulePath = MBRef.getBufferIdentifier();
557 std::string NewModulePath =
558 getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
559
560 std::error_code EC;
561 if (!LinkedObjectsFileName.empty()) {
562 if (!LinkedObjectsFile) {
563 LinkedObjectsFile = llvm::make_unique<raw_fd_ostream>(
564 LinkedObjectsFileName, EC, sys::fs::OpenFlags::F_None);
565 if (EC)
566 return errorCodeToError(EC);
567 }
568 *LinkedObjectsFile << NewModulePath << '\n';
569 }
570
571 std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
572 gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000573 ImportList, ModuleToSummariesForIndex);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000574
575 raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
576 sys::fs::OpenFlags::F_None);
577 if (EC)
578 return errorCodeToError(EC);
579 WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
580
581 if (ShouldEmitImportsFiles)
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000582 return errorCodeToError(
583 EmitImportsFiles(ModulePath, NewModulePath + ".imports", ImportList));
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000584 return Error();
585 }
586
587 Error wait() override { return Error(); }
588};
589
590ThinBackend lto::createWriteIndexesThinBackend(std::string OldPrefix,
591 std::string NewPrefix,
592 bool ShouldEmitImportsFiles,
593 std::string LinkedObjectsFile) {
594 return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
595 StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
Mehdi Amini970800e2016-08-17 06:23:09 +0000596 AddOutputFn AddOutput) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000597 return llvm::make_unique<WriteIndexesThinBackend>(
Mehdi Amini18b91112016-08-19 06:10:03 +0000598 Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
599 ShouldEmitImportsFiles, LinkedObjectsFile);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000600 };
601}
602
Mehdi Amini970800e2016-08-17 06:23:09 +0000603Error LTO::runThinLTO(AddOutputFn AddOutput) {
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000604 if (ThinLTO.ModuleMap.empty())
605 return Error();
606
607 if (Conf.CombinedIndexHook && !Conf.CombinedIndexHook(ThinLTO.CombinedIndex))
608 return Error();
609
610 // Collect for each module the list of function it defines (GUID ->
611 // Summary).
612 StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
613 ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
614 ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
615 ModuleToDefinedGVSummaries);
616
617 StringMap<FunctionImporter::ImportMapTy> ImportLists(
618 ThinLTO.ModuleMap.size());
619 StringMap<FunctionImporter::ExportSetTy> ExportLists(
620 ThinLTO.ModuleMap.size());
621 ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
622 ImportLists, ExportLists);
623
624 std::set<GlobalValue::GUID> ExportedGUIDs;
625 for (auto &Res : GlobalResolutions) {
626 if (!Res.second.IRName.empty() &&
627 Res.second.Partition == GlobalResolution::External)
628 ExportedGUIDs.insert(GlobalValue::getGUID(Res.second.IRName));
629 }
630
631 auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
632 return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
633 };
634 auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
635 const auto &ExportList = ExportLists.find(ModuleIdentifier);
636 return (ExportList != ExportLists.end() &&
637 ExportList->second.count(GUID)) ||
638 ExportedGUIDs.count(GUID);
639 };
640 thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported);
641 thinLTOResolveWeakForLinkerInIndex(
642 ThinLTO.CombinedIndex, isPrevailing,
643 [](StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes) {});
644
645 std::unique_ptr<ThinBackendProc> BackendProc = ThinLTO.Backend(
Mehdi Amini970800e2016-08-17 06:23:09 +0000646 Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries, AddOutput);
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000647
648 // Partition numbers for ThinLTO jobs start at 1 (see comments for
649 // GlobalResolution in LTO.h). Task numbers, however, start at
650 // ParallelCodeGenParallelismLevel, as tasks 0 through
651 // ParallelCodeGenParallelismLevel-1 are reserved for parallel code generation
652 // partitions.
Mehdi Aminie7494532016-08-23 18:39:12 +0000653 unsigned Task = RegularLTO.CombinedModule
654 ? RegularLTO.ParallelCodeGenParallelismLevel
655 : 0;
Teresa Johnsonfaa75062016-08-11 20:38:39 +0000656 unsigned Partition = 1;
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000657
658 for (auto &Mod : ThinLTO.ModuleMap) {
Mehdi Aminicdbcbf72016-08-16 05:46:05 +0000659 if (Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
Teresa Johnson9ba95f92016-08-11 14:58:12 +0000660 ThinLTO.ModuleMap))
661 return E;
662
663 ++Task;
664 ++Partition;
665 }
666
667 return BackendProc->wait();
Teresa Johnsondf6edc52016-05-23 22:54:06 +0000668}