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