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