1 //===- ThinLTOBitcodeWriter.cpp - Bitcode writing pass for ThinLTO --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
10 #include "llvm/Analysis/BasicAliasAnalysis.h"
11 #include "llvm/Analysis/ModuleSummaryAnalysis.h"
12 #include "llvm/Analysis/ProfileSummaryInfo.h"
13 #include "llvm/Analysis/TypeMetadataUtils.h"
14 #include "llvm/Bitcode/BitcodeWriter.h"
15 #include "llvm/IR/Constants.h"
16 #include "llvm/IR/DebugInfo.h"
17 #include "llvm/IR/Instructions.h"
18 #include "llvm/IR/Intrinsics.h"
19 #include "llvm/IR/Module.h"
20 #include "llvm/IR/PassManager.h"
21 #include "llvm/InitializePasses.h"
22 #include "llvm/Object/ModuleSymbolTable.h"
23 #include "llvm/Pass.h"
24 #include "llvm/Support/ScopedPrinter.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Transforms/IPO.h"
27 #include "llvm/Transforms/IPO/FunctionAttrs.h"
28 #include "llvm/Transforms/IPO/FunctionImport.h"
29 #include "llvm/Transforms/IPO/LowerTypeTests.h"
30 #include "llvm/Transforms/Utils/Cloning.h"
31 #include "llvm/Transforms/Utils/ModuleUtils.h"
32 using namespace llvm;
33 
34 namespace {
35 
36 // Promote each local-linkage entity defined by ExportM and used by ImportM by
37 // changing visibility and appending the given ModuleId.
38 void promoteInternals(Module &ExportM, Module &ImportM, StringRef ModuleId,
39                       SetVector<GlobalValue *> &PromoteExtra) {
40   DenseMap<const Comdat *, Comdat *> RenamedComdats;
41   for (auto &ExportGV : ExportM.global_values()) {
42     if (!ExportGV.hasLocalLinkage())
43       continue;
44 
45     auto Name = ExportGV.getName();
46     GlobalValue *ImportGV = nullptr;
47     if (!PromoteExtra.count(&ExportGV)) {
48       ImportGV = ImportM.getNamedValue(Name);
49       if (!ImportGV)
50         continue;
51       ImportGV->removeDeadConstantUsers();
52       if (ImportGV->use_empty()) {
53         ImportGV->eraseFromParent();
54         continue;
55       }
56     }
57 
58     std::string NewName = (Name + ModuleId).str();
59 
60     if (const auto *C = ExportGV.getComdat())
61       if (C->getName() == Name)
62         RenamedComdats.try_emplace(C, ExportM.getOrInsertComdat(NewName));
63 
64     ExportGV.setName(NewName);
65     ExportGV.setLinkage(GlobalValue::ExternalLinkage);
66     ExportGV.setVisibility(GlobalValue::HiddenVisibility);
67 
68     if (ImportGV) {
69       ImportGV->setName(NewName);
70       ImportGV->setVisibility(GlobalValue::HiddenVisibility);
71     }
72   }
73 
74   if (!RenamedComdats.empty())
75     for (auto &GO : ExportM.global_objects())
76       if (auto *C = GO.getComdat()) {
77         auto Replacement = RenamedComdats.find(C);
78         if (Replacement != RenamedComdats.end())
79           GO.setComdat(Replacement->second);
80       }
81 }
82 
83 // Promote all internal (i.e. distinct) type ids used by the module by replacing
84 // them with external type ids formed using the module id.
85 //
86 // Note that this needs to be done before we clone the module because each clone
87 // will receive its own set of distinct metadata nodes.
88 void promoteTypeIds(Module &M, StringRef ModuleId) {
89   DenseMap<Metadata *, Metadata *> LocalToGlobal;
90   auto ExternalizeTypeId = [&](CallInst *CI, unsigned ArgNo) {
91     Metadata *MD =
92         cast<MetadataAsValue>(CI->getArgOperand(ArgNo))->getMetadata();
93 
94     if (isa<MDNode>(MD) && cast<MDNode>(MD)->isDistinct()) {
95       Metadata *&GlobalMD = LocalToGlobal[MD];
96       if (!GlobalMD) {
97         std::string NewName = (Twine(LocalToGlobal.size()) + ModuleId).str();
98         GlobalMD = MDString::get(M.getContext(), NewName);
99       }
100 
101       CI->setArgOperand(ArgNo,
102                         MetadataAsValue::get(M.getContext(), GlobalMD));
103     }
104   };
105 
106   if (Function *TypeTestFunc =
107           M.getFunction(Intrinsic::getName(Intrinsic::type_test))) {
108     for (const Use &U : TypeTestFunc->uses()) {
109       auto CI = cast<CallInst>(U.getUser());
110       ExternalizeTypeId(CI, 1);
111     }
112   }
113 
114   if (Function *TypeCheckedLoadFunc =
115           M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load))) {
116     for (const Use &U : TypeCheckedLoadFunc->uses()) {
117       auto CI = cast<CallInst>(U.getUser());
118       ExternalizeTypeId(CI, 2);
119     }
120   }
121 
122   for (GlobalObject &GO : M.global_objects()) {
123     SmallVector<MDNode *, 1> MDs;
124     GO.getMetadata(LLVMContext::MD_type, MDs);
125 
126     GO.eraseMetadata(LLVMContext::MD_type);
127     for (auto MD : MDs) {
128       auto I = LocalToGlobal.find(MD->getOperand(1));
129       if (I == LocalToGlobal.end()) {
130         GO.addMetadata(LLVMContext::MD_type, *MD);
131         continue;
132       }
133       GO.addMetadata(
134           LLVMContext::MD_type,
135           *MDNode::get(M.getContext(), {MD->getOperand(0), I->second}));
136     }
137   }
138 }
139 
140 // Drop unused globals, and drop type information from function declarations.
141 // FIXME: If we made functions typeless then there would be no need to do this.
142 void simplifyExternals(Module &M) {
143   FunctionType *EmptyFT =
144       FunctionType::get(Type::getVoidTy(M.getContext()), false);
145 
146   for (auto I = M.begin(), E = M.end(); I != E;) {
147     Function &F = *I++;
148     if (F.isDeclaration() && F.use_empty()) {
149       F.eraseFromParent();
150       continue;
151     }
152 
153     if (!F.isDeclaration() || F.getFunctionType() == EmptyFT ||
154         // Changing the type of an intrinsic may invalidate the IR.
155         F.getName().startswith("llvm."))
156       continue;
157 
158     Function *NewF =
159         Function::Create(EmptyFT, GlobalValue::ExternalLinkage,
160                          F.getAddressSpace(), "", &M);
161     NewF->setVisibility(F.getVisibility());
162     NewF->takeName(&F);
163     F.replaceAllUsesWith(ConstantExpr::getBitCast(NewF, F.getType()));
164     F.eraseFromParent();
165   }
166 
167   for (auto I = M.global_begin(), E = M.global_end(); I != E;) {
168     GlobalVariable &GV = *I++;
169     if (GV.isDeclaration() && GV.use_empty()) {
170       GV.eraseFromParent();
171       continue;
172     }
173   }
174 }
175 
176 static void
177 filterModule(Module *M,
178              function_ref<bool(const GlobalValue *)> ShouldKeepDefinition) {
179   std::vector<GlobalValue *> V;
180   for (GlobalValue &GV : M->global_values())
181     if (!ShouldKeepDefinition(&GV))
182       V.push_back(&GV);
183 
184   for (GlobalValue *GV : V)
185     if (!convertToDeclaration(*GV))
186       GV->eraseFromParent();
187 }
188 
189 void forEachVirtualFunction(Constant *C, function_ref<void(Function *)> Fn) {
190   if (auto *F = dyn_cast<Function>(C))
191     return Fn(F);
192   if (isa<GlobalValue>(C))
193     return;
194   for (Value *Op : C->operands())
195     forEachVirtualFunction(cast<Constant>(Op), Fn);
196 }
197 
198 // Clone any @llvm[.compiler].used over to the new module and append
199 // values whose defs were cloned into that module.
200 static void cloneUsedGlobalVariables(const Module &SrcM, Module &DestM,
201                                      bool CompilerUsed) {
202   SmallPtrSet<GlobalValue *, 8> Used;
203   SmallPtrSet<GlobalValue *, 8> NewUsed;
204   // First collect those in the llvm[.compiler].used set.
205   collectUsedGlobalVariables(SrcM, Used, CompilerUsed);
206   // Next build a set of the equivalent values defined in DestM.
207   for (auto *V : Used) {
208     auto *GV = DestM.getNamedValue(V->getName());
209     if (GV && !GV->isDeclaration())
210       NewUsed.insert(GV);
211   }
212   // Finally, add them to a llvm[.compiler].used variable in DestM.
213   if (CompilerUsed)
214     appendToCompilerUsed(
215         DestM, std::vector<GlobalValue *>(NewUsed.begin(), NewUsed.end()));
216   else
217     appendToUsed(DestM,
218                  std::vector<GlobalValue *>(NewUsed.begin(), NewUsed.end()));
219 }
220 
221 // If it's possible to split M into regular and thin LTO parts, do so and write
222 // a multi-module bitcode file with the two parts to OS. Otherwise, write only a
223 // regular LTO bitcode file to OS.
224 void splitAndWriteThinLTOBitcode(
225     raw_ostream &OS, raw_ostream *ThinLinkOS,
226     function_ref<AAResults &(Function &)> AARGetter, Module &M) {
227   std::string ModuleId = getUniqueModuleId(&M);
228   if (ModuleId.empty()) {
229     // We couldn't generate a module ID for this module, write it out as a
230     // regular LTO module with an index for summary-based dead stripping.
231     ProfileSummaryInfo PSI(M);
232     M.addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
233     ModuleSummaryIndex Index = buildModuleSummaryIndex(M, nullptr, &PSI);
234     WriteBitcodeToFile(M, OS, /*ShouldPreserveUseListOrder=*/false, &Index);
235 
236     if (ThinLinkOS)
237       // We don't have a ThinLTO part, but still write the module to the
238       // ThinLinkOS if requested so that the expected output file is produced.
239       WriteBitcodeToFile(M, *ThinLinkOS, /*ShouldPreserveUseListOrder=*/false,
240                          &Index);
241 
242     return;
243   }
244 
245   promoteTypeIds(M, ModuleId);
246 
247   // Returns whether a global or its associated global has attached type
248   // metadata. The former may participate in CFI or whole-program
249   // devirtualization, so they need to appear in the merged module instead of
250   // the thin LTO module. Similarly, globals that are associated with globals
251   // with type metadata need to appear in the merged module because they will
252   // reference the global's section directly.
253   auto HasTypeMetadata = [](const GlobalObject *GO) {
254     if (MDNode *MD = GO->getMetadata(LLVMContext::MD_associated))
255       if (auto *AssocVM = dyn_cast_or_null<ValueAsMetadata>(MD->getOperand(0)))
256         if (auto *AssocGO = dyn_cast<GlobalObject>(AssocVM->getValue()))
257           if (AssocGO->hasMetadata(LLVMContext::MD_type))
258             return true;
259     return GO->hasMetadata(LLVMContext::MD_type);
260   };
261 
262   // Collect the set of virtual functions that are eligible for virtual constant
263   // propagation. Each eligible function must not access memory, must return
264   // an integer of width <=64 bits, must take at least one argument, must not
265   // use its first argument (assumed to be "this") and all arguments other than
266   // the first one must be of <=64 bit integer type.
267   //
268   // Note that we test whether this copy of the function is readnone, rather
269   // than testing function attributes, which must hold for any copy of the
270   // function, even a less optimized version substituted at link time. This is
271   // sound because the virtual constant propagation optimizations effectively
272   // inline all implementations of the virtual function into each call site,
273   // rather than using function attributes to perform local optimization.
274   DenseSet<const Function *> EligibleVirtualFns;
275   // If any member of a comdat lives in MergedM, put all members of that
276   // comdat in MergedM to keep the comdat together.
277   DenseSet<const Comdat *> MergedMComdats;
278   for (GlobalVariable &GV : M.globals())
279     if (HasTypeMetadata(&GV)) {
280       if (const auto *C = GV.getComdat())
281         MergedMComdats.insert(C);
282       forEachVirtualFunction(GV.getInitializer(), [&](Function *F) {
283         auto *RT = dyn_cast<IntegerType>(F->getReturnType());
284         if (!RT || RT->getBitWidth() > 64 || F->arg_empty() ||
285             !F->arg_begin()->use_empty())
286           return;
287         for (auto &Arg : drop_begin(F->args())) {
288           auto *ArgT = dyn_cast<IntegerType>(Arg.getType());
289           if (!ArgT || ArgT->getBitWidth() > 64)
290             return;
291         }
292         if (!F->isDeclaration() &&
293             computeFunctionBodyMemoryAccess(*F, AARGetter(*F)) == MAK_ReadNone)
294           EligibleVirtualFns.insert(F);
295       });
296     }
297 
298   ValueToValueMapTy VMap;
299   std::unique_ptr<Module> MergedM(
300       CloneModule(M, VMap, [&](const GlobalValue *GV) -> bool {
301         if (const auto *C = GV->getComdat())
302           if (MergedMComdats.count(C))
303             return true;
304         if (auto *F = dyn_cast<Function>(GV))
305           return EligibleVirtualFns.count(F);
306         if (auto *GVar = dyn_cast_or_null<GlobalVariable>(GV->getBaseObject()))
307           return HasTypeMetadata(GVar);
308         return false;
309       }));
310   StripDebugInfo(*MergedM);
311   MergedM->setModuleInlineAsm("");
312 
313   // Clone any llvm.*used globals to ensure the included values are
314   // not deleted.
315   cloneUsedGlobalVariables(M, *MergedM, /*CompilerUsed*/ false);
316   cloneUsedGlobalVariables(M, *MergedM, /*CompilerUsed*/ true);
317 
318   for (Function &F : *MergedM)
319     if (!F.isDeclaration()) {
320       // Reset the linkage of all functions eligible for virtual constant
321       // propagation. The canonical definitions live in the thin LTO module so
322       // that they can be imported.
323       F.setLinkage(GlobalValue::AvailableExternallyLinkage);
324       F.setComdat(nullptr);
325     }
326 
327   SetVector<GlobalValue *> CfiFunctions;
328   for (auto &F : M)
329     if ((!F.hasLocalLinkage() || F.hasAddressTaken()) && HasTypeMetadata(&F))
330       CfiFunctions.insert(&F);
331 
332   // Remove all globals with type metadata, globals with comdats that live in
333   // MergedM, and aliases pointing to such globals from the thin LTO module.
334   filterModule(&M, [&](const GlobalValue *GV) {
335     if (auto *GVar = dyn_cast_or_null<GlobalVariable>(GV->getBaseObject()))
336       if (HasTypeMetadata(GVar))
337         return false;
338     if (const auto *C = GV->getComdat())
339       if (MergedMComdats.count(C))
340         return false;
341     return true;
342   });
343 
344   promoteInternals(*MergedM, M, ModuleId, CfiFunctions);
345   promoteInternals(M, *MergedM, ModuleId, CfiFunctions);
346 
347   auto &Ctx = MergedM->getContext();
348   SmallVector<MDNode *, 8> CfiFunctionMDs;
349   for (auto V : CfiFunctions) {
350     Function &F = *cast<Function>(V);
351     SmallVector<MDNode *, 2> Types;
352     F.getMetadata(LLVMContext::MD_type, Types);
353 
354     SmallVector<Metadata *, 4> Elts;
355     Elts.push_back(MDString::get(Ctx, F.getName()));
356     CfiFunctionLinkage Linkage;
357     if (lowertypetests::isJumpTableCanonical(&F))
358       Linkage = CFL_Definition;
359     else if (F.hasExternalWeakLinkage())
360       Linkage = CFL_WeakDeclaration;
361     else
362       Linkage = CFL_Declaration;
363     Elts.push_back(ConstantAsMetadata::get(
364         llvm::ConstantInt::get(Type::getInt8Ty(Ctx), Linkage)));
365     append_range(Elts, Types);
366     CfiFunctionMDs.push_back(MDTuple::get(Ctx, Elts));
367   }
368 
369   if(!CfiFunctionMDs.empty()) {
370     NamedMDNode *NMD = MergedM->getOrInsertNamedMetadata("cfi.functions");
371     for (auto MD : CfiFunctionMDs)
372       NMD->addOperand(MD);
373   }
374 
375   SmallVector<MDNode *, 8> FunctionAliases;
376   for (auto &A : M.aliases()) {
377     if (!isa<Function>(A.getAliasee()))
378       continue;
379 
380     auto *F = cast<Function>(A.getAliasee());
381 
382     Metadata *Elts[] = {
383         MDString::get(Ctx, A.getName()),
384         MDString::get(Ctx, F->getName()),
385         ConstantAsMetadata::get(
386             ConstantInt::get(Type::getInt8Ty(Ctx), A.getVisibility())),
387         ConstantAsMetadata::get(
388             ConstantInt::get(Type::getInt8Ty(Ctx), A.isWeakForLinker())),
389     };
390 
391     FunctionAliases.push_back(MDTuple::get(Ctx, Elts));
392   }
393 
394   if (!FunctionAliases.empty()) {
395     NamedMDNode *NMD = MergedM->getOrInsertNamedMetadata("aliases");
396     for (auto MD : FunctionAliases)
397       NMD->addOperand(MD);
398   }
399 
400   SmallVector<MDNode *, 8> Symvers;
401   ModuleSymbolTable::CollectAsmSymvers(M, [&](StringRef Name, StringRef Alias) {
402     Function *F = M.getFunction(Name);
403     if (!F || F->use_empty())
404       return;
405 
406     Symvers.push_back(MDTuple::get(
407         Ctx, {MDString::get(Ctx, Name), MDString::get(Ctx, Alias)}));
408   });
409 
410   if (!Symvers.empty()) {
411     NamedMDNode *NMD = MergedM->getOrInsertNamedMetadata("symvers");
412     for (auto MD : Symvers)
413       NMD->addOperand(MD);
414   }
415 
416   simplifyExternals(*MergedM);
417 
418   // FIXME: Try to re-use BSI and PFI from the original module here.
419   ProfileSummaryInfo PSI(M);
420   ModuleSummaryIndex Index = buildModuleSummaryIndex(M, nullptr, &PSI);
421 
422   // Mark the merged module as requiring full LTO. We still want an index for
423   // it though, so that it can participate in summary-based dead stripping.
424   MergedM->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
425   ModuleSummaryIndex MergedMIndex =
426       buildModuleSummaryIndex(*MergedM, nullptr, &PSI);
427 
428   SmallVector<char, 0> Buffer;
429 
430   BitcodeWriter W(Buffer);
431   // Save the module hash produced for the full bitcode, which will
432   // be used in the backends, and use that in the minimized bitcode
433   // produced for the full link.
434   ModuleHash ModHash = {{0}};
435   W.writeModule(M, /*ShouldPreserveUseListOrder=*/false, &Index,
436                 /*GenerateHash=*/true, &ModHash);
437   W.writeModule(*MergedM, /*ShouldPreserveUseListOrder=*/false, &MergedMIndex);
438   W.writeSymtab();
439   W.writeStrtab();
440   OS << Buffer;
441 
442   // If a minimized bitcode module was requested for the thin link, only
443   // the information that is needed by thin link will be written in the
444   // given OS (the merged module will be written as usual).
445   if (ThinLinkOS) {
446     Buffer.clear();
447     BitcodeWriter W2(Buffer);
448     StripDebugInfo(M);
449     W2.writeThinLinkBitcode(M, Index, ModHash);
450     W2.writeModule(*MergedM, /*ShouldPreserveUseListOrder=*/false,
451                    &MergedMIndex);
452     W2.writeSymtab();
453     W2.writeStrtab();
454     *ThinLinkOS << Buffer;
455   }
456 }
457 
458 // Check if the LTO Unit splitting has been enabled.
459 bool enableSplitLTOUnit(Module &M) {
460   bool EnableSplitLTOUnit = false;
461   if (auto *MD = mdconst::extract_or_null<ConstantInt>(
462           M.getModuleFlag("EnableSplitLTOUnit")))
463     EnableSplitLTOUnit = MD->getZExtValue();
464   return EnableSplitLTOUnit;
465 }
466 
467 // Returns whether this module needs to be split because it uses type metadata.
468 bool hasTypeMetadata(Module &M) {
469   for (auto &GO : M.global_objects()) {
470     if (GO.hasMetadata(LLVMContext::MD_type))
471       return true;
472   }
473   return false;
474 }
475 
476 void writeThinLTOBitcode(raw_ostream &OS, raw_ostream *ThinLinkOS,
477                          function_ref<AAResults &(Function &)> AARGetter,
478                          Module &M, const ModuleSummaryIndex *Index) {
479   std::unique_ptr<ModuleSummaryIndex> NewIndex = nullptr;
480   // See if this module has any type metadata. If so, we try to split it
481   // or at least promote type ids to enable WPD.
482   if (hasTypeMetadata(M)) {
483     if (enableSplitLTOUnit(M))
484       return splitAndWriteThinLTOBitcode(OS, ThinLinkOS, AARGetter, M);
485     // Promote type ids as needed for index-based WPD.
486     std::string ModuleId = getUniqueModuleId(&M);
487     if (!ModuleId.empty()) {
488       promoteTypeIds(M, ModuleId);
489       // Need to rebuild the index so that it contains type metadata
490       // for the newly promoted type ids.
491       // FIXME: Probably should not bother building the index at all
492       // in the caller of writeThinLTOBitcode (which does so via the
493       // ModuleSummaryIndexAnalysis pass), since we have to rebuild it
494       // anyway whenever there is type metadata (here or in
495       // splitAndWriteThinLTOBitcode). Just always build it once via the
496       // buildModuleSummaryIndex when Module(s) are ready.
497       ProfileSummaryInfo PSI(M);
498       NewIndex = std::make_unique<ModuleSummaryIndex>(
499           buildModuleSummaryIndex(M, nullptr, &PSI));
500       Index = NewIndex.get();
501     }
502   }
503 
504   // Write it out as an unsplit ThinLTO module.
505 
506   // Save the module hash produced for the full bitcode, which will
507   // be used in the backends, and use that in the minimized bitcode
508   // produced for the full link.
509   ModuleHash ModHash = {{0}};
510   WriteBitcodeToFile(M, OS, /*ShouldPreserveUseListOrder=*/false, Index,
511                      /*GenerateHash=*/true, &ModHash);
512   // If a minimized bitcode module was requested for the thin link, only
513   // the information that is needed by thin link will be written in the
514   // given OS.
515   if (ThinLinkOS && Index)
516     WriteThinLinkBitcodeToFile(M, *ThinLinkOS, *Index, ModHash);
517 }
518 
519 class WriteThinLTOBitcode : public ModulePass {
520   raw_ostream &OS; // raw_ostream to print on
521   // The output stream on which to emit a minimized module for use
522   // just in the thin link, if requested.
523   raw_ostream *ThinLinkOS;
524 
525 public:
526   static char ID; // Pass identification, replacement for typeid
527   WriteThinLTOBitcode() : ModulePass(ID), OS(dbgs()), ThinLinkOS(nullptr) {
528     initializeWriteThinLTOBitcodePass(*PassRegistry::getPassRegistry());
529   }
530 
531   explicit WriteThinLTOBitcode(raw_ostream &o, raw_ostream *ThinLinkOS)
532       : ModulePass(ID), OS(o), ThinLinkOS(ThinLinkOS) {
533     initializeWriteThinLTOBitcodePass(*PassRegistry::getPassRegistry());
534   }
535 
536   StringRef getPassName() const override { return "ThinLTO Bitcode Writer"; }
537 
538   bool runOnModule(Module &M) override {
539     const ModuleSummaryIndex *Index =
540         &(getAnalysis<ModuleSummaryIndexWrapperPass>().getIndex());
541     writeThinLTOBitcode(OS, ThinLinkOS, LegacyAARGetter(*this), M, Index);
542     return true;
543   }
544   void getAnalysisUsage(AnalysisUsage &AU) const override {
545     AU.setPreservesAll();
546     AU.addRequired<AssumptionCacheTracker>();
547     AU.addRequired<ModuleSummaryIndexWrapperPass>();
548     AU.addRequired<TargetLibraryInfoWrapperPass>();
549   }
550 };
551 } // anonymous namespace
552 
553 char WriteThinLTOBitcode::ID = 0;
554 INITIALIZE_PASS_BEGIN(WriteThinLTOBitcode, "write-thinlto-bitcode",
555                       "Write ThinLTO Bitcode", false, true)
556 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
557 INITIALIZE_PASS_DEPENDENCY(ModuleSummaryIndexWrapperPass)
558 INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
559 INITIALIZE_PASS_END(WriteThinLTOBitcode, "write-thinlto-bitcode",
560                     "Write ThinLTO Bitcode", false, true)
561 
562 ModulePass *llvm::createWriteThinLTOBitcodePass(raw_ostream &Str,
563                                                 raw_ostream *ThinLinkOS) {
564   return new WriteThinLTOBitcode(Str, ThinLinkOS);
565 }
566 
567 PreservedAnalyses
568 llvm::ThinLTOBitcodeWriterPass::run(Module &M, ModuleAnalysisManager &AM) {
569   FunctionAnalysisManager &FAM =
570       AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
571   writeThinLTOBitcode(OS, ThinLinkOS,
572                       [&FAM](Function &F) -> AAResults & {
573                         return FAM.getResult<AAManager>(F);
574                       },
575                       M, &AM.getResult<ModuleSummaryIndexAnalysis>(M));
576   return PreservedAnalyses::all();
577 }
578