1 //===- FunctionImport.cpp - ThinLTO Summary-based Function Import ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements Function import based on summaries.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Transforms/IPO/FunctionImport.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/ADT/StringSet.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/IR/AutoUpgrade.h"
21 #include "llvm/IR/DiagnosticPrinter.h"
22 #include "llvm/IR/IntrinsicInst.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/Verifier.h"
25 #include "llvm/IRReader/IRReader.h"
26 #include "llvm/Linker/Linker.h"
27 #include "llvm/Object/IRObjectFile.h"
28 #include "llvm/Object/ModuleSummaryIndexObjectFile.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/SourceMgr.h"
32 #include "llvm/Transforms/IPO/Internalize.h"
33 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
35 #define DEBUG_TYPE "function-import"
39 STATISTIC(NumImportedFunctions, "Number of functions imported");
40 STATISTIC(NumImportedModules, "Number of modules imported from");
41 STATISTIC(NumDeadSymbols, "Number of dead stripped symbols in index");
42 STATISTIC(NumLiveSymbols, "Number of live symbols in index");
44 /// Limit on instruction count of imported functions.
45 static cl::opt<unsigned> ImportInstrLimit(
46 "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
47 cl::desc("Only import functions with less than N instructions"));
50 ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7),
51 cl::Hidden, cl::value_desc("x"),
52 cl::desc("As we import functions, multiply the "
53 "`import-instr-limit` threshold by this factor "
54 "before processing newly imported functions"));
56 static cl::opt<float> ImportHotInstrFactor(
57 "import-hot-evolution-factor", cl::init(1.0), cl::Hidden,
59 cl::desc("As we import functions called from hot callsite, multiply the "
60 "`import-instr-limit` threshold by this factor "
61 "before processing newly imported functions"));
63 static cl::opt<float> ImportHotMultiplier(
64 "import-hot-multiplier", cl::init(3.0), cl::Hidden, cl::value_desc("x"),
65 cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"));
67 // FIXME: This multiplier was not really tuned up.
68 static cl::opt<float> ImportColdMultiplier(
69 "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"),
70 cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"));
72 static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
73 cl::desc("Print imported functions"));
75 static cl::opt<bool> ComputeDead("compute-dead", cl::init(true), cl::Hidden,
76 cl::desc("Compute dead symbols"));
78 // Temporary allows the function import pass to disable always linking
79 // referenced discardable symbols.
81 DontForceImportReferencedDiscardableSymbols("disable-force-link-odr",
82 cl::init(false), cl::Hidden);
84 static cl::opt<bool> EnableImportMetadata(
85 "enable-import-metadata", cl::init(
87 true /*Enabled with asserts.*/
92 cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'"));
94 // Load lazily a module from \p FileName in \p Context.
95 static std::unique_ptr<Module> loadFile(const std::string &FileName,
96 LLVMContext &Context) {
98 DEBUG(dbgs() << "Loading '" << FileName << "'\n");
99 // Metadata isn't loaded until functions are imported, to minimize
100 // the memory overhead.
101 std::unique_ptr<Module> Result =
102 getLazyIRFileModule(FileName, Err, Context,
103 /* ShouldLazyLoadMetadata = */ true);
105 Err.print("function-import", errs());
106 report_fatal_error("Abort");
114 /// Given a list of possible callee implementation for a call site, select one
115 /// that fits the \p Threshold.
117 /// FIXME: select "best" instead of first that fits. But what is "best"?
118 /// - The smallest: more likely to be inlined.
119 /// - The one with the least outgoing edges (already well optimized).
120 /// - One from a module already being imported from in order to reduce the
121 /// number of source modules parsed/linked.
122 /// - One that has PGO data attached.
123 /// - [insert you fancy metric here]
124 static const GlobalValueSummary *
125 selectCallee(const ModuleSummaryIndex &Index,
126 const GlobalValueSummaryList &CalleeSummaryList,
127 unsigned Threshold) {
128 auto It = llvm::find_if(
130 [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
131 auto *GVSummary = SummaryPtr.get();
132 if (GlobalValue::isInterposableLinkage(GVSummary->linkage()))
133 // There is no point in importing these, we can't inline them
135 if (auto *AS = dyn_cast<AliasSummary>(GVSummary)) {
136 GVSummary = &AS->getAliasee();
137 // Alias can't point to "available_externally". However when we import
138 // linkOnceODR the linkage does not change. So we import the alias
139 // and aliasee only in this case.
140 // FIXME: we should import alias as available_externally *function*,
141 // the destination module does need to know it is an alias.
142 if (!GlobalValue::isLinkOnceODRLinkage(GVSummary->linkage()))
146 auto *Summary = cast<FunctionSummary>(GVSummary);
148 if (Summary->instCount() > Threshold)
151 if (Summary->notEligibleToImport())
156 if (It == CalleeSummaryList.end())
159 return cast<GlobalValueSummary>(It->get());
162 /// Return the summary for the function \p GUID that fits the \p Threshold, or
163 /// null if there's no match.
164 static const GlobalValueSummary *selectCallee(GlobalValue::GUID GUID,
166 const ModuleSummaryIndex &Index) {
167 auto CalleeSummaryList = Index.findGlobalValueSummaryList(GUID);
168 if (CalleeSummaryList == Index.end())
169 return nullptr; // This function does not have a summary
170 return selectCallee(Index, CalleeSummaryList->second, Threshold);
173 using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */,
176 /// Compute the list of functions to import for a given caller. Mark these
177 /// imported functions and the symbols they reference in their source module as
178 /// exported from their source module.
179 static void computeImportForFunction(
180 const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
181 const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
182 SmallVectorImpl<EdgeInfo> &Worklist,
183 FunctionImporter::ImportMapTy &ImportList,
184 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
185 for (auto &Edge : Summary.calls()) {
186 auto GUID = Edge.first.getGUID();
187 DEBUG(dbgs() << " edge -> " << GUID << " Threshold:" << Threshold << "\n");
189 if (DefinedGVSummaries.count(GUID)) {
190 DEBUG(dbgs() << "ignored! Target already in destination module.\n");
194 auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
195 if (Hotness == CalleeInfo::HotnessType::Hot)
196 return ImportHotMultiplier;
197 if (Hotness == CalleeInfo::HotnessType::Cold)
198 return ImportColdMultiplier;
202 const auto NewThreshold =
203 Threshold * GetBonusMultiplier(Edge.second.Hotness);
205 auto *CalleeSummary = selectCallee(GUID, NewThreshold, Index);
206 if (!CalleeSummary) {
207 DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n");
210 // "Resolve" the summary, traversing alias,
211 const FunctionSummary *ResolvedCalleeSummary;
212 if (isa<AliasSummary>(CalleeSummary)) {
213 ResolvedCalleeSummary = cast<FunctionSummary>(
214 &cast<AliasSummary>(CalleeSummary)->getAliasee());
216 GlobalValue::isLinkOnceODRLinkage(ResolvedCalleeSummary->linkage()) &&
217 "Unexpected alias to a non-linkonceODR in import list");
219 ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
221 assert(ResolvedCalleeSummary->instCount() <= NewThreshold &&
222 "selectCallee() didn't honor the threshold");
224 auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
225 // Adjust the threshold for next level of imported functions.
226 // The threshold is different for hot callsites because we can then
227 // inline chains of hot calls.
229 return Threshold * ImportHotInstrFactor;
230 return Threshold * ImportInstrFactor;
233 bool IsHotCallsite = Edge.second.Hotness == CalleeInfo::HotnessType::Hot;
234 const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
236 auto ExportModulePath = ResolvedCalleeSummary->modulePath();
237 auto &ProcessedThreshold = ImportList[ExportModulePath][GUID];
238 /// Since the traversal of the call graph is DFS, we can revisit a function
239 /// a second time with a higher threshold. In this case, it is added back to
240 /// the worklist with the new threshold.
241 if (ProcessedThreshold && ProcessedThreshold >= AdjThreshold) {
242 DEBUG(dbgs() << "ignored! Target was already seen with Threshold "
243 << ProcessedThreshold << "\n");
246 bool PreviouslyImported = ProcessedThreshold != 0;
247 // Mark this function as imported in this module, with the current Threshold
248 ProcessedThreshold = AdjThreshold;
250 // Make exports in the source module.
252 auto &ExportList = (*ExportLists)[ExportModulePath];
253 ExportList.insert(GUID);
254 if (!PreviouslyImported) {
255 // This is the first time this function was exported from its source
256 // module, so mark all functions and globals it references as exported
257 // to the outside if they are defined in the same source module.
258 // For efficiency, we unconditionally add all the referenced GUIDs
259 // to the ExportList for this module, and will prune out any not
260 // defined in the module later in a single pass.
261 for (auto &Edge : ResolvedCalleeSummary->calls()) {
262 auto CalleeGUID = Edge.first.getGUID();
263 ExportList.insert(CalleeGUID);
265 for (auto &Ref : ResolvedCalleeSummary->refs()) {
266 auto GUID = Ref.getGUID();
267 ExportList.insert(GUID);
272 // Insert the newly imported function to the worklist.
273 Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, GUID);
277 /// Given the list of globals defined in a module, compute the list of imports
278 /// as well as the list of "exports", i.e. the list of symbols referenced from
279 /// another module (that may require promotion).
280 static void ComputeImportForModule(
281 const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
282 FunctionImporter::ImportMapTy &ImportList,
283 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr,
284 const DenseSet<GlobalValue::GUID> *DeadSymbols = nullptr) {
285 // Worklist contains the list of function imported in this module, for which
286 // we will analyse the callees and may import further down the callgraph.
287 SmallVector<EdgeInfo, 128> Worklist;
289 // Populate the worklist with the import for the functions in the current
291 for (auto &GVSummary : DefinedGVSummaries) {
292 if (DeadSymbols && DeadSymbols->count(GVSummary.first)) {
293 DEBUG(dbgs() << "Ignores Dead GUID: " << GVSummary.first << "\n");
296 auto *Summary = GVSummary.second;
297 if (auto *AS = dyn_cast<AliasSummary>(Summary))
298 Summary = &AS->getAliasee();
299 auto *FuncSummary = dyn_cast<FunctionSummary>(Summary);
301 // Skip import for global variables
303 DEBUG(dbgs() << "Initalize import for " << GVSummary.first << "\n");
304 computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
305 DefinedGVSummaries, Worklist, ImportList,
309 // Process the newly imported functions and add callees to the worklist.
310 while (!Worklist.empty()) {
311 auto FuncInfo = Worklist.pop_back_val();
312 auto *Summary = std::get<0>(FuncInfo);
313 auto Threshold = std::get<1>(FuncInfo);
314 auto GUID = std::get<2>(FuncInfo);
316 // Check if we later added this summary with a higher threshold.
317 // If so, skip this entry.
318 auto ExportModulePath = Summary->modulePath();
319 auto &LatestProcessedThreshold = ImportList[ExportModulePath][GUID];
320 if (LatestProcessedThreshold > Threshold)
323 computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
324 Worklist, ImportList, ExportLists);
328 } // anonymous namespace
330 /// Compute all the import and export for every module using the Index.
331 void llvm::ComputeCrossModuleImport(
332 const ModuleSummaryIndex &Index,
333 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
334 StringMap<FunctionImporter::ImportMapTy> &ImportLists,
335 StringMap<FunctionImporter::ExportSetTy> &ExportLists,
336 const DenseSet<GlobalValue::GUID> *DeadSymbols) {
337 // For each module that has function defined, compute the import/export lists.
338 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
339 auto &ImportList = ImportLists[DefinedGVSummaries.first()];
340 DEBUG(dbgs() << "Computing import for Module '"
341 << DefinedGVSummaries.first() << "'\n");
342 ComputeImportForModule(DefinedGVSummaries.second, Index, ImportList,
343 &ExportLists, DeadSymbols);
346 // When computing imports we added all GUIDs referenced by anything
347 // imported from the module to its ExportList. Now we prune each ExportList
348 // of any not defined in that module. This is more efficient than checking
349 // while computing imports because some of the summary lists may be long
350 // due to linkonce (comdat) copies.
351 for (auto &ELI : ExportLists) {
352 const auto &DefinedGVSummaries =
353 ModuleToDefinedGVSummaries.lookup(ELI.first());
354 for (auto EI = ELI.second.begin(); EI != ELI.second.end();) {
355 if (!DefinedGVSummaries.count(*EI))
356 EI = ELI.second.erase(EI);
363 DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
365 for (auto &ModuleImports : ImportLists) {
366 auto ModName = ModuleImports.first();
367 auto &Exports = ExportLists[ModName];
368 DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size()
369 << " functions. Imports from " << ModuleImports.second.size()
371 for (auto &Src : ModuleImports.second) {
372 auto SrcModName = Src.first();
373 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
374 << SrcModName << "\n");
380 /// Compute all the imports for the given module in the Index.
381 void llvm::ComputeCrossModuleImportForModule(
382 StringRef ModulePath, const ModuleSummaryIndex &Index,
383 FunctionImporter::ImportMapTy &ImportList) {
385 // Collect the list of functions this module defines.
387 GVSummaryMapTy FunctionSummaryMap;
388 Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
390 // Compute the import list for this module.
391 DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
392 ComputeImportForModule(FunctionSummaryMap, Index, ImportList);
395 DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
396 << ImportList.size() << " modules.\n");
397 for (auto &Src : ImportList) {
398 auto SrcModName = Src.first();
399 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
400 << SrcModName << "\n");
405 DenseSet<GlobalValue::GUID> llvm::computeDeadSymbols(
406 const ModuleSummaryIndex &Index,
407 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
409 return DenseSet<GlobalValue::GUID>();
410 if (GUIDPreservedSymbols.empty())
411 // Don't do anything when nothing is live, this is friendly with tests.
412 return DenseSet<GlobalValue::GUID>();
413 DenseSet<GlobalValue::GUID> LiveSymbols = GUIDPreservedSymbols;
414 SmallVector<GlobalValue::GUID, 128> Worklist;
415 Worklist.reserve(LiveSymbols.size() * 2);
416 for (auto GUID : LiveSymbols) {
417 DEBUG(dbgs() << "Live root: " << GUID << "\n");
418 Worklist.push_back(GUID);
420 // Add values flagged in the index as live roots to the worklist.
421 for (const auto &Entry : Index) {
422 bool IsLiveRoot = llvm::any_of(
424 [&](const std::unique_ptr<llvm::GlobalValueSummary> &Summary) {
425 return Summary->liveRoot();
429 DEBUG(dbgs() << "Live root (summary): " << Entry.first << "\n");
430 Worklist.push_back(Entry.first);
433 while (!Worklist.empty()) {
434 auto GUID = Worklist.pop_back_val();
435 auto It = Index.findGlobalValueSummaryList(GUID);
436 if (It == Index.end()) {
437 DEBUG(dbgs() << "Not in index: " << GUID << "\n");
441 // FIXME: we should only make the prevailing copy live here
442 for (auto &Summary : It->second) {
443 for (auto Ref : Summary->refs()) {
444 auto RefGUID = Ref.getGUID();
445 if (LiveSymbols.insert(RefGUID).second) {
446 DEBUG(dbgs() << "Marking live (ref): " << RefGUID << "\n");
447 Worklist.push_back(RefGUID);
450 if (auto *FS = dyn_cast<FunctionSummary>(Summary.get())) {
451 for (auto Call : FS->calls()) {
452 auto CallGUID = Call.first.getGUID();
453 if (LiveSymbols.insert(CallGUID).second) {
454 DEBUG(dbgs() << "Marking live (call): " << CallGUID << "\n");
455 Worklist.push_back(CallGUID);
459 if (auto *AS = dyn_cast<AliasSummary>(Summary.get())) {
460 auto AliaseeGUID = AS->getAliasee().getOriginalName();
461 if (LiveSymbols.insert(AliaseeGUID).second) {
462 DEBUG(dbgs() << "Marking live (alias): " << AliaseeGUID << "\n");
463 Worklist.push_back(AliaseeGUID);
468 DenseSet<GlobalValue::GUID> DeadSymbols;
470 std::min(Index.size(), Index.size() - LiveSymbols.size()));
471 for (auto &Entry : Index) {
472 auto GUID = Entry.first;
473 if (!LiveSymbols.count(GUID)) {
474 DEBUG(dbgs() << "Marking dead: " << GUID << "\n");
475 DeadSymbols.insert(GUID);
478 DEBUG(dbgs() << LiveSymbols.size() << " symbols Live, and "
479 << DeadSymbols.size() << " symbols Dead \n");
480 NumDeadSymbols += DeadSymbols.size();
481 NumLiveSymbols += LiveSymbols.size();
485 /// Compute the set of summaries needed for a ThinLTO backend compilation of
487 void llvm::gatherImportedSummariesForModule(
488 StringRef ModulePath,
489 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
490 const FunctionImporter::ImportMapTy &ImportList,
491 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
492 // Include all summaries from the importing module.
493 ModuleToSummariesForIndex[ModulePath] =
494 ModuleToDefinedGVSummaries.lookup(ModulePath);
495 // Include summaries for imports.
496 for (auto &ILI : ImportList) {
497 auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
498 const auto &DefinedGVSummaries =
499 ModuleToDefinedGVSummaries.lookup(ILI.first());
500 for (auto &GI : ILI.second) {
501 const auto &DS = DefinedGVSummaries.find(GI.first);
502 assert(DS != DefinedGVSummaries.end() &&
503 "Expected a defined summary for imported global value");
504 SummariesForIndex[GI.first] = DS->second;
509 /// Emit the files \p ModulePath will import from into \p OutputFilename.
511 llvm::EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename,
512 const FunctionImporter::ImportMapTy &ModuleImports) {
514 raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
517 for (auto &ILI : ModuleImports)
518 ImportsOS << ILI.first() << "\n";
519 return std::error_code();
522 /// Fixup WeakForLinker linkages in \p TheModule based on summary analysis.
523 void llvm::thinLTOResolveWeakForLinkerModule(
524 Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
525 auto updateLinkage = [&](GlobalValue &GV) {
526 if (!GlobalValue::isWeakForLinker(GV.getLinkage()))
528 // See if the global summary analysis computed a new resolved linkage.
529 const auto &GS = DefinedGlobals.find(GV.getGUID());
530 if (GS == DefinedGlobals.end())
532 auto NewLinkage = GS->second->linkage();
533 if (NewLinkage == GV.getLinkage())
535 DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
536 << GV.getLinkage() << " to " << NewLinkage << "\n");
537 GV.setLinkage(NewLinkage);
538 // Remove functions converted to available_externally from comdats,
539 // as this is a declaration for the linker, and will be dropped eventually.
540 // It is illegal for comdats to contain declarations.
541 auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
542 if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) {
543 assert(GO->hasAvailableExternallyLinkage() &&
544 "Expected comdat on definition (possibly available external)");
545 GO->setComdat(nullptr);
549 // Process functions and global now
550 for (auto &GV : TheModule)
552 for (auto &GV : TheModule.globals())
554 for (auto &GV : TheModule.aliases())
558 /// Run internalization on \p TheModule based on symmary analysis.
559 void llvm::thinLTOInternalizeModule(Module &TheModule,
560 const GVSummaryMapTy &DefinedGlobals) {
561 // Parse inline ASM and collect the list of symbols that are not defined in
562 // the current module.
563 StringSet<> AsmUndefinedRefs;
564 ModuleSymbolTable::CollectAsmSymbols(
565 Triple(TheModule.getTargetTriple()), TheModule.getModuleInlineAsm(),
566 [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) {
567 if (Flags & object::BasicSymbolRef::SF_Undefined)
568 AsmUndefinedRefs.insert(Name);
571 // Declare a callback for the internalize pass that will ask for every
572 // candidate GlobalValue if it can be internalized or not.
573 auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
574 // Can't be internalized if referenced in inline asm.
575 if (AsmUndefinedRefs.count(GV.getName()))
578 // Lookup the linkage recorded in the summaries during global analysis.
579 const auto &GS = DefinedGlobals.find(GV.getGUID());
580 GlobalValue::LinkageTypes Linkage;
581 if (GS == DefinedGlobals.end()) {
582 // Must have been promoted (possibly conservatively). Find original
583 // name so that we can access the correct summary and see if it can
584 // be internalized again.
585 // FIXME: Eventually we should control promotion instead of promoting
586 // and internalizing again.
588 ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
589 std::string OrigId = GlobalValue::getGlobalIdentifier(
590 OrigName, GlobalValue::InternalLinkage,
591 TheModule.getSourceFileName());
592 const auto &GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
593 if (GS == DefinedGlobals.end()) {
594 // Also check the original non-promoted non-globalized name. In some
595 // cases a preempted weak value is linked in as a local copy because
596 // it is referenced by an alias (IRLinker::linkGlobalValueProto).
597 // In that case, since it was originally not a local value, it was
598 // recorded in the index using the original name.
599 // FIXME: This may not be needed once PR27866 is fixed.
600 const auto &GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
601 assert(GS != DefinedGlobals.end());
602 Linkage = GS->second->linkage();
604 Linkage = GS->second->linkage();
607 Linkage = GS->second->linkage();
608 return !GlobalValue::isLocalLinkage(Linkage);
611 // FIXME: See if we can just internalize directly here via linkage changes
612 // based on the index, rather than invoking internalizeModule.
613 llvm::internalizeModule(TheModule, MustPreserveGV);
616 // Automatically import functions in Module \p DestModule based on the summaries
619 Expected<bool> FunctionImporter::importFunctions(
620 Module &DestModule, const FunctionImporter::ImportMapTy &ImportList,
621 bool ForceImportReferencedDiscardableSymbols) {
622 DEBUG(dbgs() << "Starting import for Module "
623 << DestModule.getModuleIdentifier() << "\n");
624 unsigned ImportedCount = 0;
626 // Linker that will be used for importing function
627 Linker TheLinker(DestModule);
628 // Do the actual import of functions now, one Module at a time
629 std::set<StringRef> ModuleNameOrderedList;
630 for (auto &FunctionsToImportPerModule : ImportList) {
631 ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
633 for (auto &Name : ModuleNameOrderedList) {
634 // Get the module for the import
635 const auto &FunctionsToImportPerModule = ImportList.find(Name);
636 assert(FunctionsToImportPerModule != ImportList.end());
637 Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
639 return SrcModuleOrErr.takeError();
640 std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
641 assert(&DestModule.getContext() == &SrcModule->getContext() &&
644 // If modules were created with lazy metadata loading, materialize it
645 // now, before linking it (otherwise this will be a noop).
646 if (Error Err = SrcModule->materializeMetadata())
647 return std::move(Err);
649 auto &ImportGUIDs = FunctionsToImportPerModule->second;
650 // Find the globals to import
651 DenseSet<const GlobalValue *> GlobalsToImport;
652 for (Function &F : *SrcModule) {
655 auto GUID = F.getGUID();
656 auto Import = ImportGUIDs.count(GUID);
657 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " << GUID
658 << " " << F.getName() << " from "
659 << SrcModule->getSourceFileName() << "\n");
661 if (Error Err = F.materialize())
662 return std::move(Err);
663 if (EnableImportMetadata) {
664 // Add 'thinlto_src_module' metadata for statistics and debugging.
666 "thinlto_src_module",
668 DestModule.getContext(),
669 {llvm::MDString::get(DestModule.getContext(),
670 SrcModule->getSourceFileName())}));
672 GlobalsToImport.insert(&F);
675 for (GlobalVariable &GV : SrcModule->globals()) {
678 auto GUID = GV.getGUID();
679 auto Import = ImportGUIDs.count(GUID);
680 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " << GUID
681 << " " << GV.getName() << " from "
682 << SrcModule->getSourceFileName() << "\n");
684 if (Error Err = GV.materialize())
685 return std::move(Err);
686 GlobalsToImport.insert(&GV);
689 for (GlobalAlias &GA : SrcModule->aliases()) {
692 auto GUID = GA.getGUID();
693 auto Import = ImportGUIDs.count(GUID);
694 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias " << GUID
695 << " " << GA.getName() << " from "
696 << SrcModule->getSourceFileName() << "\n");
698 // Alias can't point to "available_externally". However when we import
699 // linkOnceODR the linkage does not change. So we import the alias
700 // and aliasee only in this case. This has been handled by
701 // computeImportForFunction()
702 GlobalObject *GO = GA.getBaseObject();
703 assert(GO->hasLinkOnceODRLinkage() &&
704 "Unexpected alias to a non-linkonceODR in import list");
706 if (!GlobalsToImport.count(GO))
707 DEBUG(dbgs() << " alias triggers importing aliasee " << GO->getGUID()
708 << " " << GO->getName() << " from "
709 << SrcModule->getSourceFileName() << "\n");
711 if (Error Err = GO->materialize())
712 return std::move(Err);
713 GlobalsToImport.insert(GO);
714 if (Error Err = GA.materialize())
715 return std::move(Err);
716 GlobalsToImport.insert(&GA);
720 // Upgrade debug info after we're done materializing all the globals and we
721 // have loaded all the required metadata!
722 UpgradeDebugInfo(*SrcModule);
724 // Link in the specified functions.
725 if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
729 for (const auto *GV : GlobalsToImport)
730 dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
731 << " from " << SrcModule->getSourceFileName() << "\n";
734 // Instruct the linker that the client will take care of linkonce resolution
735 unsigned Flags = Linker::Flags::None;
736 if (!ForceImportReferencedDiscardableSymbols)
737 Flags |= Linker::Flags::DontForceLinkLinkonceODR;
739 if (TheLinker.linkInModule(std::move(SrcModule), Flags, &GlobalsToImport))
740 report_fatal_error("Function Import: link error");
742 ImportedCount += GlobalsToImport.size();
743 NumImportedModules++;
746 NumImportedFunctions += ImportedCount;
748 DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
749 << DestModule.getModuleIdentifier() << "\n");
750 return ImportedCount;
753 /// Summary file to use for function importing when using -function-import from
754 /// the command line.
755 static cl::opt<std::string>
756 SummaryFile("summary-file",
757 cl::desc("The summary file to use for function importing."));
759 static bool doImportingForModule(Module &M) {
760 if (SummaryFile.empty())
761 report_fatal_error("error: -function-import requires -summary-file\n");
762 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
763 getModuleSummaryIndexForFile(SummaryFile);
764 if (!IndexPtrOrErr) {
765 logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
766 "Error loading file '" + SummaryFile + "': ");
769 std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
771 // First step is collecting the import list.
772 FunctionImporter::ImportMapTy ImportList;
773 ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
776 // Conservatively mark all internal values as promoted. This interface is
777 // only used when doing importing via the function importing pass. The pass
778 // is only enabled when testing importing via the 'opt' tool, which does
779 // not do the ThinLink that would normally determine what values to promote.
780 for (auto &I : *Index) {
781 for (auto &S : I.second) {
782 if (GlobalValue::isLocalLinkage(S->linkage()))
783 S->setLinkage(GlobalValue::ExternalLinkage);
787 // Next we need to promote to global scope and rename any local values that
788 // are potentially exported to other modules.
789 if (renameModuleForThinLTO(M, *Index, nullptr)) {
790 errs() << "Error renaming module\n";
794 // Perform the import now.
795 auto ModuleLoader = [&M](StringRef Identifier) {
796 return loadFile(Identifier, M.getContext());
798 FunctionImporter Importer(*Index, ModuleLoader);
799 Expected<bool> Result = Importer.importFunctions(
800 M, ImportList, !DontForceImportReferencedDiscardableSymbols);
802 // FIXME: Probably need to propagate Errors through the pass manager.
804 logAllUnhandledErrors(Result.takeError(), errs(),
805 "Error importing module: ");
813 /// Pass that performs cross-module function import provided a summary file.
814 class FunctionImportLegacyPass : public ModulePass {
816 /// Pass identification, replacement for typeid
819 /// Specify pass name for debug output
820 StringRef getPassName() const override { return "Function Importing"; }
822 explicit FunctionImportLegacyPass() : ModulePass(ID) {}
824 bool runOnModule(Module &M) override {
828 return doImportingForModule(M);
831 } // anonymous namespace
833 PreservedAnalyses FunctionImportPass::run(Module &M,
834 ModuleAnalysisManager &AM) {
835 if (!doImportingForModule(M))
836 return PreservedAnalyses::all();
838 return PreservedAnalyses::none();
841 char FunctionImportLegacyPass::ID = 0;
842 INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
843 "Summary Based Function Import", false, false)
846 Pass *createFunctionImportPass() {
847 return new FunctionImportLegacyPass();