]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/LTO/LTO.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r304149, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / LTO / LTO.cpp
1 //===-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"
15 #include "llvm/Analysis/TargetLibraryInfo.h"
16 #include "llvm/Analysis/TargetTransformInfo.h"
17 #include "llvm/Bitcode/BitcodeReader.h"
18 #include "llvm/Bitcode/BitcodeWriter.h"
19 #include "llvm/CodeGen/Analysis.h"
20 #include "llvm/IR/AutoUpgrade.h"
21 #include "llvm/IR/DiagnosticPrinter.h"
22 #include "llvm/IR/LegacyPassManager.h"
23 #include "llvm/IR/Mangler.h"
24 #include "llvm/IR/Metadata.h"
25 #include "llvm/LTO/LTOBackend.h"
26 #include "llvm/Linker/IRMover.h"
27 #include "llvm/Object/IRObjectFile.h"
28 #include "llvm/Support/Error.h"
29 #include "llvm/Support/ManagedStatic.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/Path.h"
32 #include "llvm/Support/SHA1.h"
33 #include "llvm/Support/SourceMgr.h"
34 #include "llvm/Support/TargetRegistry.h"
35 #include "llvm/Support/ThreadPool.h"
36 #include "llvm/Support/Threading.h"
37 #include "llvm/Support/VCSRevision.h"
38 #include "llvm/Support/raw_ostream.h"
39 #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"
44
45 #include <set>
46
47 using namespace llvm;
48 using namespace lto;
49 using namespace object;
50
51 #define DEBUG_TYPE "lto"
52
53 // The values are (type identifier, summary) pairs.
54 typedef DenseMap<
55     GlobalValue::GUID,
56     TinyPtrVector<const std::pair<const std::string, TypeIdSummary> *>>
57     TypeIdSummariesByGuidTy;
58
59 // Returns a unique hash for the Module considering the current list of
60 // export/import and other global analysis results.
61 // The hash is produced in \p Key.
62 static void computeCacheKey(
63     SmallString<40> &Key, const Config &Conf, const ModuleSummaryIndex &Index,
64     StringRef ModuleID, const FunctionImporter::ImportMapTy &ImportList,
65     const FunctionImporter::ExportSetTy &ExportList,
66     const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
67     const GVSummaryMapTy &DefinedGlobals,
68     const TypeIdSummariesByGuidTy &TypeIdSummariesByGuid) {
69   // Compute the unique hash for this entry.
70   // This is based on the current compiler version, the module itself, the
71   // export list, the hash for every single module in the import list, the
72   // list of ResolvedODR for the module, and the list of preserved symbols.
73   SHA1 Hasher;
74
75   // Start with the compiler revision
76   Hasher.update(LLVM_VERSION_STRING);
77 #ifdef LLVM_REVISION
78   Hasher.update(LLVM_REVISION);
79 #endif
80
81   // Include the parts of the LTO configuration that affect code generation.
82   auto AddString = [&](StringRef Str) {
83     Hasher.update(Str);
84     Hasher.update(ArrayRef<uint8_t>{0});
85   };
86   auto AddUnsigned = [&](unsigned I) {
87     uint8_t Data[4];
88     Data[0] = I;
89     Data[1] = I >> 8;
90     Data[2] = I >> 16;
91     Data[3] = I >> 24;
92     Hasher.update(ArrayRef<uint8_t>{Data, 4});
93   };
94   auto AddUint64 = [&](uint64_t I) {
95     uint8_t Data[8];
96     Data[0] = I;
97     Data[1] = I >> 8;
98     Data[2] = I >> 16;
99     Data[3] = I >> 24;
100     Data[4] = I >> 32;
101     Data[5] = I >> 40;
102     Data[6] = I >> 48;
103     Data[7] = I >> 56;
104     Hasher.update(ArrayRef<uint8_t>{Data, 8});
105   };
106   AddString(Conf.CPU);
107   // FIXME: Hash more of Options. For now all clients initialize Options from
108   // command-line flags (which is unsupported in production), but may set
109   // RelaxELFRelocations. The clang driver can also pass FunctionSections,
110   // DataSections and DebuggerTuning via command line flags.
111   AddUnsigned(Conf.Options.RelaxELFRelocations);
112   AddUnsigned(Conf.Options.FunctionSections);
113   AddUnsigned(Conf.Options.DataSections);
114   AddUnsigned((unsigned)Conf.Options.DebuggerTuning);
115   for (auto &A : Conf.MAttrs)
116     AddString(A);
117   if (Conf.RelocModel)
118     AddUnsigned(*Conf.RelocModel);
119   else
120     AddUnsigned(-1);
121   AddUnsigned(Conf.CodeModel);
122   AddUnsigned(Conf.CGOptLevel);
123   AddUnsigned(Conf.CGFileType);
124   AddUnsigned(Conf.OptLevel);
125   AddString(Conf.OptPipeline);
126   AddString(Conf.AAPipeline);
127   AddString(Conf.OverrideTriple);
128   AddString(Conf.DefaultTriple);
129
130   // Include the hash for the current module
131   auto ModHash = Index.getModuleHash(ModuleID);
132   Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
133   for (auto F : ExportList)
134     // The export list can impact the internalization, be conservative here
135     Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
136
137   // Include the hash for every module we import functions from. The set of
138   // imported symbols for each module may affect code generation and is
139   // sensitive to link order, so include that as well.
140   for (auto &Entry : ImportList) {
141     auto ModHash = Index.getModuleHash(Entry.first());
142     Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
143
144     AddUint64(Entry.second.size());
145     for (auto &Fn : Entry.second)
146       AddUint64(Fn.first);
147   }
148
149   // Include the hash for the resolved ODR.
150   for (auto &Entry : ResolvedODR) {
151     Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
152                                     sizeof(GlobalValue::GUID)));
153     Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
154                                     sizeof(GlobalValue::LinkageTypes)));
155   }
156
157   std::set<GlobalValue::GUID> UsedTypeIds;
158
159   auto AddUsedTypeIds = [&](GlobalValueSummary *GS) {
160     auto *FS = dyn_cast_or_null<FunctionSummary>(GS);
161     if (!FS)
162       return;
163     for (auto &TT : FS->type_tests())
164       UsedTypeIds.insert(TT);
165     for (auto &TT : FS->type_test_assume_vcalls())
166       UsedTypeIds.insert(TT.GUID);
167     for (auto &TT : FS->type_checked_load_vcalls())
168       UsedTypeIds.insert(TT.GUID);
169     for (auto &TT : FS->type_test_assume_const_vcalls())
170       UsedTypeIds.insert(TT.VFunc.GUID);
171     for (auto &TT : FS->type_checked_load_const_vcalls())
172       UsedTypeIds.insert(TT.VFunc.GUID);
173   };
174
175   // Include the hash for the linkage type to reflect internalization and weak
176   // resolution, and collect any used type identifier resolutions.
177   for (auto &GS : DefinedGlobals) {
178     GlobalValue::LinkageTypes Linkage = GS.second->linkage();
179     Hasher.update(
180         ArrayRef<uint8_t>((const uint8_t *)&Linkage, sizeof(Linkage)));
181     AddUsedTypeIds(GS.second);
182   }
183
184   // Imported functions may introduce new uses of type identifier resolutions,
185   // so we need to collect their used resolutions as well.
186   for (auto &ImpM : ImportList)
187     for (auto &ImpF : ImpM.second)
188       AddUsedTypeIds(Index.findSummaryInModule(ImpF.first, ImpM.first()));
189
190   auto AddTypeIdSummary = [&](StringRef TId, const TypeIdSummary &S) {
191     AddString(TId);
192
193     AddUnsigned(S.TTRes.TheKind);
194     AddUnsigned(S.TTRes.SizeM1BitWidth);
195
196     AddUint64(S.WPDRes.size());
197     for (auto &WPD : S.WPDRes) {
198       AddUnsigned(WPD.first);
199       AddUnsigned(WPD.second.TheKind);
200       AddString(WPD.second.SingleImplName);
201
202       AddUint64(WPD.second.ResByArg.size());
203       for (auto &ByArg : WPD.second.ResByArg) {
204         AddUint64(ByArg.first.size());
205         for (uint64_t Arg : ByArg.first)
206           AddUint64(Arg);
207         AddUnsigned(ByArg.second.TheKind);
208         AddUint64(ByArg.second.Info);
209       }
210     }
211   };
212
213   // Include the hash for all type identifiers used by this module.
214   for (GlobalValue::GUID TId : UsedTypeIds) {
215     auto SummariesI = TypeIdSummariesByGuid.find(TId);
216     if (SummariesI != TypeIdSummariesByGuid.end())
217       for (auto *Summary : SummariesI->second)
218         AddTypeIdSummary(Summary->first, Summary->second);
219   }
220
221   if (!Conf.SampleProfile.empty()) {
222     auto FileOrErr = MemoryBuffer::getFile(Conf.SampleProfile);
223     if (FileOrErr)
224       Hasher.update(FileOrErr.get()->getBuffer());
225   }
226
227   Key = toHex(Hasher.result());
228 }
229
230 static void thinLTOResolveWeakForLinkerGUID(
231     GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
232     DenseSet<GlobalValueSummary *> &GlobalInvolvedWithAlias,
233     function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
234         isPrevailing,
235     function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
236         recordNewLinkage) {
237   for (auto &S : GVSummaryList) {
238     GlobalValue::LinkageTypes OriginalLinkage = S->linkage();
239     if (!GlobalValue::isWeakForLinker(OriginalLinkage))
240       continue;
241     // We need to emit only one of these. The prevailing module will keep it,
242     // but turned into a weak, while the others will drop it when possible.
243     // This is both a compile-time optimization and a correctness
244     // transformation. This is necessary for correctness when we have exported
245     // a reference - we need to convert the linkonce to weak to
246     // ensure a copy is kept to satisfy the exported reference.
247     // FIXME: We may want to split the compile time and correctness
248     // aspects into separate routines.
249     if (isPrevailing(GUID, S.get())) {
250       if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
251         S->setLinkage(GlobalValue::getWeakLinkage(
252             GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
253     }
254     // Alias and aliasee can't be turned into available_externally.
255     else if (!isa<AliasSummary>(S.get()) &&
256              !GlobalInvolvedWithAlias.count(S.get()))
257       S->setLinkage(GlobalValue::AvailableExternallyLinkage);
258     if (S->linkage() != OriginalLinkage)
259       recordNewLinkage(S->modulePath(), GUID, S->linkage());
260   }
261 }
262
263 // Resolve Weak and LinkOnce values in the \p Index.
264 //
265 // We'd like to drop these functions if they are no longer referenced in the
266 // current module. However there is a chance that another module is still
267 // referencing them because of the import. We make sure we always emit at least
268 // one copy.
269 void llvm::thinLTOResolveWeakForLinkerInIndex(
270     ModuleSummaryIndex &Index,
271     function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
272         isPrevailing,
273     function_ref<void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)>
274         recordNewLinkage) {
275   // We won't optimize the globals that are referenced by an alias for now
276   // Ideally we should turn the alias into a global and duplicate the definition
277   // when needed.
278   DenseSet<GlobalValueSummary *> GlobalInvolvedWithAlias;
279   for (auto &I : Index)
280     for (auto &S : I.second.SummaryList)
281       if (auto AS = dyn_cast<AliasSummary>(S.get()))
282         GlobalInvolvedWithAlias.insert(&AS->getAliasee());
283
284   for (auto &I : Index)
285     thinLTOResolveWeakForLinkerGUID(I.second.SummaryList, I.first,
286                                     GlobalInvolvedWithAlias, isPrevailing,
287                                     recordNewLinkage);
288 }
289
290 static void thinLTOInternalizeAndPromoteGUID(
291     GlobalValueSummaryList &GVSummaryList, GlobalValue::GUID GUID,
292     function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
293   for (auto &S : GVSummaryList) {
294     if (isExported(S->modulePath(), GUID)) {
295       if (GlobalValue::isLocalLinkage(S->linkage()))
296         S->setLinkage(GlobalValue::ExternalLinkage);
297     } else if (!GlobalValue::isLocalLinkage(S->linkage()))
298       S->setLinkage(GlobalValue::InternalLinkage);
299   }
300 }
301
302 // Update the linkages in the given \p Index to mark exported values
303 // as external and non-exported values as internal.
304 void llvm::thinLTOInternalizeAndPromoteInIndex(
305     ModuleSummaryIndex &Index,
306     function_ref<bool(StringRef, GlobalValue::GUID)> isExported) {
307   for (auto &I : Index)
308     thinLTOInternalizeAndPromoteGUID(I.second.SummaryList, I.first, isExported);
309 }
310
311 // Requires a destructor for std::vector<InputModule>.
312 InputFile::~InputFile() = default;
313
314 Expected<std::unique_ptr<InputFile>> InputFile::create(MemoryBufferRef Object) {
315   std::unique_ptr<InputFile> File(new InputFile);
316
317   ErrorOr<MemoryBufferRef> BCOrErr =
318       IRObjectFile::findBitcodeInMemBuffer(Object);
319   if (!BCOrErr)
320     return errorCodeToError(BCOrErr.getError());
321
322   Expected<std::vector<BitcodeModule>> BMsOrErr =
323       getBitcodeModuleList(*BCOrErr);
324   if (!BMsOrErr)
325     return BMsOrErr.takeError();
326
327   if (BMsOrErr->empty())
328     return make_error<StringError>("Bitcode file does not contain any modules",
329                                    inconvertibleErrorCode());
330
331   File->Mods = *BMsOrErr;
332
333   LLVMContext Ctx;
334   std::vector<Module *> Mods;
335   std::vector<std::unique_ptr<Module>> OwnedMods;
336   for (auto BM : *BMsOrErr) {
337     Expected<std::unique_ptr<Module>> MOrErr =
338         BM.getLazyModule(Ctx, /*ShouldLazyLoadMetadata*/ true,
339                          /*IsImporting*/ false);
340     if (!MOrErr)
341       return MOrErr.takeError();
342
343     if ((*MOrErr)->getDataLayoutStr().empty())
344       return make_error<StringError>("input module has no datalayout",
345                                      inconvertibleErrorCode());
346
347     Mods.push_back(MOrErr->get());
348     OwnedMods.push_back(std::move(*MOrErr));
349   }
350
351   SmallVector<char, 0> Symtab;
352   if (Error E = irsymtab::build(Mods, Symtab, File->Strtab))
353     return std::move(E);
354
355   irsymtab::Reader R({Symtab.data(), Symtab.size()},
356                      {File->Strtab.data(), File->Strtab.size()});
357   File->TargetTriple = R.getTargetTriple();
358   File->SourceFileName = R.getSourceFileName();
359   File->COFFLinkerOpts = R.getCOFFLinkerOpts();
360   File->ComdatTable = R.getComdatTable();
361
362   for (unsigned I = 0; I != Mods.size(); ++I) {
363     size_t Begin = File->Symbols.size();
364     for (const irsymtab::Reader::SymbolRef &Sym : R.module_symbols(I))
365       // Skip symbols that are irrelevant to LTO. Note that this condition needs
366       // to match the one in Skip() in LTO::addRegularLTO().
367       if (Sym.isGlobal() && !Sym.isFormatSpecific())
368         File->Symbols.push_back(Sym);
369     File->ModuleSymIndices.push_back({Begin, File->Symbols.size()});
370   }
371
372   return std::move(File);
373 }
374
375 StringRef InputFile::getName() const {
376   return Mods[0].getModuleIdentifier();
377 }
378
379 LTO::RegularLTOState::RegularLTOState(unsigned ParallelCodeGenParallelismLevel,
380                                       Config &Conf)
381     : ParallelCodeGenParallelismLevel(ParallelCodeGenParallelismLevel),
382       Ctx(Conf) {}
383
384 LTO::ThinLTOState::ThinLTOState(ThinBackend Backend) : Backend(Backend) {
385   if (!Backend)
386     this->Backend =
387         createInProcessThinBackend(llvm::heavyweight_hardware_concurrency());
388 }
389
390 LTO::LTO(Config Conf, ThinBackend Backend,
391          unsigned ParallelCodeGenParallelismLevel)
392     : Conf(std::move(Conf)),
393       RegularLTO(ParallelCodeGenParallelismLevel, this->Conf),
394       ThinLTO(std::move(Backend)) {}
395
396 // Requires a destructor for MapVector<BitcodeModule>.
397 LTO::~LTO() = default;
398
399 // Add the given symbol to the GlobalResolutions map, and resolve its partition.
400 void LTO::addSymbolToGlobalRes(const InputFile::Symbol &Sym,
401                                SymbolResolution Res, unsigned Partition) {
402   auto &GlobalRes = GlobalResolutions[Sym.getName()];
403   GlobalRes.UnnamedAddr &= Sym.isUnnamedAddr();
404   if (Res.Prevailing)
405     GlobalRes.IRName = Sym.getIRName();
406
407   // Set the partition to external if we know it is used elsewhere, e.g.
408   // it is visible to a regular object, is referenced from llvm.compiler_used,
409   // or was already recorded as being referenced from a different partition.
410   if (Res.VisibleToRegularObj || Sym.isUsed() ||
411       (GlobalRes.Partition != GlobalResolution::Unknown &&
412        GlobalRes.Partition != Partition)) {
413     GlobalRes.Partition = GlobalResolution::External;
414   } else
415     // First recorded reference, save the current partition.
416     GlobalRes.Partition = Partition;
417
418   // Flag as visible outside of ThinLTO if visible from a regular object or
419   // if this is a reference in the regular LTO partition.
420   GlobalRes.VisibleOutsideThinLTO |=
421       (Res.VisibleToRegularObj || Sym.isUsed() ||
422        Partition == GlobalResolution::RegularLTO);
423 }
424
425 static void writeToResolutionFile(raw_ostream &OS, InputFile *Input,
426                                   ArrayRef<SymbolResolution> Res) {
427   StringRef Path = Input->getName();
428   OS << Path << '\n';
429   auto ResI = Res.begin();
430   for (const InputFile::Symbol &Sym : Input->symbols()) {
431     assert(ResI != Res.end());
432     SymbolResolution Res = *ResI++;
433
434     OS << "-r=" << Path << ',' << Sym.getName() << ',';
435     if (Res.Prevailing)
436       OS << 'p';
437     if (Res.FinalDefinitionInLinkageUnit)
438       OS << 'l';
439     if (Res.VisibleToRegularObj)
440       OS << 'x';
441     OS << '\n';
442   }
443   OS.flush();
444   assert(ResI == Res.end());
445 }
446
447 Error LTO::add(std::unique_ptr<InputFile> Input,
448                ArrayRef<SymbolResolution> Res) {
449   assert(!CalledGetMaxTasks);
450
451   if (Conf.ResolutionFile)
452     writeToResolutionFile(*Conf.ResolutionFile, Input.get(), Res);
453
454   const SymbolResolution *ResI = Res.begin();
455   for (unsigned I = 0; I != Input->Mods.size(); ++I)
456     if (Error Err = addModule(*Input, I, ResI, Res.end()))
457       return Err;
458
459   assert(ResI == Res.end());
460   return Error::success();
461 }
462
463 Error LTO::addModule(InputFile &Input, unsigned ModI,
464                      const SymbolResolution *&ResI,
465                      const SymbolResolution *ResE) {
466   Expected<bool> HasThinLTOSummary = Input.Mods[ModI].hasSummary();
467   if (!HasThinLTOSummary)
468     return HasThinLTOSummary.takeError();
469
470   auto ModSyms = Input.module_symbols(ModI);
471   if (*HasThinLTOSummary)
472     return addThinLTO(Input.Mods[ModI], ModSyms, ResI, ResE);
473   else
474     return addRegularLTO(Input.Mods[ModI], ModSyms, ResI, ResE);
475 }
476
477 // Add a regular LTO object to the link.
478 Error LTO::addRegularLTO(BitcodeModule BM,
479                          ArrayRef<InputFile::Symbol> Syms,
480                          const SymbolResolution *&ResI,
481                          const SymbolResolution *ResE) {
482   if (!RegularLTO.CombinedModule) {
483     RegularLTO.CombinedModule =
484         llvm::make_unique<Module>("ld-temp.o", RegularLTO.Ctx);
485     RegularLTO.Mover = llvm::make_unique<IRMover>(*RegularLTO.CombinedModule);
486   }
487   Expected<std::unique_ptr<Module>> MOrErr =
488       BM.getLazyModule(RegularLTO.Ctx, /*ShouldLazyLoadMetadata*/ true,
489                        /*IsImporting*/ false);
490   if (!MOrErr)
491     return MOrErr.takeError();
492
493   Module &M = **MOrErr;
494   if (Error Err = M.materializeMetadata())
495     return Err;
496   UpgradeDebugInfo(M);
497
498   ModuleSymbolTable SymTab;
499   SymTab.addModule(&M);
500
501   std::vector<GlobalValue *> Keep;
502
503   for (GlobalVariable &GV : M.globals())
504     if (GV.hasAppendingLinkage())
505       Keep.push_back(&GV);
506
507   DenseSet<GlobalObject *> AliasedGlobals;
508   for (auto &GA : M.aliases())
509     if (GlobalObject *GO = GA.getBaseObject())
510       AliasedGlobals.insert(GO);
511
512   // In this function we need IR GlobalValues matching the symbols in Syms
513   // (which is not backed by a module), so we need to enumerate them in the same
514   // order. The symbol enumeration order of a ModuleSymbolTable intentionally
515   // matches the order of an irsymtab, but when we read the irsymtab in
516   // InputFile::create we omit some symbols that are irrelevant to LTO. The
517   // Skip() function skips the same symbols from the module as InputFile does
518   // from the symbol table.
519   auto MsymI = SymTab.symbols().begin(), MsymE = SymTab.symbols().end();
520   auto Skip = [&]() {
521     while (MsymI != MsymE) {
522       auto Flags = SymTab.getSymbolFlags(*MsymI);
523       if ((Flags & object::BasicSymbolRef::SF_Global) &&
524           !(Flags & object::BasicSymbolRef::SF_FormatSpecific))
525         return;
526       ++MsymI;
527     }
528   };
529   Skip();
530
531   for (const InputFile::Symbol &Sym : Syms) {
532     assert(ResI != ResE);
533     SymbolResolution Res = *ResI++;
534     addSymbolToGlobalRes(Sym, Res, 0);
535
536     assert(MsymI != MsymE);
537     ModuleSymbolTable::Symbol Msym = *MsymI++;
538     Skip();
539
540     if (GlobalValue *GV = Msym.dyn_cast<GlobalValue *>()) {
541       if (Res.Prevailing) {
542         if (Sym.isUndefined())
543           continue;
544         Keep.push_back(GV);
545         GlobalValue::LinkageTypes OriginalLinkage = GV->getLinkage();
546         if (GlobalValue::isLinkOnceLinkage(OriginalLinkage))
547           GV->setLinkage(GlobalValue::getWeakLinkage(
548               GlobalValue::isLinkOnceODRLinkage(OriginalLinkage)));
549       } else if (isa<GlobalObject>(GV) &&
550                  (GV->hasLinkOnceODRLinkage() || GV->hasWeakODRLinkage() ||
551                   GV->hasAvailableExternallyLinkage()) &&
552                  !AliasedGlobals.count(cast<GlobalObject>(GV))) {
553         // Either of the above three types of linkage indicates that the
554         // chosen prevailing symbol will have the same semantics as this copy of
555         // the symbol, so we can link it with available_externally linkage. We
556         // only need to do this if the symbol is undefined.
557         GlobalValue *CombinedGV =
558             RegularLTO.CombinedModule->getNamedValue(GV->getName());
559         if (!CombinedGV || CombinedGV->isDeclaration()) {
560           Keep.push_back(GV);
561           GV->setLinkage(GlobalValue::AvailableExternallyLinkage);
562           cast<GlobalObject>(GV)->setComdat(nullptr);
563         }
564       }
565     }
566     // Common resolution: collect the maximum size/alignment over all commons.
567     // We also record if we see an instance of a common as prevailing, so that
568     // if none is prevailing we can ignore it later.
569     if (Sym.isCommon()) {
570       // FIXME: We should figure out what to do about commons defined by asm.
571       // For now they aren't reported correctly by ModuleSymbolTable.
572       auto &CommonRes = RegularLTO.Commons[Sym.getIRName()];
573       CommonRes.Size = std::max(CommonRes.Size, Sym.getCommonSize());
574       CommonRes.Align = std::max(CommonRes.Align, Sym.getCommonAlignment());
575       CommonRes.Prevailing |= Res.Prevailing;
576     }
577
578     // FIXME: use proposed local attribute for FinalDefinitionInLinkageUnit.
579   }
580   assert(MsymI == MsymE);
581
582   return RegularLTO.Mover->move(std::move(*MOrErr), Keep,
583                                 [](GlobalValue &, IRMover::ValueAdder) {},
584                                 /* IsPerformingImport */ false);
585 }
586
587 // Add a ThinLTO object to the link.
588 Error LTO::addThinLTO(BitcodeModule BM,
589                       ArrayRef<InputFile::Symbol> Syms,
590                       const SymbolResolution *&ResI,
591                       const SymbolResolution *ResE) {
592   if (Error Err =
593           BM.readSummary(ThinLTO.CombinedIndex, ThinLTO.ModuleMap.size()))
594     return Err;
595
596   for (const InputFile::Symbol &Sym : Syms) {
597     assert(ResI != ResE);
598     SymbolResolution Res = *ResI++;
599     addSymbolToGlobalRes(Sym, Res, ThinLTO.ModuleMap.size() + 1);
600
601     if (Res.Prevailing) {
602       if (!Sym.getIRName().empty()) {
603         auto GUID = GlobalValue::getGUID(GlobalValue::getGlobalIdentifier(
604             Sym.getIRName(), GlobalValue::ExternalLinkage, ""));
605         ThinLTO.PrevailingModuleForGUID[GUID] = BM.getModuleIdentifier();
606       }
607     }
608   }
609
610   if (!ThinLTO.ModuleMap.insert({BM.getModuleIdentifier(), BM}).second)
611     return make_error<StringError>(
612         "Expected at most one ThinLTO module per bitcode file",
613         inconvertibleErrorCode());
614
615   return Error::success();
616 }
617
618 unsigned LTO::getMaxTasks() const {
619   CalledGetMaxTasks = true;
620   return RegularLTO.ParallelCodeGenParallelismLevel + ThinLTO.ModuleMap.size();
621 }
622
623 Error LTO::run(AddStreamFn AddStream, NativeObjectCache Cache) {
624   // Save the status of having a regularLTO combined module, as
625   // this is needed for generating the ThinLTO Task ID, and
626   // the CombinedModule will be moved at the end of runRegularLTO.
627   bool HasRegularLTO = RegularLTO.CombinedModule != nullptr;
628   // Invoke regular LTO if there was a regular LTO module to start with.
629   if (HasRegularLTO)
630     if (auto E = runRegularLTO(AddStream))
631       return E;
632   return runThinLTO(AddStream, Cache, HasRegularLTO);
633 }
634
635 Error LTO::runRegularLTO(AddStreamFn AddStream) {
636   // Make sure commons have the right size/alignment: we kept the largest from
637   // all the prevailing when adding the inputs, and we apply it here.
638   const DataLayout &DL = RegularLTO.CombinedModule->getDataLayout();
639   for (auto &I : RegularLTO.Commons) {
640     if (!I.second.Prevailing)
641       // Don't do anything if no instance of this common was prevailing.
642       continue;
643     GlobalVariable *OldGV = RegularLTO.CombinedModule->getNamedGlobal(I.first);
644     if (OldGV && DL.getTypeAllocSize(OldGV->getValueType()) == I.second.Size) {
645       // Don't create a new global if the type is already correct, just make
646       // sure the alignment is correct.
647       OldGV->setAlignment(I.second.Align);
648       continue;
649     }
650     ArrayType *Ty =
651         ArrayType::get(Type::getInt8Ty(RegularLTO.Ctx), I.second.Size);
652     auto *GV = new GlobalVariable(*RegularLTO.CombinedModule, Ty, false,
653                                   GlobalValue::CommonLinkage,
654                                   ConstantAggregateZero::get(Ty), "");
655     GV->setAlignment(I.second.Align);
656     if (OldGV) {
657       OldGV->replaceAllUsesWith(ConstantExpr::getBitCast(GV, OldGV->getType()));
658       GV->takeName(OldGV);
659       OldGV->eraseFromParent();
660     } else {
661       GV->setName(I.first);
662     }
663   }
664
665   if (Conf.PreOptModuleHook &&
666       !Conf.PreOptModuleHook(0, *RegularLTO.CombinedModule))
667     return Error::success();
668
669   if (!Conf.CodeGenOnly) {
670     for (const auto &R : GlobalResolutions) {
671       if (R.second.IRName.empty())
672         continue;
673       if (R.second.Partition != 0 &&
674           R.second.Partition != GlobalResolution::External)
675         continue;
676
677       GlobalValue *GV =
678           RegularLTO.CombinedModule->getNamedValue(R.second.IRName);
679       // Ignore symbols defined in other partitions.
680       if (!GV || GV->hasLocalLinkage())
681         continue;
682       GV->setUnnamedAddr(R.second.UnnamedAddr ? GlobalValue::UnnamedAddr::Global
683                                               : GlobalValue::UnnamedAddr::None);
684       if (R.second.Partition == 0)
685         GV->setLinkage(GlobalValue::InternalLinkage);
686     }
687
688     if (Conf.PostInternalizeModuleHook &&
689         !Conf.PostInternalizeModuleHook(0, *RegularLTO.CombinedModule))
690       return Error::success();
691   }
692   return backend(Conf, AddStream, RegularLTO.ParallelCodeGenParallelismLevel,
693                  std::move(RegularLTO.CombinedModule), ThinLTO.CombinedIndex);
694 }
695
696 /// This class defines the interface to the ThinLTO backend.
697 class lto::ThinBackendProc {
698 protected:
699   Config &Conf;
700   ModuleSummaryIndex &CombinedIndex;
701   const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries;
702
703 public:
704   ThinBackendProc(Config &Conf, ModuleSummaryIndex &CombinedIndex,
705                   const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries)
706       : Conf(Conf), CombinedIndex(CombinedIndex),
707         ModuleToDefinedGVSummaries(ModuleToDefinedGVSummaries) {}
708
709   virtual ~ThinBackendProc() {}
710   virtual Error start(
711       unsigned Task, BitcodeModule BM,
712       const FunctionImporter::ImportMapTy &ImportList,
713       const FunctionImporter::ExportSetTy &ExportList,
714       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
715       MapVector<StringRef, BitcodeModule> &ModuleMap) = 0;
716   virtual Error wait() = 0;
717 };
718
719 namespace {
720 class InProcessThinBackend : public ThinBackendProc {
721   ThreadPool BackendThreadPool;
722   AddStreamFn AddStream;
723   NativeObjectCache Cache;
724   TypeIdSummariesByGuidTy TypeIdSummariesByGuid;
725
726   Optional<Error> Err;
727   std::mutex ErrMu;
728
729 public:
730   InProcessThinBackend(
731       Config &Conf, ModuleSummaryIndex &CombinedIndex,
732       unsigned ThinLTOParallelismLevel,
733       const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
734       AddStreamFn AddStream, NativeObjectCache Cache)
735       : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
736         BackendThreadPool(ThinLTOParallelismLevel),
737         AddStream(std::move(AddStream)), Cache(std::move(Cache)) {
738     // Create a mapping from type identifier GUIDs to type identifier summaries.
739     // This allows backends to use the type identifier GUIDs stored in the
740     // function summaries to determine which type identifier summaries affect
741     // each function without needing to compute GUIDs in each backend.
742     for (auto &TId : CombinedIndex.typeIds())
743       TypeIdSummariesByGuid[GlobalValue::getGUID(TId.first)].push_back(&TId);
744   }
745
746   Error runThinLTOBackendThread(
747       AddStreamFn AddStream, NativeObjectCache Cache, unsigned Task,
748       BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
749       const FunctionImporter::ImportMapTy &ImportList,
750       const FunctionImporter::ExportSetTy &ExportList,
751       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
752       const GVSummaryMapTy &DefinedGlobals,
753       MapVector<StringRef, BitcodeModule> &ModuleMap,
754       const TypeIdSummariesByGuidTy &TypeIdSummariesByGuid) {
755     auto RunThinBackend = [&](AddStreamFn AddStream) {
756       LTOLLVMContext BackendContext(Conf);
757       Expected<std::unique_ptr<Module>> MOrErr = BM.parseModule(BackendContext);
758       if (!MOrErr)
759         return MOrErr.takeError();
760
761       return thinBackend(Conf, Task, AddStream, **MOrErr, CombinedIndex,
762                          ImportList, DefinedGlobals, ModuleMap);
763     };
764
765     auto ModuleID = BM.getModuleIdentifier();
766
767     if (!Cache || !CombinedIndex.modulePaths().count(ModuleID) ||
768         all_of(CombinedIndex.getModuleHash(ModuleID),
769                [](uint32_t V) { return V == 0; }))
770       // Cache disabled or no entry for this module in the combined index or
771       // no module hash.
772       return RunThinBackend(AddStream);
773
774     SmallString<40> Key;
775     // The module may be cached, this helps handling it.
776     computeCacheKey(Key, Conf, CombinedIndex, ModuleID, ImportList, ExportList,
777                     ResolvedODR, DefinedGlobals, TypeIdSummariesByGuid);
778     if (AddStreamFn CacheAddStream = Cache(Task, Key))
779       return RunThinBackend(CacheAddStream);
780
781     return Error::success();
782   }
783
784   Error start(
785       unsigned Task, BitcodeModule BM,
786       const FunctionImporter::ImportMapTy &ImportList,
787       const FunctionImporter::ExportSetTy &ExportList,
788       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
789       MapVector<StringRef, BitcodeModule> &ModuleMap) override {
790     StringRef ModulePath = BM.getModuleIdentifier();
791     assert(ModuleToDefinedGVSummaries.count(ModulePath));
792     const GVSummaryMapTy &DefinedGlobals =
793         ModuleToDefinedGVSummaries.find(ModulePath)->second;
794     BackendThreadPool.async(
795         [=](BitcodeModule BM, ModuleSummaryIndex &CombinedIndex,
796             const FunctionImporter::ImportMapTy &ImportList,
797             const FunctionImporter::ExportSetTy &ExportList,
798             const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>
799                 &ResolvedODR,
800             const GVSummaryMapTy &DefinedGlobals,
801             MapVector<StringRef, BitcodeModule> &ModuleMap,
802             const TypeIdSummariesByGuidTy &TypeIdSummariesByGuid) {
803           Error E = runThinLTOBackendThread(
804               AddStream, Cache, Task, BM, CombinedIndex, ImportList, ExportList,
805               ResolvedODR, DefinedGlobals, ModuleMap, TypeIdSummariesByGuid);
806           if (E) {
807             std::unique_lock<std::mutex> L(ErrMu);
808             if (Err)
809               Err = joinErrors(std::move(*Err), std::move(E));
810             else
811               Err = std::move(E);
812           }
813         },
814         BM, std::ref(CombinedIndex), std::ref(ImportList), std::ref(ExportList),
815         std::ref(ResolvedODR), std::ref(DefinedGlobals), std::ref(ModuleMap),
816         std::ref(TypeIdSummariesByGuid));
817     return Error::success();
818   }
819
820   Error wait() override {
821     BackendThreadPool.wait();
822     if (Err)
823       return std::move(*Err);
824     else
825       return Error::success();
826   }
827 };
828 } // end anonymous namespace
829
830 ThinBackend lto::createInProcessThinBackend(unsigned ParallelismLevel) {
831   return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
832              const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
833              AddStreamFn AddStream, NativeObjectCache Cache) {
834     return llvm::make_unique<InProcessThinBackend>(
835         Conf, CombinedIndex, ParallelismLevel, ModuleToDefinedGVSummaries,
836         AddStream, Cache);
837   };
838 }
839
840 // Given the original \p Path to an output file, replace any path
841 // prefix matching \p OldPrefix with \p NewPrefix. Also, create the
842 // resulting directory if it does not yet exist.
843 std::string lto::getThinLTOOutputFile(const std::string &Path,
844                                       const std::string &OldPrefix,
845                                       const std::string &NewPrefix) {
846   if (OldPrefix.empty() && NewPrefix.empty())
847     return Path;
848   SmallString<128> NewPath(Path);
849   llvm::sys::path::replace_path_prefix(NewPath, OldPrefix, NewPrefix);
850   StringRef ParentPath = llvm::sys::path::parent_path(NewPath.str());
851   if (!ParentPath.empty()) {
852     // Make sure the new directory exists, creating it if necessary.
853     if (std::error_code EC = llvm::sys::fs::create_directories(ParentPath))
854       llvm::errs() << "warning: could not create directory '" << ParentPath
855                    << "': " << EC.message() << '\n';
856   }
857   return NewPath.str();
858 }
859
860 namespace {
861 class WriteIndexesThinBackend : public ThinBackendProc {
862   std::string OldPrefix, NewPrefix;
863   bool ShouldEmitImportsFiles;
864
865   std::string LinkedObjectsFileName;
866   std::unique_ptr<llvm::raw_fd_ostream> LinkedObjectsFile;
867
868 public:
869   WriteIndexesThinBackend(
870       Config &Conf, ModuleSummaryIndex &CombinedIndex,
871       const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
872       std::string OldPrefix, std::string NewPrefix, bool ShouldEmitImportsFiles,
873       std::string LinkedObjectsFileName)
874       : ThinBackendProc(Conf, CombinedIndex, ModuleToDefinedGVSummaries),
875         OldPrefix(OldPrefix), NewPrefix(NewPrefix),
876         ShouldEmitImportsFiles(ShouldEmitImportsFiles),
877         LinkedObjectsFileName(LinkedObjectsFileName) {}
878
879   Error start(
880       unsigned Task, BitcodeModule BM,
881       const FunctionImporter::ImportMapTy &ImportList,
882       const FunctionImporter::ExportSetTy &ExportList,
883       const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
884       MapVector<StringRef, BitcodeModule> &ModuleMap) override {
885     StringRef ModulePath = BM.getModuleIdentifier();
886     std::string NewModulePath =
887         getThinLTOOutputFile(ModulePath, OldPrefix, NewPrefix);
888
889     std::error_code EC;
890     if (!LinkedObjectsFileName.empty()) {
891       if (!LinkedObjectsFile) {
892         LinkedObjectsFile = llvm::make_unique<raw_fd_ostream>(
893             LinkedObjectsFileName, EC, sys::fs::OpenFlags::F_None);
894         if (EC)
895           return errorCodeToError(EC);
896       }
897       *LinkedObjectsFile << NewModulePath << '\n';
898     }
899
900     std::map<std::string, GVSummaryMapTy> ModuleToSummariesForIndex;
901     gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
902                                      ImportList, ModuleToSummariesForIndex);
903
904     raw_fd_ostream OS(NewModulePath + ".thinlto.bc", EC,
905                       sys::fs::OpenFlags::F_None);
906     if (EC)
907       return errorCodeToError(EC);
908     WriteIndexToFile(CombinedIndex, OS, &ModuleToSummariesForIndex);
909
910     if (ShouldEmitImportsFiles)
911       return errorCodeToError(
912           EmitImportsFiles(ModulePath, NewModulePath + ".imports", ImportList));
913     return Error::success();
914   }
915
916   Error wait() override { return Error::success(); }
917 };
918 } // end anonymous namespace
919
920 ThinBackend lto::createWriteIndexesThinBackend(std::string OldPrefix,
921                                                std::string NewPrefix,
922                                                bool ShouldEmitImportsFiles,
923                                                std::string LinkedObjectsFile) {
924   return [=](Config &Conf, ModuleSummaryIndex &CombinedIndex,
925              const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
926              AddStreamFn AddStream, NativeObjectCache Cache) {
927     return llvm::make_unique<WriteIndexesThinBackend>(
928         Conf, CombinedIndex, ModuleToDefinedGVSummaries, OldPrefix, NewPrefix,
929         ShouldEmitImportsFiles, LinkedObjectsFile);
930   };
931 }
932
933 Error LTO::runThinLTO(AddStreamFn AddStream, NativeObjectCache Cache,
934                       bool HasRegularLTO) {
935   if (ThinLTO.ModuleMap.empty())
936     return Error::success();
937
938   if (Conf.CombinedIndexHook && !Conf.CombinedIndexHook(ThinLTO.CombinedIndex))
939     return Error::success();
940
941   // Collect for each module the list of function it defines (GUID ->
942   // Summary).
943   StringMap<std::map<GlobalValue::GUID, GlobalValueSummary *>>
944       ModuleToDefinedGVSummaries(ThinLTO.ModuleMap.size());
945   ThinLTO.CombinedIndex.collectDefinedGVSummariesPerModule(
946       ModuleToDefinedGVSummaries);
947   // Create entries for any modules that didn't have any GV summaries
948   // (either they didn't have any GVs to start with, or we suppressed
949   // generation of the summaries because they e.g. had inline assembly
950   // uses that couldn't be promoted/renamed on export). This is so
951   // InProcessThinBackend::start can still launch a backend thread, which
952   // is passed the map of summaries for the module, without any special
953   // handling for this case.
954   for (auto &Mod : ThinLTO.ModuleMap)
955     if (!ModuleToDefinedGVSummaries.count(Mod.first))
956       ModuleToDefinedGVSummaries.try_emplace(Mod.first);
957
958   StringMap<FunctionImporter::ImportMapTy> ImportLists(
959       ThinLTO.ModuleMap.size());
960   StringMap<FunctionImporter::ExportSetTy> ExportLists(
961       ThinLTO.ModuleMap.size());
962   StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>> ResolvedODR;
963
964   if (Conf.OptLevel > 0) {
965     // Compute "dead" symbols, we don't want to import/export these!
966     DenseSet<GlobalValue::GUID> GUIDPreservedSymbols;
967     for (auto &Res : GlobalResolutions) {
968       if (Res.second.VisibleOutsideThinLTO &&
969           // IRName will be defined if we have seen the prevailing copy of
970           // this value. If not, no need to preserve any ThinLTO copies.
971           !Res.second.IRName.empty())
972         GUIDPreservedSymbols.insert(GlobalValue::getGUID(
973             GlobalValue::dropLLVMManglingEscape(Res.second.IRName)));
974     }
975
976     auto DeadSymbols =
977         computeDeadSymbols(ThinLTO.CombinedIndex, GUIDPreservedSymbols);
978
979     ComputeCrossModuleImport(ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
980                              ImportLists, ExportLists, &DeadSymbols);
981
982     std::set<GlobalValue::GUID> ExportedGUIDs;
983     for (auto &Res : GlobalResolutions) {
984       // First check if the symbol was flagged as having external references.
985       if (Res.second.Partition != GlobalResolution::External)
986         continue;
987       // IRName will be defined if we have seen the prevailing copy of
988       // this value. If not, no need to mark as exported from a ThinLTO
989       // partition (and we can't get the GUID).
990       if (Res.second.IRName.empty())
991         continue;
992       auto GUID = GlobalValue::getGUID(
993           GlobalValue::dropLLVMManglingEscape(Res.second.IRName));
994       // Mark exported unless index-based analysis determined it to be dead.
995       if (!DeadSymbols.count(GUID))
996         ExportedGUIDs.insert(GUID);
997     }
998
999     auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
1000       const auto &ExportList = ExportLists.find(ModuleIdentifier);
1001       return (ExportList != ExportLists.end() &&
1002               ExportList->second.count(GUID)) ||
1003              ExportedGUIDs.count(GUID);
1004     };
1005     thinLTOInternalizeAndPromoteInIndex(ThinLTO.CombinedIndex, isExported);
1006   }
1007
1008   auto isPrevailing = [&](GlobalValue::GUID GUID,
1009                           const GlobalValueSummary *S) {
1010     return ThinLTO.PrevailingModuleForGUID[GUID] == S->modulePath();
1011   };
1012   auto recordNewLinkage = [&](StringRef ModuleIdentifier,
1013                               GlobalValue::GUID GUID,
1014                               GlobalValue::LinkageTypes NewLinkage) {
1015     ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
1016   };
1017   thinLTOResolveWeakForLinkerInIndex(ThinLTO.CombinedIndex, isPrevailing,
1018                                      recordNewLinkage);
1019
1020   std::unique_ptr<ThinBackendProc> BackendProc =
1021       ThinLTO.Backend(Conf, ThinLTO.CombinedIndex, ModuleToDefinedGVSummaries,
1022                       AddStream, Cache);
1023
1024   // Task numbers start at ParallelCodeGenParallelismLevel if an LTO
1025   // module is present, as tasks 0 through ParallelCodeGenParallelismLevel-1
1026   // are reserved for parallel code generation partitions.
1027   unsigned Task =
1028       HasRegularLTO ? RegularLTO.ParallelCodeGenParallelismLevel : 0;
1029   for (auto &Mod : ThinLTO.ModuleMap) {
1030     if (Error E = BackendProc->start(Task, Mod.second, ImportLists[Mod.first],
1031                                      ExportLists[Mod.first],
1032                                      ResolvedODR[Mod.first], ThinLTO.ModuleMap))
1033       return E;
1034     ++Task;
1035   }
1036
1037   return BackendProc->wait();
1038 }
1039
1040 Expected<std::unique_ptr<tool_output_file>>
1041 lto::setupOptimizationRemarks(LLVMContext &Context,
1042                               StringRef LTORemarksFilename,
1043                               bool LTOPassRemarksWithHotness, int Count) {
1044   if (LTORemarksFilename.empty())
1045     return nullptr;
1046
1047   std::string Filename = LTORemarksFilename;
1048   if (Count != -1)
1049     Filename += ".thin." + llvm::utostr(Count) + ".yaml";
1050
1051   std::error_code EC;
1052   auto DiagnosticFile =
1053       llvm::make_unique<tool_output_file>(Filename, EC, sys::fs::F_None);
1054   if (EC)
1055     return errorCodeToError(EC);
1056   Context.setDiagnosticsOutputFile(
1057       llvm::make_unique<yaml::Output>(DiagnosticFile->os()));
1058   if (LTOPassRemarksWithHotness)
1059     Context.setDiagnosticHotnessRequested(true);
1060   DiagnosticFile->keep();
1061   return std::move(DiagnosticFile);
1062 }