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