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/Bitcode/BitcodeReader.h"
21 #include "llvm/IR/AutoUpgrade.h"
22 #include "llvm/IR/DiagnosticPrinter.h"
23 #include "llvm/IR/IntrinsicInst.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/IR/Verifier.h"
26 #include "llvm/IRReader/IRReader.h"
27 #include "llvm/Linker/Linker.h"
28 #include "llvm/Object/IRObjectFile.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 static cl::opt<bool> EnableImportMetadata(
79 "enable-import-metadata", cl::init(
81 true /*Enabled with asserts.*/
86 cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'"));
88 // Load lazily a module from \p FileName in \p Context.
89 static std::unique_ptr<Module> loadFile(const std::string &FileName,
90 LLVMContext &Context) {
92 DEBUG(dbgs() << "Loading '" << FileName << "'\n");
93 // Metadata isn't loaded until functions are imported, to minimize
94 // the memory overhead.
95 std::unique_ptr<Module> Result =
96 getLazyIRFileModule(FileName, Err, Context,
97 /* ShouldLazyLoadMetadata = */ true);
99 Err.print("function-import", errs());
100 report_fatal_error("Abort");
108 /// Given a list of possible callee implementation for a call site, select one
109 /// that fits the \p Threshold.
111 /// FIXME: select "best" instead of first that fits. But what is "best"?
112 /// - The smallest: more likely to be inlined.
113 /// - The one with the least outgoing edges (already well optimized).
114 /// - One from a module already being imported from in order to reduce the
115 /// number of source modules parsed/linked.
116 /// - One that has PGO data attached.
117 /// - [insert you fancy metric here]
118 static const GlobalValueSummary *
119 selectCallee(const ModuleSummaryIndex &Index,
120 ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
121 unsigned Threshold, StringRef CallerModulePath) {
122 auto It = llvm::find_if(
124 [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
125 auto *GVSummary = SummaryPtr.get();
126 if (GlobalValue::isInterposableLinkage(GVSummary->linkage()))
127 // There is no point in importing these, we can't inline them
129 if (auto *AS = dyn_cast<AliasSummary>(GVSummary)) {
130 GVSummary = &AS->getAliasee();
131 // Alias can't point to "available_externally". However when we import
132 // linkOnceODR the linkage does not change. So we import the alias
133 // and aliasee only in this case.
134 // FIXME: we should import alias as available_externally *function*,
135 // the destination module does need to know it is an alias.
136 if (!GlobalValue::isLinkOnceODRLinkage(GVSummary->linkage()))
140 auto *Summary = cast<FunctionSummary>(GVSummary);
142 // If this is a local function, make sure we import the copy
143 // in the caller's module. The only time a local function can
144 // share an entry in the index is if there is a local with the same name
145 // in another module that had the same source file name (in a different
146 // directory), where each was compiled in their own directory so there
147 // was not distinguishing path.
148 // However, do the import from another module if there is only one
149 // entry in the list - in that case this must be a reference due
150 // to indirect call profile data, since a function pointer can point to
151 // a local in another module.
152 if (GlobalValue::isLocalLinkage(Summary->linkage()) &&
153 CalleeSummaryList.size() > 1 &&
154 Summary->modulePath() != CallerModulePath)
157 if (Summary->instCount() > Threshold)
160 if (Summary->notEligibleToImport())
165 if (It == CalleeSummaryList.end())
168 return cast<GlobalValueSummary>(It->get());
171 using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */,
174 /// Compute the list of functions to import for a given caller. Mark these
175 /// imported functions and the symbols they reference in their source module as
176 /// exported from their source module.
177 static void computeImportForFunction(
178 const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
179 const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
180 SmallVectorImpl<EdgeInfo> &Worklist,
181 FunctionImporter::ImportMapTy &ImportList,
182 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
183 for (auto &Edge : Summary.calls()) {
184 ValueInfo VI = Edge.first;
185 DEBUG(dbgs() << " edge -> " << VI.getGUID() << " Threshold:" << Threshold
188 if (VI.getSummaryList().empty()) {
189 // For SamplePGO, the indirect call targets for local functions will
190 // have its original name annotated in profile. We try to find the
191 // corresponding PGOFuncName as the GUID.
192 auto GUID = Index.getGUIDFromOriginalID(VI.getGUID());
195 VI = Index.getValueInfo(GUID);
200 if (DefinedGVSummaries.count(VI.getGUID())) {
201 DEBUG(dbgs() << "ignored! Target already in destination module.\n");
205 auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
206 if (Hotness == CalleeInfo::HotnessType::Hot)
207 return ImportHotMultiplier;
208 if (Hotness == CalleeInfo::HotnessType::Cold)
209 return ImportColdMultiplier;
213 const auto NewThreshold =
214 Threshold * GetBonusMultiplier(Edge.second.Hotness);
216 auto *CalleeSummary = selectCallee(Index, VI.getSummaryList(), NewThreshold,
217 Summary.modulePath());
218 if (!CalleeSummary) {
219 DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n");
222 // "Resolve" the summary, traversing alias,
223 const FunctionSummary *ResolvedCalleeSummary;
224 if (isa<AliasSummary>(CalleeSummary)) {
225 ResolvedCalleeSummary = cast<FunctionSummary>(
226 &cast<AliasSummary>(CalleeSummary)->getAliasee());
228 GlobalValue::isLinkOnceODRLinkage(ResolvedCalleeSummary->linkage()) &&
229 "Unexpected alias to a non-linkonceODR in import list");
231 ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
233 assert(ResolvedCalleeSummary->instCount() <= NewThreshold &&
234 "selectCallee() didn't honor the threshold");
236 auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
237 // Adjust the threshold for next level of imported functions.
238 // The threshold is different for hot callsites because we can then
239 // inline chains of hot calls.
241 return Threshold * ImportHotInstrFactor;
242 return Threshold * ImportInstrFactor;
245 bool IsHotCallsite = Edge.second.Hotness == CalleeInfo::HotnessType::Hot;
246 const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
248 auto ExportModulePath = ResolvedCalleeSummary->modulePath();
249 auto &ProcessedThreshold = ImportList[ExportModulePath][VI.getGUID()];
250 /// Since the traversal of the call graph is DFS, we can revisit a function
251 /// a second time with a higher threshold. In this case, it is added back to
252 /// the worklist with the new threshold.
253 if (ProcessedThreshold && ProcessedThreshold >= AdjThreshold) {
254 DEBUG(dbgs() << "ignored! Target was already seen with Threshold "
255 << ProcessedThreshold << "\n");
258 bool PreviouslyImported = ProcessedThreshold != 0;
259 // Mark this function as imported in this module, with the current Threshold
260 ProcessedThreshold = AdjThreshold;
262 // Make exports in the source module.
264 auto &ExportList = (*ExportLists)[ExportModulePath];
265 ExportList.insert(VI.getGUID());
266 if (!PreviouslyImported) {
267 // This is the first time this function was exported from its source
268 // module, so mark all functions and globals it references as exported
269 // to the outside if they are defined in the same source module.
270 // For efficiency, we unconditionally add all the referenced GUIDs
271 // to the ExportList for this module, and will prune out any not
272 // defined in the module later in a single pass.
273 for (auto &Edge : ResolvedCalleeSummary->calls()) {
274 auto CalleeGUID = Edge.first.getGUID();
275 ExportList.insert(CalleeGUID);
277 for (auto &Ref : ResolvedCalleeSummary->refs()) {
278 auto GUID = Ref.getGUID();
279 ExportList.insert(GUID);
284 // Insert the newly imported function to the worklist.
285 Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, VI.getGUID());
289 /// Given the list of globals defined in a module, compute the list of imports
290 /// as well as the list of "exports", i.e. the list of symbols referenced from
291 /// another module (that may require promotion).
292 static void ComputeImportForModule(
293 const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
294 FunctionImporter::ImportMapTy &ImportList,
295 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
296 // Worklist contains the list of function imported in this module, for which
297 // we will analyse the callees and may import further down the callgraph.
298 SmallVector<EdgeInfo, 128> Worklist;
300 // Populate the worklist with the import for the functions in the current
302 for (auto &GVSummary : DefinedGVSummaries) {
303 if (!Index.isGlobalValueLive(GVSummary.second)) {
304 DEBUG(dbgs() << "Ignores Dead GUID: " << GVSummary.first << "\n");
307 auto *Summary = GVSummary.second;
308 if (auto *AS = dyn_cast<AliasSummary>(Summary))
309 Summary = &AS->getAliasee();
310 auto *FuncSummary = dyn_cast<FunctionSummary>(Summary);
312 // Skip import for global variables
314 DEBUG(dbgs() << "Initalize import for " << GVSummary.first << "\n");
315 computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
316 DefinedGVSummaries, Worklist, ImportList,
320 // Process the newly imported functions and add callees to the worklist.
321 while (!Worklist.empty()) {
322 auto FuncInfo = Worklist.pop_back_val();
323 auto *Summary = std::get<0>(FuncInfo);
324 auto Threshold = std::get<1>(FuncInfo);
325 auto GUID = std::get<2>(FuncInfo);
327 // Check if we later added this summary with a higher threshold.
328 // If so, skip this entry.
329 auto ExportModulePath = Summary->modulePath();
330 auto &LatestProcessedThreshold = ImportList[ExportModulePath][GUID];
331 if (LatestProcessedThreshold > Threshold)
334 computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
335 Worklist, ImportList, ExportLists);
339 } // anonymous namespace
341 /// Compute all the import and export for every module using the Index.
342 void llvm::ComputeCrossModuleImport(
343 const ModuleSummaryIndex &Index,
344 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
345 StringMap<FunctionImporter::ImportMapTy> &ImportLists,
346 StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
347 // For each module that has function defined, compute the import/export lists.
348 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
349 auto &ImportList = ImportLists[DefinedGVSummaries.first()];
350 DEBUG(dbgs() << "Computing import for Module '"
351 << DefinedGVSummaries.first() << "'\n");
352 ComputeImportForModule(DefinedGVSummaries.second, Index, ImportList,
356 // When computing imports we added all GUIDs referenced by anything
357 // imported from the module to its ExportList. Now we prune each ExportList
358 // of any not defined in that module. This is more efficient than checking
359 // while computing imports because some of the summary lists may be long
360 // due to linkonce (comdat) copies.
361 for (auto &ELI : ExportLists) {
362 const auto &DefinedGVSummaries =
363 ModuleToDefinedGVSummaries.lookup(ELI.first());
364 for (auto EI = ELI.second.begin(); EI != ELI.second.end();) {
365 if (!DefinedGVSummaries.count(*EI))
366 EI = ELI.second.erase(EI);
373 DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
375 for (auto &ModuleImports : ImportLists) {
376 auto ModName = ModuleImports.first();
377 auto &Exports = ExportLists[ModName];
378 DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size()
379 << " functions. Imports from " << ModuleImports.second.size()
381 for (auto &Src : ModuleImports.second) {
382 auto SrcModName = Src.first();
383 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
384 << SrcModName << "\n");
390 /// Compute all the imports for the given module in the Index.
391 void llvm::ComputeCrossModuleImportForModule(
392 StringRef ModulePath, const ModuleSummaryIndex &Index,
393 FunctionImporter::ImportMapTy &ImportList) {
395 // Collect the list of functions this module defines.
397 GVSummaryMapTy FunctionSummaryMap;
398 Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
400 // Compute the import list for this module.
401 DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
402 ComputeImportForModule(FunctionSummaryMap, Index, ImportList);
405 DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
406 << ImportList.size() << " modules.\n");
407 for (auto &Src : ImportList) {
408 auto SrcModName = Src.first();
409 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
410 << SrcModName << "\n");
415 void llvm::computeDeadSymbols(
416 ModuleSummaryIndex &Index,
417 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
418 assert(!Index.withGlobalValueDeadStripping());
421 if (GUIDPreservedSymbols.empty())
422 // Don't do anything when nothing is live, this is friendly with tests.
424 unsigned LiveSymbols = 0;
425 SmallVector<ValueInfo, 128> Worklist;
426 Worklist.reserve(GUIDPreservedSymbols.size() * 2);
427 for (auto GUID : GUIDPreservedSymbols) {
428 ValueInfo VI = Index.getValueInfo(GUID);
431 for (auto &S : VI.getSummaryList())
435 // Add values flagged in the index as live roots to the worklist.
436 for (const auto &Entry : Index)
437 for (auto &S : Entry.second.SummaryList)
439 DEBUG(dbgs() << "Live root: " << Entry.first << "\n");
440 Worklist.push_back(ValueInfo(&Entry));
445 // Make value live and add it to the worklist if it was not live before.
446 // FIXME: we should only make the prevailing copy live here
447 auto visit = [&](ValueInfo VI) {
448 for (auto &S : VI.getSummaryList())
451 for (auto &S : VI.getSummaryList())
454 Worklist.push_back(VI);
457 while (!Worklist.empty()) {
458 auto VI = Worklist.pop_back_val();
459 for (auto &Summary : VI.getSummaryList()) {
460 for (auto Ref : Summary->refs())
462 if (auto *FS = dyn_cast<FunctionSummary>(Summary.get()))
463 for (auto Call : FS->calls())
465 if (auto *AS = dyn_cast<AliasSummary>(Summary.get())) {
466 auto AliaseeGUID = AS->getAliasee().getOriginalName();
467 ValueInfo AliaseeVI = Index.getValueInfo(AliaseeGUID);
473 Index.setWithGlobalValueDeadStripping();
475 unsigned DeadSymbols = Index.size() - LiveSymbols;
476 DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols
477 << " symbols Dead \n");
478 NumDeadSymbols += DeadSymbols;
479 NumLiveSymbols += LiveSymbols;
482 /// Compute the set of summaries needed for a ThinLTO backend compilation of
484 void llvm::gatherImportedSummariesForModule(
485 StringRef ModulePath,
486 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
487 const FunctionImporter::ImportMapTy &ImportList,
488 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
489 // Include all summaries from the importing module.
490 ModuleToSummariesForIndex[ModulePath] =
491 ModuleToDefinedGVSummaries.lookup(ModulePath);
492 // Include summaries for imports.
493 for (auto &ILI : ImportList) {
494 auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
495 const auto &DefinedGVSummaries =
496 ModuleToDefinedGVSummaries.lookup(ILI.first());
497 for (auto &GI : ILI.second) {
498 const auto &DS = DefinedGVSummaries.find(GI.first);
499 assert(DS != DefinedGVSummaries.end() &&
500 "Expected a defined summary for imported global value");
501 SummariesForIndex[GI.first] = DS->second;
506 /// Emit the files \p ModulePath will import from into \p OutputFilename.
508 llvm::EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename,
509 const FunctionImporter::ImportMapTy &ModuleImports) {
511 raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
514 for (auto &ILI : ModuleImports)
515 ImportsOS << ILI.first() << "\n";
516 return std::error_code();
519 /// Fixup WeakForLinker linkages in \p TheModule based on summary analysis.
520 void llvm::thinLTOResolveWeakForLinkerModule(
521 Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
522 auto ConvertToDeclaration = [](GlobalValue &GV) {
523 DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName() << "\n");
524 if (Function *F = dyn_cast<Function>(&GV)) {
527 } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
528 V->setInitializer(nullptr);
529 V->setLinkage(GlobalValue::ExternalLinkage);
532 // For now we don't resolve or drop aliases. Once we do we'll
533 // need to add support here for creating either a function or
534 // variable declaration, and return the new GlobalValue* for
535 // the caller to use.
536 llvm_unreachable("Expected function or variable");
539 auto updateLinkage = [&](GlobalValue &GV) {
540 if (!GlobalValue::isWeakForLinker(GV.getLinkage()))
542 // See if the global summary analysis computed a new resolved linkage.
543 const auto &GS = DefinedGlobals.find(GV.getGUID());
544 if (GS == DefinedGlobals.end())
546 auto NewLinkage = GS->second->linkage();
547 if (NewLinkage == GV.getLinkage())
549 // Check for a non-prevailing def that has interposable linkage
550 // (e.g. non-odr weak or linkonce). In that case we can't simply
551 // convert to available_externally, since it would lose the
552 // interposable property and possibly get inlined. Simply drop
553 // the definition in that case.
554 if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) &&
555 GlobalValue::isInterposableLinkage(GV.getLinkage()))
556 ConvertToDeclaration(GV);
558 DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
559 << GV.getLinkage() << " to " << NewLinkage << "\n");
560 GV.setLinkage(NewLinkage);
562 // Remove declarations from comdats, including available_externally
563 // as this is a declaration for the linker, and will be dropped eventually.
564 // It is illegal for comdats to contain declarations.
565 auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
566 if (GO && GO->isDeclarationForLinker() && GO->hasComdat())
567 GO->setComdat(nullptr);
570 // Process functions and global now
571 for (auto &GV : TheModule)
573 for (auto &GV : TheModule.globals())
575 for (auto &GV : TheModule.aliases())
579 /// Run internalization on \p TheModule based on symmary analysis.
580 void llvm::thinLTOInternalizeModule(Module &TheModule,
581 const GVSummaryMapTy &DefinedGlobals) {
582 // Parse inline ASM and collect the list of symbols that are not defined in
583 // the current module.
584 StringSet<> AsmUndefinedRefs;
585 ModuleSymbolTable::CollectAsmSymbols(
587 [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) {
588 if (Flags & object::BasicSymbolRef::SF_Undefined)
589 AsmUndefinedRefs.insert(Name);
592 // Declare a callback for the internalize pass that will ask for every
593 // candidate GlobalValue if it can be internalized or not.
594 auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
595 // Can't be internalized if referenced in inline asm.
596 if (AsmUndefinedRefs.count(GV.getName()))
599 // Lookup the linkage recorded in the summaries during global analysis.
600 auto GS = DefinedGlobals.find(GV.getGUID());
601 if (GS == DefinedGlobals.end()) {
602 // Must have been promoted (possibly conservatively). Find original
603 // name so that we can access the correct summary and see if it can
604 // be internalized again.
605 // FIXME: Eventually we should control promotion instead of promoting
606 // and internalizing again.
608 ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
609 std::string OrigId = GlobalValue::getGlobalIdentifier(
610 OrigName, GlobalValue::InternalLinkage,
611 TheModule.getSourceFileName());
612 GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
613 if (GS == DefinedGlobals.end()) {
614 // Also check the original non-promoted non-globalized name. In some
615 // cases a preempted weak value is linked in as a local copy because
616 // it is referenced by an alias (IRLinker::linkGlobalValueProto).
617 // In that case, since it was originally not a local value, it was
618 // recorded in the index using the original name.
619 // FIXME: This may not be needed once PR27866 is fixed.
620 GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
621 assert(GS != DefinedGlobals.end());
624 return !GlobalValue::isLocalLinkage(GS->second->linkage());
627 // FIXME: See if we can just internalize directly here via linkage changes
628 // based on the index, rather than invoking internalizeModule.
629 llvm::internalizeModule(TheModule, MustPreserveGV);
632 // Automatically import functions in Module \p DestModule based on the summaries
635 Expected<bool> FunctionImporter::importFunctions(
636 Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
637 DEBUG(dbgs() << "Starting import for Module "
638 << DestModule.getModuleIdentifier() << "\n");
639 unsigned ImportedCount = 0;
641 IRMover Mover(DestModule);
642 // Do the actual import of functions now, one Module at a time
643 std::set<StringRef> ModuleNameOrderedList;
644 for (auto &FunctionsToImportPerModule : ImportList) {
645 ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
647 for (auto &Name : ModuleNameOrderedList) {
648 // Get the module for the import
649 const auto &FunctionsToImportPerModule = ImportList.find(Name);
650 assert(FunctionsToImportPerModule != ImportList.end());
651 Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
653 return SrcModuleOrErr.takeError();
654 std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
655 assert(&DestModule.getContext() == &SrcModule->getContext() &&
658 // If modules were created with lazy metadata loading, materialize it
659 // now, before linking it (otherwise this will be a noop).
660 if (Error Err = SrcModule->materializeMetadata())
661 return std::move(Err);
663 auto &ImportGUIDs = FunctionsToImportPerModule->second;
664 // Find the globals to import
665 SetVector<GlobalValue *> GlobalsToImport;
666 for (Function &F : *SrcModule) {
669 auto GUID = F.getGUID();
670 auto Import = ImportGUIDs.count(GUID);
671 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " << GUID
672 << " " << F.getName() << " from "
673 << SrcModule->getSourceFileName() << "\n");
675 if (Error Err = F.materialize())
676 return std::move(Err);
677 if (EnableImportMetadata) {
678 // Add 'thinlto_src_module' metadata for statistics and debugging.
680 "thinlto_src_module",
682 DestModule.getContext(),
683 {llvm::MDString::get(DestModule.getContext(),
684 SrcModule->getSourceFileName())}));
686 GlobalsToImport.insert(&F);
689 for (GlobalVariable &GV : SrcModule->globals()) {
692 auto GUID = GV.getGUID();
693 auto Import = ImportGUIDs.count(GUID);
694 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " << GUID
695 << " " << GV.getName() << " from "
696 << SrcModule->getSourceFileName() << "\n");
698 if (Error Err = GV.materialize())
699 return std::move(Err);
700 GlobalsToImport.insert(&GV);
703 for (GlobalAlias &GA : SrcModule->aliases()) {
704 // FIXME: This should eventually be controlled entirely by the summary.
705 if (FunctionImportGlobalProcessing::doImportAsDefinition(
706 &GA, &GlobalsToImport)) {
707 GlobalsToImport.insert(&GA);
713 auto GUID = GA.getGUID();
714 auto Import = ImportGUIDs.count(GUID);
715 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias " << GUID
716 << " " << GA.getName() << " from "
717 << SrcModule->getSourceFileName() << "\n");
719 // Alias can't point to "available_externally". However when we import
720 // linkOnceODR the linkage does not change. So we import the alias
721 // and aliasee only in this case. This has been handled by
722 // computeImportForFunction()
723 GlobalObject *GO = GA.getBaseObject();
724 assert(GO->hasLinkOnceODRLinkage() &&
725 "Unexpected alias to a non-linkonceODR in import list");
727 if (!GlobalsToImport.count(GO))
728 DEBUG(dbgs() << " alias triggers importing aliasee " << GO->getGUID()
729 << " " << GO->getName() << " from "
730 << SrcModule->getSourceFileName() << "\n");
732 if (Error Err = GO->materialize())
733 return std::move(Err);
734 GlobalsToImport.insert(GO);
735 if (Error Err = GA.materialize())
736 return std::move(Err);
737 GlobalsToImport.insert(&GA);
741 // Upgrade debug info after we're done materializing all the globals and we
742 // have loaded all the required metadata!
743 UpgradeDebugInfo(*SrcModule);
745 // Link in the specified functions.
746 if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
750 for (const auto *GV : GlobalsToImport)
751 dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
752 << " from " << SrcModule->getSourceFileName() << "\n";
755 if (Mover.move(std::move(SrcModule), GlobalsToImport.getArrayRef(),
756 [](GlobalValue &, IRMover::ValueAdder) {},
757 /*IsPerformingImport=*/true))
758 report_fatal_error("Function Import: link error");
760 ImportedCount += GlobalsToImport.size();
761 NumImportedModules++;
764 NumImportedFunctions += ImportedCount;
766 DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
767 << DestModule.getModuleIdentifier() << "\n");
768 return ImportedCount;
771 /// Summary file to use for function importing when using -function-import from
772 /// the command line.
773 static cl::opt<std::string>
774 SummaryFile("summary-file",
775 cl::desc("The summary file to use for function importing."));
777 static bool doImportingForModule(Module &M) {
778 if (SummaryFile.empty())
779 report_fatal_error("error: -function-import requires -summary-file\n");
780 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
781 getModuleSummaryIndexForFile(SummaryFile);
782 if (!IndexPtrOrErr) {
783 logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
784 "Error loading file '" + SummaryFile + "': ");
787 std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
789 // First step is collecting the import list.
790 FunctionImporter::ImportMapTy ImportList;
791 ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
794 // Conservatively mark all internal values as promoted. This interface is
795 // only used when doing importing via the function importing pass. The pass
796 // is only enabled when testing importing via the 'opt' tool, which does
797 // not do the ThinLink that would normally determine what values to promote.
798 for (auto &I : *Index) {
799 for (auto &S : I.second.SummaryList) {
800 if (GlobalValue::isLocalLinkage(S->linkage()))
801 S->setLinkage(GlobalValue::ExternalLinkage);
805 // Next we need to promote to global scope and rename any local values that
806 // are potentially exported to other modules.
807 if (renameModuleForThinLTO(M, *Index, nullptr)) {
808 errs() << "Error renaming module\n";
812 // Perform the import now.
813 auto ModuleLoader = [&M](StringRef Identifier) {
814 return loadFile(Identifier, M.getContext());
816 FunctionImporter Importer(*Index, ModuleLoader);
817 Expected<bool> Result = Importer.importFunctions(M, ImportList);
819 // FIXME: Probably need to propagate Errors through the pass manager.
821 logAllUnhandledErrors(Result.takeError(), errs(),
822 "Error importing module: ");
830 /// Pass that performs cross-module function import provided a summary file.
831 class FunctionImportLegacyPass : public ModulePass {
833 /// Pass identification, replacement for typeid
836 /// Specify pass name for debug output
837 StringRef getPassName() const override { return "Function Importing"; }
839 explicit FunctionImportLegacyPass() : ModulePass(ID) {}
841 bool runOnModule(Module &M) override {
845 return doImportingForModule(M);
848 } // anonymous namespace
850 PreservedAnalyses FunctionImportPass::run(Module &M,
851 ModuleAnalysisManager &AM) {
852 if (!doImportingForModule(M))
853 return PreservedAnalyses::all();
855 return PreservedAnalyses::none();
858 char FunctionImportLegacyPass::ID = 0;
859 INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
860 "Summary Based Function Import", false, false)
863 Pass *createFunctionImportPass() {
864 return new FunctionImportLegacyPass();