1 //===- FunctionImport.cpp - ThinLTO Summary-based Function Import ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements Function import based on summaries.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/IPO/FunctionImport.h"
15 
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"
34 
35 #define DEBUG_TYPE "function-import"
36 
37 using namespace llvm;
38 
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");
43 
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"));
48 
49 static cl::opt<float>
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"));
55 
56 static cl::opt<float> ImportHotInstrFactor(
57     "import-hot-evolution-factor", cl::init(1.0), cl::Hidden,
58     cl::value_desc("x"),
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"));
62 
63 static cl::opt<float> ImportHotMultiplier(
64     "import-hot-multiplier", cl::init(10.0), cl::Hidden, cl::value_desc("x"),
65     cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"));
66 
67 static cl::opt<float> ImportCriticalMultiplier(
68     "import-critical-multiplier", cl::init(100.0), cl::Hidden,
69     cl::value_desc("x"),
70     cl::desc(
71         "Multiply the `import-instr-limit` threshold for critical callsites"));
72 
73 // FIXME: This multiplier was not really tuned up.
74 static cl::opt<float> ImportColdMultiplier(
75     "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"),
76     cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"));
77 
78 static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
79                                   cl::desc("Print imported functions"));
80 
81 static cl::opt<bool> ComputeDead("compute-dead", cl::init(true), cl::Hidden,
82                                  cl::desc("Compute dead symbols"));
83 
84 static cl::opt<bool> EnableImportMetadata(
85     "enable-import-metadata", cl::init(
86 #if !defined(NDEBUG)
87                                   true /*Enabled with asserts.*/
88 #else
89                                   false
90 #endif
91                                   ),
92     cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'"));
93 
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) {
97   SMDiagnostic Err;
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);
104   if (!Result) {
105     Err.print("function-import", errs());
106     report_fatal_error("Abort");
107   }
108 
109   return Result;
110 }
111 
112 namespace {
113 
114 /// Given a list of possible callee implementation for a call site, select one
115 /// that fits the \p Threshold.
116 ///
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              ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
127              unsigned Threshold, StringRef CallerModulePath) {
128   auto It = llvm::find_if(
129       CalleeSummaryList,
130       [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
131         auto *GVSummary = SummaryPtr.get();
132         // For SamplePGO, in computeImportForFunction the OriginalId
133         // may have been used to locate the callee summary list (See
134         // comment there).
135         // The mapping from OriginalId to GUID may return a GUID
136         // that corresponds to a static variable. Filter it out here.
137         // This can happen when
138         // 1) There is a call to a library function which is not defined
139         // in the index.
140         // 2) There is a static variable with the  OriginalGUID identical
141         // to the GUID of the library function in 1);
142         // When this happens, the logic for SamplePGO kicks in and
143         // the static variable in 2) will be found, which needs to be
144         // filtered out.
145         if (GVSummary->getSummaryKind() == GlobalValueSummary::GlobalVarKind)
146           return false;
147         if (GlobalValue::isInterposableLinkage(GVSummary->linkage()))
148           // There is no point in importing these, we can't inline them
149           return false;
150         if (isa<AliasSummary>(GVSummary))
151           // Aliases can't point to "available_externally".
152           // FIXME: we should import alias as available_externally *function*,
153           // the destination module does not need to know it is an alias.
154           return false;
155 
156         auto *Summary = cast<FunctionSummary>(GVSummary);
157 
158         // If this is a local function, make sure we import the copy
159         // in the caller's module. The only time a local function can
160         // share an entry in the index is if there is a local with the same name
161         // in another module that had the same source file name (in a different
162         // directory), where each was compiled in their own directory so there
163         // was not distinguishing path.
164         // However, do the import from another module if there is only one
165         // entry in the list - in that case this must be a reference due
166         // to indirect call profile data, since a function pointer can point to
167         // a local in another module.
168         if (GlobalValue::isLocalLinkage(Summary->linkage()) &&
169             CalleeSummaryList.size() > 1 &&
170             Summary->modulePath() != CallerModulePath)
171           return false;
172 
173         if (Summary->instCount() > Threshold)
174           return false;
175 
176         if (Summary->notEligibleToImport())
177           return false;
178 
179         return true;
180       });
181   if (It == CalleeSummaryList.end())
182     return nullptr;
183 
184   return cast<GlobalValueSummary>(It->get());
185 }
186 
187 using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */,
188                             GlobalValue::GUID>;
189 
190 static ValueInfo
191 updateValueInfoForIndirectCalls(const ModuleSummaryIndex &Index, ValueInfo VI) {
192   if (!VI.getSummaryList().empty())
193     return VI;
194   // For SamplePGO, the indirect call targets for local functions will
195   // have its original name annotated in profile. We try to find the
196   // corresponding PGOFuncName as the GUID.
197   // FIXME: Consider updating the edges in the graph after building
198   // it, rather than needing to perform this mapping on each walk.
199   auto GUID = Index.getGUIDFromOriginalID(VI.getGUID());
200   if (GUID == 0)
201     return nullptr;
202   return Index.getValueInfo(GUID);
203 }
204 
205 /// Compute the list of functions to import for a given caller. Mark these
206 /// imported functions and the symbols they reference in their source module as
207 /// exported from their source module.
208 static void computeImportForFunction(
209     const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
210     const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
211     SmallVectorImpl<EdgeInfo> &Worklist,
212     FunctionImporter::ImportMapTy &ImportList,
213     StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
214   for (auto &Edge : Summary.calls()) {
215     ValueInfo VI = Edge.first;
216     DEBUG(dbgs() << " edge -> " << VI.getGUID() << " Threshold:" << Threshold
217                  << "\n");
218 
219     VI = updateValueInfoForIndirectCalls(Index, VI);
220     if (!VI)
221       continue;
222 
223     if (DefinedGVSummaries.count(VI.getGUID())) {
224       DEBUG(dbgs() << "ignored! Target already in destination module.\n");
225       continue;
226     }
227 
228     auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
229       if (Hotness == CalleeInfo::HotnessType::Hot)
230         return ImportHotMultiplier;
231       if (Hotness == CalleeInfo::HotnessType::Cold)
232         return ImportColdMultiplier;
233       if (Hotness == CalleeInfo::HotnessType::Critical)
234         return ImportCriticalMultiplier;
235       return 1.0;
236     };
237 
238     const auto NewThreshold =
239         Threshold * GetBonusMultiplier(Edge.second.Hotness);
240 
241     auto *CalleeSummary = selectCallee(Index, VI.getSummaryList(), NewThreshold,
242                                        Summary.modulePath());
243     if (!CalleeSummary) {
244       DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n");
245       continue;
246     }
247 
248     // "Resolve" the summary
249     assert(!isa<AliasSummary>(CalleeSummary) &&
250            "Unexpected alias in import list");
251     const auto *ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
252 
253     assert(ResolvedCalleeSummary->instCount() <= NewThreshold &&
254            "selectCallee() didn't honor the threshold");
255 
256     auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
257       // Adjust the threshold for next level of imported functions.
258       // The threshold is different for hot callsites because we can then
259       // inline chains of hot calls.
260       if (IsHotCallsite)
261         return Threshold * ImportHotInstrFactor;
262       return Threshold * ImportInstrFactor;
263     };
264 
265     bool IsHotCallsite = Edge.second.Hotness == CalleeInfo::HotnessType::Hot;
266     const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
267 
268     auto ExportModulePath = ResolvedCalleeSummary->modulePath();
269     auto &ProcessedThreshold = ImportList[ExportModulePath][VI.getGUID()];
270     /// Since the traversal of the call graph is DFS, we can revisit a function
271     /// a second time with a higher threshold. In this case, it is added back to
272     /// the worklist with the new threshold.
273     if (ProcessedThreshold && ProcessedThreshold >= AdjThreshold) {
274       DEBUG(dbgs() << "ignored! Target was already seen with Threshold "
275                    << ProcessedThreshold << "\n");
276       continue;
277     }
278     bool PreviouslyImported = ProcessedThreshold != 0;
279     // Mark this function as imported in this module, with the current Threshold
280     ProcessedThreshold = AdjThreshold;
281 
282     // Make exports in the source module.
283     if (ExportLists) {
284       auto &ExportList = (*ExportLists)[ExportModulePath];
285       ExportList.insert(VI.getGUID());
286       if (!PreviouslyImported) {
287         // This is the first time this function was exported from its source
288         // module, so mark all functions and globals it references as exported
289         // to the outside if they are defined in the same source module.
290         // For efficiency, we unconditionally add all the referenced GUIDs
291         // to the ExportList for this module, and will prune out any not
292         // defined in the module later in a single pass.
293         for (auto &Edge : ResolvedCalleeSummary->calls()) {
294           auto CalleeGUID = Edge.first.getGUID();
295           ExportList.insert(CalleeGUID);
296         }
297         for (auto &Ref : ResolvedCalleeSummary->refs()) {
298           auto GUID = Ref.getGUID();
299           ExportList.insert(GUID);
300         }
301       }
302     }
303 
304     // Insert the newly imported function to the worklist.
305     Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, VI.getGUID());
306   }
307 }
308 
309 /// Given the list of globals defined in a module, compute the list of imports
310 /// as well as the list of "exports", i.e. the list of symbols referenced from
311 /// another module (that may require promotion).
312 static void ComputeImportForModule(
313     const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
314     FunctionImporter::ImportMapTy &ImportList,
315     StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
316   // Worklist contains the list of function imported in this module, for which
317   // we will analyse the callees and may import further down the callgraph.
318   SmallVector<EdgeInfo, 128> Worklist;
319 
320   // Populate the worklist with the import for the functions in the current
321   // module
322   for (auto &GVSummary : DefinedGVSummaries) {
323     if (!Index.isGlobalValueLive(GVSummary.second)) {
324       DEBUG(dbgs() << "Ignores Dead GUID: " << GVSummary.first << "\n");
325       continue;
326     }
327     auto *FuncSummary =
328         dyn_cast<FunctionSummary>(GVSummary.second->getBaseObject());
329     if (!FuncSummary)
330       // Skip import for global variables
331       continue;
332     DEBUG(dbgs() << "Initialize import for " << GVSummary.first << "\n");
333     computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
334                              DefinedGVSummaries, Worklist, ImportList,
335                              ExportLists);
336   }
337 
338   // Process the newly imported functions and add callees to the worklist.
339   while (!Worklist.empty()) {
340     auto FuncInfo = Worklist.pop_back_val();
341     auto *Summary = std::get<0>(FuncInfo);
342     auto Threshold = std::get<1>(FuncInfo);
343     auto GUID = std::get<2>(FuncInfo);
344 
345     // Check if we later added this summary with a higher threshold.
346     // If so, skip this entry.
347     auto ExportModulePath = Summary->modulePath();
348     auto &LatestProcessedThreshold = ImportList[ExportModulePath][GUID];
349     if (LatestProcessedThreshold > Threshold)
350       continue;
351 
352     computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
353                              Worklist, ImportList, ExportLists);
354   }
355 }
356 
357 } // anonymous namespace
358 
359 /// Compute all the import and export for every module using the Index.
360 void llvm::ComputeCrossModuleImport(
361     const ModuleSummaryIndex &Index,
362     const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
363     StringMap<FunctionImporter::ImportMapTy> &ImportLists,
364     StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
365   // For each module that has function defined, compute the import/export lists.
366   for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
367     auto &ImportList = ImportLists[DefinedGVSummaries.first()];
368     DEBUG(dbgs() << "Computing import for Module '"
369                  << DefinedGVSummaries.first() << "'\n");
370     ComputeImportForModule(DefinedGVSummaries.second, Index, ImportList,
371                            &ExportLists);
372   }
373 
374   // When computing imports we added all GUIDs referenced by anything
375   // imported from the module to its ExportList. Now we prune each ExportList
376   // of any not defined in that module. This is more efficient than checking
377   // while computing imports because some of the summary lists may be long
378   // due to linkonce (comdat) copies.
379   for (auto &ELI : ExportLists) {
380     const auto &DefinedGVSummaries =
381         ModuleToDefinedGVSummaries.lookup(ELI.first());
382     for (auto EI = ELI.second.begin(); EI != ELI.second.end();) {
383       if (!DefinedGVSummaries.count(*EI))
384         EI = ELI.second.erase(EI);
385       else
386         ++EI;
387     }
388   }
389 
390 #ifndef NDEBUG
391   DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
392                << " modules:\n");
393   for (auto &ModuleImports : ImportLists) {
394     auto ModName = ModuleImports.first();
395     auto &Exports = ExportLists[ModName];
396     DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size()
397                  << " functions. Imports from " << ModuleImports.second.size()
398                  << " modules.\n");
399     for (auto &Src : ModuleImports.second) {
400       auto SrcModName = Src.first();
401       DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
402                    << SrcModName << "\n");
403     }
404   }
405 #endif
406 }
407 
408 /// Compute all the imports for the given module in the Index.
409 void llvm::ComputeCrossModuleImportForModule(
410     StringRef ModulePath, const ModuleSummaryIndex &Index,
411     FunctionImporter::ImportMapTy &ImportList) {
412 
413   // Collect the list of functions this module defines.
414   // GUID -> Summary
415   GVSummaryMapTy FunctionSummaryMap;
416   Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
417 
418   // Compute the import list for this module.
419   DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
420   ComputeImportForModule(FunctionSummaryMap, Index, ImportList);
421 
422 #ifndef NDEBUG
423   DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
424                << ImportList.size() << " modules.\n");
425   for (auto &Src : ImportList) {
426     auto SrcModName = Src.first();
427     DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
428                  << SrcModName << "\n");
429   }
430 #endif
431 }
432 
433 void llvm::computeDeadSymbols(
434     ModuleSummaryIndex &Index,
435     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
436   assert(!Index.withGlobalValueDeadStripping());
437   if (!ComputeDead)
438     return;
439   if (GUIDPreservedSymbols.empty())
440     // Don't do anything when nothing is live, this is friendly with tests.
441     return;
442   unsigned LiveSymbols = 0;
443   SmallVector<ValueInfo, 128> Worklist;
444   Worklist.reserve(GUIDPreservedSymbols.size() * 2);
445   for (auto GUID : GUIDPreservedSymbols) {
446     ValueInfo VI = Index.getValueInfo(GUID);
447     if (!VI)
448       continue;
449     for (auto &S : VI.getSummaryList())
450       S->setLive(true);
451   }
452 
453   // Add values flagged in the index as live roots to the worklist.
454   for (const auto &Entry : Index)
455     for (auto &S : Entry.second.SummaryList)
456       if (S->isLive()) {
457         DEBUG(dbgs() << "Live root: " << Entry.first << "\n");
458         Worklist.push_back(ValueInfo(&Entry));
459         ++LiveSymbols;
460         break;
461       }
462 
463   // Make value live and add it to the worklist if it was not live before.
464   // FIXME: we should only make the prevailing copy live here
465   auto visit = [&](ValueInfo VI) {
466     for (auto &S : VI.getSummaryList())
467       S->setLive(true);
468     ++LiveSymbols;
469     Worklist.push_back(VI);
470     // FIXME: If we knew which edges were created for indirect call profiles,
471     // we could skip them here. Any that are live should be reached via
472     // other edges, e.g. reference edges. Otherwise, using a profile collected
473     // on a slightly different binary might provoke preserving, importing
474     // and ultimately promoting calls to functions not linked into this
475     // binary, which increases the binary size unnecessarily. Note that
476     // if this code changes, the importer needs to change so that edges
477     // to functions marked dead are skipped.
478     VI = updateValueInfoForIndirectCalls(Index, VI);
479     if (!VI)
480       return;
481     for (auto &S : VI.getSummaryList())
482       if (S->isLive())
483         return;
484     for (auto &S : VI.getSummaryList())
485       S->setLive(true);
486     ++LiveSymbols;
487     Worklist.push_back(VI);
488   };
489 
490   while (!Worklist.empty()) {
491     auto VI = Worklist.pop_back_val();
492     for (auto &Summary : VI.getSummaryList()) {
493       GlobalValueSummary *Base = Summary->getBaseObject();
494       for (auto Ref : Base->refs())
495         visit(Ref);
496       if (auto *FS = dyn_cast<FunctionSummary>(Base))
497         for (auto Call : FS->calls())
498           visit(Call.first);
499     }
500   }
501   Index.setWithGlobalValueDeadStripping();
502 
503   unsigned DeadSymbols = Index.size() - LiveSymbols;
504   DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols
505                << " symbols Dead \n");
506   NumDeadSymbols += DeadSymbols;
507   NumLiveSymbols += LiveSymbols;
508 }
509 
510 /// Compute the set of summaries needed for a ThinLTO backend compilation of
511 /// \p ModulePath.
512 void llvm::gatherImportedSummariesForModule(
513     StringRef ModulePath,
514     const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
515     const FunctionImporter::ImportMapTy &ImportList,
516     std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
517   // Include all summaries from the importing module.
518   ModuleToSummariesForIndex[ModulePath] =
519       ModuleToDefinedGVSummaries.lookup(ModulePath);
520   // Include summaries for imports.
521   for (auto &ILI : ImportList) {
522     auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
523     const auto &DefinedGVSummaries =
524         ModuleToDefinedGVSummaries.lookup(ILI.first());
525     for (auto &GI : ILI.second) {
526       const auto &DS = DefinedGVSummaries.find(GI.first);
527       assert(DS != DefinedGVSummaries.end() &&
528              "Expected a defined summary for imported global value");
529       SummariesForIndex[GI.first] = DS->second;
530     }
531   }
532 }
533 
534 /// Emit the files \p ModulePath will import from into \p OutputFilename.
535 std::error_code
536 llvm::EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename,
537                        const FunctionImporter::ImportMapTy &ModuleImports) {
538   std::error_code EC;
539   raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
540   if (EC)
541     return EC;
542   for (auto &ILI : ModuleImports)
543     ImportsOS << ILI.first() << "\n";
544   return std::error_code();
545 }
546 
547 /// Fixup WeakForLinker linkages in \p TheModule based on summary analysis.
548 void llvm::thinLTOResolveWeakForLinkerModule(
549     Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
550   auto ConvertToDeclaration = [](GlobalValue &GV) {
551     DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName() << "\n");
552     if (Function *F = dyn_cast<Function>(&GV)) {
553       F->deleteBody();
554       F->clearMetadata();
555     } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
556       V->setInitializer(nullptr);
557       V->setLinkage(GlobalValue::ExternalLinkage);
558       V->clearMetadata();
559     } else
560       // For now we don't resolve or drop aliases. Once we do we'll
561       // need to add support here for creating either a function or
562       // variable declaration, and return the new GlobalValue* for
563       // the caller to use.
564       llvm_unreachable("Expected function or variable");
565   };
566 
567   auto updateLinkage = [&](GlobalValue &GV) {
568     // See if the global summary analysis computed a new resolved linkage.
569     const auto &GS = DefinedGlobals.find(GV.getGUID());
570     if (GS == DefinedGlobals.end())
571       return;
572     auto NewLinkage = GS->second->linkage();
573     if (NewLinkage == GV.getLinkage())
574       return;
575 
576     // Switch the linkage to weakany if asked for, e.g. we do this for
577     // linker redefined symbols (via --wrap or --defsym).
578     // We record that the visibility should be changed here in `addThinLTO`
579     // as we need access to the resolution vectors for each input file in
580     // order to find which symbols have been redefined.
581     // We may consider reorganizing this code and moving the linkage recording
582     // somewhere else, e.g. in thinLTOResolveWeakForLinkerInIndex.
583     if (NewLinkage == GlobalValue::WeakAnyLinkage) {
584       GV.setLinkage(NewLinkage);
585       return;
586     }
587 
588     if (!GlobalValue::isWeakForLinker(GV.getLinkage()))
589       return;
590     // Check for a non-prevailing def that has interposable linkage
591     // (e.g. non-odr weak or linkonce). In that case we can't simply
592     // convert to available_externally, since it would lose the
593     // interposable property and possibly get inlined. Simply drop
594     // the definition in that case.
595     if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) &&
596         GlobalValue::isInterposableLinkage(GV.getLinkage()))
597       ConvertToDeclaration(GV);
598     else {
599       DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
600                    << GV.getLinkage() << " to " << NewLinkage << "\n");
601       GV.setLinkage(NewLinkage);
602     }
603     // Remove declarations from comdats, including available_externally
604     // as this is a declaration for the linker, and will be dropped eventually.
605     // It is illegal for comdats to contain declarations.
606     auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
607     if (GO && GO->isDeclarationForLinker() && GO->hasComdat())
608       GO->setComdat(nullptr);
609   };
610 
611   // Process functions and global now
612   for (auto &GV : TheModule)
613     updateLinkage(GV);
614   for (auto &GV : TheModule.globals())
615     updateLinkage(GV);
616   for (auto &GV : TheModule.aliases())
617     updateLinkage(GV);
618 }
619 
620 /// Run internalization on \p TheModule based on symmary analysis.
621 void llvm::thinLTOInternalizeModule(Module &TheModule,
622                                     const GVSummaryMapTy &DefinedGlobals) {
623   // Parse inline ASM and collect the list of symbols that are not defined in
624   // the current module.
625   StringSet<> AsmUndefinedRefs;
626   ModuleSymbolTable::CollectAsmSymbols(
627       TheModule,
628       [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) {
629         if (Flags & object::BasicSymbolRef::SF_Undefined)
630           AsmUndefinedRefs.insert(Name);
631       });
632 
633   // Declare a callback for the internalize pass that will ask for every
634   // candidate GlobalValue if it can be internalized or not.
635   auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
636     // Can't be internalized if referenced in inline asm.
637     if (AsmUndefinedRefs.count(GV.getName()))
638       return true;
639 
640     // Lookup the linkage recorded in the summaries during global analysis.
641     auto GS = DefinedGlobals.find(GV.getGUID());
642     if (GS == DefinedGlobals.end()) {
643       // Must have been promoted (possibly conservatively). Find original
644       // name so that we can access the correct summary and see if it can
645       // be internalized again.
646       // FIXME: Eventually we should control promotion instead of promoting
647       // and internalizing again.
648       StringRef OrigName =
649           ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
650       std::string OrigId = GlobalValue::getGlobalIdentifier(
651           OrigName, GlobalValue::InternalLinkage,
652           TheModule.getSourceFileName());
653       GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
654       if (GS == DefinedGlobals.end()) {
655         // Also check the original non-promoted non-globalized name. In some
656         // cases a preempted weak value is linked in as a local copy because
657         // it is referenced by an alias (IRLinker::linkGlobalValueProto).
658         // In that case, since it was originally not a local value, it was
659         // recorded in the index using the original name.
660         // FIXME: This may not be needed once PR27866 is fixed.
661         GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
662         assert(GS != DefinedGlobals.end());
663       }
664     }
665     return !GlobalValue::isLocalLinkage(GS->second->linkage());
666   };
667 
668   // FIXME: See if we can just internalize directly here via linkage changes
669   // based on the index, rather than invoking internalizeModule.
670   llvm::internalizeModule(TheModule, MustPreserveGV);
671 }
672 
673 // Automatically import functions in Module \p DestModule based on the summaries
674 // index.
675 //
676 Expected<bool> FunctionImporter::importFunctions(
677     Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
678   DEBUG(dbgs() << "Starting import for Module "
679                << DestModule.getModuleIdentifier() << "\n");
680   unsigned ImportedCount = 0;
681 
682   IRMover Mover(DestModule);
683   // Do the actual import of functions now, one Module at a time
684   std::set<StringRef> ModuleNameOrderedList;
685   for (auto &FunctionsToImportPerModule : ImportList) {
686     ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
687   }
688   for (auto &Name : ModuleNameOrderedList) {
689     // Get the module for the import
690     const auto &FunctionsToImportPerModule = ImportList.find(Name);
691     assert(FunctionsToImportPerModule != ImportList.end());
692     Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
693     if (!SrcModuleOrErr)
694       return SrcModuleOrErr.takeError();
695     std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
696     assert(&DestModule.getContext() == &SrcModule->getContext() &&
697            "Context mismatch");
698 
699     // If modules were created with lazy metadata loading, materialize it
700     // now, before linking it (otherwise this will be a noop).
701     if (Error Err = SrcModule->materializeMetadata())
702       return std::move(Err);
703 
704     auto &ImportGUIDs = FunctionsToImportPerModule->second;
705     // Find the globals to import
706     SetVector<GlobalValue *> GlobalsToImport;
707     for (Function &F : *SrcModule) {
708       if (!F.hasName())
709         continue;
710       auto GUID = F.getGUID();
711       auto Import = ImportGUIDs.count(GUID);
712       DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " << GUID
713                    << " " << F.getName() << " from "
714                    << SrcModule->getSourceFileName() << "\n");
715       if (Import) {
716         if (Error Err = F.materialize())
717           return std::move(Err);
718         if (EnableImportMetadata) {
719           // Add 'thinlto_src_module' metadata for statistics and debugging.
720           F.setMetadata(
721               "thinlto_src_module",
722               llvm::MDNode::get(
723                   DestModule.getContext(),
724                   {llvm::MDString::get(DestModule.getContext(),
725                                        SrcModule->getSourceFileName())}));
726         }
727         GlobalsToImport.insert(&F);
728       }
729     }
730     for (GlobalVariable &GV : SrcModule->globals()) {
731       if (!GV.hasName())
732         continue;
733       auto GUID = GV.getGUID();
734       auto Import = ImportGUIDs.count(GUID);
735       DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " << GUID
736                    << " " << GV.getName() << " from "
737                    << SrcModule->getSourceFileName() << "\n");
738       if (Import) {
739         if (Error Err = GV.materialize())
740           return std::move(Err);
741         GlobalsToImport.insert(&GV);
742       }
743     }
744 #ifndef NDEBUG
745     for (GlobalAlias &GA : SrcModule->aliases()) {
746       if (!GA.hasName())
747         continue;
748       auto GUID = GA.getGUID();
749       assert(!ImportGUIDs.count(GUID) && "Unexpected alias in import list");
750       DEBUG(dbgs() << "Not importing alias " << GUID
751                    << " " << GA.getName() << " from "
752                    << SrcModule->getSourceFileName() << "\n");
753     }
754 #endif
755 
756     // Upgrade debug info after we're done materializing all the globals and we
757     // have loaded all the required metadata!
758     UpgradeDebugInfo(*SrcModule);
759 
760     // Link in the specified functions.
761     if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
762       return true;
763 
764     if (PrintImports) {
765       for (const auto *GV : GlobalsToImport)
766         dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
767                << " from " << SrcModule->getSourceFileName() << "\n";
768     }
769 
770     if (Mover.move(std::move(SrcModule), GlobalsToImport.getArrayRef(),
771                    [](GlobalValue &, IRMover::ValueAdder) {},
772                    /*IsPerformingImport=*/true))
773       report_fatal_error("Function Import: link error");
774 
775     ImportedCount += GlobalsToImport.size();
776     NumImportedModules++;
777   }
778 
779   NumImportedFunctions += ImportedCount;
780 
781   DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
782                << DestModule.getModuleIdentifier() << "\n");
783   return ImportedCount;
784 }
785 
786 /// Summary file to use for function importing when using -function-import from
787 /// the command line.
788 static cl::opt<std::string>
789     SummaryFile("summary-file",
790                 cl::desc("The summary file to use for function importing."));
791 
792 static bool doImportingForModule(Module &M) {
793   if (SummaryFile.empty())
794     report_fatal_error("error: -function-import requires -summary-file\n");
795   Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
796       getModuleSummaryIndexForFile(SummaryFile);
797   if (!IndexPtrOrErr) {
798     logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
799                           "Error loading file '" + SummaryFile + "': ");
800     return false;
801   }
802   std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
803 
804   // First step is collecting the import list.
805   FunctionImporter::ImportMapTy ImportList;
806   ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
807                                     ImportList);
808 
809   // Conservatively mark all internal values as promoted. This interface is
810   // only used when doing importing via the function importing pass. The pass
811   // is only enabled when testing importing via the 'opt' tool, which does
812   // not do the ThinLink that would normally determine what values to promote.
813   for (auto &I : *Index) {
814     for (auto &S : I.second.SummaryList) {
815       if (GlobalValue::isLocalLinkage(S->linkage()))
816         S->setLinkage(GlobalValue::ExternalLinkage);
817     }
818   }
819 
820   // Next we need to promote to global scope and rename any local values that
821   // are potentially exported to other modules.
822   if (renameModuleForThinLTO(M, *Index, nullptr)) {
823     errs() << "Error renaming module\n";
824     return false;
825   }
826 
827   // Perform the import now.
828   auto ModuleLoader = [&M](StringRef Identifier) {
829     return loadFile(Identifier, M.getContext());
830   };
831   FunctionImporter Importer(*Index, ModuleLoader);
832   Expected<bool> Result = Importer.importFunctions(M, ImportList);
833 
834   // FIXME: Probably need to propagate Errors through the pass manager.
835   if (!Result) {
836     logAllUnhandledErrors(Result.takeError(), errs(),
837                           "Error importing module: ");
838     return false;
839   }
840 
841   return *Result;
842 }
843 
844 namespace {
845 /// Pass that performs cross-module function import provided a summary file.
846 class FunctionImportLegacyPass : public ModulePass {
847 public:
848   /// Pass identification, replacement for typeid
849   static char ID;
850 
851   /// Specify pass name for debug output
852   StringRef getPassName() const override { return "Function Importing"; }
853 
854   explicit FunctionImportLegacyPass() : ModulePass(ID) {}
855 
856   bool runOnModule(Module &M) override {
857     if (skipModule(M))
858       return false;
859 
860     return doImportingForModule(M);
861   }
862 };
863 } // anonymous namespace
864 
865 PreservedAnalyses FunctionImportPass::run(Module &M,
866                                           ModuleAnalysisManager &AM) {
867   if (!doImportingForModule(M))
868     return PreservedAnalyses::all();
869 
870   return PreservedAnalyses::none();
871 }
872 
873 char FunctionImportLegacyPass::ID = 0;
874 INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
875                 "Summary Based Function Import", false, false)
876 
877 namespace llvm {
878 Pass *createFunctionImportPass() {
879   return new FunctionImportLegacyPass();
880 }
881 }
882