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/IR/AutoUpgrade.h"
21 #include "llvm/IR/DiagnosticPrinter.h"
22 #include "llvm/IR/IntrinsicInst.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IRReader/IRReader.h"
25 #include "llvm/Linker/Linker.h"
26 #include "llvm/Object/IRObjectFile.h"
27 #include "llvm/Object/ModuleSummaryIndexObjectFile.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/SourceMgr.h"
31 #include "llvm/Transforms/IPO/Internalize.h"
32 #include "llvm/Transforms/Utils/FunctionImportUtils.h"
33 
34 #define DEBUG_TYPE "function-import"
35 
36 using namespace llvm;
37 
38 STATISTIC(NumImported, "Number of functions imported");
39 
40 /// Limit on instruction count of imported functions.
41 static cl::opt<unsigned> ImportInstrLimit(
42     "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
43     cl::desc("Only import functions with less than N instructions"));
44 
45 static cl::opt<float>
46     ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7),
47                       cl::Hidden, cl::value_desc("x"),
48                       cl::desc("As we import functions, multiply the "
49                                "`import-instr-limit` threshold by this factor "
50                                "before processing newly imported functions"));
51 
52 static cl::opt<float> ImportHotInstrFactor(
53     "import-hot-evolution-factor", cl::init(1.0), cl::Hidden,
54     cl::value_desc("x"),
55     cl::desc("As we import functions called from hot callsite, multiply the "
56              "`import-instr-limit` threshold by this factor "
57              "before processing newly imported functions"));
58 
59 static cl::opt<float> ImportHotMultiplier(
60     "import-hot-multiplier", cl::init(3.0), cl::Hidden, cl::value_desc("x"),
61     cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"));
62 
63 // FIXME: This multiplier was not really tuned up.
64 static cl::opt<float> ImportColdMultiplier(
65     "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"),
66     cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"));
67 
68 static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
69                                   cl::desc("Print imported functions"));
70 
71 // Temporary allows the function import pass to disable always linking
72 // referenced discardable symbols.
73 static cl::opt<bool>
74     DontForceImportReferencedDiscardableSymbols("disable-force-link-odr",
75                                                 cl::init(false), cl::Hidden);
76 
77 static cl::opt<bool> EnableImportMetadata(
78     "enable-import-metadata", cl::init(
79 #if !defined(NDEBUG)
80                                   true /*Enabled with asserts.*/
81 #else
82                                   false
83 #endif
84                                   ),
85     cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'"));
86 
87 // Load lazily a module from \p FileName in \p Context.
88 static std::unique_ptr<Module> loadFile(const std::string &FileName,
89                                         LLVMContext &Context) {
90   SMDiagnostic Err;
91   DEBUG(dbgs() << "Loading '" << FileName << "'\n");
92   // Metadata isn't loaded until functions are imported, to minimize
93   // the memory overhead.
94   std::unique_ptr<Module> Result =
95       getLazyIRFileModule(FileName, Err, Context,
96                           /* ShouldLazyLoadMetadata = */ true);
97   if (!Result) {
98     Err.print("function-import", errs());
99     report_fatal_error("Abort");
100   }
101 
102   return Result;
103 }
104 
105 namespace {
106 
107 // Return true if the Summary describes a GlobalValue that can be externally
108 // referenced, i.e. it does not need renaming (linkage is not local) or renaming
109 // is possible (does not have a section for instance).
110 static bool canBeExternallyReferenced(const GlobalValueSummary &Summary) {
111   if (!Summary.needsRenaming())
112     return true;
113 
114   if (Summary.noRename())
115     // Can't externally reference a global that needs renaming if has a section
116     // or is referenced from inline assembly, for example.
117     return false;
118 
119   return true;
120 }
121 
122 // Return true if \p GUID describes a GlobalValue that can be externally
123 // referenced, i.e. it does not need renaming (linkage is not local) or
124 // renaming is possible (does not have a section for instance).
125 static bool canBeExternallyReferenced(const ModuleSummaryIndex &Index,
126                                       GlobalValue::GUID GUID) {
127   auto Summaries = Index.findGlobalValueSummaryList(GUID);
128   if (Summaries == Index.end())
129     return true;
130   if (Summaries->second.size() != 1)
131     // If there are multiple globals with this GUID, then we know it is
132     // not a local symbol, and it is necessarily externally referenced.
133     return true;
134 
135   // We don't need to check for the module path, because if it can't be
136   // externally referenced and we call it, it is necessarilly in the same
137   // module
138   return canBeExternallyReferenced(**Summaries->second.begin());
139 }
140 
141 // Return true if the global described by \p Summary can be imported in another
142 // module.
143 static bool eligibleForImport(const ModuleSummaryIndex &Index,
144                               const GlobalValueSummary &Summary) {
145   if (!canBeExternallyReferenced(Summary))
146     // Can't import a global that needs renaming if has a section for instance.
147     // FIXME: we may be able to import it by copying it without promotion.
148     return false;
149 
150   // Don't import functions that are not viable to inline.
151   if (Summary.isNotViableToInline())
152     return false;
153 
154   // Check references (and potential calls) in the same module. If the current
155   // value references a global that can't be externally referenced it is not
156   // eligible for import. First check the flag set when we have possible
157   // opaque references (e.g. inline asm calls), then check the call and
158   // reference sets.
159   if (Summary.hasInlineAsmMaybeReferencingInternal())
160     return false;
161   bool AllRefsCanBeExternallyReferenced =
162       llvm::all_of(Summary.refs(), [&](const ValueInfo &VI) {
163         return canBeExternallyReferenced(Index, VI.getGUID());
164       });
165   if (!AllRefsCanBeExternallyReferenced)
166     return false;
167 
168   if (auto *FuncSummary = dyn_cast<FunctionSummary>(&Summary)) {
169     bool AllCallsCanBeExternallyReferenced = llvm::all_of(
170         FuncSummary->calls(), [&](const FunctionSummary::EdgeTy &Edge) {
171           return canBeExternallyReferenced(Index, Edge.first.getGUID());
172         });
173     if (!AllCallsCanBeExternallyReferenced)
174       return false;
175   }
176   return true;
177 }
178 
179 /// Given a list of possible callee implementation for a call site, select one
180 /// that fits the \p Threshold.
181 ///
182 /// FIXME: select "best" instead of first that fits. But what is "best"?
183 /// - The smallest: more likely to be inlined.
184 /// - The one with the least outgoing edges (already well optimized).
185 /// - One from a module already being imported from in order to reduce the
186 ///   number of source modules parsed/linked.
187 /// - One that has PGO data attached.
188 /// - [insert you fancy metric here]
189 static const GlobalValueSummary *
190 selectCallee(const ModuleSummaryIndex &Index,
191              const GlobalValueSummaryList &CalleeSummaryList,
192              unsigned Threshold) {
193   auto It = llvm::find_if(
194       CalleeSummaryList,
195       [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
196         auto *GVSummary = SummaryPtr.get();
197         if (GlobalValue::isInterposableLinkage(GVSummary->linkage()))
198           // There is no point in importing these, we can't inline them
199           return false;
200         if (auto *AS = dyn_cast<AliasSummary>(GVSummary)) {
201           GVSummary = &AS->getAliasee();
202           // Alias can't point to "available_externally". However when we import
203           // linkOnceODR the linkage does not change. So we import the alias
204           // and aliasee only in this case.
205           // FIXME: we should import alias as available_externally *function*,
206           // the destination module does need to know it is an alias.
207           if (!GlobalValue::isLinkOnceODRLinkage(GVSummary->linkage()))
208             return false;
209         }
210 
211         auto *Summary = cast<FunctionSummary>(GVSummary);
212 
213         if (Summary->instCount() > Threshold)
214           return false;
215 
216         if (!eligibleForImport(Index, *Summary))
217           return false;
218 
219         return true;
220       });
221   if (It == CalleeSummaryList.end())
222     return nullptr;
223 
224   return cast<GlobalValueSummary>(It->get());
225 }
226 
227 /// Return the summary for the function \p GUID that fits the \p Threshold, or
228 /// null if there's no match.
229 static const GlobalValueSummary *selectCallee(GlobalValue::GUID GUID,
230                                               unsigned Threshold,
231                                               const ModuleSummaryIndex &Index) {
232   auto CalleeSummaryList = Index.findGlobalValueSummaryList(GUID);
233   if (CalleeSummaryList == Index.end())
234     return nullptr; // This function does not have a summary
235   return selectCallee(Index, CalleeSummaryList->second, Threshold);
236 }
237 
238 using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */,
239                             GlobalValue::GUID>;
240 
241 /// Compute the list of functions to import for a given caller. Mark these
242 /// imported functions and the symbols they reference in their source module as
243 /// exported from their source module.
244 static void computeImportForFunction(
245     const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
246     const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
247     SmallVectorImpl<EdgeInfo> &Worklist,
248     FunctionImporter::ImportMapTy &ImportList,
249     StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
250   for (auto &Edge : Summary.calls()) {
251     auto GUID = Edge.first.getGUID();
252     DEBUG(dbgs() << " edge -> " << GUID << " Threshold:" << Threshold << "\n");
253 
254     if (DefinedGVSummaries.count(GUID)) {
255       DEBUG(dbgs() << "ignored! Target already in destination module.\n");
256       continue;
257     }
258 
259     auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
260       if (Hotness == CalleeInfo::HotnessType::Hot)
261         return ImportHotMultiplier;
262       if (Hotness == CalleeInfo::HotnessType::Cold)
263         return ImportColdMultiplier;
264       return 1.0;
265     };
266 
267     const auto NewThreshold =
268         Threshold * GetBonusMultiplier(Edge.second.Hotness);
269 
270     auto *CalleeSummary = selectCallee(GUID, NewThreshold, Index);
271     if (!CalleeSummary) {
272       DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n");
273       continue;
274     }
275     // "Resolve" the summary, traversing alias,
276     const FunctionSummary *ResolvedCalleeSummary;
277     if (isa<AliasSummary>(CalleeSummary)) {
278       ResolvedCalleeSummary = cast<FunctionSummary>(
279           &cast<AliasSummary>(CalleeSummary)->getAliasee());
280       assert(
281           GlobalValue::isLinkOnceODRLinkage(ResolvedCalleeSummary->linkage()) &&
282           "Unexpected alias to a non-linkonceODR in import list");
283     } else
284       ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
285 
286     assert(ResolvedCalleeSummary->instCount() <= NewThreshold &&
287            "selectCallee() didn't honor the threshold");
288 
289     auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
290       // Adjust the threshold for next level of imported functions.
291       // The threshold is different for hot callsites because we can then
292       // inline chains of hot calls.
293       if (IsHotCallsite)
294         return Threshold * ImportHotInstrFactor;
295       return Threshold * ImportInstrFactor;
296     };
297 
298     bool IsHotCallsite = Edge.second.Hotness == CalleeInfo::HotnessType::Hot;
299     const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
300 
301     auto ExportModulePath = ResolvedCalleeSummary->modulePath();
302     auto &ProcessedThreshold = ImportList[ExportModulePath][GUID];
303     /// Since the traversal of the call graph is DFS, we can revisit a function
304     /// a second time with a higher threshold. In this case, it is added back to
305     /// the worklist with the new threshold.
306     if (ProcessedThreshold && ProcessedThreshold >= AdjThreshold) {
307       DEBUG(dbgs() << "ignored! Target was already seen with Threshold "
308                    << ProcessedThreshold << "\n");
309       continue;
310     }
311     bool PreviouslyImported = ProcessedThreshold != 0;
312     // Mark this function as imported in this module, with the current Threshold
313     ProcessedThreshold = AdjThreshold;
314 
315     // Make exports in the source module.
316     if (ExportLists) {
317       auto &ExportList = (*ExportLists)[ExportModulePath];
318       ExportList.insert(GUID);
319       if (!PreviouslyImported) {
320         // This is the first time this function was exported from its source
321         // module, so mark all functions and globals it references as exported
322         // to the outside if they are defined in the same source module.
323         // For efficiency, we unconditionally add all the referenced GUIDs
324         // to the ExportList for this module, and will prune out any not
325         // defined in the module later in a single pass.
326         for (auto &Edge : ResolvedCalleeSummary->calls()) {
327           auto CalleeGUID = Edge.first.getGUID();
328           ExportList.insert(CalleeGUID);
329         }
330         for (auto &Ref : ResolvedCalleeSummary->refs()) {
331           auto GUID = Ref.getGUID();
332           ExportList.insert(GUID);
333         }
334       }
335     }
336 
337     // Insert the newly imported function to the worklist.
338     Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, GUID);
339   }
340 }
341 
342 /// Given the list of globals defined in a module, compute the list of imports
343 /// as well as the list of "exports", i.e. the list of symbols referenced from
344 /// another module (that may require promotion).
345 static void ComputeImportForModule(
346     const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
347     FunctionImporter::ImportMapTy &ImportList,
348     StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
349   // Worklist contains the list of function imported in this module, for which
350   // we will analyse the callees and may import further down the callgraph.
351   SmallVector<EdgeInfo, 128> Worklist;
352 
353   // Populate the worklist with the import for the functions in the current
354   // module
355   for (auto &GVSummary : DefinedGVSummaries) {
356     auto *Summary = GVSummary.second;
357     if (auto *AS = dyn_cast<AliasSummary>(Summary))
358       Summary = &AS->getAliasee();
359     auto *FuncSummary = dyn_cast<FunctionSummary>(Summary);
360     if (!FuncSummary)
361       // Skip import for global variables
362       continue;
363     DEBUG(dbgs() << "Initalize import for " << GVSummary.first << "\n");
364     computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
365                              DefinedGVSummaries, Worklist, ImportList,
366                              ExportLists);
367   }
368 
369   // Process the newly imported functions and add callees to the worklist.
370   while (!Worklist.empty()) {
371     auto FuncInfo = Worklist.pop_back_val();
372     auto *Summary = std::get<0>(FuncInfo);
373     auto Threshold = std::get<1>(FuncInfo);
374     auto GUID = std::get<2>(FuncInfo);
375 
376     // Check if we later added this summary with a higher threshold.
377     // If so, skip this entry.
378     auto ExportModulePath = Summary->modulePath();
379     auto &LatestProcessedThreshold = ImportList[ExportModulePath][GUID];
380     if (LatestProcessedThreshold > Threshold)
381       continue;
382 
383     computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
384                              Worklist, ImportList, ExportLists);
385   }
386 }
387 
388 } // anonymous namespace
389 
390 /// Compute all the import and export for every module using the Index.
391 void llvm::ComputeCrossModuleImport(
392     const ModuleSummaryIndex &Index,
393     const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
394     StringMap<FunctionImporter::ImportMapTy> &ImportLists,
395     StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
396   // For each module that has function defined, compute the import/export lists.
397   for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
398     auto &ImportList = ImportLists[DefinedGVSummaries.first()];
399     DEBUG(dbgs() << "Computing import for Module '"
400                  << DefinedGVSummaries.first() << "'\n");
401     ComputeImportForModule(DefinedGVSummaries.second, Index, ImportList,
402                            &ExportLists);
403   }
404 
405   // When computing imports we added all GUIDs referenced by anything
406   // imported from the module to its ExportList. Now we prune each ExportList
407   // of any not defined in that module. This is more efficient than checking
408   // while computing imports because some of the summary lists may be long
409   // due to linkonce (comdat) copies.
410   for (auto &ELI : ExportLists) {
411     const auto &DefinedGVSummaries =
412         ModuleToDefinedGVSummaries.lookup(ELI.first());
413     for (auto EI = ELI.second.begin(); EI != ELI.second.end();) {
414       if (!DefinedGVSummaries.count(*EI))
415         EI = ELI.second.erase(EI);
416       else
417         ++EI;
418     }
419   }
420 
421 #ifndef NDEBUG
422   DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
423                << " modules:\n");
424   for (auto &ModuleImports : ImportLists) {
425     auto ModName = ModuleImports.first();
426     auto &Exports = ExportLists[ModName];
427     DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size()
428                  << " functions. Imports from " << ModuleImports.second.size()
429                  << " modules.\n");
430     for (auto &Src : ModuleImports.second) {
431       auto SrcModName = Src.first();
432       DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
433                    << SrcModName << "\n");
434     }
435   }
436 #endif
437 }
438 
439 /// Compute all the imports for the given module in the Index.
440 void llvm::ComputeCrossModuleImportForModule(
441     StringRef ModulePath, const ModuleSummaryIndex &Index,
442     FunctionImporter::ImportMapTy &ImportList) {
443 
444   // Collect the list of functions this module defines.
445   // GUID -> Summary
446   GVSummaryMapTy FunctionSummaryMap;
447   Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
448 
449   // Compute the import list for this module.
450   DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
451   ComputeImportForModule(FunctionSummaryMap, Index, ImportList);
452 
453 #ifndef NDEBUG
454   DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
455                << ImportList.size() << " modules.\n");
456   for (auto &Src : ImportList) {
457     auto SrcModName = Src.first();
458     DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
459                  << SrcModName << "\n");
460   }
461 #endif
462 }
463 
464 /// Compute the set of summaries needed for a ThinLTO backend compilation of
465 /// \p ModulePath.
466 void llvm::gatherImportedSummariesForModule(
467     StringRef ModulePath,
468     const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
469     const FunctionImporter::ImportMapTy &ImportList,
470     std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
471   // Include all summaries from the importing module.
472   ModuleToSummariesForIndex[ModulePath] =
473       ModuleToDefinedGVSummaries.lookup(ModulePath);
474   // Include summaries for imports.
475   for (auto &ILI : ImportList) {
476     auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
477     const auto &DefinedGVSummaries =
478         ModuleToDefinedGVSummaries.lookup(ILI.first());
479     for (auto &GI : ILI.second) {
480       const auto &DS = DefinedGVSummaries.find(GI.first);
481       assert(DS != DefinedGVSummaries.end() &&
482              "Expected a defined summary for imported global value");
483       SummariesForIndex[GI.first] = DS->second;
484     }
485   }
486 }
487 
488 /// Emit the files \p ModulePath will import from into \p OutputFilename.
489 std::error_code
490 llvm::EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename,
491                        const FunctionImporter::ImportMapTy &ModuleImports) {
492   std::error_code EC;
493   raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
494   if (EC)
495     return EC;
496   for (auto &ILI : ModuleImports)
497     ImportsOS << ILI.first() << "\n";
498   return std::error_code();
499 }
500 
501 /// Fixup WeakForLinker linkages in \p TheModule based on summary analysis.
502 void llvm::thinLTOResolveWeakForLinkerModule(
503     Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
504   auto updateLinkage = [&](GlobalValue &GV) {
505     if (!GlobalValue::isWeakForLinker(GV.getLinkage()))
506       return;
507     // See if the global summary analysis computed a new resolved linkage.
508     const auto &GS = DefinedGlobals.find(GV.getGUID());
509     if (GS == DefinedGlobals.end())
510       return;
511     auto NewLinkage = GS->second->linkage();
512     if (NewLinkage == GV.getLinkage())
513       return;
514     DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
515                  << GV.getLinkage() << " to " << NewLinkage << "\n");
516     GV.setLinkage(NewLinkage);
517     // Remove functions converted to available_externally from comdats,
518     // as this is a declaration for the linker, and will be dropped eventually.
519     // It is illegal for comdats to contain declarations.
520     auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
521     if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) {
522       assert(GO->hasAvailableExternallyLinkage() &&
523              "Expected comdat on definition (possibly available external)");
524       GO->setComdat(nullptr);
525     }
526   };
527 
528   // Process functions and global now
529   for (auto &GV : TheModule)
530     updateLinkage(GV);
531   for (auto &GV : TheModule.globals())
532     updateLinkage(GV);
533   for (auto &GV : TheModule.aliases())
534     updateLinkage(GV);
535 }
536 
537 /// Run internalization on \p TheModule based on symmary analysis.
538 void llvm::thinLTOInternalizeModule(Module &TheModule,
539                                     const GVSummaryMapTy &DefinedGlobals) {
540   // Parse inline ASM and collect the list of symbols that are not defined in
541   // the current module.
542   StringSet<> AsmUndefinedRefs;
543   ModuleSymbolTable::CollectAsmSymbols(
544       Triple(TheModule.getTargetTriple()), TheModule.getModuleInlineAsm(),
545       [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) {
546         if (Flags & object::BasicSymbolRef::SF_Undefined)
547           AsmUndefinedRefs.insert(Name);
548       });
549 
550   // Declare a callback for the internalize pass that will ask for every
551   // candidate GlobalValue if it can be internalized or not.
552   auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
553     // Can't be internalized if referenced in inline asm.
554     if (AsmUndefinedRefs.count(GV.getName()))
555       return true;
556 
557     // Lookup the linkage recorded in the summaries during global analysis.
558     const auto &GS = DefinedGlobals.find(GV.getGUID());
559     GlobalValue::LinkageTypes Linkage;
560     if (GS == DefinedGlobals.end()) {
561       // Must have been promoted (possibly conservatively). Find original
562       // name so that we can access the correct summary and see if it can
563       // be internalized again.
564       // FIXME: Eventually we should control promotion instead of promoting
565       // and internalizing again.
566       StringRef OrigName =
567           ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
568       std::string OrigId = GlobalValue::getGlobalIdentifier(
569           OrigName, GlobalValue::InternalLinkage,
570           TheModule.getSourceFileName());
571       const auto &GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
572       if (GS == DefinedGlobals.end()) {
573         // Also check the original non-promoted non-globalized name. In some
574         // cases a preempted weak value is linked in as a local copy because
575         // it is referenced by an alias (IRLinker::linkGlobalValueProto).
576         // In that case, since it was originally not a local value, it was
577         // recorded in the index using the original name.
578         // FIXME: This may not be needed once PR27866 is fixed.
579         const auto &GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
580         assert(GS != DefinedGlobals.end());
581         Linkage = GS->second->linkage();
582       } else {
583         Linkage = GS->second->linkage();
584       }
585     } else
586       Linkage = GS->second->linkage();
587     return !GlobalValue::isLocalLinkage(Linkage);
588   };
589 
590   // FIXME: See if we can just internalize directly here via linkage changes
591   // based on the index, rather than invoking internalizeModule.
592   llvm::internalizeModule(TheModule, MustPreserveGV);
593 }
594 
595 // Automatically import functions in Module \p DestModule based on the summaries
596 // index.
597 //
598 Expected<bool> FunctionImporter::importFunctions(
599     Module &DestModule, const FunctionImporter::ImportMapTy &ImportList,
600     bool ForceImportReferencedDiscardableSymbols) {
601   DEBUG(dbgs() << "Starting import for Module "
602                << DestModule.getModuleIdentifier() << "\n");
603   unsigned ImportedCount = 0;
604 
605   // Linker that will be used for importing function
606   Linker TheLinker(DestModule);
607   // Do the actual import of functions now, one Module at a time
608   std::set<StringRef> ModuleNameOrderedList;
609   for (auto &FunctionsToImportPerModule : ImportList) {
610     ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
611   }
612   for (auto &Name : ModuleNameOrderedList) {
613     // Get the module for the import
614     const auto &FunctionsToImportPerModule = ImportList.find(Name);
615     assert(FunctionsToImportPerModule != ImportList.end());
616     Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
617     if (!SrcModuleOrErr)
618       return SrcModuleOrErr.takeError();
619     std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
620     assert(&DestModule.getContext() == &SrcModule->getContext() &&
621            "Context mismatch");
622 
623     // If modules were created with lazy metadata loading, materialize it
624     // now, before linking it (otherwise this will be a noop).
625     if (Error Err = SrcModule->materializeMetadata())
626       return std::move(Err);
627     UpgradeDebugInfo(*SrcModule);
628 
629     auto &ImportGUIDs = FunctionsToImportPerModule->second;
630     // Find the globals to import
631     DenseSet<const GlobalValue *> GlobalsToImport;
632     for (Function &F : *SrcModule) {
633       if (!F.hasName())
634         continue;
635       auto GUID = F.getGUID();
636       auto Import = ImportGUIDs.count(GUID);
637       DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " << GUID
638                    << " " << F.getName() << " from "
639                    << SrcModule->getSourceFileName() << "\n");
640       if (Import) {
641         if (Error Err = F.materialize())
642           return std::move(Err);
643         if (EnableImportMetadata) {
644           // Add 'thinlto_src_module' metadata for statistics and debugging.
645           F.setMetadata(
646               "thinlto_src_module",
647               llvm::MDNode::get(
648                   DestModule.getContext(),
649                   {llvm::MDString::get(DestModule.getContext(),
650                                        SrcModule->getSourceFileName())}));
651         }
652         GlobalsToImport.insert(&F);
653       }
654     }
655     for (GlobalVariable &GV : SrcModule->globals()) {
656       if (!GV.hasName())
657         continue;
658       auto GUID = GV.getGUID();
659       auto Import = ImportGUIDs.count(GUID);
660       DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " << GUID
661                    << " " << GV.getName() << " from "
662                    << SrcModule->getSourceFileName() << "\n");
663       if (Import) {
664         if (Error Err = GV.materialize())
665           return std::move(Err);
666         GlobalsToImport.insert(&GV);
667       }
668     }
669     for (GlobalAlias &GA : SrcModule->aliases()) {
670       if (!GA.hasName())
671         continue;
672       auto GUID = GA.getGUID();
673       auto Import = ImportGUIDs.count(GUID);
674       DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias " << GUID
675                    << " " << GA.getName() << " from "
676                    << SrcModule->getSourceFileName() << "\n");
677       if (Import) {
678         // Alias can't point to "available_externally". However when we import
679         // linkOnceODR the linkage does not change. So we import the alias
680         // and aliasee only in this case. This has been handled by
681         // computeImportForFunction()
682         GlobalObject *GO = GA.getBaseObject();
683         assert(GO->hasLinkOnceODRLinkage() &&
684                "Unexpected alias to a non-linkonceODR in import list");
685 #ifndef NDEBUG
686         if (!GlobalsToImport.count(GO))
687           DEBUG(dbgs() << " alias triggers importing aliasee " << GO->getGUID()
688                        << " " << GO->getName() << " from "
689                        << SrcModule->getSourceFileName() << "\n");
690 #endif
691         if (Error Err = GO->materialize())
692           return std::move(Err);
693         GlobalsToImport.insert(GO);
694         if (Error Err = GA.materialize())
695           return std::move(Err);
696         GlobalsToImport.insert(&GA);
697       }
698     }
699 
700     // Link in the specified functions.
701     if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
702       return true;
703 
704     if (PrintImports) {
705       for (const auto *GV : GlobalsToImport)
706         dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
707                << " from " << SrcModule->getSourceFileName() << "\n";
708     }
709 
710     // Instruct the linker that the client will take care of linkonce resolution
711     unsigned Flags = Linker::Flags::None;
712     if (!ForceImportReferencedDiscardableSymbols)
713       Flags |= Linker::Flags::DontForceLinkLinkonceODR;
714 
715     if (TheLinker.linkInModule(std::move(SrcModule), Flags, &GlobalsToImport))
716       report_fatal_error("Function Import: link error");
717 
718     ImportedCount += GlobalsToImport.size();
719   }
720 
721   NumImported += ImportedCount;
722 
723   DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
724                << DestModule.getModuleIdentifier() << "\n");
725   return ImportedCount;
726 }
727 
728 /// Summary file to use for function importing when using -function-import from
729 /// the command line.
730 static cl::opt<std::string>
731     SummaryFile("summary-file",
732                 cl::desc("The summary file to use for function importing."));
733 
734 static bool doImportingForModule(Module &M) {
735   if (SummaryFile.empty())
736     report_fatal_error("error: -function-import requires -summary-file\n");
737   Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
738       getModuleSummaryIndexForFile(SummaryFile);
739   if (!IndexPtrOrErr) {
740     logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
741                           "Error loading file '" + SummaryFile + "': ");
742     return false;
743   }
744   std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
745 
746   // First step is collecting the import list.
747   FunctionImporter::ImportMapTy ImportList;
748   ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
749                                     ImportList);
750 
751   // Conservatively mark all internal values as promoted. This interface is
752   // only used when doing importing via the function importing pass. The pass
753   // is only enabled when testing importing via the 'opt' tool, which does
754   // not do the ThinLink that would normally determine what values to promote.
755   for (auto &I : *Index) {
756     for (auto &S : I.second) {
757       if (GlobalValue::isLocalLinkage(S->linkage()))
758         S->setLinkage(GlobalValue::ExternalLinkage);
759     }
760   }
761 
762   // Next we need to promote to global scope and rename any local values that
763   // are potentially exported to other modules.
764   if (renameModuleForThinLTO(M, *Index, nullptr)) {
765     errs() << "Error renaming module\n";
766     return false;
767   }
768 
769   // Perform the import now.
770   auto ModuleLoader = [&M](StringRef Identifier) {
771     return loadFile(Identifier, M.getContext());
772   };
773   FunctionImporter Importer(*Index, ModuleLoader);
774   Expected<bool> Result = Importer.importFunctions(
775       M, ImportList, !DontForceImportReferencedDiscardableSymbols);
776 
777   // FIXME: Probably need to propagate Errors through the pass manager.
778   if (!Result) {
779     logAllUnhandledErrors(Result.takeError(), errs(),
780                           "Error importing module: ");
781     return false;
782   }
783 
784   return *Result;
785 }
786 
787 namespace {
788 /// Pass that performs cross-module function import provided a summary file.
789 class FunctionImportLegacyPass : public ModulePass {
790 public:
791   /// Pass identification, replacement for typeid
792   static char ID;
793 
794   /// Specify pass name for debug output
795   StringRef getPassName() const override { return "Function Importing"; }
796 
797   explicit FunctionImportLegacyPass() : ModulePass(ID) {}
798 
799   bool runOnModule(Module &M) override {
800     if (skipModule(M))
801       return false;
802 
803     return doImportingForModule(M);
804   }
805 };
806 } // anonymous namespace
807 
808 PreservedAnalyses FunctionImportPass::run(Module &M,
809                                           ModuleAnalysisManager &AM) {
810   if (!doImportingForModule(M))
811     return PreservedAnalyses::all();
812 
813   return PreservedAnalyses::none();
814 }
815 
816 char FunctionImportLegacyPass::ID = 0;
817 INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
818                 "Summary Based Function Import", false, false)
819 
820 namespace llvm {
821 Pass *createFunctionImportPass() {
822   return new FunctionImportLegacyPass();
823 }
824 }
825