ThinLTOBitcodeWriter.cpp 21 KB

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