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