blob: 9bca88a54b34d7419c0b5bdd38f951d57b4428c5 [file] [log] [blame]
Peter Collingbourne1398a322016-12-16 00:26:30 +00001//===- ThinLTOBitcodeWriter.cpp - Bitcode writing pass for ThinLTO --------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
Peter Collingbourne1398a322016-12-16 00:26:30 +00009
Tim Shen6b4114182017-06-01 01:02:12 +000010#include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h"
Peter Collingbourne002c2d52017-02-14 03:42:38 +000011#include "llvm/Analysis/BasicAliasAnalysis.h"
Peter Collingbourne1398a322016-12-16 00:26:30 +000012#include "llvm/Analysis/ModuleSummaryAnalysis.h"
Teresa Johnson94624ac2017-05-10 18:52:16 +000013#include "llvm/Analysis/ProfileSummaryInfo.h"
Peter Collingbourne1398a322016-12-16 00:26:30 +000014#include "llvm/Analysis/TypeMetadataUtils.h"
15#include "llvm/Bitcode/BitcodeWriter.h"
16#include "llvm/IR/Constants.h"
Peter Collingbourne28ffd322017-02-08 20:44:00 +000017#include "llvm/IR/DebugInfo.h"
Peter Collingbourne1398a322016-12-16 00:26:30 +000018#include "llvm/IR/Intrinsics.h"
19#include "llvm/IR/Module.h"
20#include "llvm/IR/PassManager.h"
21#include "llvm/Pass.h"
22#include "llvm/Support/ScopedPrinter.h"
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +000023#include "llvm/Support/raw_ostream.h"
24#include "llvm/Transforms/IPO.h"
Peter Collingbourne002c2d52017-02-14 03:42:38 +000025#include "llvm/Transforms/IPO/FunctionAttrs.h"
George Rimard3704f62018-02-08 07:23:24 +000026#include "llvm/Transforms/IPO/FunctionImport.h"
Peter Collingbourne1398a322016-12-16 00:26:30 +000027#include "llvm/Transforms/Utils/Cloning.h"
Evgeniy Stepanov964f4662017-04-27 20:27:27 +000028#include "llvm/Transforms/Utils/ModuleUtils.h"
Peter Collingbourne1398a322016-12-16 00:26:30 +000029using namespace llvm;
30
31namespace {
32
Peter Collingbourne1398a322016-12-16 00:26:30 +000033// Promote each local-linkage entity defined by ExportM and used by ImportM by
34// changing visibility and appending the given ModuleId.
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +000035void promoteInternals(Module &ExportM, Module &ImportM, StringRef ModuleId,
36 SetVector<GlobalValue *> &PromoteExtra) {
Bob Haarman4075ccc2017-04-12 01:43:07 +000037 DenseMap<const Comdat *, Comdat *> RenamedComdats;
Peter Collingbourne6b193962017-03-30 23:43:08 +000038 for (auto &ExportGV : ExportM.global_values()) {
Peter Collingbourne1398a322016-12-16 00:26:30 +000039 if (!ExportGV.hasLocalLinkage())
Peter Collingbourne6b193962017-03-30 23:43:08 +000040 continue;
Peter Collingbourne1398a322016-12-16 00:26:30 +000041
Bob Haarman4075ccc2017-04-12 01:43:07 +000042 auto Name = ExportGV.getName();
Peter Collingbourne1f034222017-11-30 23:05:52 +000043 GlobalValue *ImportGV = nullptr;
44 if (!PromoteExtra.count(&ExportGV)) {
45 ImportGV = ImportM.getNamedValue(Name);
46 if (!ImportGV)
47 continue;
48 ImportGV->removeDeadConstantUsers();
49 if (ImportGV->use_empty()) {
50 ImportGV->eraseFromParent();
51 continue;
52 }
53 }
Peter Collingbourne1398a322016-12-16 00:26:30 +000054
Bob Haarman4075ccc2017-04-12 01:43:07 +000055 std::string NewName = (Name + ModuleId).str();
56
57 if (const auto *C = ExportGV.getComdat())
58 if (C->getName() == Name)
59 RenamedComdats.try_emplace(C, ExportM.getOrInsertComdat(NewName));
Peter Collingbourne1398a322016-12-16 00:26:30 +000060
61 ExportGV.setName(NewName);
62 ExportGV.setLinkage(GlobalValue::ExternalLinkage);
63 ExportGV.setVisibility(GlobalValue::HiddenVisibility);
64
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +000065 if (ImportGV) {
66 ImportGV->setName(NewName);
67 ImportGV->setVisibility(GlobalValue::HiddenVisibility);
68 }
Peter Collingbourne6b193962017-03-30 23:43:08 +000069 }
Bob Haarman4075ccc2017-04-12 01:43:07 +000070
71 if (!RenamedComdats.empty())
72 for (auto &GO : ExportM.global_objects())
73 if (auto *C = GO.getComdat()) {
74 auto Replacement = RenamedComdats.find(C);
75 if (Replacement != RenamedComdats.end())
76 GO.setComdat(Replacement->second);
77 }
Peter Collingbourne1398a322016-12-16 00:26:30 +000078}
79
80// Promote all internal (i.e. distinct) type ids used by the module by replacing
81// them with external type ids formed using the module id.
82//
83// Note that this needs to be done before we clone the module because each clone
84// will receive its own set of distinct metadata nodes.
85void promoteTypeIds(Module &M, StringRef ModuleId) {
86 DenseMap<Metadata *, Metadata *> LocalToGlobal;
87 auto ExternalizeTypeId = [&](CallInst *CI, unsigned ArgNo) {
88 Metadata *MD =
89 cast<MetadataAsValue>(CI->getArgOperand(ArgNo))->getMetadata();
90
91 if (isa<MDNode>(MD) && cast<MDNode>(MD)->isDistinct()) {
92 Metadata *&GlobalMD = LocalToGlobal[MD];
93 if (!GlobalMD) {
Benjamin Kramer3a13ed62017-12-28 16:58:54 +000094 std::string NewName = (Twine(LocalToGlobal.size()) + ModuleId).str();
Peter Collingbourne1398a322016-12-16 00:26:30 +000095 GlobalMD = MDString::get(M.getContext(), NewName);
96 }
97
98 CI->setArgOperand(ArgNo,
99 MetadataAsValue::get(M.getContext(), GlobalMD));
100 }
101 };
102
103 if (Function *TypeTestFunc =
104 M.getFunction(Intrinsic::getName(Intrinsic::type_test))) {
105 for (const Use &U : TypeTestFunc->uses()) {
106 auto CI = cast<CallInst>(U.getUser());
107 ExternalizeTypeId(CI, 1);
108 }
109 }
110
111 if (Function *TypeCheckedLoadFunc =
112 M.getFunction(Intrinsic::getName(Intrinsic::type_checked_load))) {
113 for (const Use &U : TypeCheckedLoadFunc->uses()) {
114 auto CI = cast<CallInst>(U.getUser());
115 ExternalizeTypeId(CI, 2);
116 }
117 }
118
119 for (GlobalObject &GO : M.global_objects()) {
120 SmallVector<MDNode *, 1> MDs;
121 GO.getMetadata(LLVMContext::MD_type, MDs);
122
123 GO.eraseMetadata(LLVMContext::MD_type);
124 for (auto MD : MDs) {
125 auto I = LocalToGlobal.find(MD->getOperand(1));
126 if (I == LocalToGlobal.end()) {
127 GO.addMetadata(LLVMContext::MD_type, *MD);
128 continue;
129 }
130 GO.addMetadata(
131 LLVMContext::MD_type,
132 *MDNode::get(M.getContext(),
133 ArrayRef<Metadata *>{MD->getOperand(0), I->second}));
134 }
135 }
136}
137
138// Drop unused globals, and drop type information from function declarations.
139// FIXME: If we made functions typeless then there would be no need to do this.
140void simplifyExternals(Module &M) {
141 FunctionType *EmptyFT =
142 FunctionType::get(Type::getVoidTy(M.getContext()), false);
143
144 for (auto I = M.begin(), E = M.end(); I != E;) {
145 Function &F = *I++;
146 if (F.isDeclaration() && F.use_empty()) {
147 F.eraseFromParent();
148 continue;
149 }
150
Peter Collingbourne93fdaca2017-07-19 17:54:29 +0000151 if (!F.isDeclaration() || F.getFunctionType() == EmptyFT ||
152 // Changing the type of an intrinsic may invalidate the IR.
153 F.getName().startswith("llvm."))
Peter Collingbourne1398a322016-12-16 00:26:30 +0000154 continue;
155
156 Function *NewF =
157 Function::Create(EmptyFT, GlobalValue::ExternalLinkage, "", &M);
158 NewF->setVisibility(F.getVisibility());
159 NewF->takeName(&F);
160 F.replaceAllUsesWith(ConstantExpr::getBitCast(NewF, F.getType()));
161 F.eraseFromParent();
162 }
163
164 for (auto I = M.global_begin(), E = M.global_end(); I != E;) {
165 GlobalVariable &GV = *I++;
166 if (GV.isDeclaration() && GV.use_empty()) {
167 GV.eraseFromParent();
168 continue;
169 }
170 }
171}
172
George Rimard3704f62018-02-08 07:23:24 +0000173static void
174filterModule(Module *M,
175 function_ref<bool(const GlobalValue *)> ShouldKeepDefinition) {
176 std::vector<GlobalValue *> V;
177 for (GlobalValue &GV : M->global_values())
178 if (!ShouldKeepDefinition(&GV))
179 V.push_back(&GV);
George Rimar54565242018-02-07 08:46:36 +0000180
George Rimard3704f62018-02-08 07:23:24 +0000181 for (GlobalValue *GV : V)
182 if (!convertToDeclaration(*GV))
183 GV->eraseFromParent();
Peter Collingbourne1398a322016-12-16 00:26:30 +0000184}
185
Peter Collingbourne002c2d52017-02-14 03:42:38 +0000186void forEachVirtualFunction(Constant *C, function_ref<void(Function *)> Fn) {
187 if (auto *F = dyn_cast<Function>(C))
188 return Fn(F);
Peter Collingbourne3baa72a2017-03-02 23:10:17 +0000189 if (isa<GlobalValue>(C))
190 return;
Peter Collingbourne002c2d52017-02-14 03:42:38 +0000191 for (Value *Op : C->operands())
192 forEachVirtualFunction(cast<Constant>(Op), Fn);
193}
194
Peter Collingbourne1398a322016-12-16 00:26:30 +0000195// If it's possible to split M into regular and thin LTO parts, do so and write
196// a multi-module bitcode file with the two parts to OS. Otherwise, write only a
197// regular LTO bitcode file to OS.
Peter Collingbourne002c2d52017-02-14 03:42:38 +0000198void splitAndWriteThinLTOBitcode(
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000199 raw_ostream &OS, raw_ostream *ThinLinkOS,
200 function_ref<AAResults &(Function &)> AARGetter, Module &M) {
Evgeniy Stepanov964f4662017-04-27 20:27:27 +0000201 std::string ModuleId = getUniqueModuleId(&M);
Peter Collingbourne1398a322016-12-16 00:26:30 +0000202 if (ModuleId.empty()) {
203 // We couldn't generate a module ID for this module, just write it out as a
204 // regular LTO module.
Rafael Espindola6a86e252018-02-14 19:11:32 +0000205 WriteBitcodeToFile(M, OS);
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000206 if (ThinLinkOS)
207 // We don't have a ThinLTO part, but still write the module to the
208 // ThinLinkOS if requested so that the expected output file is produced.
Rafael Espindola6a86e252018-02-14 19:11:32 +0000209 WriteBitcodeToFile(M, *ThinLinkOS);
Peter Collingbourne1398a322016-12-16 00:26:30 +0000210 return;
211 }
212
213 promoteTypeIds(M, ModuleId);
214
Peter Collingbourne002c2d52017-02-14 03:42:38 +0000215 // Returns whether a global has attached type metadata. Such globals may
216 // participate in CFI or whole-program devirtualization, so they need to
217 // appear in the merged module instead of the thin LTO module.
218 auto HasTypeMetadata = [&](const GlobalObject *GO) {
Peter Collingbourne1398a322016-12-16 00:26:30 +0000219 SmallVector<MDNode *, 1> MDs;
Peter Collingbourne002c2d52017-02-14 03:42:38 +0000220 GO->getMetadata(LLVMContext::MD_type, MDs);
Peter Collingbourne1398a322016-12-16 00:26:30 +0000221 return !MDs.empty();
222 };
223
Peter Collingbourne002c2d52017-02-14 03:42:38 +0000224 // Collect the set of virtual functions that are eligible for virtual constant
225 // propagation. Each eligible function must not access memory, must return
226 // an integer of width <=64 bits, must take at least one argument, must not
227 // use its first argument (assumed to be "this") and all arguments other than
228 // the first one must be of <=64 bit integer type.
229 //
230 // Note that we test whether this copy of the function is readnone, rather
231 // than testing function attributes, which must hold for any copy of the
232 // function, even a less optimized version substituted at link time. This is
233 // sound because the virtual constant propagation optimizations effectively
234 // inline all implementations of the virtual function into each call site,
235 // rather than using function attributes to perform local optimization.
236 std::set<const Function *> EligibleVirtualFns;
Bob Haarman4075ccc2017-04-12 01:43:07 +0000237 // If any member of a comdat lives in MergedM, put all members of that
238 // comdat in MergedM to keep the comdat together.
239 DenseSet<const Comdat *> MergedMComdats;
Peter Collingbourne002c2d52017-02-14 03:42:38 +0000240 for (GlobalVariable &GV : M.globals())
Bob Haarman4075ccc2017-04-12 01:43:07 +0000241 if (HasTypeMetadata(&GV)) {
242 if (const auto *C = GV.getComdat())
243 MergedMComdats.insert(C);
Peter Collingbourne002c2d52017-02-14 03:42:38 +0000244 forEachVirtualFunction(GV.getInitializer(), [&](Function *F) {
245 auto *RT = dyn_cast<IntegerType>(F->getReturnType());
246 if (!RT || RT->getBitWidth() > 64 || F->arg_empty() ||
247 !F->arg_begin()->use_empty())
248 return;
249 for (auto &Arg : make_range(std::next(F->arg_begin()), F->arg_end())) {
250 auto *ArgT = dyn_cast<IntegerType>(Arg.getType());
251 if (!ArgT || ArgT->getBitWidth() > 64)
252 return;
253 }
Chandler Carruth01f0c8a2017-07-11 05:39:20 +0000254 if (!F->isDeclaration() &&
255 computeFunctionBodyMemoryAccess(*F, AARGetter(*F)) == MAK_ReadNone)
Peter Collingbourne002c2d52017-02-14 03:42:38 +0000256 EligibleVirtualFns.insert(F);
257 });
Bob Haarman4075ccc2017-04-12 01:43:07 +0000258 }
Peter Collingbourne002c2d52017-02-14 03:42:38 +0000259
Peter Collingbourne1398a322016-12-16 00:26:30 +0000260 ValueToValueMapTy VMap;
Peter Collingbourne002c2d52017-02-14 03:42:38 +0000261 std::unique_ptr<Module> MergedM(
Rafael Espindola71867532018-02-14 19:50:40 +0000262 CloneModule(M, VMap, [&](const GlobalValue *GV) -> bool {
Bob Haarman4075ccc2017-04-12 01:43:07 +0000263 if (const auto *C = GV->getComdat())
264 if (MergedMComdats.count(C))
265 return true;
Peter Collingbourne002c2d52017-02-14 03:42:38 +0000266 if (auto *F = dyn_cast<Function>(GV))
267 return EligibleVirtualFns.count(F);
268 if (auto *GVar = dyn_cast_or_null<GlobalVariable>(GV->getBaseObject()))
269 return HasTypeMetadata(GVar);
270 return false;
271 }));
Peter Collingbourne28ffd322017-02-08 20:44:00 +0000272 StripDebugInfo(*MergedM);
Peter Collingbourne29c6f482018-02-06 03:29:18 +0000273 MergedM->setModuleInlineAsm("");
Peter Collingbourne1398a322016-12-16 00:26:30 +0000274
Peter Collingbourne002c2d52017-02-14 03:42:38 +0000275 for (Function &F : *MergedM)
276 if (!F.isDeclaration()) {
277 // Reset the linkage of all functions eligible for virtual constant
278 // propagation. The canonical definitions live in the thin LTO module so
279 // that they can be imported.
280 F.setLinkage(GlobalValue::AvailableExternallyLinkage);
281 F.setComdat(nullptr);
282 }
283
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +0000284 SetVector<GlobalValue *> CfiFunctions;
285 for (auto &F : M)
286 if ((!F.hasLocalLinkage() || F.hasAddressTaken()) && HasTypeMetadata(&F))
287 CfiFunctions.insert(&F);
288
Bob Haarman4075ccc2017-04-12 01:43:07 +0000289 // Remove all globals with type metadata, globals with comdats that live in
290 // MergedM, and aliases pointing to such globals from the thin LTO module.
Peter Collingbourne002c2d52017-02-14 03:42:38 +0000291 filterModule(&M, [&](const GlobalValue *GV) {
292 if (auto *GVar = dyn_cast_or_null<GlobalVariable>(GV->getBaseObject()))
Bob Haarman4075ccc2017-04-12 01:43:07 +0000293 if (HasTypeMetadata(GVar))
294 return false;
295 if (const auto *C = GV->getComdat())
296 if (MergedMComdats.count(C))
297 return false;
Peter Collingbourne002c2d52017-02-14 03:42:38 +0000298 return true;
299 });
Peter Collingbourne1398a322016-12-16 00:26:30 +0000300
Evgeniy Stepanov4d4ee932017-06-16 00:18:29 +0000301 promoteInternals(*MergedM, M, ModuleId, CfiFunctions);
302 promoteInternals(M, *MergedM, ModuleId, CfiFunctions);
303
304 SmallVector<MDNode *, 8> CfiFunctionMDs;
305 for (auto V : CfiFunctions) {
306 Function &F = *cast<Function>(V);
307 SmallVector<MDNode *, 2> Types;
308 F.getMetadata(LLVMContext::MD_type, Types);
309
310 auto &Ctx = MergedM->getContext();
311 SmallVector<Metadata *, 4> Elts;
312 Elts.push_back(MDString::get(Ctx, F.getName()));
313 CfiFunctionLinkage Linkage;
314 if (!F.isDeclarationForLinker())
315 Linkage = CFL_Definition;
316 else if (F.isWeakForLinker())
317 Linkage = CFL_WeakDeclaration;
318 else
319 Linkage = CFL_Declaration;
320 Elts.push_back(ConstantAsMetadata::get(
321 llvm::ConstantInt::get(Type::getInt8Ty(Ctx), Linkage)));
322 for (auto Type : Types)
323 Elts.push_back(Type);
324 CfiFunctionMDs.push_back(MDTuple::get(Ctx, Elts));
325 }
326
327 if(!CfiFunctionMDs.empty()) {
328 NamedMDNode *NMD = MergedM->getOrInsertNamedMetadata("cfi.functions");
329 for (auto MD : CfiFunctionMDs)
330 NMD->addOperand(MD);
331 }
Peter Collingbourne1398a322016-12-16 00:26:30 +0000332
Vlad Tsyrklevichcdec22e2018-01-10 00:00:51 +0000333 SmallVector<MDNode *, 8> FunctionAliases;
334 for (auto &A : M.aliases()) {
335 if (!isa<Function>(A.getAliasee()))
336 continue;
337
338 auto *F = cast<Function>(A.getAliasee());
339 auto &Ctx = MergedM->getContext();
340 SmallVector<Metadata *, 4> Elts;
341
342 Elts.push_back(MDString::get(Ctx, A.getName()));
343 Elts.push_back(MDString::get(Ctx, F->getName()));
344 Elts.push_back(ConstantAsMetadata::get(
345 llvm::ConstantInt::get(Type::getInt8Ty(Ctx), A.getVisibility())));
346 Elts.push_back(ConstantAsMetadata::get(
347 llvm::ConstantInt::get(Type::getInt8Ty(Ctx), A.isWeakForLinker())));
348
349 FunctionAliases.push_back(MDTuple::get(Ctx, Elts));
350 }
351
352 if (!FunctionAliases.empty()) {
353 NamedMDNode *NMD = MergedM->getOrInsertNamedMetadata("aliases");
354 for (auto MD : FunctionAliases)
355 NMD->addOperand(MD);
356 }
357
Peter Collingbourne1398a322016-12-16 00:26:30 +0000358 simplifyExternals(*MergedM);
359
Peter Collingbourne1398a322016-12-16 00:26:30 +0000360 // FIXME: Try to re-use BSI and PFI from the original module here.
Teresa Johnson94624ac2017-05-10 18:52:16 +0000361 ProfileSummaryInfo PSI(M);
362 ModuleSummaryIndex Index = buildModuleSummaryIndex(M, nullptr, &PSI);
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000363
Peter Collingbournee357fbd2017-06-08 23:01:49 +0000364 // Mark the merged module as requiring full LTO. We still want an index for
365 // it though, so that it can participate in summary-based dead stripping.
366 MergedM->addModuleFlag(Module::Error, "ThinLTO", uint32_t(0));
367 ModuleSummaryIndex MergedMIndex =
368 buildModuleSummaryIndex(*MergedM, nullptr, &PSI);
369
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000370 SmallVector<char, 0> Buffer;
371
372 BitcodeWriter W(Buffer);
373 // Save the module hash produced for the full bitcode, which will
374 // be used in the backends, and use that in the minimized bitcode
375 // produced for the full link.
376 ModuleHash ModHash = {{0}};
Rafael Espindola6a86e252018-02-14 19:11:32 +0000377 W.writeModule(M, /*ShouldPreserveUseListOrder=*/false, &Index,
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000378 /*GenerateHash=*/true, &ModHash);
Rafael Espindola6a86e252018-02-14 19:11:32 +0000379 W.writeModule(*MergedM, /*ShouldPreserveUseListOrder=*/false, &MergedMIndex);
Peter Collingbourne92648c22017-06-27 23:50:11 +0000380 W.writeSymtab();
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000381 W.writeStrtab();
Peter Collingbourne1398a322016-12-16 00:26:30 +0000382 OS << Buffer;
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000383
Haojie Wang1dec57d2017-07-21 17:25:20 +0000384 // If a minimized bitcode module was requested for the thin link, only
385 // the information that is needed by thin link will be written in the
386 // given OS (the merged module will be written as usual).
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000387 if (ThinLinkOS) {
388 Buffer.clear();
389 BitcodeWriter W2(Buffer);
390 StripDebugInfo(M);
Rafael Espindola6a86e252018-02-14 19:11:32 +0000391 W2.writeThinLinkBitcode(M, Index, ModHash);
392 W2.writeModule(*MergedM, /*ShouldPreserveUseListOrder=*/false,
Peter Collingbournee357fbd2017-06-08 23:01:49 +0000393 &MergedMIndex);
Peter Collingbourne92648c22017-06-27 23:50:11 +0000394 W2.writeSymtab();
Peter Collingbournea0f371a2017-04-17 17:51:36 +0000395 W2.writeStrtab();
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000396 *ThinLinkOS << Buffer;
397 }
Peter Collingbourne1398a322016-12-16 00:26:30 +0000398}
399
400// Returns whether this module needs to be split because it uses type metadata.
401bool requiresSplit(Module &M) {
402 SmallVector<MDNode *, 1> MDs;
403 for (auto &GO : M.global_objects()) {
404 GO.getMetadata(LLVMContext::MD_type, MDs);
405 if (!MDs.empty())
406 return true;
407 }
408
409 return false;
410}
411
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000412void writeThinLTOBitcode(raw_ostream &OS, raw_ostream *ThinLinkOS,
Peter Collingbourne002c2d52017-02-14 03:42:38 +0000413 function_ref<AAResults &(Function &)> AARGetter,
414 Module &M, const ModuleSummaryIndex *Index) {
Peter Collingbourne1398a322016-12-16 00:26:30 +0000415 // See if this module has any type metadata. If so, we need to split it.
416 if (requiresSplit(M))
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000417 return splitAndWriteThinLTOBitcode(OS, ThinLinkOS, AARGetter, M);
Peter Collingbourne1398a322016-12-16 00:26:30 +0000418
419 // Otherwise we can just write it out as a regular module.
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000420
421 // Save the module hash produced for the full bitcode, which will
422 // be used in the backends, and use that in the minimized bitcode
423 // produced for the full link.
424 ModuleHash ModHash = {{0}};
Rafael Espindola6a86e252018-02-14 19:11:32 +0000425 WriteBitcodeToFile(M, OS, /*ShouldPreserveUseListOrder=*/false, Index,
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000426 /*GenerateHash=*/true, &ModHash);
Haojie Wang1dec57d2017-07-21 17:25:20 +0000427 // If a minimized bitcode module was requested for the thin link, only
428 // the information that is needed by thin link will be written in the
429 // given OS.
430 if (ThinLinkOS && Index)
Rafael Espindola6a86e252018-02-14 19:11:32 +0000431 WriteThinLinkBitcodeToFile(M, *ThinLinkOS, *Index, ModHash);
Peter Collingbourne1398a322016-12-16 00:26:30 +0000432}
433
434class WriteThinLTOBitcode : public ModulePass {
435 raw_ostream &OS; // raw_ostream to print on
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000436 // The output stream on which to emit a minimized module for use
437 // just in the thin link, if requested.
438 raw_ostream *ThinLinkOS;
Peter Collingbourne1398a322016-12-16 00:26:30 +0000439
440public:
441 static char ID; // Pass identification, replacement for typeid
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000442 WriteThinLTOBitcode() : ModulePass(ID), OS(dbgs()), ThinLinkOS(nullptr) {
Peter Collingbourne1398a322016-12-16 00:26:30 +0000443 initializeWriteThinLTOBitcodePass(*PassRegistry::getPassRegistry());
444 }
445
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000446 explicit WriteThinLTOBitcode(raw_ostream &o, raw_ostream *ThinLinkOS)
447 : ModulePass(ID), OS(o), ThinLinkOS(ThinLinkOS) {
Peter Collingbourne1398a322016-12-16 00:26:30 +0000448 initializeWriteThinLTOBitcodePass(*PassRegistry::getPassRegistry());
449 }
450
451 StringRef getPassName() const override { return "ThinLTO Bitcode Writer"; }
452
453 bool runOnModule(Module &M) override {
454 const ModuleSummaryIndex *Index =
455 &(getAnalysis<ModuleSummaryIndexWrapperPass>().getIndex());
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000456 writeThinLTOBitcode(OS, ThinLinkOS, LegacyAARGetter(*this), M, Index);
Peter Collingbourne1398a322016-12-16 00:26:30 +0000457 return true;
458 }
459 void getAnalysisUsage(AnalysisUsage &AU) const override {
460 AU.setPreservesAll();
Peter Collingbourne002c2d52017-02-14 03:42:38 +0000461 AU.addRequired<AssumptionCacheTracker>();
Peter Collingbourne1398a322016-12-16 00:26:30 +0000462 AU.addRequired<ModuleSummaryIndexWrapperPass>();
Peter Collingbourne002c2d52017-02-14 03:42:38 +0000463 AU.addRequired<TargetLibraryInfoWrapperPass>();
Peter Collingbourne1398a322016-12-16 00:26:30 +0000464 }
465};
466} // anonymous namespace
467
468char WriteThinLTOBitcode::ID = 0;
469INITIALIZE_PASS_BEGIN(WriteThinLTOBitcode, "write-thinlto-bitcode",
470 "Write ThinLTO Bitcode", false, true)
Peter Collingbourne002c2d52017-02-14 03:42:38 +0000471INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
Peter Collingbourne1398a322016-12-16 00:26:30 +0000472INITIALIZE_PASS_DEPENDENCY(ModuleSummaryIndexWrapperPass)
Peter Collingbourne002c2d52017-02-14 03:42:38 +0000473INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
Peter Collingbourne1398a322016-12-16 00:26:30 +0000474INITIALIZE_PASS_END(WriteThinLTOBitcode, "write-thinlto-bitcode",
475 "Write ThinLTO Bitcode", false, true)
476
Teresa Johnson0c6a4ff2017-03-23 19:47:39 +0000477ModulePass *llvm::createWriteThinLTOBitcodePass(raw_ostream &Str,
478 raw_ostream *ThinLinkOS) {
479 return new WriteThinLTOBitcode(Str, ThinLinkOS);
Peter Collingbourne1398a322016-12-16 00:26:30 +0000480}
Tim Shen6b4114182017-06-01 01:02:12 +0000481
482PreservedAnalyses
483llvm::ThinLTOBitcodeWriterPass::run(Module &M, ModuleAnalysisManager &AM) {
484 FunctionAnalysisManager &FAM =
485 AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager();
486 writeThinLTOBitcode(OS, ThinLinkOS,
487 [&FAM](Function &F) -> AAResults & {
488 return FAM.getResult<AAManager>(F);
489 },
490 M, &AM.getResult<ModuleSummaryIndexAnalysis>(M));
491 return PreservedAnalyses::all();
492}