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