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