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