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