1 //===- FunctionImport.cpp - ThinLTO Summary-based Function Import ---------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements Function import based on summaries.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "llvm/Transforms/IPO/FunctionImport.h"
14 #include "llvm/ADT/ArrayRef.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SetVector.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/ADT/StringMap.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/StringSet.h"
22 #include "llvm/Bitcode/BitcodeReader.h"
23 #include "llvm/IR/AutoUpgrade.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/IR/GlobalAlias.h"
27 #include "llvm/IR/GlobalObject.h"
28 #include "llvm/IR/GlobalValue.h"
29 #include "llvm/IR/GlobalVariable.h"
30 #include "llvm/IR/Metadata.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/ModuleSummaryIndex.h"
33 #include "llvm/IRReader/IRReader.h"
34 #include "llvm/InitializePasses.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(NumImportedFunctionsThinLink,
64           "Number of functions thin link decided to import");
65 STATISTIC(NumImportedHotFunctionsThinLink,
66           "Number of hot functions thin link decided to import");
67 STATISTIC(NumImportedCriticalFunctionsThinLink,
68           "Number of critical functions thin link decided to import");
69 STATISTIC(NumImportedGlobalVarsThinLink,
70           "Number of global variables thin link decided to import");
71 STATISTIC(NumImportedFunctions, "Number of functions imported in backend");
72 STATISTIC(NumImportedGlobalVars,
73           "Number of global variables imported in backend");
74 STATISTIC(NumImportedModules, "Number of modules imported from");
75 STATISTIC(NumDeadSymbols, "Number of dead stripped symbols in index");
76 STATISTIC(NumLiveSymbols, "Number of live symbols in index");
77 
78 /// Limit on instruction count of imported functions.
79 static cl::opt<unsigned> ImportInstrLimit(
80     "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
81     cl::desc("Only import functions with less than N instructions"));
82 
83 static cl::opt<int> ImportCutoff(
84     "import-cutoff", cl::init(-1), cl::Hidden, cl::value_desc("N"),
85     cl::desc("Only import first N functions if N>=0 (default -1)"));
86 
87 static cl::opt<float>
88     ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7),
89                       cl::Hidden, cl::value_desc("x"),
90                       cl::desc("As we import functions, multiply the "
91                                "`import-instr-limit` threshold by this factor "
92                                "before processing newly imported functions"));
93 
94 static cl::opt<float> ImportHotInstrFactor(
95     "import-hot-evolution-factor", cl::init(1.0), cl::Hidden,
96     cl::value_desc("x"),
97     cl::desc("As we import functions called from hot callsite, multiply the "
98              "`import-instr-limit` threshold by this factor "
99              "before processing newly imported functions"));
100 
101 static cl::opt<float> ImportHotMultiplier(
102     "import-hot-multiplier", cl::init(10.0), cl::Hidden, cl::value_desc("x"),
103     cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"));
104 
105 static cl::opt<float> ImportCriticalMultiplier(
106     "import-critical-multiplier", cl::init(100.0), cl::Hidden,
107     cl::value_desc("x"),
108     cl::desc(
109         "Multiply the `import-instr-limit` threshold for critical callsites"));
110 
111 // FIXME: This multiplier was not really tuned up.
112 static cl::opt<float> ImportColdMultiplier(
113     "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"),
114     cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"));
115 
116 static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
117                                   cl::desc("Print imported functions"));
118 
119 static cl::opt<bool> PrintImportFailures(
120     "print-import-failures", cl::init(false), cl::Hidden,
121     cl::desc("Print information for functions rejected for importing"));
122 
123 static cl::opt<bool> ComputeDead("compute-dead", cl::init(true), cl::Hidden,
124                                  cl::desc("Compute dead symbols"));
125 
126 static cl::opt<bool> EnableImportMetadata(
127     "enable-import-metadata", cl::init(false), cl::Hidden,
128     cl::desc("Enable import metadata like 'thinlto_src_module'"));
129 
130 /// Summary file to use for function importing when using -function-import from
131 /// the command line.
132 static cl::opt<std::string>
133     SummaryFile("summary-file",
134                 cl::desc("The summary file to use for function importing."));
135 
136 /// Used when testing importing from distributed indexes via opt
137 // -function-import.
138 static cl::opt<bool>
139     ImportAllIndex("import-all-index",
140                    cl::desc("Import all external functions in index."));
141 
142 // Load lazily a module from \p FileName in \p Context.
143 static std::unique_ptr<Module> loadFile(const std::string &FileName,
144                                         LLVMContext &Context) {
145   SMDiagnostic Err;
146   LLVM_DEBUG(dbgs() << "Loading '" << FileName << "'\n");
147   // Metadata isn't loaded until functions are imported, to minimize
148   // the memory overhead.
149   std::unique_ptr<Module> Result =
150       getLazyIRFileModule(FileName, Err, Context,
151                           /* ShouldLazyLoadMetadata = */ true);
152   if (!Result) {
153     Err.print("function-import", errs());
154     report_fatal_error("Abort");
155   }
156 
157   return Result;
158 }
159 
160 /// Given a list of possible callee implementation for a call site, select one
161 /// that fits the \p Threshold.
162 ///
163 /// FIXME: select "best" instead of first that fits. But what is "best"?
164 /// - The smallest: more likely to be inlined.
165 /// - The one with the least outgoing edges (already well optimized).
166 /// - One from a module already being imported from in order to reduce the
167 ///   number of source modules parsed/linked.
168 /// - One that has PGO data attached.
169 /// - [insert you fancy metric here]
170 static const GlobalValueSummary *
171 selectCallee(const ModuleSummaryIndex &Index,
172              ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
173              unsigned Threshold, StringRef CallerModulePath,
174              FunctionImporter::ImportFailureReason &Reason,
175              GlobalValue::GUID GUID) {
176   Reason = FunctionImporter::ImportFailureReason::None;
177   auto It = llvm::find_if(
178       CalleeSummaryList,
179       [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
180         auto *GVSummary = SummaryPtr.get();
181         if (!Index.isGlobalValueLive(GVSummary)) {
182           Reason = FunctionImporter::ImportFailureReason::NotLive;
183           return false;
184         }
185 
186         // For SamplePGO, in computeImportForFunction the OriginalId
187         // may have been used to locate the callee summary list (See
188         // comment there).
189         // The mapping from OriginalId to GUID may return a GUID
190         // that corresponds to a static variable. Filter it out here.
191         // This can happen when
192         // 1) There is a call to a library function which is not defined
193         // in the index.
194         // 2) There is a static variable with the  OriginalGUID identical
195         // to the GUID of the library function in 1);
196         // When this happens, the logic for SamplePGO kicks in and
197         // the static variable in 2) will be found, which needs to be
198         // filtered out.
199         if (GVSummary->getSummaryKind() == GlobalValueSummary::GlobalVarKind) {
200           Reason = FunctionImporter::ImportFailureReason::GlobalVar;
201           return false;
202         }
203         if (GlobalValue::isInterposableLinkage(GVSummary->linkage())) {
204           Reason = FunctionImporter::ImportFailureReason::InterposableLinkage;
205           // There is no point in importing these, we can't inline them
206           return false;
207         }
208 
209         auto *Summary = cast<FunctionSummary>(GVSummary->getBaseObject());
210 
211         // If this is a local function, make sure we import the copy
212         // in the caller's module. The only time a local function can
213         // share an entry in the index is if there is a local with the same name
214         // in another module that had the same source file name (in a different
215         // directory), where each was compiled in their own directory so there
216         // was not distinguishing path.
217         // However, do the import from another module if there is only one
218         // entry in the list - in that case this must be a reference due
219         // to indirect call profile data, since a function pointer can point to
220         // a local in another module.
221         if (GlobalValue::isLocalLinkage(Summary->linkage()) &&
222             CalleeSummaryList.size() > 1 &&
223             Summary->modulePath() != CallerModulePath) {
224           Reason =
225               FunctionImporter::ImportFailureReason::LocalLinkageNotInModule;
226           return false;
227         }
228 
229         if ((Summary->instCount() > Threshold) &&
230             !Summary->fflags().AlwaysInline) {
231           Reason = FunctionImporter::ImportFailureReason::TooLarge;
232           return false;
233         }
234 
235         // Skip if it isn't legal to import (e.g. may reference unpromotable
236         // locals).
237         if (Summary->notEligibleToImport()) {
238           Reason = FunctionImporter::ImportFailureReason::NotEligible;
239           return false;
240         }
241 
242         // Don't bother importing if we can't inline it anyway.
243         if (Summary->fflags().NoInline) {
244           Reason = FunctionImporter::ImportFailureReason::NoInline;
245           return false;
246         }
247 
248         return true;
249       });
250   if (It == CalleeSummaryList.end())
251     return nullptr;
252 
253   return cast<GlobalValueSummary>(It->get());
254 }
255 
256 namespace {
257 
258 using EdgeInfo =
259     std::tuple<const GlobalValueSummary *, unsigned /* Threshold */>;
260 
261 } // anonymous namespace
262 
263 static ValueInfo
264 updateValueInfoForIndirectCalls(const ModuleSummaryIndex &Index, ValueInfo VI) {
265   if (!VI.getSummaryList().empty())
266     return VI;
267   // For SamplePGO, the indirect call targets for local functions will
268   // have its original name annotated in profile. We try to find the
269   // corresponding PGOFuncName as the GUID.
270   // FIXME: Consider updating the edges in the graph after building
271   // it, rather than needing to perform this mapping on each walk.
272   auto GUID = Index.getGUIDFromOriginalID(VI.getGUID());
273   if (GUID == 0)
274     return ValueInfo();
275   return Index.getValueInfo(GUID);
276 }
277 
278 static bool shouldImportGlobal(const ValueInfo &VI,
279                                const GVSummaryMapTy &DefinedGVSummaries) {
280   const auto &GVS = DefinedGVSummaries.find(VI.getGUID());
281   if (GVS == DefinedGVSummaries.end())
282     return true;
283   // We should not skip import if the module contains a definition with
284   // interposable linkage type. This is required for correctness in
285   // the situation with two following conditions:
286   // * the def with interposable linkage is non-prevailing,
287   // * there is a prevailing def available for import and marked read-only.
288   // In this case, the non-prevailing def will be converted to a declaration,
289   // while the prevailing one becomes internal, thus no definitions will be
290   // available for linking. In order to prevent undefined symbol link error,
291   // the prevailing definition must be imported.
292   // FIXME: Consider adding a check that the suitable prevailing definition
293   // exists and marked read-only.
294   if (VI.getSummaryList().size() > 1 &&
295       GlobalValue::isInterposableLinkage(GVS->second->linkage()))
296     return true;
297 
298   return false;
299 }
300 
301 static void computeImportForReferencedGlobals(
302     const GlobalValueSummary &Summary, const ModuleSummaryIndex &Index,
303     const GVSummaryMapTy &DefinedGVSummaries,
304     SmallVectorImpl<EdgeInfo> &Worklist,
305     FunctionImporter::ImportMapTy &ImportList,
306     StringMap<FunctionImporter::ExportSetTy> *ExportLists) {
307   for (auto &VI : Summary.refs()) {
308     if (!shouldImportGlobal(VI, DefinedGVSummaries)) {
309       LLVM_DEBUG(
310           dbgs() << "Ref ignored! Target already in destination module.\n");
311       continue;
312     }
313 
314     LLVM_DEBUG(dbgs() << " ref -> " << VI << "\n");
315 
316     // If this is a local variable, make sure we import the copy
317     // in the caller's module. The only time a local variable can
318     // share an entry in the index is if there is a local with the same name
319     // in another module that had the same source file name (in a different
320     // directory), where each was compiled in their own directory so there
321     // was not distinguishing path.
322     auto LocalNotInModule = [&](const GlobalValueSummary *RefSummary) -> bool {
323       return GlobalValue::isLocalLinkage(RefSummary->linkage()) &&
324              RefSummary->modulePath() != Summary.modulePath();
325     };
326 
327     for (auto &RefSummary : VI.getSummaryList())
328       if (isa<GlobalVarSummary>(RefSummary.get()) &&
329           Index.canImportGlobalVar(RefSummary.get(), /* AnalyzeRefs */ true) &&
330           !LocalNotInModule(RefSummary.get())) {
331         auto ILI = ImportList[RefSummary->modulePath()].insert(VI.getGUID());
332         // Only update stat and exports if we haven't already imported this
333         // variable.
334         if (!ILI.second)
335           break;
336         NumImportedGlobalVarsThinLink++;
337         // Any references made by this variable will be marked exported later,
338         // in ComputeCrossModuleImport, after import decisions are complete,
339         // which is more efficient than adding them here.
340         if (ExportLists)
341           (*ExportLists)[RefSummary->modulePath()].insert(VI);
342 
343         // If variable is not writeonly we attempt to recursively analyze
344         // its references in order to import referenced constants.
345         if (!Index.isWriteOnly(cast<GlobalVarSummary>(RefSummary.get())))
346           Worklist.emplace_back(RefSummary.get(), 0);
347         break;
348       }
349   }
350 }
351 
352 static const char *
353 getFailureName(FunctionImporter::ImportFailureReason Reason) {
354   switch (Reason) {
355   case FunctionImporter::ImportFailureReason::None:
356     return "None";
357   case FunctionImporter::ImportFailureReason::GlobalVar:
358     return "GlobalVar";
359   case FunctionImporter::ImportFailureReason::NotLive:
360     return "NotLive";
361   case FunctionImporter::ImportFailureReason::TooLarge:
362     return "TooLarge";
363   case FunctionImporter::ImportFailureReason::InterposableLinkage:
364     return "InterposableLinkage";
365   case FunctionImporter::ImportFailureReason::LocalLinkageNotInModule:
366     return "LocalLinkageNotInModule";
367   case FunctionImporter::ImportFailureReason::NotEligible:
368     return "NotEligible";
369   case FunctionImporter::ImportFailureReason::NoInline:
370     return "NoInline";
371   }
372   llvm_unreachable("invalid reason");
373 }
374 
375 /// Compute the list of functions to import for a given caller. Mark these
376 /// imported functions and the symbols they reference in their source module as
377 /// exported from their source module.
378 static void computeImportForFunction(
379     const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
380     const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
381     SmallVectorImpl<EdgeInfo> &Worklist,
382     FunctionImporter::ImportMapTy &ImportList,
383     StringMap<FunctionImporter::ExportSetTy> *ExportLists,
384     FunctionImporter::ImportThresholdsTy &ImportThresholds) {
385   computeImportForReferencedGlobals(Summary, Index, DefinedGVSummaries,
386                                     Worklist, ImportList, ExportLists);
387   static int ImportCount = 0;
388   for (auto &Edge : Summary.calls()) {
389     ValueInfo VI = Edge.first;
390     LLVM_DEBUG(dbgs() << " edge -> " << VI << " Threshold:" << Threshold
391                       << "\n");
392 
393     if (ImportCutoff >= 0 && ImportCount >= ImportCutoff) {
394       LLVM_DEBUG(dbgs() << "ignored! import-cutoff value of " << ImportCutoff
395                         << " reached.\n");
396       continue;
397     }
398 
399     VI = updateValueInfoForIndirectCalls(Index, VI);
400     if (!VI)
401       continue;
402 
403     if (DefinedGVSummaries.count(VI.getGUID())) {
404       // FIXME: Consider not skipping import if the module contains
405       // a non-prevailing def with interposable linkage. The prevailing copy
406       // can safely be imported (see shouldImportGlobal()).
407       LLVM_DEBUG(dbgs() << "ignored! Target already in destination module.\n");
408       continue;
409     }
410 
411     auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
412       if (Hotness == CalleeInfo::HotnessType::Hot)
413         return ImportHotMultiplier;
414       if (Hotness == CalleeInfo::HotnessType::Cold)
415         return ImportColdMultiplier;
416       if (Hotness == CalleeInfo::HotnessType::Critical)
417         return ImportCriticalMultiplier;
418       return 1.0;
419     };
420 
421     const auto NewThreshold =
422         Threshold * GetBonusMultiplier(Edge.second.getHotness());
423 
424     auto IT = ImportThresholds.insert(std::make_pair(
425         VI.getGUID(), std::make_tuple(NewThreshold, nullptr, nullptr)));
426     bool PreviouslyVisited = !IT.second;
427     auto &ProcessedThreshold = std::get<0>(IT.first->second);
428     auto &CalleeSummary = std::get<1>(IT.first->second);
429     auto &FailureInfo = std::get<2>(IT.first->second);
430 
431     bool IsHotCallsite =
432         Edge.second.getHotness() == CalleeInfo::HotnessType::Hot;
433     bool IsCriticalCallsite =
434         Edge.second.getHotness() == CalleeInfo::HotnessType::Critical;
435 
436     const FunctionSummary *ResolvedCalleeSummary = nullptr;
437     if (CalleeSummary) {
438       assert(PreviouslyVisited);
439       // Since the traversal of the call graph is DFS, we can revisit a function
440       // a second time with a higher threshold. In this case, it is added back
441       // to the worklist with the new threshold (so that its own callee chains
442       // can be considered with the higher threshold).
443       if (NewThreshold <= ProcessedThreshold) {
444         LLVM_DEBUG(
445             dbgs() << "ignored! Target was already imported with Threshold "
446                    << ProcessedThreshold << "\n");
447         continue;
448       }
449       // Update with new larger threshold.
450       ProcessedThreshold = NewThreshold;
451       ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
452     } else {
453       // If we already rejected importing a callee at the same or higher
454       // threshold, don't waste time calling selectCallee.
455       if (PreviouslyVisited && NewThreshold <= ProcessedThreshold) {
456         LLVM_DEBUG(
457             dbgs() << "ignored! Target was already rejected with Threshold "
458             << ProcessedThreshold << "\n");
459         if (PrintImportFailures) {
460           assert(FailureInfo &&
461                  "Expected FailureInfo for previously rejected candidate");
462           FailureInfo->Attempts++;
463         }
464         continue;
465       }
466 
467       FunctionImporter::ImportFailureReason Reason;
468       CalleeSummary = selectCallee(Index, VI.getSummaryList(), NewThreshold,
469                                    Summary.modulePath(), Reason, VI.getGUID());
470       if (!CalleeSummary) {
471         // Update with new larger threshold if this was a retry (otherwise
472         // we would have already inserted with NewThreshold above). Also
473         // update failure info if requested.
474         if (PreviouslyVisited) {
475           ProcessedThreshold = NewThreshold;
476           if (PrintImportFailures) {
477             assert(FailureInfo &&
478                    "Expected FailureInfo for previously rejected candidate");
479             FailureInfo->Reason = Reason;
480             FailureInfo->Attempts++;
481             FailureInfo->MaxHotness =
482                 std::max(FailureInfo->MaxHotness, Edge.second.getHotness());
483           }
484         } else if (PrintImportFailures) {
485           assert(!FailureInfo &&
486                  "Expected no FailureInfo for newly rejected candidate");
487           FailureInfo = std::make_unique<FunctionImporter::ImportFailureInfo>(
488               VI, Edge.second.getHotness(), Reason, 1);
489         }
490         LLVM_DEBUG(
491             dbgs() << "ignored! No qualifying callee with summary found.\n");
492         continue;
493       }
494 
495       // "Resolve" the summary
496       CalleeSummary = CalleeSummary->getBaseObject();
497       ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
498 
499       assert((ResolvedCalleeSummary->fflags().AlwaysInline ||
500 	     (ResolvedCalleeSummary->instCount() <= NewThreshold)) &&
501              "selectCallee() didn't honor the threshold");
502 
503       auto ExportModulePath = ResolvedCalleeSummary->modulePath();
504       auto ILI = ImportList[ExportModulePath].insert(VI.getGUID());
505       // We previously decided to import this GUID definition if it was already
506       // inserted in the set of imports from the exporting module.
507       bool PreviouslyImported = !ILI.second;
508       if (!PreviouslyImported) {
509         NumImportedFunctionsThinLink++;
510         if (IsHotCallsite)
511           NumImportedHotFunctionsThinLink++;
512         if (IsCriticalCallsite)
513           NumImportedCriticalFunctionsThinLink++;
514       }
515 
516       // Any calls/references made by this function will be marked exported
517       // later, in ComputeCrossModuleImport, after import decisions are
518       // complete, which is more efficient than adding them here.
519       if (ExportLists)
520         (*ExportLists)[ExportModulePath].insert(VI);
521     }
522 
523     auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
524       // Adjust the threshold for next level of imported functions.
525       // The threshold is different for hot callsites because we can then
526       // inline chains of hot calls.
527       if (IsHotCallsite)
528         return Threshold * ImportHotInstrFactor;
529       return Threshold * ImportInstrFactor;
530     };
531 
532     const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
533 
534     ImportCount++;
535 
536     // Insert the newly imported function to the worklist.
537     Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold);
538   }
539 }
540 
541 /// Given the list of globals defined in a module, compute the list of imports
542 /// as well as the list of "exports", i.e. the list of symbols referenced from
543 /// another module (that may require promotion).
544 static void ComputeImportForModule(
545     const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
546     StringRef ModName, FunctionImporter::ImportMapTy &ImportList,
547     StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
548   // Worklist contains the list of function imported in this module, for which
549   // we will analyse the callees and may import further down the callgraph.
550   SmallVector<EdgeInfo, 128> Worklist;
551   FunctionImporter::ImportThresholdsTy ImportThresholds;
552 
553   // Populate the worklist with the import for the functions in the current
554   // module
555   for (auto &GVSummary : DefinedGVSummaries) {
556 #ifndef NDEBUG
557     // FIXME: Change the GVSummaryMapTy to hold ValueInfo instead of GUID
558     // so this map look up (and possibly others) can be avoided.
559     auto VI = Index.getValueInfo(GVSummary.first);
560 #endif
561     if (!Index.isGlobalValueLive(GVSummary.second)) {
562       LLVM_DEBUG(dbgs() << "Ignores Dead GUID: " << VI << "\n");
563       continue;
564     }
565     auto *FuncSummary =
566         dyn_cast<FunctionSummary>(GVSummary.second->getBaseObject());
567     if (!FuncSummary)
568       // Skip import for global variables
569       continue;
570     LLVM_DEBUG(dbgs() << "Initialize import for " << VI << "\n");
571     computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
572                              DefinedGVSummaries, Worklist, ImportList,
573                              ExportLists, ImportThresholds);
574   }
575 
576   // Process the newly imported functions and add callees to the worklist.
577   while (!Worklist.empty()) {
578     auto GVInfo = Worklist.pop_back_val();
579     auto *Summary = std::get<0>(GVInfo);
580     auto Threshold = std::get<1>(GVInfo);
581 
582     if (auto *FS = dyn_cast<FunctionSummary>(Summary))
583       computeImportForFunction(*FS, Index, Threshold, DefinedGVSummaries,
584                                Worklist, ImportList, ExportLists,
585                                ImportThresholds);
586     else
587       computeImportForReferencedGlobals(*Summary, Index, DefinedGVSummaries,
588                                         Worklist, ImportList, ExportLists);
589   }
590 
591   // Print stats about functions considered but rejected for importing
592   // when requested.
593   if (PrintImportFailures) {
594     dbgs() << "Missed imports into module " << ModName << "\n";
595     for (auto &I : ImportThresholds) {
596       auto &ProcessedThreshold = std::get<0>(I.second);
597       auto &CalleeSummary = std::get<1>(I.second);
598       auto &FailureInfo = std::get<2>(I.second);
599       if (CalleeSummary)
600         continue; // We are going to import.
601       assert(FailureInfo);
602       FunctionSummary *FS = nullptr;
603       if (!FailureInfo->VI.getSummaryList().empty())
604         FS = dyn_cast<FunctionSummary>(
605             FailureInfo->VI.getSummaryList()[0]->getBaseObject());
606       dbgs() << FailureInfo->VI
607              << ": Reason = " << getFailureName(FailureInfo->Reason)
608              << ", Threshold = " << ProcessedThreshold
609              << ", Size = " << (FS ? (int)FS->instCount() : -1)
610              << ", MaxHotness = " << getHotnessName(FailureInfo->MaxHotness)
611              << ", Attempts = " << FailureInfo->Attempts << "\n";
612     }
613   }
614 }
615 
616 #ifndef NDEBUG
617 static bool isGlobalVarSummary(const ModuleSummaryIndex &Index, ValueInfo VI) {
618   auto SL = VI.getSummaryList();
619   return SL.empty()
620              ? false
621              : SL[0]->getSummaryKind() == GlobalValueSummary::GlobalVarKind;
622 }
623 
624 static bool isGlobalVarSummary(const ModuleSummaryIndex &Index,
625                                GlobalValue::GUID G) {
626   if (const auto &VI = Index.getValueInfo(G))
627     return isGlobalVarSummary(Index, VI);
628   return false;
629 }
630 
631 template <class T>
632 static unsigned numGlobalVarSummaries(const ModuleSummaryIndex &Index,
633                                       T &Cont) {
634   unsigned NumGVS = 0;
635   for (auto &V : Cont)
636     if (isGlobalVarSummary(Index, V))
637       ++NumGVS;
638   return NumGVS;
639 }
640 #endif
641 
642 #ifndef NDEBUG
643 static bool
644 checkVariableImport(const ModuleSummaryIndex &Index,
645                     StringMap<FunctionImporter::ImportMapTy> &ImportLists,
646                     StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
647 
648   DenseSet<GlobalValue::GUID> FlattenedImports;
649 
650   for (auto &ImportPerModule : ImportLists)
651     for (auto &ExportPerModule : ImportPerModule.second)
652       FlattenedImports.insert(ExportPerModule.second.begin(),
653                               ExportPerModule.second.end());
654 
655   // Checks that all GUIDs of read/writeonly vars we see in export lists
656   // are also in the import lists. Otherwise we my face linker undefs,
657   // because readonly and writeonly vars are internalized in their
658   // source modules.
659   auto IsReadOrWriteOnlyVar = [&](StringRef ModulePath, const ValueInfo &VI) {
660     auto *GVS = dyn_cast_or_null<GlobalVarSummary>(
661         Index.findSummaryInModule(VI, ModulePath));
662     return GVS && (Index.isReadOnly(GVS) || Index.isWriteOnly(GVS));
663   };
664 
665   for (auto &ExportPerModule : ExportLists)
666     for (auto &VI : ExportPerModule.second)
667       if (!FlattenedImports.count(VI.getGUID()) &&
668           IsReadOrWriteOnlyVar(ExportPerModule.first(), VI))
669         return false;
670 
671   return true;
672 }
673 #endif
674 
675 /// Compute all the import and export for every module using the Index.
676 void llvm::ComputeCrossModuleImport(
677     const ModuleSummaryIndex &Index,
678     const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
679     StringMap<FunctionImporter::ImportMapTy> &ImportLists,
680     StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
681   // For each module that has function defined, compute the import/export lists.
682   for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
683     auto &ImportList = ImportLists[DefinedGVSummaries.first()];
684     LLVM_DEBUG(dbgs() << "Computing import for Module '"
685                       << DefinedGVSummaries.first() << "'\n");
686     ComputeImportForModule(DefinedGVSummaries.second, Index,
687                            DefinedGVSummaries.first(), ImportList,
688                            &ExportLists);
689   }
690 
691   // When computing imports we only added the variables and functions being
692   // imported to the export list. We also need to mark any references and calls
693   // they make as exported as well. We do this here, as it is more efficient
694   // since we may import the same values multiple times into different modules
695   // during the import computation.
696   for (auto &ELI : ExportLists) {
697     FunctionImporter::ExportSetTy NewExports;
698     const auto &DefinedGVSummaries =
699         ModuleToDefinedGVSummaries.lookup(ELI.first());
700     for (auto &EI : ELI.second) {
701       // Find the copy defined in the exporting module so that we can mark the
702       // values it references in that specific definition as exported.
703       // Below we will add all references and called values, without regard to
704       // whether they are also defined in this module. We subsequently prune the
705       // list to only include those defined in the exporting module, see comment
706       // there as to why.
707       auto DS = DefinedGVSummaries.find(EI.getGUID());
708       // Anything marked exported during the import computation must have been
709       // defined in the exporting module.
710       assert(DS != DefinedGVSummaries.end());
711       auto *S = DS->getSecond();
712       S = S->getBaseObject();
713       if (auto *GVS = dyn_cast<GlobalVarSummary>(S)) {
714         // Export referenced functions and variables. We don't export/promote
715         // objects referenced by writeonly variable initializer, because
716         // we convert such variables initializers to "zeroinitializer".
717         // See processGlobalForThinLTO.
718         if (!Index.isWriteOnly(GVS))
719           for (const auto &VI : GVS->refs())
720             NewExports.insert(VI);
721       } else {
722         auto *FS = cast<FunctionSummary>(S);
723         for (auto &Edge : FS->calls())
724           NewExports.insert(Edge.first);
725         for (auto &Ref : FS->refs())
726           NewExports.insert(Ref);
727       }
728     }
729     // Prune list computed above to only include values defined in the exporting
730     // module. We do this after the above insertion since we may hit the same
731     // ref/call target multiple times in above loop, and it is more efficient to
732     // avoid a set lookup each time.
733     for (auto EI = NewExports.begin(); EI != NewExports.end();) {
734       if (!DefinedGVSummaries.count(EI->getGUID()))
735         NewExports.erase(EI++);
736       else
737         ++EI;
738     }
739     ELI.second.insert(NewExports.begin(), NewExports.end());
740   }
741 
742   assert(checkVariableImport(Index, ImportLists, ExportLists));
743 #ifndef NDEBUG
744   LLVM_DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
745                     << " modules:\n");
746   for (auto &ModuleImports : ImportLists) {
747     auto ModName = ModuleImports.first();
748     auto &Exports = ExportLists[ModName];
749     unsigned NumGVS = numGlobalVarSummaries(Index, Exports);
750     LLVM_DEBUG(dbgs() << "* Module " << ModName << " exports "
751                       << Exports.size() - NumGVS << " functions and " << NumGVS
752                       << " vars. Imports from " << ModuleImports.second.size()
753                       << " modules.\n");
754     for (auto &Src : ModuleImports.second) {
755       auto SrcModName = Src.first();
756       unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second);
757       LLVM_DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod
758                         << " functions imported from " << SrcModName << "\n");
759       LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod
760                         << " global vars imported from " << SrcModName << "\n");
761     }
762   }
763 #endif
764 }
765 
766 #ifndef NDEBUG
767 static void dumpImportListForModule(const ModuleSummaryIndex &Index,
768                                     StringRef ModulePath,
769                                     FunctionImporter::ImportMapTy &ImportList) {
770   LLVM_DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
771                     << ImportList.size() << " modules.\n");
772   for (auto &Src : ImportList) {
773     auto SrcModName = Src.first();
774     unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second);
775     LLVM_DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod
776                       << " functions imported from " << SrcModName << "\n");
777     LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod << " vars imported from "
778                       << SrcModName << "\n");
779   }
780 }
781 #endif
782 
783 /// Compute all the imports for the given module in the Index.
784 void llvm::ComputeCrossModuleImportForModule(
785     StringRef ModulePath, const ModuleSummaryIndex &Index,
786     FunctionImporter::ImportMapTy &ImportList) {
787   // Collect the list of functions this module defines.
788   // GUID -> Summary
789   GVSummaryMapTy FunctionSummaryMap;
790   Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
791 
792   // Compute the import list for this module.
793   LLVM_DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
794   ComputeImportForModule(FunctionSummaryMap, Index, ModulePath, ImportList);
795 
796 #ifndef NDEBUG
797   dumpImportListForModule(Index, ModulePath, ImportList);
798 #endif
799 }
800 
801 // Mark all external summaries in Index for import into the given module.
802 // Used for distributed builds using a distributed index.
803 void llvm::ComputeCrossModuleImportForModuleFromIndex(
804     StringRef ModulePath, const ModuleSummaryIndex &Index,
805     FunctionImporter::ImportMapTy &ImportList) {
806   for (auto &GlobalList : Index) {
807     // Ignore entries for undefined references.
808     if (GlobalList.second.SummaryList.empty())
809       continue;
810 
811     auto GUID = GlobalList.first;
812     assert(GlobalList.second.SummaryList.size() == 1 &&
813            "Expected individual combined index to have one summary per GUID");
814     auto &Summary = GlobalList.second.SummaryList[0];
815     // Skip the summaries for the importing module. These are included to
816     // e.g. record required linkage changes.
817     if (Summary->modulePath() == ModulePath)
818       continue;
819     // Add an entry to provoke importing by thinBackend.
820     ImportList[Summary->modulePath()].insert(GUID);
821   }
822 #ifndef NDEBUG
823   dumpImportListForModule(Index, ModulePath, ImportList);
824 #endif
825 }
826 
827 void llvm::computeDeadSymbols(
828     ModuleSummaryIndex &Index,
829     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
830     function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing) {
831   assert(!Index.withGlobalValueDeadStripping());
832   if (!ComputeDead)
833     return;
834   if (GUIDPreservedSymbols.empty())
835     // Don't do anything when nothing is live, this is friendly with tests.
836     return;
837   unsigned LiveSymbols = 0;
838   SmallVector<ValueInfo, 128> Worklist;
839   Worklist.reserve(GUIDPreservedSymbols.size() * 2);
840   for (auto GUID : GUIDPreservedSymbols) {
841     ValueInfo VI = Index.getValueInfo(GUID);
842     if (!VI)
843       continue;
844     for (auto &S : VI.getSummaryList())
845       S->setLive(true);
846   }
847 
848   // Add values flagged in the index as live roots to the worklist.
849   for (const auto &Entry : Index) {
850     auto VI = Index.getValueInfo(Entry);
851     for (auto &S : Entry.second.SummaryList)
852       if (S->isLive()) {
853         LLVM_DEBUG(dbgs() << "Live root: " << VI << "\n");
854         Worklist.push_back(VI);
855         ++LiveSymbols;
856         break;
857       }
858   }
859 
860   // Make value live and add it to the worklist if it was not live before.
861   auto visit = [&](ValueInfo VI, bool IsAliasee) {
862     // FIXME: If we knew which edges were created for indirect call profiles,
863     // we could skip them here. Any that are live should be reached via
864     // other edges, e.g. reference edges. Otherwise, using a profile collected
865     // on a slightly different binary might provoke preserving, importing
866     // and ultimately promoting calls to functions not linked into this
867     // binary, which increases the binary size unnecessarily. Note that
868     // if this code changes, the importer needs to change so that edges
869     // to functions marked dead are skipped.
870     VI = updateValueInfoForIndirectCalls(Index, VI);
871     if (!VI)
872       return;
873 
874     if (llvm::any_of(VI.getSummaryList(),
875                      [](const std::unique_ptr<llvm::GlobalValueSummary> &S) {
876                        return S->isLive();
877                      }))
878       return;
879 
880     // We only keep live symbols that are known to be non-prevailing if any are
881     // available_externally, linkonceodr, weakodr. Those symbols are discarded
882     // later in the EliminateAvailableExternally pass and setting them to
883     // not-live could break downstreams users of liveness information (PR36483)
884     // or limit optimization opportunities.
885     if (isPrevailing(VI.getGUID()) == PrevailingType::No) {
886       bool KeepAliveLinkage = false;
887       bool Interposable = false;
888       for (auto &S : VI.getSummaryList()) {
889         if (S->linkage() == GlobalValue::AvailableExternallyLinkage ||
890             S->linkage() == GlobalValue::WeakODRLinkage ||
891             S->linkage() == GlobalValue::LinkOnceODRLinkage)
892           KeepAliveLinkage = true;
893         else if (GlobalValue::isInterposableLinkage(S->linkage()))
894           Interposable = true;
895       }
896 
897       if (!IsAliasee) {
898         if (!KeepAliveLinkage)
899           return;
900 
901         if (Interposable)
902           report_fatal_error(
903               "Interposable and available_externally/linkonce_odr/weak_odr "
904               "symbol");
905       }
906     }
907 
908     for (auto &S : VI.getSummaryList())
909       S->setLive(true);
910     ++LiveSymbols;
911     Worklist.push_back(VI);
912   };
913 
914   while (!Worklist.empty()) {
915     auto VI = Worklist.pop_back_val();
916     for (auto &Summary : VI.getSummaryList()) {
917       if (auto *AS = dyn_cast<AliasSummary>(Summary.get())) {
918         // If this is an alias, visit the aliasee VI to ensure that all copies
919         // are marked live and it is added to the worklist for further
920         // processing of its references.
921         visit(AS->getAliaseeVI(), true);
922         continue;
923       }
924       for (auto Ref : Summary->refs())
925         visit(Ref, false);
926       if (auto *FS = dyn_cast<FunctionSummary>(Summary.get()))
927         for (auto Call : FS->calls())
928           visit(Call.first, false);
929     }
930   }
931   Index.setWithGlobalValueDeadStripping();
932 
933   unsigned DeadSymbols = Index.size() - LiveSymbols;
934   LLVM_DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols
935                     << " symbols Dead \n");
936   NumDeadSymbols += DeadSymbols;
937   NumLiveSymbols += LiveSymbols;
938 }
939 
940 // Compute dead symbols and propagate constants in combined index.
941 void llvm::computeDeadSymbolsWithConstProp(
942     ModuleSummaryIndex &Index,
943     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
944     function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing,
945     bool ImportEnabled) {
946   computeDeadSymbols(Index, GUIDPreservedSymbols, isPrevailing);
947   if (ImportEnabled)
948     Index.propagateAttributes(GUIDPreservedSymbols);
949 }
950 
951 /// Compute the set of summaries needed for a ThinLTO backend compilation of
952 /// \p ModulePath.
953 void llvm::gatherImportedSummariesForModule(
954     StringRef ModulePath,
955     const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
956     const FunctionImporter::ImportMapTy &ImportList,
957     std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
958   // Include all summaries from the importing module.
959   ModuleToSummariesForIndex[std::string(ModulePath)] =
960       ModuleToDefinedGVSummaries.lookup(ModulePath);
961   // Include summaries for imports.
962   for (auto &ILI : ImportList) {
963     auto &SummariesForIndex =
964         ModuleToSummariesForIndex[std::string(ILI.first())];
965     const auto &DefinedGVSummaries =
966         ModuleToDefinedGVSummaries.lookup(ILI.first());
967     for (auto &GI : ILI.second) {
968       const auto &DS = DefinedGVSummaries.find(GI);
969       assert(DS != DefinedGVSummaries.end() &&
970              "Expected a defined summary for imported global value");
971       SummariesForIndex[GI] = DS->second;
972     }
973   }
974 }
975 
976 /// Emit the files \p ModulePath will import from into \p OutputFilename.
977 std::error_code llvm::EmitImportsFiles(
978     StringRef ModulePath, StringRef OutputFilename,
979     const std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
980   std::error_code EC;
981   raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::OF_None);
982   if (EC)
983     return EC;
984   for (auto &ILI : ModuleToSummariesForIndex)
985     // The ModuleToSummariesForIndex map includes an entry for the current
986     // Module (needed for writing out the index files). We don't want to
987     // include it in the imports file, however, so filter it out.
988     if (ILI.first != ModulePath)
989       ImportsOS << ILI.first << "\n";
990   return std::error_code();
991 }
992 
993 bool llvm::convertToDeclaration(GlobalValue &GV) {
994   LLVM_DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName()
995                     << "\n");
996   if (Function *F = dyn_cast<Function>(&GV)) {
997     F->deleteBody();
998     F->clearMetadata();
999     F->setComdat(nullptr);
1000   } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
1001     V->setInitializer(nullptr);
1002     V->setLinkage(GlobalValue::ExternalLinkage);
1003     V->clearMetadata();
1004     V->setComdat(nullptr);
1005   } else {
1006     GlobalValue *NewGV;
1007     if (GV.getValueType()->isFunctionTy())
1008       NewGV =
1009           Function::Create(cast<FunctionType>(GV.getValueType()),
1010                            GlobalValue::ExternalLinkage, GV.getAddressSpace(),
1011                            "", GV.getParent());
1012     else
1013       NewGV =
1014           new GlobalVariable(*GV.getParent(), GV.getValueType(),
1015                              /*isConstant*/ false, GlobalValue::ExternalLinkage,
1016                              /*init*/ nullptr, "",
1017                              /*insertbefore*/ nullptr, GV.getThreadLocalMode(),
1018                              GV.getType()->getAddressSpace());
1019     NewGV->takeName(&GV);
1020     GV.replaceAllUsesWith(NewGV);
1021     return false;
1022   }
1023   if (!GV.isImplicitDSOLocal())
1024     GV.setDSOLocal(false);
1025   return true;
1026 }
1027 
1028 void llvm::thinLTOResolvePrevailingInModule(
1029     Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
1030   auto updateLinkage = [&](GlobalValue &GV) {
1031     // See if the global summary analysis computed a new resolved linkage.
1032     const auto &GS = DefinedGlobals.find(GV.getGUID());
1033     if (GS == DefinedGlobals.end())
1034       return;
1035     auto NewLinkage = GS->second->linkage();
1036     if (GlobalValue::isLocalLinkage(GV.getLinkage()) ||
1037         // Don't internalize anything here, because the code below
1038         // lacks necessary correctness checks. Leave this job to
1039         // LLVM 'internalize' pass.
1040         GlobalValue::isLocalLinkage(NewLinkage) ||
1041         // In case it was dead and already converted to declaration.
1042         GV.isDeclaration())
1043       return;
1044 
1045     // Set the potentially more constraining visibility computed from summaries.
1046     // The DefaultVisibility condition is because older GlobalValueSummary does
1047     // not record DefaultVisibility and we don't want to change protected/hidden
1048     // to default.
1049     if (GS->second->getVisibility() != GlobalValue::DefaultVisibility)
1050       GV.setVisibility(GS->second->getVisibility());
1051 
1052     if (NewLinkage == GV.getLinkage())
1053       return;
1054 
1055     // Check for a non-prevailing def that has interposable linkage
1056     // (e.g. non-odr weak or linkonce). In that case we can't simply
1057     // convert to available_externally, since it would lose the
1058     // interposable property and possibly get inlined. Simply drop
1059     // the definition in that case.
1060     if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) &&
1061         GlobalValue::isInterposableLinkage(GV.getLinkage())) {
1062       if (!convertToDeclaration(GV))
1063         // FIXME: Change this to collect replaced GVs and later erase
1064         // them from the parent module once thinLTOResolvePrevailingGUID is
1065         // changed to enable this for aliases.
1066         llvm_unreachable("Expected GV to be converted");
1067     } else {
1068       // If all copies of the original symbol had global unnamed addr and
1069       // linkonce_odr linkage, it should be an auto hide symbol. In that case
1070       // the thin link would have marked it as CanAutoHide. Add hidden visibility
1071       // to the symbol to preserve the property.
1072       if (NewLinkage == GlobalValue::WeakODRLinkage &&
1073           GS->second->canAutoHide()) {
1074         assert(GV.hasLinkOnceODRLinkage() && GV.hasGlobalUnnamedAddr());
1075         GV.setVisibility(GlobalValue::HiddenVisibility);
1076       }
1077 
1078       LLVM_DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName()
1079                         << "` from " << GV.getLinkage() << " to " << NewLinkage
1080                         << "\n");
1081       GV.setLinkage(NewLinkage);
1082     }
1083     // Remove declarations from comdats, including available_externally
1084     // as this is a declaration for the linker, and will be dropped eventually.
1085     // It is illegal for comdats to contain declarations.
1086     auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
1087     if (GO && GO->isDeclarationForLinker() && GO->hasComdat())
1088       GO->setComdat(nullptr);
1089   };
1090 
1091   // Process functions and global now
1092   for (auto &GV : TheModule)
1093     updateLinkage(GV);
1094   for (auto &GV : TheModule.globals())
1095     updateLinkage(GV);
1096   for (auto &GV : TheModule.aliases())
1097     updateLinkage(GV);
1098 }
1099 
1100 /// Run internalization on \p TheModule based on symmary analysis.
1101 void llvm::thinLTOInternalizeModule(Module &TheModule,
1102                                     const GVSummaryMapTy &DefinedGlobals) {
1103   // Declare a callback for the internalize pass that will ask for every
1104   // candidate GlobalValue if it can be internalized or not.
1105   auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
1106     // Lookup the linkage recorded in the summaries during global analysis.
1107     auto GS = DefinedGlobals.find(GV.getGUID());
1108     if (GS == DefinedGlobals.end()) {
1109       // Must have been promoted (possibly conservatively). Find original
1110       // name so that we can access the correct summary and see if it can
1111       // be internalized again.
1112       // FIXME: Eventually we should control promotion instead of promoting
1113       // and internalizing again.
1114       StringRef OrigName =
1115           ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
1116       std::string OrigId = GlobalValue::getGlobalIdentifier(
1117           OrigName, GlobalValue::InternalLinkage,
1118           TheModule.getSourceFileName());
1119       GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
1120       if (GS == DefinedGlobals.end()) {
1121         // Also check the original non-promoted non-globalized name. In some
1122         // cases a preempted weak value is linked in as a local copy because
1123         // it is referenced by an alias (IRLinker::linkGlobalValueProto).
1124         // In that case, since it was originally not a local value, it was
1125         // recorded in the index using the original name.
1126         // FIXME: This may not be needed once PR27866 is fixed.
1127         GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
1128         assert(GS != DefinedGlobals.end());
1129       }
1130     }
1131     return !GlobalValue::isLocalLinkage(GS->second->linkage());
1132   };
1133 
1134   // FIXME: See if we can just internalize directly here via linkage changes
1135   // based on the index, rather than invoking internalizeModule.
1136   internalizeModule(TheModule, MustPreserveGV);
1137 }
1138 
1139 /// Make alias a clone of its aliasee.
1140 static Function *replaceAliasWithAliasee(Module *SrcModule, GlobalAlias *GA) {
1141   Function *Fn = cast<Function>(GA->getBaseObject());
1142 
1143   ValueToValueMapTy VMap;
1144   Function *NewFn = CloneFunction(Fn, VMap);
1145   // Clone should use the original alias's linkage, visibility and name, and we
1146   // ensure all uses of alias instead use the new clone (casted if necessary).
1147   NewFn->setLinkage(GA->getLinkage());
1148   NewFn->setVisibility(GA->getVisibility());
1149   GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewFn, GA->getType()));
1150   NewFn->takeName(GA);
1151   return NewFn;
1152 }
1153 
1154 // Internalize values that we marked with specific attribute
1155 // in processGlobalForThinLTO.
1156 static void internalizeGVsAfterImport(Module &M) {
1157   for (auto &GV : M.globals())
1158     // Skip GVs which have been converted to declarations
1159     // by dropDeadSymbols.
1160     if (!GV.isDeclaration() && GV.hasAttribute("thinlto-internalize")) {
1161       GV.setLinkage(GlobalValue::InternalLinkage);
1162       GV.setVisibility(GlobalValue::DefaultVisibility);
1163     }
1164 }
1165 
1166 // Automatically import functions in Module \p DestModule based on the summaries
1167 // index.
1168 Expected<bool> FunctionImporter::importFunctions(
1169     Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
1170   LLVM_DEBUG(dbgs() << "Starting import for Module "
1171                     << DestModule.getModuleIdentifier() << "\n");
1172   unsigned ImportedCount = 0, ImportedGVCount = 0;
1173 
1174   IRMover Mover(DestModule);
1175   // Do the actual import of functions now, one Module at a time
1176   std::set<StringRef> ModuleNameOrderedList;
1177   for (auto &FunctionsToImportPerModule : ImportList) {
1178     ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
1179   }
1180   for (auto &Name : ModuleNameOrderedList) {
1181     // Get the module for the import
1182     const auto &FunctionsToImportPerModule = ImportList.find(Name);
1183     assert(FunctionsToImportPerModule != ImportList.end());
1184     Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
1185     if (!SrcModuleOrErr)
1186       return SrcModuleOrErr.takeError();
1187     std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
1188     assert(&DestModule.getContext() == &SrcModule->getContext() &&
1189            "Context mismatch");
1190 
1191     // If modules were created with lazy metadata loading, materialize it
1192     // now, before linking it (otherwise this will be a noop).
1193     if (Error Err = SrcModule->materializeMetadata())
1194       return std::move(Err);
1195 
1196     auto &ImportGUIDs = FunctionsToImportPerModule->second;
1197     // Find the globals to import
1198     SetVector<GlobalValue *> GlobalsToImport;
1199     for (Function &F : *SrcModule) {
1200       if (!F.hasName())
1201         continue;
1202       auto GUID = F.getGUID();
1203       auto Import = ImportGUIDs.count(GUID);
1204       LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function "
1205                         << GUID << " " << F.getName() << " from "
1206                         << SrcModule->getSourceFileName() << "\n");
1207       if (Import) {
1208         if (Error Err = F.materialize())
1209           return std::move(Err);
1210         if (EnableImportMetadata) {
1211           // Add 'thinlto_src_module' metadata for statistics and debugging.
1212           F.setMetadata(
1213               "thinlto_src_module",
1214               MDNode::get(DestModule.getContext(),
1215                           {MDString::get(DestModule.getContext(),
1216                                          SrcModule->getSourceFileName())}));
1217         }
1218         GlobalsToImport.insert(&F);
1219       }
1220     }
1221     for (GlobalVariable &GV : SrcModule->globals()) {
1222       if (!GV.hasName())
1223         continue;
1224       auto GUID = GV.getGUID();
1225       auto Import = ImportGUIDs.count(GUID);
1226       LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global "
1227                         << GUID << " " << GV.getName() << " from "
1228                         << SrcModule->getSourceFileName() << "\n");
1229       if (Import) {
1230         if (Error Err = GV.materialize())
1231           return std::move(Err);
1232         ImportedGVCount += GlobalsToImport.insert(&GV);
1233       }
1234     }
1235     for (GlobalAlias &GA : SrcModule->aliases()) {
1236       if (!GA.hasName())
1237         continue;
1238       auto GUID = GA.getGUID();
1239       auto Import = ImportGUIDs.count(GUID);
1240       LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias "
1241                         << GUID << " " << GA.getName() << " from "
1242                         << SrcModule->getSourceFileName() << "\n");
1243       if (Import) {
1244         if (Error Err = GA.materialize())
1245           return std::move(Err);
1246         // Import alias as a copy of its aliasee.
1247         GlobalObject *Base = GA.getBaseObject();
1248         if (Error Err = Base->materialize())
1249           return std::move(Err);
1250         auto *Fn = replaceAliasWithAliasee(SrcModule.get(), &GA);
1251         LLVM_DEBUG(dbgs() << "Is importing aliasee fn " << Base->getGUID()
1252                           << " " << Base->getName() << " from "
1253                           << SrcModule->getSourceFileName() << "\n");
1254         if (EnableImportMetadata) {
1255           // Add 'thinlto_src_module' metadata for statistics and debugging.
1256           Fn->setMetadata(
1257               "thinlto_src_module",
1258               MDNode::get(DestModule.getContext(),
1259                           {MDString::get(DestModule.getContext(),
1260                                          SrcModule->getSourceFileName())}));
1261         }
1262         GlobalsToImport.insert(Fn);
1263       }
1264     }
1265 
1266     // Upgrade debug info after we're done materializing all the globals and we
1267     // have loaded all the required metadata!
1268     UpgradeDebugInfo(*SrcModule);
1269 
1270     // Set the partial sample profile ratio in the profile summary module flag
1271     // of the imported source module, if applicable, so that the profile summary
1272     // module flag will match with that of the destination module when it's
1273     // imported.
1274     SrcModule->setPartialSampleProfileRatio(Index);
1275 
1276     // Link in the specified functions.
1277     if (renameModuleForThinLTO(*SrcModule, Index, ClearDSOLocalOnDeclarations,
1278                                &GlobalsToImport))
1279       return true;
1280 
1281     if (PrintImports) {
1282       for (const auto *GV : GlobalsToImport)
1283         dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
1284                << " from " << SrcModule->getSourceFileName() << "\n";
1285     }
1286 
1287     if (Error Err = Mover.move(
1288             std::move(SrcModule), GlobalsToImport.getArrayRef(),
1289             [](GlobalValue &, IRMover::ValueAdder) {},
1290             /*IsPerformingImport=*/true))
1291       report_fatal_error("Function Import: link error: " +
1292                          toString(std::move(Err)));
1293 
1294     ImportedCount += GlobalsToImport.size();
1295     NumImportedModules++;
1296   }
1297 
1298   internalizeGVsAfterImport(DestModule);
1299 
1300   NumImportedFunctions += (ImportedCount - ImportedGVCount);
1301   NumImportedGlobalVars += ImportedGVCount;
1302 
1303   LLVM_DEBUG(dbgs() << "Imported " << ImportedCount - ImportedGVCount
1304                     << " functions for Module "
1305                     << DestModule.getModuleIdentifier() << "\n");
1306   LLVM_DEBUG(dbgs() << "Imported " << ImportedGVCount
1307                     << " global variables for Module "
1308                     << DestModule.getModuleIdentifier() << "\n");
1309   return ImportedCount;
1310 }
1311 
1312 static bool doImportingForModule(Module &M) {
1313   if (SummaryFile.empty())
1314     report_fatal_error("error: -function-import requires -summary-file\n");
1315   Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
1316       getModuleSummaryIndexForFile(SummaryFile);
1317   if (!IndexPtrOrErr) {
1318     logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
1319                           "Error loading file '" + SummaryFile + "': ");
1320     return false;
1321   }
1322   std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
1323 
1324   // First step is collecting the import list.
1325   FunctionImporter::ImportMapTy ImportList;
1326   // If requested, simply import all functions in the index. This is used
1327   // when testing distributed backend handling via the opt tool, when
1328   // we have distributed indexes containing exactly the summaries to import.
1329   if (ImportAllIndex)
1330     ComputeCrossModuleImportForModuleFromIndex(M.getModuleIdentifier(), *Index,
1331                                                ImportList);
1332   else
1333     ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
1334                                       ImportList);
1335 
1336   // Conservatively mark all internal values as promoted. This interface is
1337   // only used when doing importing via the function importing pass. The pass
1338   // is only enabled when testing importing via the 'opt' tool, which does
1339   // not do the ThinLink that would normally determine what values to promote.
1340   for (auto &I : *Index) {
1341     for (auto &S : I.second.SummaryList) {
1342       if (GlobalValue::isLocalLinkage(S->linkage()))
1343         S->setLinkage(GlobalValue::ExternalLinkage);
1344     }
1345   }
1346 
1347   // Next we need to promote to global scope and rename any local values that
1348   // are potentially exported to other modules.
1349   if (renameModuleForThinLTO(M, *Index, /*ClearDSOLocalOnDeclarations=*/false,
1350                              /*GlobalsToImport=*/nullptr)) {
1351     errs() << "Error renaming module\n";
1352     return false;
1353   }
1354 
1355   // Perform the import now.
1356   auto ModuleLoader = [&M](StringRef Identifier) {
1357     return loadFile(std::string(Identifier), M.getContext());
1358   };
1359   FunctionImporter Importer(*Index, ModuleLoader,
1360                             /*ClearDSOLocalOnDeclarations=*/false);
1361   Expected<bool> Result = Importer.importFunctions(M, ImportList);
1362 
1363   // FIXME: Probably need to propagate Errors through the pass manager.
1364   if (!Result) {
1365     logAllUnhandledErrors(Result.takeError(), errs(),
1366                           "Error importing module: ");
1367     return false;
1368   }
1369 
1370   return *Result;
1371 }
1372 
1373 namespace {
1374 
1375 /// Pass that performs cross-module function import provided a summary file.
1376 class FunctionImportLegacyPass : public ModulePass {
1377 public:
1378   /// Pass identification, replacement for typeid
1379   static char ID;
1380 
1381   explicit FunctionImportLegacyPass() : ModulePass(ID) {}
1382 
1383   /// Specify pass name for debug output
1384   StringRef getPassName() const override { return "Function Importing"; }
1385 
1386   bool runOnModule(Module &M) override {
1387     if (skipModule(M))
1388       return false;
1389 
1390     return doImportingForModule(M);
1391   }
1392 };
1393 
1394 } // end anonymous namespace
1395 
1396 PreservedAnalyses FunctionImportPass::run(Module &M,
1397                                           ModuleAnalysisManager &AM) {
1398   if (!doImportingForModule(M))
1399     return PreservedAnalyses::all();
1400 
1401   return PreservedAnalyses::none();
1402 }
1403 
1404 char FunctionImportLegacyPass::ID = 0;
1405 INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
1406                 "Summary Based Function Import", false, false)
1407 
1408 namespace llvm {
1409 
1410 Pass *createFunctionImportPass() {
1411   return new FunctionImportLegacyPass();
1412 }
1413 
1414 } // end namespace llvm
1415