142418abaSMehdi Amini //===- FunctionImport.cpp - ThinLTO Summary-based Function Import ---------===//
242418abaSMehdi Amini //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
642418abaSMehdi Amini //
742418abaSMehdi Amini //===----------------------------------------------------------------------===//
842418abaSMehdi Amini //
942418abaSMehdi Amini // This file implements Function import based on summaries.
1042418abaSMehdi Amini //
1142418abaSMehdi Amini //===----------------------------------------------------------------------===//
1242418abaSMehdi Amini 
1342418abaSMehdi Amini #include "llvm/Transforms/IPO/FunctionImport.h"
14e9ea08a0SEugene Zelenko #include "llvm/ADT/ArrayRef.h"
15e9ea08a0SEugene Zelenko #include "llvm/ADT/STLExtras.h"
16e9ea08a0SEugene Zelenko #include "llvm/ADT/SetVector.h"
1701e32130SMehdi Amini #include "llvm/ADT/SmallVector.h"
18d29478f7STeresa Johnson #include "llvm/ADT/Statistic.h"
19e9ea08a0SEugene Zelenko #include "llvm/ADT/StringMap.h"
200efed325SSimon Pilgrim #include "llvm/ADT/StringRef.h"
21b040fcc6SCharles Saternos #include "llvm/ADT/StringSet.h"
22c15d60b7SPeter Collingbourne #include "llvm/Bitcode/BitcodeReader.h"
2342418abaSMehdi Amini #include "llvm/IR/AutoUpgrade.h"
2481bbf742STeresa Johnson #include "llvm/IR/Constants.h"
25e9ea08a0SEugene Zelenko #include "llvm/IR/Function.h"
26e9ea08a0SEugene Zelenko #include "llvm/IR/GlobalAlias.h"
27e9ea08a0SEugene Zelenko #include "llvm/IR/GlobalObject.h"
28e9ea08a0SEugene Zelenko #include "llvm/IR/GlobalValue.h"
29e9ea08a0SEugene Zelenko #include "llvm/IR/GlobalVariable.h"
30e9ea08a0SEugene Zelenko #include "llvm/IR/Metadata.h"
3142418abaSMehdi Amini #include "llvm/IR/Module.h"
32e9ea08a0SEugene Zelenko #include "llvm/IR/ModuleSummaryIndex.h"
3342418abaSMehdi Amini #include "llvm/IRReader/IRReader.h"
34e9ea08a0SEugene Zelenko #include "llvm/Linker/IRMover.h"
35e9ea08a0SEugene Zelenko #include "llvm/Object/ModuleSymbolTable.h"
36e9ea08a0SEugene Zelenko #include "llvm/Object/SymbolicFile.h"
37e9ea08a0SEugene Zelenko #include "llvm/Pass.h"
38e9ea08a0SEugene Zelenko #include "llvm/Support/Casting.h"
3942418abaSMehdi Amini #include "llvm/Support/CommandLine.h"
4042418abaSMehdi Amini #include "llvm/Support/Debug.h"
41e9ea08a0SEugene Zelenko #include "llvm/Support/Error.h"
42e9ea08a0SEugene Zelenko #include "llvm/Support/ErrorHandling.h"
43e9ea08a0SEugene Zelenko #include "llvm/Support/FileSystem.h"
4442418abaSMehdi Amini #include "llvm/Support/SourceMgr.h"
45e9ea08a0SEugene Zelenko #include "llvm/Support/raw_ostream.h"
4604c9a2d6STeresa Johnson #include "llvm/Transforms/IPO/Internalize.h"
4781bbf742STeresa Johnson #include "llvm/Transforms/Utils/Cloning.h"
48488a800aSTeresa Johnson #include "llvm/Transforms/Utils/FunctionImportUtils.h"
4981bbf742STeresa Johnson #include "llvm/Transforms/Utils/ValueMapper.h"
50e9ea08a0SEugene Zelenko #include <cassert>
51e9ea08a0SEugene Zelenko #include <memory>
52e9ea08a0SEugene Zelenko #include <set>
53e9ea08a0SEugene Zelenko #include <string>
54e9ea08a0SEugene Zelenko #include <system_error>
55e9ea08a0SEugene Zelenko #include <tuple>
56e9ea08a0SEugene Zelenko #include <utility>
577e88d0daSMehdi Amini 
5842418abaSMehdi Amini using namespace llvm;
5942418abaSMehdi Amini 
60e9ea08a0SEugene Zelenko #define DEBUG_TYPE "function-import"
61e9ea08a0SEugene Zelenko 
62d2c234a4STeresa Johnson STATISTIC(NumImportedFunctionsThinLink,
63d2c234a4STeresa Johnson           "Number of functions thin link decided to import");
64d2c234a4STeresa Johnson STATISTIC(NumImportedHotFunctionsThinLink,
65d2c234a4STeresa Johnson           "Number of hot functions thin link decided to import");
66d2c234a4STeresa Johnson STATISTIC(NumImportedCriticalFunctionsThinLink,
67d2c234a4STeresa Johnson           "Number of critical functions thin link decided to import");
68d2c234a4STeresa Johnson STATISTIC(NumImportedGlobalVarsThinLink,
69d2c234a4STeresa Johnson           "Number of global variables thin link decided to import");
70d2c234a4STeresa Johnson STATISTIC(NumImportedFunctions, "Number of functions imported in backend");
71d2c234a4STeresa Johnson STATISTIC(NumImportedGlobalVars,
72d2c234a4STeresa Johnson           "Number of global variables imported in backend");
736c475a75STeresa Johnson STATISTIC(NumImportedModules, "Number of modules imported from");
746c475a75STeresa Johnson STATISTIC(NumDeadSymbols, "Number of dead stripped symbols in index");
756c475a75STeresa Johnson STATISTIC(NumLiveSymbols, "Number of live symbols in index");
76d29478f7STeresa Johnson 
7739303619STeresa Johnson /// Limit on instruction count of imported functions.
7839303619STeresa Johnson static cl::opt<unsigned> ImportInstrLimit(
7939303619STeresa Johnson     "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
8039303619STeresa Johnson     cl::desc("Only import functions with less than N instructions"));
8139303619STeresa Johnson 
82974706ebSTeresa Johnson static cl::opt<int> ImportCutoff(
83974706ebSTeresa Johnson     "import-cutoff", cl::init(-1), cl::Hidden, cl::value_desc("N"),
84974706ebSTeresa Johnson     cl::desc("Only import first N functions if N>=0 (default -1)"));
85974706ebSTeresa Johnson 
8640641748SMehdi Amini static cl::opt<float>
8740641748SMehdi Amini     ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7),
8840641748SMehdi Amini                       cl::Hidden, cl::value_desc("x"),
8940641748SMehdi Amini                       cl::desc("As we import functions, multiply the "
9040641748SMehdi Amini                                "`import-instr-limit` threshold by this factor "
9140641748SMehdi Amini                                "before processing newly imported functions"));
92ba72b95fSPiotr Padlewski 
93d2869473SPiotr Padlewski static cl::opt<float> ImportHotInstrFactor(
94d2869473SPiotr Padlewski     "import-hot-evolution-factor", cl::init(1.0), cl::Hidden,
95d2869473SPiotr Padlewski     cl::value_desc("x"),
96d2869473SPiotr Padlewski     cl::desc("As we import functions called from hot callsite, multiply the "
97d2869473SPiotr Padlewski              "`import-instr-limit` threshold by this factor "
98d2869473SPiotr Padlewski              "before processing newly imported functions"));
99d2869473SPiotr Padlewski 
100d9830eb7SPiotr Padlewski static cl::opt<float> ImportHotMultiplier(
1018260d665SDehao Chen     "import-hot-multiplier", cl::init(10.0), cl::Hidden, cl::value_desc("x"),
102ba72b95fSPiotr Padlewski     cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"));
103ba72b95fSPiotr Padlewski 
10464c46574SDehao Chen static cl::opt<float> ImportCriticalMultiplier(
10564c46574SDehao Chen     "import-critical-multiplier", cl::init(100.0), cl::Hidden,
10664c46574SDehao Chen     cl::value_desc("x"),
10764c46574SDehao Chen     cl::desc(
10864c46574SDehao Chen         "Multiply the `import-instr-limit` threshold for critical callsites"));
10964c46574SDehao Chen 
110ba72b95fSPiotr Padlewski // FIXME: This multiplier was not really tuned up.
111ba72b95fSPiotr Padlewski static cl::opt<float> ImportColdMultiplier(
112ba72b95fSPiotr Padlewski     "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"),
113ba72b95fSPiotr Padlewski     cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"));
11440641748SMehdi Amini 
115d29478f7STeresa Johnson static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
116d29478f7STeresa Johnson                                   cl::desc("Print imported functions"));
117d29478f7STeresa Johnson 
118cb9a82fcSTeresa Johnson static cl::opt<bool> PrintImportFailures(
119cb9a82fcSTeresa Johnson     "print-import-failures", cl::init(false), cl::Hidden,
120cb9a82fcSTeresa Johnson     cl::desc("Print information for functions rejected for importing"));
121cb9a82fcSTeresa Johnson 
1226c475a75STeresa Johnson static cl::opt<bool> ComputeDead("compute-dead", cl::init(true), cl::Hidden,
1236c475a75STeresa Johnson                                  cl::desc("Compute dead symbols"));
1246c475a75STeresa Johnson 
1253b776128SPiotr Padlewski static cl::opt<bool> EnableImportMetadata(
1263b776128SPiotr Padlewski     "enable-import-metadata", cl::init(
1273b776128SPiotr Padlewski #if !defined(NDEBUG)
1283b776128SPiotr Padlewski                                   true /*Enabled with asserts.*/
1293b776128SPiotr Padlewski #else
1303b776128SPiotr Padlewski                                   false
1313b776128SPiotr Padlewski #endif
1323b776128SPiotr Padlewski                                   ),
1333b776128SPiotr Padlewski     cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'"));
1343b776128SPiotr Padlewski 
135e9ea08a0SEugene Zelenko /// Summary file to use for function importing when using -function-import from
136e9ea08a0SEugene Zelenko /// the command line.
137e9ea08a0SEugene Zelenko static cl::opt<std::string>
138e9ea08a0SEugene Zelenko     SummaryFile("summary-file",
139e9ea08a0SEugene Zelenko                 cl::desc("The summary file to use for function importing."));
140e9ea08a0SEugene Zelenko 
14181bbf742STeresa Johnson /// Used when testing importing from distributed indexes via opt
14281bbf742STeresa Johnson // -function-import.
14381bbf742STeresa Johnson static cl::opt<bool>
14481bbf742STeresa Johnson     ImportAllIndex("import-all-index",
14581bbf742STeresa Johnson                    cl::desc("Import all external functions in index."));
14681bbf742STeresa Johnson 
14742418abaSMehdi Amini // Load lazily a module from \p FileName in \p Context.
14842418abaSMehdi Amini static std::unique_ptr<Module> loadFile(const std::string &FileName,
14942418abaSMehdi Amini                                         LLVMContext &Context) {
15042418abaSMehdi Amini   SMDiagnostic Err;
151d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Loading '" << FileName << "'\n");
1526cba37ceSTeresa Johnson   // Metadata isn't loaded until functions are imported, to minimize
1536cba37ceSTeresa Johnson   // the memory overhead.
154a1080ee6STeresa Johnson   std::unique_ptr<Module> Result =
155a1080ee6STeresa Johnson       getLazyIRFileModule(FileName, Err, Context,
156a1080ee6STeresa Johnson                           /* ShouldLazyLoadMetadata = */ true);
15742418abaSMehdi Amini   if (!Result) {
15842418abaSMehdi Amini     Err.print("function-import", errs());
159d7ad221cSMehdi Amini     report_fatal_error("Abort");
16042418abaSMehdi Amini   }
16142418abaSMehdi Amini 
16242418abaSMehdi Amini   return Result;
16342418abaSMehdi Amini }
16442418abaSMehdi Amini 
16501e32130SMehdi Amini /// Given a list of possible callee implementation for a call site, select one
16601e32130SMehdi Amini /// that fits the \p Threshold.
16701e32130SMehdi Amini ///
16801e32130SMehdi Amini /// FIXME: select "best" instead of first that fits. But what is "best"?
16901e32130SMehdi Amini /// - The smallest: more likely to be inlined.
17001e32130SMehdi Amini /// - The one with the least outgoing edges (already well optimized).
17101e32130SMehdi Amini /// - One from a module already being imported from in order to reduce the
17201e32130SMehdi Amini ///   number of source modules parsed/linked.
17301e32130SMehdi Amini /// - One that has PGO data attached.
17401e32130SMehdi Amini /// - [insert you fancy metric here]
1752d28f7aaSMehdi Amini static const GlobalValueSummary *
176b4e1e829SMehdi Amini selectCallee(const ModuleSummaryIndex &Index,
1779667b91bSPeter Collingbourne              ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
178cb9a82fcSTeresa Johnson              unsigned Threshold, StringRef CallerModulePath,
179cb9a82fcSTeresa Johnson              FunctionImporter::ImportFailureReason &Reason,
180cb9a82fcSTeresa Johnson              GlobalValue::GUID GUID) {
181cb9a82fcSTeresa Johnson   Reason = FunctionImporter::ImportFailureReason::None;
18201e32130SMehdi Amini   auto It = llvm::find_if(
18328e457bcSTeresa Johnson       CalleeSummaryList,
18428e457bcSTeresa Johnson       [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
18528e457bcSTeresa Johnson         auto *GVSummary = SummaryPtr.get();
186cb9a82fcSTeresa Johnson         if (!Index.isGlobalValueLive(GVSummary)) {
187cb9a82fcSTeresa Johnson           Reason = FunctionImporter::ImportFailureReason::NotLive;
188eaf5172cSGeorge Rimar           return false;
189cb9a82fcSTeresa Johnson         }
190eaf5172cSGeorge Rimar 
19173305f82STeresa Johnson         // For SamplePGO, in computeImportForFunction the OriginalId
19273305f82STeresa Johnson         // may have been used to locate the callee summary list (See
19373305f82STeresa Johnson         // comment there).
19473305f82STeresa Johnson         // The mapping from OriginalId to GUID may return a GUID
19573305f82STeresa Johnson         // that corresponds to a static variable. Filter it out here.
19673305f82STeresa Johnson         // This can happen when
19773305f82STeresa Johnson         // 1) There is a call to a library function which is not defined
19873305f82STeresa Johnson         // in the index.
19973305f82STeresa Johnson         // 2) There is a static variable with the  OriginalGUID identical
20073305f82STeresa Johnson         // to the GUID of the library function in 1);
20173305f82STeresa Johnson         // When this happens, the logic for SamplePGO kicks in and
20273305f82STeresa Johnson         // the static variable in 2) will be found, which needs to be
20373305f82STeresa Johnson         // filtered out.
204cb9a82fcSTeresa Johnson         if (GVSummary->getSummaryKind() == GlobalValueSummary::GlobalVarKind) {
205cb9a82fcSTeresa Johnson           Reason = FunctionImporter::ImportFailureReason::GlobalVar;
20673305f82STeresa Johnson           return false;
207cb9a82fcSTeresa Johnson         }
208cb9a82fcSTeresa Johnson         if (GlobalValue::isInterposableLinkage(GVSummary->linkage())) {
209cb9a82fcSTeresa Johnson           Reason = FunctionImporter::ImportFailureReason::InterposableLinkage;
2105b85d8d6SMehdi Amini           // There is no point in importing these, we can't inline them
21101e32130SMehdi Amini           return false;
212cb9a82fcSTeresa Johnson         }
2132c719cc1SMehdi Amini 
21481bbf742STeresa Johnson         auto *Summary = cast<FunctionSummary>(GVSummary->getBaseObject());
2157e88d0daSMehdi Amini 
21683aaf358STeresa Johnson         // If this is a local function, make sure we import the copy
21783aaf358STeresa Johnson         // in the caller's module. The only time a local function can
21883aaf358STeresa Johnson         // share an entry in the index is if there is a local with the same name
21983aaf358STeresa Johnson         // in another module that had the same source file name (in a different
22083aaf358STeresa Johnson         // directory), where each was compiled in their own directory so there
22183aaf358STeresa Johnson         // was not distinguishing path.
22283aaf358STeresa Johnson         // However, do the import from another module if there is only one
22383aaf358STeresa Johnson         // entry in the list - in that case this must be a reference due
22483aaf358STeresa Johnson         // to indirect call profile data, since a function pointer can point to
22583aaf358STeresa Johnson         // a local in another module.
22683aaf358STeresa Johnson         if (GlobalValue::isLocalLinkage(Summary->linkage()) &&
22783aaf358STeresa Johnson             CalleeSummaryList.size() > 1 &&
228cb9a82fcSTeresa Johnson             Summary->modulePath() != CallerModulePath) {
229cb9a82fcSTeresa Johnson           Reason =
230cb9a82fcSTeresa Johnson               FunctionImporter::ImportFailureReason::LocalLinkageNotInModule;
23183aaf358STeresa Johnson           return false;
232cb9a82fcSTeresa Johnson         }
23383aaf358STeresa Johnson 
234cb9a82fcSTeresa Johnson         if (Summary->instCount() > Threshold) {
235cb9a82fcSTeresa Johnson           Reason = FunctionImporter::ImportFailureReason::TooLarge;
236f9dc3deaSTeresa Johnson           return false;
237cb9a82fcSTeresa Johnson         }
238f9dc3deaSTeresa Johnson 
239cb397461STeresa Johnson         // Skip if it isn't legal to import (e.g. may reference unpromotable
240cb397461STeresa Johnson         // locals).
241cb9a82fcSTeresa Johnson         if (Summary->notEligibleToImport()) {
242cb9a82fcSTeresa Johnson           Reason = FunctionImporter::ImportFailureReason::NotEligible;
243b4e1e829SMehdi Amini           return false;
244cb9a82fcSTeresa Johnson         }
245b4e1e829SMehdi Amini 
246cb397461STeresa Johnson         // Don't bother importing if we can't inline it anyway.
247cb397461STeresa Johnson         if (Summary->fflags().NoInline) {
248cb397461STeresa Johnson           Reason = FunctionImporter::ImportFailureReason::NoInline;
249cb397461STeresa Johnson           return false;
250cb397461STeresa Johnson         }
251cb397461STeresa Johnson 
25201e32130SMehdi Amini         return true;
25301e32130SMehdi Amini       });
25428e457bcSTeresa Johnson   if (It == CalleeSummaryList.end())
25501e32130SMehdi Amini     return nullptr;
2567e88d0daSMehdi Amini 
257f9dc3deaSTeresa Johnson   return cast<GlobalValueSummary>(It->get());
258434e9561SRafael Espindola }
2597e88d0daSMehdi Amini 
260e9ea08a0SEugene Zelenko namespace {
261e9ea08a0SEugene Zelenko 
262475b51a7STeresa Johnson using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */,
263475b51a7STeresa Johnson                             GlobalValue::GUID>;
26401e32130SMehdi Amini 
265e9ea08a0SEugene Zelenko } // anonymous namespace
266e9ea08a0SEugene Zelenko 
2671958083dSTeresa Johnson static ValueInfo
2681958083dSTeresa Johnson updateValueInfoForIndirectCalls(const ModuleSummaryIndex &Index, ValueInfo VI) {
2691958083dSTeresa Johnson   if (!VI.getSummaryList().empty())
2701958083dSTeresa Johnson     return VI;
2711958083dSTeresa Johnson   // For SamplePGO, the indirect call targets for local functions will
2721958083dSTeresa Johnson   // have its original name annotated in profile. We try to find the
2731958083dSTeresa Johnson   // corresponding PGOFuncName as the GUID.
2741958083dSTeresa Johnson   // FIXME: Consider updating the edges in the graph after building
2751958083dSTeresa Johnson   // it, rather than needing to perform this mapping on each walk.
2761958083dSTeresa Johnson   auto GUID = Index.getGUIDFromOriginalID(VI.getGUID());
2771958083dSTeresa Johnson   if (GUID == 0)
27828d8a49fSEugene Leviant     return ValueInfo();
2791958083dSTeresa Johnson   return Index.getValueInfo(GUID);
2801958083dSTeresa Johnson }
2811958083dSTeresa Johnson 
28219e23874SEugene Leviant static void computeImportForReferencedGlobals(
283dde58938Sevgeny     const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
284dde58938Sevgeny     const GVSummaryMapTy &DefinedGVSummaries,
28519e23874SEugene Leviant     FunctionImporter::ImportMapTy &ImportList,
28619e23874SEugene Leviant     StringMap<FunctionImporter::ExportSetTy> *ExportLists) {
28719e23874SEugene Leviant   for (auto &VI : Summary.refs()) {
28819e23874SEugene Leviant     if (DefinedGVSummaries.count(VI.getGUID())) {
289d34e60caSNicola Zaghen       LLVM_DEBUG(
290d34e60caSNicola Zaghen           dbgs() << "Ref ignored! Target already in destination module.\n");
29119e23874SEugene Leviant       continue;
29219e23874SEugene Leviant     }
29319e23874SEugene Leviant 
2947e7b13d0STeresa Johnson     LLVM_DEBUG(dbgs() << " ref -> " << VI << "\n");
29519e23874SEugene Leviant 
29693f99962STeresa Johnson     // If this is a local variable, make sure we import the copy
29793f99962STeresa Johnson     // in the caller's module. The only time a local variable can
29893f99962STeresa Johnson     // share an entry in the index is if there is a local with the same name
29993f99962STeresa Johnson     // in another module that had the same source file name (in a different
30093f99962STeresa Johnson     // directory), where each was compiled in their own directory so there
30193f99962STeresa Johnson     // was not distinguishing path.
30293f99962STeresa Johnson     auto LocalNotInModule = [&](const GlobalValueSummary *RefSummary) -> bool {
30393f99962STeresa Johnson       return GlobalValue::isLocalLinkage(RefSummary->linkage()) &&
30493f99962STeresa Johnson              RefSummary->modulePath() != Summary.modulePath();
30593f99962STeresa Johnson     };
30693f99962STeresa Johnson 
307dde58938Sevgeny     auto MarkExported = [&](const ValueInfo &VI, const GlobalValueSummary *S) {
308dde58938Sevgeny       if (ExportLists)
309dde58938Sevgeny         (*ExportLists)[S->modulePath()].insert(VI.getGUID());
310dde58938Sevgeny     };
311dde58938Sevgeny 
31219e23874SEugene Leviant     for (auto &RefSummary : VI.getSummaryList())
313bf46e741SEugene Leviant       if (isa<GlobalVarSummary>(RefSummary.get()) &&
314dde58938Sevgeny           Index.canImportGlobalVar(RefSummary.get(), /* AnalyzeRefs */ true) &&
31593f99962STeresa Johnson           !LocalNotInModule(RefSummary.get())) {
316d2c234a4STeresa Johnson         auto ILI = ImportList[RefSummary->modulePath()].insert(VI.getGUID());
317d2c234a4STeresa Johnson         // Only update stat if we haven't already imported this variable.
318d2c234a4STeresa Johnson         if (ILI.second)
319d2c234a4STeresa Johnson           NumImportedGlobalVarsThinLink++;
320dde58938Sevgeny         MarkExported(VI, RefSummary.get());
321*7f92d66fSevgeny         // Promote referenced functions and variables. We don't promote
322*7f92d66fSevgeny         // objects referenced by writeonly variable initializer, because
323*7f92d66fSevgeny         // we convert such variables initializers to "zeroinitializer".
324*7f92d66fSevgeny         // See processGlobalForThinLTO.
325*7f92d66fSevgeny         if (!Index.isWriteOnly(cast<GlobalVarSummary>(RefSummary.get())))
326dde58938Sevgeny           for (const auto &VI : RefSummary->refs())
327dde58938Sevgeny             for (const auto &RefFn : VI.getSummaryList())
328dde58938Sevgeny               MarkExported(VI, RefFn.get());
32919e23874SEugene Leviant         break;
33019e23874SEugene Leviant       }
33119e23874SEugene Leviant   }
33219e23874SEugene Leviant }
33319e23874SEugene Leviant 
334cb9a82fcSTeresa Johnson static const char *
335cb9a82fcSTeresa Johnson getFailureName(FunctionImporter::ImportFailureReason Reason) {
336cb9a82fcSTeresa Johnson   switch (Reason) {
337cb9a82fcSTeresa Johnson   case FunctionImporter::ImportFailureReason::None:
338cb9a82fcSTeresa Johnson     return "None";
339cb9a82fcSTeresa Johnson   case FunctionImporter::ImportFailureReason::GlobalVar:
340cb9a82fcSTeresa Johnson     return "GlobalVar";
341cb9a82fcSTeresa Johnson   case FunctionImporter::ImportFailureReason::NotLive:
342cb9a82fcSTeresa Johnson     return "NotLive";
343cb9a82fcSTeresa Johnson   case FunctionImporter::ImportFailureReason::TooLarge:
344cb9a82fcSTeresa Johnson     return "TooLarge";
345cb9a82fcSTeresa Johnson   case FunctionImporter::ImportFailureReason::InterposableLinkage:
346cb9a82fcSTeresa Johnson     return "InterposableLinkage";
347cb9a82fcSTeresa Johnson   case FunctionImporter::ImportFailureReason::LocalLinkageNotInModule:
348cb9a82fcSTeresa Johnson     return "LocalLinkageNotInModule";
349cb9a82fcSTeresa Johnson   case FunctionImporter::ImportFailureReason::NotEligible:
350cb9a82fcSTeresa Johnson     return "NotEligible";
351cb397461STeresa Johnson   case FunctionImporter::ImportFailureReason::NoInline:
352cb397461STeresa Johnson     return "NoInline";
353cb9a82fcSTeresa Johnson   }
354cb9a82fcSTeresa Johnson   llvm_unreachable("invalid reason");
355cb9a82fcSTeresa Johnson }
356cb9a82fcSTeresa Johnson 
35701e32130SMehdi Amini /// Compute the list of functions to import for a given caller. Mark these
35801e32130SMehdi Amini /// imported functions and the symbols they reference in their source module as
35901e32130SMehdi Amini /// exported from their source module.
36001e32130SMehdi Amini static void computeImportForFunction(
3613255eec1STeresa Johnson     const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
362d9830eb7SPiotr Padlewski     const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
36301e32130SMehdi Amini     SmallVectorImpl<EdgeInfo> &Worklist,
3649b490f10SMehdi Amini     FunctionImporter::ImportMapTy &ImportList,
365d68935c5STeresa Johnson     StringMap<FunctionImporter::ExportSetTy> *ExportLists,
366d68935c5STeresa Johnson     FunctionImporter::ImportThresholdsTy &ImportThresholds) {
367dde58938Sevgeny   computeImportForReferencedGlobals(Summary, Index, DefinedGVSummaries,
368dde58938Sevgeny                                     ImportList, ExportLists);
369974706ebSTeresa Johnson   static int ImportCount = 0;
37001e32130SMehdi Amini   for (auto &Edge : Summary.calls()) {
3719667b91bSPeter Collingbourne     ValueInfo VI = Edge.first;
3727e7b13d0STeresa Johnson     LLVM_DEBUG(dbgs() << " edge -> " << VI << " Threshold:" << Threshold
3737e7b13d0STeresa Johnson                       << "\n");
37401e32130SMehdi Amini 
375974706ebSTeresa Johnson     if (ImportCutoff >= 0 && ImportCount >= ImportCutoff) {
376d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "ignored! import-cutoff value of " << ImportCutoff
377974706ebSTeresa Johnson                         << " reached.\n");
378974706ebSTeresa Johnson       continue;
379974706ebSTeresa Johnson     }
380974706ebSTeresa Johnson 
3811958083dSTeresa Johnson     VI = updateValueInfoForIndirectCalls(Index, VI);
3829667b91bSPeter Collingbourne     if (!VI)
3839667b91bSPeter Collingbourne       continue;
3844a435e08SDehao Chen 
3859667b91bSPeter Collingbourne     if (DefinedGVSummaries.count(VI.getGUID())) {
386d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "ignored! Target already in destination module.\n");
3877e88d0daSMehdi Amini       continue;
388d450da32STeresa Johnson     }
38940641748SMehdi Amini 
390ba72b95fSPiotr Padlewski     auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
391ba72b95fSPiotr Padlewski       if (Hotness == CalleeInfo::HotnessType::Hot)
392ba72b95fSPiotr Padlewski         return ImportHotMultiplier;
393ba72b95fSPiotr Padlewski       if (Hotness == CalleeInfo::HotnessType::Cold)
394ba72b95fSPiotr Padlewski         return ImportColdMultiplier;
39564c46574SDehao Chen       if (Hotness == CalleeInfo::HotnessType::Critical)
39664c46574SDehao Chen         return ImportCriticalMultiplier;
397ba72b95fSPiotr Padlewski       return 1.0;
398ba72b95fSPiotr Padlewski     };
399ba72b95fSPiotr Padlewski 
400d9830eb7SPiotr Padlewski     const auto NewThreshold =
401c73cec84SEaswaran Raman         Threshold * GetBonusMultiplier(Edge.second.getHotness());
402d2869473SPiotr Padlewski 
403cb9a82fcSTeresa Johnson     auto IT = ImportThresholds.insert(std::make_pair(
404cb9a82fcSTeresa Johnson         VI.getGUID(), std::make_tuple(NewThreshold, nullptr, nullptr)));
405d68935c5STeresa Johnson     bool PreviouslyVisited = !IT.second;
406cb9a82fcSTeresa Johnson     auto &ProcessedThreshold = std::get<0>(IT.first->second);
407cb9a82fcSTeresa Johnson     auto &CalleeSummary = std::get<1>(IT.first->second);
408cb9a82fcSTeresa Johnson     auto &FailureInfo = std::get<2>(IT.first->second);
409d68935c5STeresa Johnson 
410d2c234a4STeresa Johnson     bool IsHotCallsite =
411d2c234a4STeresa Johnson         Edge.second.getHotness() == CalleeInfo::HotnessType::Hot;
412d2c234a4STeresa Johnson     bool IsCriticalCallsite =
413d2c234a4STeresa Johnson         Edge.second.getHotness() == CalleeInfo::HotnessType::Critical;
414d2c234a4STeresa Johnson 
415d68935c5STeresa Johnson     const FunctionSummary *ResolvedCalleeSummary = nullptr;
416d68935c5STeresa Johnson     if (CalleeSummary) {
417d68935c5STeresa Johnson       assert(PreviouslyVisited);
418d68935c5STeresa Johnson       // Since the traversal of the call graph is DFS, we can revisit a function
419d68935c5STeresa Johnson       // a second time with a higher threshold. In this case, it is added back
420d68935c5STeresa Johnson       // to the worklist with the new threshold (so that its own callee chains
421d68935c5STeresa Johnson       // can be considered with the higher threshold).
422d68935c5STeresa Johnson       if (NewThreshold <= ProcessedThreshold) {
423d68935c5STeresa Johnson         LLVM_DEBUG(
424d68935c5STeresa Johnson             dbgs() << "ignored! Target was already imported with Threshold "
425d68935c5STeresa Johnson                    << ProcessedThreshold << "\n");
426d68935c5STeresa Johnson         continue;
427d68935c5STeresa Johnson       }
428d68935c5STeresa Johnson       // Update with new larger threshold.
429d68935c5STeresa Johnson       ProcessedThreshold = NewThreshold;
430d68935c5STeresa Johnson       ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
431d68935c5STeresa Johnson     } else {
432d68935c5STeresa Johnson       // If we already rejected importing a callee at the same or higher
433d68935c5STeresa Johnson       // threshold, don't waste time calling selectCallee.
434d68935c5STeresa Johnson       if (PreviouslyVisited && NewThreshold <= ProcessedThreshold) {
435d68935c5STeresa Johnson         LLVM_DEBUG(
436d68935c5STeresa Johnson             dbgs() << "ignored! Target was already rejected with Threshold "
437d68935c5STeresa Johnson             << ProcessedThreshold << "\n");
438cb9a82fcSTeresa Johnson         if (PrintImportFailures) {
439cb9a82fcSTeresa Johnson           assert(FailureInfo &&
440cb9a82fcSTeresa Johnson                  "Expected FailureInfo for previously rejected candidate");
441cb9a82fcSTeresa Johnson           FailureInfo->Attempts++;
442cb9a82fcSTeresa Johnson         }
443d68935c5STeresa Johnson         continue;
444d68935c5STeresa Johnson       }
445d68935c5STeresa Johnson 
446cb9a82fcSTeresa Johnson       FunctionImporter::ImportFailureReason Reason;
447d68935c5STeresa Johnson       CalleeSummary = selectCallee(Index, VI.getSummaryList(), NewThreshold,
448cb9a82fcSTeresa Johnson                                    Summary.modulePath(), Reason, VI.getGUID());
44901e32130SMehdi Amini       if (!CalleeSummary) {
450d68935c5STeresa Johnson         // Update with new larger threshold if this was a retry (otherwise
451cb9a82fcSTeresa Johnson         // we would have already inserted with NewThreshold above). Also
452cb9a82fcSTeresa Johnson         // update failure info if requested.
453cb9a82fcSTeresa Johnson         if (PreviouslyVisited) {
454d68935c5STeresa Johnson           ProcessedThreshold = NewThreshold;
455cb9a82fcSTeresa Johnson           if (PrintImportFailures) {
456cb9a82fcSTeresa Johnson             assert(FailureInfo &&
457cb9a82fcSTeresa Johnson                    "Expected FailureInfo for previously rejected candidate");
458cb9a82fcSTeresa Johnson             FailureInfo->Reason = Reason;
459cb9a82fcSTeresa Johnson             FailureInfo->Attempts++;
460cb9a82fcSTeresa Johnson             FailureInfo->MaxHotness =
461cb9a82fcSTeresa Johnson                 std::max(FailureInfo->MaxHotness, Edge.second.getHotness());
462cb9a82fcSTeresa Johnson           }
463cb9a82fcSTeresa Johnson         } else if (PrintImportFailures) {
464cb9a82fcSTeresa Johnson           assert(!FailureInfo &&
465cb9a82fcSTeresa Johnson                  "Expected no FailureInfo for newly rejected candidate");
4660eaee545SJonas Devlieghere           FailureInfo = std::make_unique<FunctionImporter::ImportFailureInfo>(
467cb9a82fcSTeresa Johnson               VI, Edge.second.getHotness(), Reason, 1);
468cb9a82fcSTeresa Johnson         }
469d34e60caSNicola Zaghen         LLVM_DEBUG(
470d34e60caSNicola Zaghen             dbgs() << "ignored! No qualifying callee with summary found.\n");
4717e88d0daSMehdi Amini         continue;
4727e88d0daSMehdi Amini       }
4732f0cc477SDavid Blaikie 
4742f0cc477SDavid Blaikie       // "Resolve" the summary
475d68935c5STeresa Johnson       CalleeSummary = CalleeSummary->getBaseObject();
476d68935c5STeresa Johnson       ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
4772d28f7aaSMehdi Amini 
478d9830eb7SPiotr Padlewski       assert(ResolvedCalleeSummary->instCount() <= NewThreshold &&
47901e32130SMehdi Amini              "selectCallee() didn't honor the threshold");
48001e32130SMehdi Amini 
4811b859a23STeresa Johnson       auto ExportModulePath = ResolvedCalleeSummary->modulePath();
482d68935c5STeresa Johnson       auto ILI = ImportList[ExportModulePath].insert(VI.getGUID());
483d68935c5STeresa Johnson       // We previously decided to import this GUID definition if it was already
484d68935c5STeresa Johnson       // inserted in the set of imports from the exporting module.
485d68935c5STeresa Johnson       bool PreviouslyImported = !ILI.second;
486d2c234a4STeresa Johnson       if (!PreviouslyImported) {
487d2c234a4STeresa Johnson         NumImportedFunctionsThinLink++;
488d2c234a4STeresa Johnson         if (IsHotCallsite)
489d2c234a4STeresa Johnson           NumImportedHotFunctionsThinLink++;
490d2c234a4STeresa Johnson         if (IsCriticalCallsite)
491d2c234a4STeresa Johnson           NumImportedCriticalFunctionsThinLink++;
492d2c234a4STeresa Johnson       }
493974706ebSTeresa Johnson 
4941b859a23STeresa Johnson       // Make exports in the source module.
4951b859a23STeresa Johnson       if (ExportLists) {
4961b859a23STeresa Johnson         auto &ExportList = (*ExportLists)[ExportModulePath];
4979667b91bSPeter Collingbourne         ExportList.insert(VI.getGUID());
49819f2aa78STeresa Johnson         if (!PreviouslyImported) {
49919f2aa78STeresa Johnson           // This is the first time this function was exported from its source
50019f2aa78STeresa Johnson           // module, so mark all functions and globals it references as exported
5011b859a23STeresa Johnson           // to the outside if they are defined in the same source module.
502edddca22STeresa Johnson           // For efficiency, we unconditionally add all the referenced GUIDs
503edddca22STeresa Johnson           // to the ExportList for this module, and will prune out any not
504edddca22STeresa Johnson           // defined in the module later in a single pass.
5051b859a23STeresa Johnson           for (auto &Edge : ResolvedCalleeSummary->calls()) {
5061b859a23STeresa Johnson             auto CalleeGUID = Edge.first.getGUID();
507edddca22STeresa Johnson             ExportList.insert(CalleeGUID);
5081b859a23STeresa Johnson           }
5091b859a23STeresa Johnson           for (auto &Ref : ResolvedCalleeSummary->refs()) {
5101b859a23STeresa Johnson             auto GUID = Ref.getGUID();
511edddca22STeresa Johnson             ExportList.insert(GUID);
5121b859a23STeresa Johnson           }
5131b859a23STeresa Johnson         }
51419f2aa78STeresa Johnson       }
515d68935c5STeresa Johnson     }
516d68935c5STeresa Johnson 
517d68935c5STeresa Johnson     auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
518d68935c5STeresa Johnson       // Adjust the threshold for next level of imported functions.
519d68935c5STeresa Johnson       // The threshold is different for hot callsites because we can then
520d68935c5STeresa Johnson       // inline chains of hot calls.
521d68935c5STeresa Johnson       if (IsHotCallsite)
522d68935c5STeresa Johnson         return Threshold * ImportHotInstrFactor;
523d68935c5STeresa Johnson       return Threshold * ImportInstrFactor;
524d68935c5STeresa Johnson     };
525d68935c5STeresa Johnson 
526d68935c5STeresa Johnson     const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
527d68935c5STeresa Johnson 
528d68935c5STeresa Johnson     ImportCount++;
529d2869473SPiotr Padlewski 
53001e32130SMehdi Amini     // Insert the newly imported function to the worklist.
5319667b91bSPeter Collingbourne     Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, VI.getGUID());
532d450da32STeresa Johnson   }
533d450da32STeresa Johnson }
534d450da32STeresa Johnson 
53501e32130SMehdi Amini /// Given the list of globals defined in a module, compute the list of imports
53601e32130SMehdi Amini /// as well as the list of "exports", i.e. the list of symbols referenced from
53701e32130SMehdi Amini /// another module (that may require promotion).
53801e32130SMehdi Amini static void ComputeImportForModule(
539c851d216STeresa Johnson     const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
540cb9a82fcSTeresa Johnson     StringRef ModName, FunctionImporter::ImportMapTy &ImportList,
54156584bbfSEvgeniy Stepanov     StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
54201e32130SMehdi Amini   // Worklist contains the list of function imported in this module, for which
54301e32130SMehdi Amini   // we will analyse the callees and may import further down the callgraph.
54401e32130SMehdi Amini   SmallVector<EdgeInfo, 128> Worklist;
545d68935c5STeresa Johnson   FunctionImporter::ImportThresholdsTy ImportThresholds;
54601e32130SMehdi Amini 
54701e32130SMehdi Amini   // Populate the worklist with the import for the functions in the current
54801e32130SMehdi Amini   // module
54928e457bcSTeresa Johnson   for (auto &GVSummary : DefinedGVSummaries) {
5507e7b13d0STeresa Johnson #ifndef NDEBUG
5517e7b13d0STeresa Johnson     // FIXME: Change the GVSummaryMapTy to hold ValueInfo instead of GUID
5527e7b13d0STeresa Johnson     // so this map look up (and possibly others) can be avoided.
5537e7b13d0STeresa Johnson     auto VI = Index.getValueInfo(GVSummary.first);
5547e7b13d0STeresa Johnson #endif
55556584bbfSEvgeniy Stepanov     if (!Index.isGlobalValueLive(GVSummary.second)) {
5567e7b13d0STeresa Johnson       LLVM_DEBUG(dbgs() << "Ignores Dead GUID: " << VI << "\n");
5576c475a75STeresa Johnson       continue;
5586c475a75STeresa Johnson     }
559cfbd0892SPeter Collingbourne     auto *FuncSummary =
560cfbd0892SPeter Collingbourne         dyn_cast<FunctionSummary>(GVSummary.second->getBaseObject());
5611aafabf7SMehdi Amini     if (!FuncSummary)
5621aafabf7SMehdi Amini       // Skip import for global variables
5631aafabf7SMehdi Amini       continue;
5647e7b13d0STeresa Johnson     LLVM_DEBUG(dbgs() << "Initialize import for " << VI << "\n");
5652d28f7aaSMehdi Amini     computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
5669b490f10SMehdi Amini                              DefinedGVSummaries, Worklist, ImportList,
567d68935c5STeresa Johnson                              ExportLists, ImportThresholds);
56801e32130SMehdi Amini   }
56901e32130SMehdi Amini 
570d2869473SPiotr Padlewski   // Process the newly imported functions and add callees to the worklist.
57142418abaSMehdi Amini   while (!Worklist.empty()) {
57201e32130SMehdi Amini     auto FuncInfo = Worklist.pop_back_val();
573475b51a7STeresa Johnson     auto *Summary = std::get<0>(FuncInfo);
574475b51a7STeresa Johnson     auto Threshold = std::get<1>(FuncInfo);
57542418abaSMehdi Amini 
5761aafabf7SMehdi Amini     computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
577d68935c5STeresa Johnson                              Worklist, ImportList, ExportLists,
578d68935c5STeresa Johnson                              ImportThresholds);
579c8c55170SMehdi Amini   }
580cb9a82fcSTeresa Johnson 
581cb9a82fcSTeresa Johnson   // Print stats about functions considered but rejected for importing
582cb9a82fcSTeresa Johnson   // when requested.
583cb9a82fcSTeresa Johnson   if (PrintImportFailures) {
584cb9a82fcSTeresa Johnson     dbgs() << "Missed imports into module " << ModName << "\n";
585cb9a82fcSTeresa Johnson     for (auto &I : ImportThresholds) {
586cb9a82fcSTeresa Johnson       auto &ProcessedThreshold = std::get<0>(I.second);
587cb9a82fcSTeresa Johnson       auto &CalleeSummary = std::get<1>(I.second);
588cb9a82fcSTeresa Johnson       auto &FailureInfo = std::get<2>(I.second);
589cb9a82fcSTeresa Johnson       if (CalleeSummary)
590cb9a82fcSTeresa Johnson         continue; // We are going to import.
591cb9a82fcSTeresa Johnson       assert(FailureInfo);
592cb9a82fcSTeresa Johnson       FunctionSummary *FS = nullptr;
593cb9a82fcSTeresa Johnson       if (!FailureInfo->VI.getSummaryList().empty())
594cb9a82fcSTeresa Johnson         FS = dyn_cast<FunctionSummary>(
595cb9a82fcSTeresa Johnson             FailureInfo->VI.getSummaryList()[0]->getBaseObject());
596cb9a82fcSTeresa Johnson       dbgs() << FailureInfo->VI
597cb9a82fcSTeresa Johnson              << ": Reason = " << getFailureName(FailureInfo->Reason)
598cb9a82fcSTeresa Johnson              << ", Threshold = " << ProcessedThreshold
599cb9a82fcSTeresa Johnson              << ", Size = " << (FS ? (int)FS->instCount() : -1)
600cb9a82fcSTeresa Johnson              << ", MaxHotness = " << getHotnessName(FailureInfo->MaxHotness)
601cb9a82fcSTeresa Johnson              << ", Attempts = " << FailureInfo->Attempts << "\n";
602cb9a82fcSTeresa Johnson     }
603cb9a82fcSTeresa Johnson   }
60442418abaSMehdi Amini }
605ffe2e4aaSMehdi Amini 
60619e23874SEugene Leviant #ifndef NDEBUG
60719e23874SEugene Leviant static bool isGlobalVarSummary(const ModuleSummaryIndex &Index,
60819e23874SEugene Leviant                                GlobalValue::GUID G) {
60919e23874SEugene Leviant   if (const auto &VI = Index.getValueInfo(G)) {
61019e23874SEugene Leviant     auto SL = VI.getSummaryList();
61119e23874SEugene Leviant     if (!SL.empty())
61219e23874SEugene Leviant       return SL[0]->getSummaryKind() == GlobalValueSummary::GlobalVarKind;
61319e23874SEugene Leviant   }
61419e23874SEugene Leviant   return false;
61519e23874SEugene Leviant }
61619e23874SEugene Leviant 
61719e23874SEugene Leviant static GlobalValue::GUID getGUID(GlobalValue::GUID G) { return G; }
61819e23874SEugene Leviant 
61919e23874SEugene Leviant template <class T>
6201fc0da48SBenjamin Kramer static unsigned numGlobalVarSummaries(const ModuleSummaryIndex &Index,
6211fc0da48SBenjamin Kramer                                       T &Cont) {
62219e23874SEugene Leviant   unsigned NumGVS = 0;
62319e23874SEugene Leviant   for (auto &V : Cont)
62419e23874SEugene Leviant     if (isGlobalVarSummary(Index, getGUID(V)))
62519e23874SEugene Leviant       ++NumGVS;
62619e23874SEugene Leviant   return NumGVS;
62719e23874SEugene Leviant }
62819e23874SEugene Leviant #endif
62919e23874SEugene Leviant 
630c86af334STeresa Johnson /// Compute all the import and export for every module using the Index.
63101e32130SMehdi Amini void llvm::ComputeCrossModuleImport(
63201e32130SMehdi Amini     const ModuleSummaryIndex &Index,
633c851d216STeresa Johnson     const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
63401e32130SMehdi Amini     StringMap<FunctionImporter::ImportMapTy> &ImportLists,
63556584bbfSEvgeniy Stepanov     StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
63601e32130SMehdi Amini   // For each module that has function defined, compute the import/export lists.
6371aafabf7SMehdi Amini   for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
6389b490f10SMehdi Amini     auto &ImportList = ImportLists[DefinedGVSummaries.first()];
639d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Computing import for Module '"
6401aafabf7SMehdi Amini                       << DefinedGVSummaries.first() << "'\n");
641cb9a82fcSTeresa Johnson     ComputeImportForModule(DefinedGVSummaries.second, Index,
642cb9a82fcSTeresa Johnson                            DefinedGVSummaries.first(), ImportList,
64356584bbfSEvgeniy Stepanov                            &ExportLists);
64401e32130SMehdi Amini   }
64501e32130SMehdi Amini 
646edddca22STeresa Johnson   // When computing imports we added all GUIDs referenced by anything
647edddca22STeresa Johnson   // imported from the module to its ExportList. Now we prune each ExportList
648edddca22STeresa Johnson   // of any not defined in that module. This is more efficient than checking
649edddca22STeresa Johnson   // while computing imports because some of the summary lists may be long
650edddca22STeresa Johnson   // due to linkonce (comdat) copies.
651edddca22STeresa Johnson   for (auto &ELI : ExportLists) {
652edddca22STeresa Johnson     const auto &DefinedGVSummaries =
653edddca22STeresa Johnson         ModuleToDefinedGVSummaries.lookup(ELI.first());
654edddca22STeresa Johnson     for (auto EI = ELI.second.begin(); EI != ELI.second.end();) {
655edddca22STeresa Johnson       if (!DefinedGVSummaries.count(*EI))
656edddca22STeresa Johnson         EI = ELI.second.erase(EI);
657edddca22STeresa Johnson       else
658edddca22STeresa Johnson         ++EI;
659edddca22STeresa Johnson     }
660edddca22STeresa Johnson   }
661edddca22STeresa Johnson 
66201e32130SMehdi Amini #ifndef NDEBUG
663d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
66401e32130SMehdi Amini                     << " modules:\n");
66501e32130SMehdi Amini   for (auto &ModuleImports : ImportLists) {
66601e32130SMehdi Amini     auto ModName = ModuleImports.first();
66701e32130SMehdi Amini     auto &Exports = ExportLists[ModName];
66819e23874SEugene Leviant     unsigned NumGVS = numGlobalVarSummaries(Index, Exports);
669d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "* Module " << ModName << " exports "
67019e23874SEugene Leviant                       << Exports.size() - NumGVS << " functions and " << NumGVS
671d34e60caSNicola Zaghen                       << " vars. Imports from " << ModuleImports.second.size()
672d34e60caSNicola Zaghen                       << " modules.\n");
67301e32130SMehdi Amini     for (auto &Src : ModuleImports.second) {
67401e32130SMehdi Amini       auto SrcModName = Src.first();
67519e23874SEugene Leviant       unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second);
676d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod
67719e23874SEugene Leviant                         << " functions imported from " << SrcModName << "\n");
678d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod
679d34e60caSNicola Zaghen                         << " global vars imported from " << SrcModName << "\n");
68001e32130SMehdi Amini     }
68101e32130SMehdi Amini   }
68201e32130SMehdi Amini #endif
68301e32130SMehdi Amini }
68401e32130SMehdi Amini 
68581bbf742STeresa Johnson #ifndef NDEBUG
68619e23874SEugene Leviant static void dumpImportListForModule(const ModuleSummaryIndex &Index,
68719e23874SEugene Leviant                                     StringRef ModulePath,
68881bbf742STeresa Johnson                                     FunctionImporter::ImportMapTy &ImportList) {
689d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
69081bbf742STeresa Johnson                     << ImportList.size() << " modules.\n");
69181bbf742STeresa Johnson   for (auto &Src : ImportList) {
69281bbf742STeresa Johnson     auto SrcModName = Src.first();
69319e23874SEugene Leviant     unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second);
694d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod
69519e23874SEugene Leviant                       << " functions imported from " << SrcModName << "\n");
696d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod << " vars imported from "
69781bbf742STeresa Johnson                       << SrcModName << "\n");
69881bbf742STeresa Johnson   }
69981bbf742STeresa Johnson }
70069b2de84STeresa Johnson #endif
70181bbf742STeresa Johnson 
702c86af334STeresa Johnson /// Compute all the imports for the given module in the Index.
703c86af334STeresa Johnson void llvm::ComputeCrossModuleImportForModule(
704c86af334STeresa Johnson     StringRef ModulePath, const ModuleSummaryIndex &Index,
705c86af334STeresa Johnson     FunctionImporter::ImportMapTy &ImportList) {
706c86af334STeresa Johnson   // Collect the list of functions this module defines.
707c86af334STeresa Johnson   // GUID -> Summary
708c851d216STeresa Johnson   GVSummaryMapTy FunctionSummaryMap;
70928e457bcSTeresa Johnson   Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
710c86af334STeresa Johnson 
711c86af334STeresa Johnson   // Compute the import list for this module.
712d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
713cb9a82fcSTeresa Johnson   ComputeImportForModule(FunctionSummaryMap, Index, ModulePath, ImportList);
714c86af334STeresa Johnson 
715c86af334STeresa Johnson #ifndef NDEBUG
71619e23874SEugene Leviant   dumpImportListForModule(Index, ModulePath, ImportList);
71781bbf742STeresa Johnson #endif
718c86af334STeresa Johnson }
71981bbf742STeresa Johnson 
72081bbf742STeresa Johnson // Mark all external summaries in Index for import into the given module.
72181bbf742STeresa Johnson // Used for distributed builds using a distributed index.
72281bbf742STeresa Johnson void llvm::ComputeCrossModuleImportForModuleFromIndex(
72381bbf742STeresa Johnson     StringRef ModulePath, const ModuleSummaryIndex &Index,
72481bbf742STeresa Johnson     FunctionImporter::ImportMapTy &ImportList) {
72581bbf742STeresa Johnson   for (auto &GlobalList : Index) {
72681bbf742STeresa Johnson     // Ignore entries for undefined references.
72781bbf742STeresa Johnson     if (GlobalList.second.SummaryList.empty())
72881bbf742STeresa Johnson       continue;
72981bbf742STeresa Johnson 
73081bbf742STeresa Johnson     auto GUID = GlobalList.first;
73181bbf742STeresa Johnson     assert(GlobalList.second.SummaryList.size() == 1 &&
73281bbf742STeresa Johnson            "Expected individual combined index to have one summary per GUID");
73381bbf742STeresa Johnson     auto &Summary = GlobalList.second.SummaryList[0];
73481bbf742STeresa Johnson     // Skip the summaries for the importing module. These are included to
73581bbf742STeresa Johnson     // e.g. record required linkage changes.
73681bbf742STeresa Johnson     if (Summary->modulePath() == ModulePath)
73781bbf742STeresa Johnson       continue;
738d68935c5STeresa Johnson     // Add an entry to provoke importing by thinBackend.
739d68935c5STeresa Johnson     ImportList[Summary->modulePath()].insert(GUID);
74081bbf742STeresa Johnson   }
74181bbf742STeresa Johnson #ifndef NDEBUG
74219e23874SEugene Leviant   dumpImportListForModule(Index, ModulePath, ImportList);
743c86af334STeresa Johnson #endif
744c86af334STeresa Johnson }
745c86af334STeresa Johnson 
74656584bbfSEvgeniy Stepanov void llvm::computeDeadSymbols(
74756584bbfSEvgeniy Stepanov     ModuleSummaryIndex &Index,
748eaf5172cSGeorge Rimar     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
749eaf5172cSGeorge Rimar     function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing) {
75056584bbfSEvgeniy Stepanov   assert(!Index.withGlobalValueDeadStripping());
7516c475a75STeresa Johnson   if (!ComputeDead)
75256584bbfSEvgeniy Stepanov     return;
7536c475a75STeresa Johnson   if (GUIDPreservedSymbols.empty())
7546c475a75STeresa Johnson     // Don't do anything when nothing is live, this is friendly with tests.
75556584bbfSEvgeniy Stepanov     return;
75656584bbfSEvgeniy Stepanov   unsigned LiveSymbols = 0;
7579667b91bSPeter Collingbourne   SmallVector<ValueInfo, 128> Worklist;
7589667b91bSPeter Collingbourne   Worklist.reserve(GUIDPreservedSymbols.size() * 2);
7599667b91bSPeter Collingbourne   for (auto GUID : GUIDPreservedSymbols) {
7609667b91bSPeter Collingbourne     ValueInfo VI = Index.getValueInfo(GUID);
7619667b91bSPeter Collingbourne     if (!VI)
7629667b91bSPeter Collingbourne       continue;
76356584bbfSEvgeniy Stepanov     for (auto &S : VI.getSummaryList())
76456584bbfSEvgeniy Stepanov       S->setLive(true);
7656c475a75STeresa Johnson   }
76656584bbfSEvgeniy Stepanov 
7676c475a75STeresa Johnson   // Add values flagged in the index as live roots to the worklist.
7687e7b13d0STeresa Johnson   for (const auto &Entry : Index) {
7697e7b13d0STeresa Johnson     auto VI = Index.getValueInfo(Entry);
77056584bbfSEvgeniy Stepanov     for (auto &S : Entry.second.SummaryList)
77156584bbfSEvgeniy Stepanov       if (S->isLive()) {
7727e7b13d0STeresa Johnson         LLVM_DEBUG(dbgs() << "Live root: " << VI << "\n");
7737e7b13d0STeresa Johnson         Worklist.push_back(VI);
77456584bbfSEvgeniy Stepanov         ++LiveSymbols;
77556584bbfSEvgeniy Stepanov         break;
7766c475a75STeresa Johnson       }
7777e7b13d0STeresa Johnson   }
7786c475a75STeresa Johnson 
77956584bbfSEvgeniy Stepanov   // Make value live and add it to the worklist if it was not live before.
780ea314fd4STeresa Johnson   auto visit = [&](ValueInfo VI, bool IsAliasee) {
7811958083dSTeresa Johnson     // FIXME: If we knew which edges were created for indirect call profiles,
7821958083dSTeresa Johnson     // we could skip them here. Any that are live should be reached via
7831958083dSTeresa Johnson     // other edges, e.g. reference edges. Otherwise, using a profile collected
7841958083dSTeresa Johnson     // on a slightly different binary might provoke preserving, importing
7851958083dSTeresa Johnson     // and ultimately promoting calls to functions not linked into this
7861958083dSTeresa Johnson     // binary, which increases the binary size unnecessarily. Note that
7871958083dSTeresa Johnson     // if this code changes, the importer needs to change so that edges
7881958083dSTeresa Johnson     // to functions marked dead are skipped.
7891958083dSTeresa Johnson     VI = updateValueInfoForIndirectCalls(Index, VI);
7901958083dSTeresa Johnson     if (!VI)
7911958083dSTeresa Johnson       return;
79233e3b4b9SXin Tong 
7935b2f6a1bSTeresa Johnson     if (llvm::any_of(VI.getSummaryList(),
79433e3b4b9SXin Tong                      [](const std::unique_ptr<llvm::GlobalValueSummary> &S) {
79533e3b4b9SXin Tong                        return S->isLive();
79633e3b4b9SXin Tong                      }))
797f625118eSTeresa Johnson       return;
798eaf5172cSGeorge Rimar 
799aab60006SVlad Tsyrklevich     // We only keep live symbols that are known to be non-prevailing if any are
800bfdad33bSXin Tong     // available_externally, linkonceodr, weakodr. Those symbols are discarded
801bfdad33bSXin Tong     // later in the EliminateAvailableExternally pass and setting them to
802bfdad33bSXin Tong     // not-live could break downstreams users of liveness information (PR36483)
803bfdad33bSXin Tong     // or limit optimization opportunities.
804aab60006SVlad Tsyrklevich     if (isPrevailing(VI.getGUID()) == PrevailingType::No) {
805bfdad33bSXin Tong       bool KeepAliveLinkage = false;
806aab60006SVlad Tsyrklevich       bool Interposable = false;
807aab60006SVlad Tsyrklevich       for (auto &S : VI.getSummaryList()) {
808bfdad33bSXin Tong         if (S->linkage() == GlobalValue::AvailableExternallyLinkage ||
809bfdad33bSXin Tong             S->linkage() == GlobalValue::WeakODRLinkage ||
810bfdad33bSXin Tong             S->linkage() == GlobalValue::LinkOnceODRLinkage)
811bfdad33bSXin Tong           KeepAliveLinkage = true;
812aab60006SVlad Tsyrklevich         else if (GlobalValue::isInterposableLinkage(S->linkage()))
813aab60006SVlad Tsyrklevich           Interposable = true;
814aab60006SVlad Tsyrklevich       }
815aab60006SVlad Tsyrklevich 
816ea314fd4STeresa Johnson       if (!IsAliasee) {
817bfdad33bSXin Tong         if (!KeepAliveLinkage)
818eaf5172cSGeorge Rimar           return;
819eaf5172cSGeorge Rimar 
820aab60006SVlad Tsyrklevich         if (Interposable)
821bfdad33bSXin Tong           report_fatal_error(
822ea314fd4STeresa Johnson               "Interposable and available_externally/linkonce_odr/weak_odr "
823ea314fd4STeresa Johnson               "symbol");
824ea314fd4STeresa Johnson       }
825aab60006SVlad Tsyrklevich     }
826aab60006SVlad Tsyrklevich 
827f625118eSTeresa Johnson     for (auto &S : VI.getSummaryList())
82856584bbfSEvgeniy Stepanov       S->setLive(true);
82956584bbfSEvgeniy Stepanov     ++LiveSymbols;
83056584bbfSEvgeniy Stepanov     Worklist.push_back(VI);
83156584bbfSEvgeniy Stepanov   };
83256584bbfSEvgeniy Stepanov 
8336c475a75STeresa Johnson   while (!Worklist.empty()) {
8349667b91bSPeter Collingbourne     auto VI = Worklist.pop_back_val();
8359667b91bSPeter Collingbourne     for (auto &Summary : VI.getSummaryList()) {
8365b2f6a1bSTeresa Johnson       if (auto *AS = dyn_cast<AliasSummary>(Summary.get())) {
8375b2f6a1bSTeresa Johnson         // If this is an alias, visit the aliasee VI to ensure that all copies
8385b2f6a1bSTeresa Johnson         // are marked live and it is added to the worklist for further
8395b2f6a1bSTeresa Johnson         // processing of its references.
840ea314fd4STeresa Johnson         visit(AS->getAliaseeVI(), true);
8415b2f6a1bSTeresa Johnson         continue;
8425b2f6a1bSTeresa Johnson       }
8435b2f6a1bSTeresa Johnson 
8445b2f6a1bSTeresa Johnson       Summary->setLive(true);
8455b2f6a1bSTeresa Johnson       for (auto Ref : Summary->refs())
846ea314fd4STeresa Johnson         visit(Ref, false);
8475b2f6a1bSTeresa Johnson       if (auto *FS = dyn_cast<FunctionSummary>(Summary.get()))
84856584bbfSEvgeniy Stepanov         for (auto Call : FS->calls())
849ea314fd4STeresa Johnson           visit(Call.first, false);
8506c475a75STeresa Johnson     }
8516c475a75STeresa Johnson   }
85256584bbfSEvgeniy Stepanov   Index.setWithGlobalValueDeadStripping();
85356584bbfSEvgeniy Stepanov 
85456584bbfSEvgeniy Stepanov   unsigned DeadSymbols = Index.size() - LiveSymbols;
855d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols
85656584bbfSEvgeniy Stepanov                     << " symbols Dead \n");
85756584bbfSEvgeniy Stepanov   NumDeadSymbols += DeadSymbols;
85856584bbfSEvgeniy Stepanov   NumLiveSymbols += LiveSymbols;
8596c475a75STeresa Johnson }
8606c475a75STeresa Johnson 
861bf46e741SEugene Leviant // Compute dead symbols and propagate constants in combined index.
862bf46e741SEugene Leviant void llvm::computeDeadSymbolsWithConstProp(
863bf46e741SEugene Leviant     ModuleSummaryIndex &Index,
864bf46e741SEugene Leviant     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
865bf46e741SEugene Leviant     function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing,
866bf46e741SEugene Leviant     bool ImportEnabled) {
867bf46e741SEugene Leviant   computeDeadSymbols(Index, GUIDPreservedSymbols, isPrevailing);
868bf46e741SEugene Leviant   if (ImportEnabled) {
8693aef3528SEugene Leviant     Index.propagateAttributes(GUIDPreservedSymbols);
870bf46e741SEugene Leviant   } else {
8713aef3528SEugene Leviant     // If import is disabled we should drop read/write-only attribute
872bf46e741SEugene Leviant     // from all summaries to prevent internalization.
873bf46e741SEugene Leviant     for (auto &P : Index)
874bf46e741SEugene Leviant       for (auto &S : P.second.SummaryList)
8753aef3528SEugene Leviant         if (auto *GVS = dyn_cast<GlobalVarSummary>(S.get())) {
876bf46e741SEugene Leviant           GVS->setReadOnly(false);
8773aef3528SEugene Leviant           GVS->setWriteOnly(false);
8783aef3528SEugene Leviant         }
879bf46e741SEugene Leviant   }
880dde58938Sevgeny   Index.setWithAttributePropagation();
881bf46e741SEugene Leviant }
882bf46e741SEugene Leviant 
88384174c37STeresa Johnson /// Compute the set of summaries needed for a ThinLTO backend compilation of
88484174c37STeresa Johnson /// \p ModulePath.
88584174c37STeresa Johnson void llvm::gatherImportedSummariesForModule(
88684174c37STeresa Johnson     StringRef ModulePath,
88784174c37STeresa Johnson     const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
888cdbcbf74SMehdi Amini     const FunctionImporter::ImportMapTy &ImportList,
88984174c37STeresa Johnson     std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
89084174c37STeresa Johnson   // Include all summaries from the importing module.
89184174c37STeresa Johnson   ModuleToSummariesForIndex[ModulePath] =
89284174c37STeresa Johnson       ModuleToDefinedGVSummaries.lookup(ModulePath);
89384174c37STeresa Johnson   // Include summaries for imports.
89488c491ddSMehdi Amini   for (auto &ILI : ImportList) {
89584174c37STeresa Johnson     auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
89684174c37STeresa Johnson     const auto &DefinedGVSummaries =
89784174c37STeresa Johnson         ModuleToDefinedGVSummaries.lookup(ILI.first());
89884174c37STeresa Johnson     for (auto &GI : ILI.second) {
899d68935c5STeresa Johnson       const auto &DS = DefinedGVSummaries.find(GI);
90084174c37STeresa Johnson       assert(DS != DefinedGVSummaries.end() &&
90184174c37STeresa Johnson              "Expected a defined summary for imported global value");
902d68935c5STeresa Johnson       SummariesForIndex[GI] = DS->second;
90384174c37STeresa Johnson     }
90484174c37STeresa Johnson   }
90584174c37STeresa Johnson }
90684174c37STeresa Johnson 
9078570fe47STeresa Johnson /// Emit the files \p ModulePath will import from into \p OutputFilename.
908c0320ef4STeresa Johnson std::error_code llvm::EmitImportsFiles(
909c0320ef4STeresa Johnson     StringRef ModulePath, StringRef OutputFilename,
910c0320ef4STeresa Johnson     const std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
9118570fe47STeresa Johnson   std::error_code EC;
912d9b948b6SFangrui Song   raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::OF_None);
9138570fe47STeresa Johnson   if (EC)
9148570fe47STeresa Johnson     return EC;
915c0320ef4STeresa Johnson   for (auto &ILI : ModuleToSummariesForIndex)
916c0320ef4STeresa Johnson     // The ModuleToSummariesForIndex map includes an entry for the current
917c0320ef4STeresa Johnson     // Module (needed for writing out the index files). We don't want to
918c0320ef4STeresa Johnson     // include it in the imports file, however, so filter it out.
919c0320ef4STeresa Johnson     if (ILI.first != ModulePath)
920c0320ef4STeresa Johnson       ImportsOS << ILI.first << "\n";
9218570fe47STeresa Johnson   return std::error_code();
9228570fe47STeresa Johnson }
9238570fe47STeresa Johnson 
9245a95c477STeresa Johnson bool llvm::convertToDeclaration(GlobalValue &GV) {
925d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName()
926d34e60caSNicola Zaghen                     << "\n");
9274566c6dbSTeresa Johnson   if (Function *F = dyn_cast<Function>(&GV)) {
9284566c6dbSTeresa Johnson     F->deleteBody();
9294566c6dbSTeresa Johnson     F->clearMetadata();
9307873669bSPeter Collingbourne     F->setComdat(nullptr);
9314566c6dbSTeresa Johnson   } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
9324566c6dbSTeresa Johnson     V->setInitializer(nullptr);
9334566c6dbSTeresa Johnson     V->setLinkage(GlobalValue::ExternalLinkage);
9344566c6dbSTeresa Johnson     V->clearMetadata();
9357873669bSPeter Collingbourne     V->setComdat(nullptr);
9365a95c477STeresa Johnson   } else {
9375a95c477STeresa Johnson     GlobalValue *NewGV;
9385a95c477STeresa Johnson     if (GV.getValueType()->isFunctionTy())
9395a95c477STeresa Johnson       NewGV =
9405a95c477STeresa Johnson           Function::Create(cast<FunctionType>(GV.getValueType()),
941f920da00SDylan McKay                            GlobalValue::ExternalLinkage, GV.getAddressSpace(),
942f920da00SDylan McKay                            "", GV.getParent());
9435a95c477STeresa Johnson     else
9445a95c477STeresa Johnson       NewGV =
9455a95c477STeresa Johnson           new GlobalVariable(*GV.getParent(), GV.getValueType(),
9465a95c477STeresa Johnson                              /*isConstant*/ false, GlobalValue::ExternalLinkage,
9475a95c477STeresa Johnson                              /*init*/ nullptr, "",
9485a95c477STeresa Johnson                              /*insertbefore*/ nullptr, GV.getThreadLocalMode(),
9495a95c477STeresa Johnson                              GV.getType()->getAddressSpace());
9505a95c477STeresa Johnson     NewGV->takeName(&GV);
9515a95c477STeresa Johnson     GV.replaceAllUsesWith(NewGV);
9525a95c477STeresa Johnson     return false;
9535a95c477STeresa Johnson   }
9545a95c477STeresa Johnson   return true;
955eaf5172cSGeorge Rimar }
9564566c6dbSTeresa Johnson 
957e61652a3SPirama Arumuga Nainar /// Fixup prevailing symbol linkages in \p TheModule based on summary analysis.
958e61652a3SPirama Arumuga Nainar void llvm::thinLTOResolvePrevailingInModule(
959eaf5172cSGeorge Rimar     Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
96004c9a2d6STeresa Johnson   auto updateLinkage = [&](GlobalValue &GV) {
96104c9a2d6STeresa Johnson     // See if the global summary analysis computed a new resolved linkage.
96204c9a2d6STeresa Johnson     const auto &GS = DefinedGlobals.find(GV.getGUID());
96304c9a2d6STeresa Johnson     if (GS == DefinedGlobals.end())
96404c9a2d6STeresa Johnson       return;
96504c9a2d6STeresa Johnson     auto NewLinkage = GS->second->linkage();
96604c9a2d6STeresa Johnson     if (NewLinkage == GV.getLinkage())
96704c9a2d6STeresa Johnson       return;
968e61652a3SPirama Arumuga Nainar     if (GlobalValue::isLocalLinkage(GV.getLinkage()) ||
969e5dd30f7SEugene Leviant         // Don't internalize anything here, because the code below
970e5dd30f7SEugene Leviant         // lacks necessary correctness checks. Leave this job to
971e5dd30f7SEugene Leviant         // LLVM 'internalize' pass.
9720f418677SEugene Leviant         GlobalValue::isLocalLinkage(NewLinkage) ||
973e61652a3SPirama Arumuga Nainar         // In case it was dead and already converted to declaration.
974e61652a3SPirama Arumuga Nainar         GV.isDeclaration())
9756a5fbe52SDavide Italiano       return;
976ea314fd4STeresa Johnson 
9774566c6dbSTeresa Johnson     // Check for a non-prevailing def that has interposable linkage
9784566c6dbSTeresa Johnson     // (e.g. non-odr weak or linkonce). In that case we can't simply
9794566c6dbSTeresa Johnson     // convert to available_externally, since it would lose the
9804566c6dbSTeresa Johnson     // interposable property and possibly get inlined. Simply drop
9814566c6dbSTeresa Johnson     // the definition in that case.
9824566c6dbSTeresa Johnson     if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) &&
9835a95c477STeresa Johnson         GlobalValue::isInterposableLinkage(GV.getLinkage())) {
9845a95c477STeresa Johnson       if (!convertToDeclaration(GV))
9855a95c477STeresa Johnson         // FIXME: Change this to collect replaced GVs and later erase
986e61652a3SPirama Arumuga Nainar         // them from the parent module once thinLTOResolvePrevailingGUID is
9875a95c477STeresa Johnson         // changed to enable this for aliases.
9885a95c477STeresa Johnson         llvm_unreachable("Expected GV to be converted");
9895a95c477STeresa Johnson     } else {
99037b80122STeresa Johnson       // If all copies of the original symbol had global unnamed addr and
99137b80122STeresa Johnson       // linkonce_odr linkage, it should be an auto hide symbol. In that case
99237b80122STeresa Johnson       // the thin link would have marked it as CanAutoHide. Add hidden visibility
99337b80122STeresa Johnson       // to the symbol to preserve the property.
99437b80122STeresa Johnson       if (NewLinkage == GlobalValue::WeakODRLinkage &&
99537b80122STeresa Johnson           GS->second->canAutoHide()) {
99637b80122STeresa Johnson         assert(GV.hasLinkOnceODRLinkage() && GV.hasGlobalUnnamedAddr());
99733ba93c2SSteven Wu         GV.setVisibility(GlobalValue::HiddenVisibility);
99837b80122STeresa Johnson       }
99933ba93c2SSteven Wu 
1000d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName()
1001d34e60caSNicola Zaghen                         << "` from " << GV.getLinkage() << " to " << NewLinkage
1002d34e60caSNicola Zaghen                         << "\n");
100304c9a2d6STeresa Johnson       GV.setLinkage(NewLinkage);
10044566c6dbSTeresa Johnson     }
10054566c6dbSTeresa Johnson     // Remove declarations from comdats, including available_externally
10066107a419STeresa Johnson     // as this is a declaration for the linker, and will be dropped eventually.
10076107a419STeresa Johnson     // It is illegal for comdats to contain declarations.
10086107a419STeresa Johnson     auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
10094566c6dbSTeresa Johnson     if (GO && GO->isDeclarationForLinker() && GO->hasComdat())
10106107a419STeresa Johnson       GO->setComdat(nullptr);
101104c9a2d6STeresa Johnson   };
101204c9a2d6STeresa Johnson 
101304c9a2d6STeresa Johnson   // Process functions and global now
101404c9a2d6STeresa Johnson   for (auto &GV : TheModule)
101504c9a2d6STeresa Johnson     updateLinkage(GV);
101604c9a2d6STeresa Johnson   for (auto &GV : TheModule.globals())
101704c9a2d6STeresa Johnson     updateLinkage(GV);
101804c9a2d6STeresa Johnson   for (auto &GV : TheModule.aliases())
101904c9a2d6STeresa Johnson     updateLinkage(GV);
102004c9a2d6STeresa Johnson }
102104c9a2d6STeresa Johnson 
102204c9a2d6STeresa Johnson /// Run internalization on \p TheModule based on symmary analysis.
102304c9a2d6STeresa Johnson void llvm::thinLTOInternalizeModule(Module &TheModule,
102404c9a2d6STeresa Johnson                                     const GVSummaryMapTy &DefinedGlobals) {
102504c9a2d6STeresa Johnson   // Declare a callback for the internalize pass that will ask for every
102604c9a2d6STeresa Johnson   // candidate GlobalValue if it can be internalized or not.
102704c9a2d6STeresa Johnson   auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
102804c9a2d6STeresa Johnson     // Lookup the linkage recorded in the summaries during global analysis.
1029c3d677f9SPeter Collingbourne     auto GS = DefinedGlobals.find(GV.getGUID());
103004c9a2d6STeresa Johnson     if (GS == DefinedGlobals.end()) {
103104c9a2d6STeresa Johnson       // Must have been promoted (possibly conservatively). Find original
103204c9a2d6STeresa Johnson       // name so that we can access the correct summary and see if it can
103304c9a2d6STeresa Johnson       // be internalized again.
103404c9a2d6STeresa Johnson       // FIXME: Eventually we should control promotion instead of promoting
103504c9a2d6STeresa Johnson       // and internalizing again.
103604c9a2d6STeresa Johnson       StringRef OrigName =
103704c9a2d6STeresa Johnson           ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
103804c9a2d6STeresa Johnson       std::string OrigId = GlobalValue::getGlobalIdentifier(
103904c9a2d6STeresa Johnson           OrigName, GlobalValue::InternalLinkage,
104004c9a2d6STeresa Johnson           TheModule.getSourceFileName());
1041c3d677f9SPeter Collingbourne       GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
10427ab1f692STeresa Johnson       if (GS == DefinedGlobals.end()) {
10437ab1f692STeresa Johnson         // Also check the original non-promoted non-globalized name. In some
10447ab1f692STeresa Johnson         // cases a preempted weak value is linked in as a local copy because
10457ab1f692STeresa Johnson         // it is referenced by an alias (IRLinker::linkGlobalValueProto).
10467ab1f692STeresa Johnson         // In that case, since it was originally not a local value, it was
10477ab1f692STeresa Johnson         // recorded in the index using the original name.
10487ab1f692STeresa Johnson         // FIXME: This may not be needed once PR27866 is fixed.
1049c3d677f9SPeter Collingbourne         GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
105004c9a2d6STeresa Johnson         assert(GS != DefinedGlobals.end());
10517ab1f692STeresa Johnson       }
1052c3d677f9SPeter Collingbourne     }
1053c3d677f9SPeter Collingbourne     return !GlobalValue::isLocalLinkage(GS->second->linkage());
105404c9a2d6STeresa Johnson   };
105504c9a2d6STeresa Johnson 
105604c9a2d6STeresa Johnson   // FIXME: See if we can just internalize directly here via linkage changes
105704c9a2d6STeresa Johnson   // based on the index, rather than invoking internalizeModule.
1058e9ea08a0SEugene Zelenko   internalizeModule(TheModule, MustPreserveGV);
105904c9a2d6STeresa Johnson }
106004c9a2d6STeresa Johnson 
106181bbf742STeresa Johnson /// Make alias a clone of its aliasee.
106281bbf742STeresa Johnson static Function *replaceAliasWithAliasee(Module *SrcModule, GlobalAlias *GA) {
106381bbf742STeresa Johnson   Function *Fn = cast<Function>(GA->getBaseObject());
106481bbf742STeresa Johnson 
106581bbf742STeresa Johnson   ValueToValueMapTy VMap;
106681bbf742STeresa Johnson   Function *NewFn = CloneFunction(Fn, VMap);
10675b2088d1STeresa Johnson   // Clone should use the original alias's linkage, visibility and name, and we
10685b2088d1STeresa Johnson   // ensure all uses of alias instead use the new clone (casted if necessary).
106981bbf742STeresa Johnson   NewFn->setLinkage(GA->getLinkage());
10705b2088d1STeresa Johnson   NewFn->setVisibility(GA->getVisibility());
107181bbf742STeresa Johnson   GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewFn, GA->getType()));
107281bbf742STeresa Johnson   NewFn->takeName(GA);
107381bbf742STeresa Johnson   return NewFn;
107481bbf742STeresa Johnson }
107581bbf742STeresa Johnson 
1076bf46e741SEugene Leviant // Internalize values that we marked with specific attribute
1077bf46e741SEugene Leviant // in processGlobalForThinLTO.
10783aef3528SEugene Leviant static void internalizeGVsAfterImport(Module &M) {
1079bf46e741SEugene Leviant   for (auto &GV : M.globals())
1080bf46e741SEugene Leviant     // Skip GVs which have been converted to declarations
1081bf46e741SEugene Leviant     // by dropDeadSymbols.
1082bf46e741SEugene Leviant     if (!GV.isDeclaration() && GV.hasAttribute("thinlto-internalize")) {
1083bf46e741SEugene Leviant       GV.setLinkage(GlobalValue::InternalLinkage);
1084bf46e741SEugene Leviant       GV.setVisibility(GlobalValue::DefaultVisibility);
1085bf46e741SEugene Leviant     }
1086bf46e741SEugene Leviant }
1087bf46e741SEugene Leviant 
1088c8c55170SMehdi Amini // Automatically import functions in Module \p DestModule based on the summaries
1089c8c55170SMehdi Amini // index.
10907f00d0a1SPeter Collingbourne Expected<bool> FunctionImporter::importFunctions(
109166043797SAdrian Prantl     Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
1092d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Starting import for Module "
1093311fef6eSMehdi Amini                     << DestModule.getModuleIdentifier() << "\n");
109419e23874SEugene Leviant   unsigned ImportedCount = 0, ImportedGVCount = 0;
1095c8c55170SMehdi Amini 
10966d8f817fSPeter Collingbourne   IRMover Mover(DestModule);
10977e88d0daSMehdi Amini   // Do the actual import of functions now, one Module at a time
109801e32130SMehdi Amini   std::set<StringRef> ModuleNameOrderedList;
109901e32130SMehdi Amini   for (auto &FunctionsToImportPerModule : ImportList) {
110001e32130SMehdi Amini     ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
110101e32130SMehdi Amini   }
110201e32130SMehdi Amini   for (auto &Name : ModuleNameOrderedList) {
11037e88d0daSMehdi Amini     // Get the module for the import
110401e32130SMehdi Amini     const auto &FunctionsToImportPerModule = ImportList.find(Name);
110501e32130SMehdi Amini     assert(FunctionsToImportPerModule != ImportList.end());
1106d9445c49SPeter Collingbourne     Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
1107d9445c49SPeter Collingbourne     if (!SrcModuleOrErr)
1108d9445c49SPeter Collingbourne       return SrcModuleOrErr.takeError();
1109d9445c49SPeter Collingbourne     std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
11107e88d0daSMehdi Amini     assert(&DestModule.getContext() == &SrcModule->getContext() &&
11117e88d0daSMehdi Amini            "Context mismatch");
11127e88d0daSMehdi Amini 
11136cba37ceSTeresa Johnson     // If modules were created with lazy metadata loading, materialize it
11146cba37ceSTeresa Johnson     // now, before linking it (otherwise this will be a noop).
11157f00d0a1SPeter Collingbourne     if (Error Err = SrcModule->materializeMetadata())
11167f00d0a1SPeter Collingbourne       return std::move(Err);
1117e5a61917STeresa Johnson 
111801e32130SMehdi Amini     auto &ImportGUIDs = FunctionsToImportPerModule->second;
111901e32130SMehdi Amini     // Find the globals to import
11206d8f817fSPeter Collingbourne     SetVector<GlobalValue *> GlobalsToImport;
11211f685e01SPiotr Padlewski     for (Function &F : *SrcModule) {
11221f685e01SPiotr Padlewski       if (!F.hasName())
11230beb858eSTeresa Johnson         continue;
11241f685e01SPiotr Padlewski       auto GUID = F.getGUID();
11250beb858eSTeresa Johnson       auto Import = ImportGUIDs.count(GUID);
1126d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function "
1127d34e60caSNicola Zaghen                         << GUID << " " << F.getName() << " from "
1128aeb1e59bSMehdi Amini                         << SrcModule->getSourceFileName() << "\n");
11290beb858eSTeresa Johnson       if (Import) {
11307f00d0a1SPeter Collingbourne         if (Error Err = F.materialize())
11317f00d0a1SPeter Collingbourne           return std::move(Err);
11323b776128SPiotr Padlewski         if (EnableImportMetadata) {
11336deaa6afSPiotr Padlewski           // Add 'thinlto_src_module' metadata for statistics and debugging.
11343b776128SPiotr Padlewski           F.setMetadata(
11353b776128SPiotr Padlewski               "thinlto_src_module",
1136e9ea08a0SEugene Zelenko               MDNode::get(DestModule.getContext(),
1137e9ea08a0SEugene Zelenko                           {MDString::get(DestModule.getContext(),
11386deaa6afSPiotr Padlewski                                          SrcModule->getSourceFileName())}));
11393b776128SPiotr Padlewski         }
11401f685e01SPiotr Padlewski         GlobalsToImport.insert(&F);
114101e32130SMehdi Amini       }
114201e32130SMehdi Amini     }
11431f685e01SPiotr Padlewski     for (GlobalVariable &GV : SrcModule->globals()) {
11442d28f7aaSMehdi Amini       if (!GV.hasName())
11452d28f7aaSMehdi Amini         continue;
11462d28f7aaSMehdi Amini       auto GUID = GV.getGUID();
11472d28f7aaSMehdi Amini       auto Import = ImportGUIDs.count(GUID);
1148d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global "
1149d34e60caSNicola Zaghen                         << GUID << " " << GV.getName() << " from "
1150aeb1e59bSMehdi Amini                         << SrcModule->getSourceFileName() << "\n");
11512d28f7aaSMehdi Amini       if (Import) {
11527f00d0a1SPeter Collingbourne         if (Error Err = GV.materialize())
11537f00d0a1SPeter Collingbourne           return std::move(Err);
115419e23874SEugene Leviant         ImportedGVCount += GlobalsToImport.insert(&GV);
11552d28f7aaSMehdi Amini       }
11562d28f7aaSMehdi Amini     }
11571f685e01SPiotr Padlewski     for (GlobalAlias &GA : SrcModule->aliases()) {
11581f685e01SPiotr Padlewski       if (!GA.hasName())
115901e32130SMehdi Amini         continue;
11601f685e01SPiotr Padlewski       auto GUID = GA.getGUID();
116181bbf742STeresa Johnson       auto Import = ImportGUIDs.count(GUID);
1162d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias "
1163d34e60caSNicola Zaghen                         << GUID << " " << GA.getName() << " from "
1164aeb1e59bSMehdi Amini                         << SrcModule->getSourceFileName() << "\n");
116581bbf742STeresa Johnson       if (Import) {
116681bbf742STeresa Johnson         if (Error Err = GA.materialize())
116781bbf742STeresa Johnson           return std::move(Err);
116881bbf742STeresa Johnson         // Import alias as a copy of its aliasee.
116981bbf742STeresa Johnson         GlobalObject *Base = GA.getBaseObject();
117081bbf742STeresa Johnson         if (Error Err = Base->materialize())
117181bbf742STeresa Johnson           return std::move(Err);
117281bbf742STeresa Johnson         auto *Fn = replaceAliasWithAliasee(SrcModule.get(), &GA);
1173d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "Is importing aliasee fn " << Base->getGUID()
117481bbf742STeresa Johnson                           << " " << Base->getName() << " from "
117581bbf742STeresa Johnson                           << SrcModule->getSourceFileName() << "\n");
117681bbf742STeresa Johnson         if (EnableImportMetadata) {
117781bbf742STeresa Johnson           // Add 'thinlto_src_module' metadata for statistics and debugging.
117881bbf742STeresa Johnson           Fn->setMetadata(
117981bbf742STeresa Johnson               "thinlto_src_module",
118081bbf742STeresa Johnson               MDNode::get(DestModule.getContext(),
118181bbf742STeresa Johnson                           {MDString::get(DestModule.getContext(),
118281bbf742STeresa Johnson                                          SrcModule->getSourceFileName())}));
118301e32130SMehdi Amini         }
118481bbf742STeresa Johnson         GlobalsToImport.insert(Fn);
118581bbf742STeresa Johnson       }
118681bbf742STeresa Johnson     }
118701e32130SMehdi Amini 
118819ef4fadSMehdi Amini     // Upgrade debug info after we're done materializing all the globals and we
118919ef4fadSMehdi Amini     // have loaded all the required metadata!
119019ef4fadSMehdi Amini     UpgradeDebugInfo(*SrcModule);
119119ef4fadSMehdi Amini 
11927e88d0daSMehdi Amini     // Link in the specified functions.
119301e32130SMehdi Amini     if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
11948d05185aSMehdi Amini       return true;
11958d05185aSMehdi Amini 
1196d29478f7STeresa Johnson     if (PrintImports) {
1197d29478f7STeresa Johnson       for (const auto *GV : GlobalsToImport)
1198d29478f7STeresa Johnson         dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
1199d29478f7STeresa Johnson                << " from " << SrcModule->getSourceFileName() << "\n";
1200d29478f7STeresa Johnson     }
1201d29478f7STeresa Johnson 
12026d8f817fSPeter Collingbourne     if (Mover.move(std::move(SrcModule), GlobalsToImport.getArrayRef(),
12036d8f817fSPeter Collingbourne                    [](GlobalValue &, IRMover::ValueAdder) {},
1204e6fd9ff9SPeter Collingbourne                    /*IsPerformingImport=*/true))
12057e88d0daSMehdi Amini       report_fatal_error("Function Import: link error");
12067e88d0daSMehdi Amini 
120701e32130SMehdi Amini     ImportedCount += GlobalsToImport.size();
12086c475a75STeresa Johnson     NumImportedModules++;
12097e88d0daSMehdi Amini   }
1210e5a61917STeresa Johnson 
12113aef3528SEugene Leviant   internalizeGVsAfterImport(DestModule);
1212bf46e741SEugene Leviant 
121319e23874SEugene Leviant   NumImportedFunctions += (ImportedCount - ImportedGVCount);
121419e23874SEugene Leviant   NumImportedGlobalVars += ImportedGVCount;
1215d29478f7STeresa Johnson 
1216d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Imported " << ImportedCount - ImportedGVCount
1217d34e60caSNicola Zaghen                     << " functions for Module "
1218d34e60caSNicola Zaghen                     << DestModule.getModuleIdentifier() << "\n");
1219d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Imported " << ImportedGVCount
122019e23874SEugene Leviant                     << " global variables for Module "
1221c8c55170SMehdi Amini                     << DestModule.getModuleIdentifier() << "\n");
1222c8c55170SMehdi Amini   return ImportedCount;
122342418abaSMehdi Amini }
122442418abaSMehdi Amini 
1225598bd2a2SPeter Collingbourne static bool doImportingForModule(Module &M) {
1226598bd2a2SPeter Collingbourne   if (SummaryFile.empty())
1227598bd2a2SPeter Collingbourne     report_fatal_error("error: -function-import requires -summary-file\n");
12286de481a3SPeter Collingbourne   Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
12296de481a3SPeter Collingbourne       getModuleSummaryIndexForFile(SummaryFile);
12306de481a3SPeter Collingbourne   if (!IndexPtrOrErr) {
12316de481a3SPeter Collingbourne     logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
12326de481a3SPeter Collingbourne                           "Error loading file '" + SummaryFile + "': ");
123342418abaSMehdi Amini     return false;
123442418abaSMehdi Amini   }
1235598bd2a2SPeter Collingbourne   std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
123642418abaSMehdi Amini 
1237c86af334STeresa Johnson   // First step is collecting the import list.
1238c86af334STeresa Johnson   FunctionImporter::ImportMapTy ImportList;
123981bbf742STeresa Johnson   // If requested, simply import all functions in the index. This is used
124081bbf742STeresa Johnson   // when testing distributed backend handling via the opt tool, when
124181bbf742STeresa Johnson   // we have distributed indexes containing exactly the summaries to import.
124281bbf742STeresa Johnson   if (ImportAllIndex)
124381bbf742STeresa Johnson     ComputeCrossModuleImportForModuleFromIndex(M.getModuleIdentifier(), *Index,
124481bbf742STeresa Johnson                                                ImportList);
124581bbf742STeresa Johnson   else
1246c86af334STeresa Johnson     ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
1247c86af334STeresa Johnson                                       ImportList);
124801e32130SMehdi Amini 
12494fef68cbSTeresa Johnson   // Conservatively mark all internal values as promoted. This interface is
12504fef68cbSTeresa Johnson   // only used when doing importing via the function importing pass. The pass
12514fef68cbSTeresa Johnson   // is only enabled when testing importing via the 'opt' tool, which does
12524fef68cbSTeresa Johnson   // not do the ThinLink that would normally determine what values to promote.
12534fef68cbSTeresa Johnson   for (auto &I : *Index) {
12549667b91bSPeter Collingbourne     for (auto &S : I.second.SummaryList) {
12554fef68cbSTeresa Johnson       if (GlobalValue::isLocalLinkage(S->linkage()))
12564fef68cbSTeresa Johnson         S->setLinkage(GlobalValue::ExternalLinkage);
12574fef68cbSTeresa Johnson     }
12584fef68cbSTeresa Johnson   }
12594fef68cbSTeresa Johnson 
126001e32130SMehdi Amini   // Next we need to promote to global scope and rename any local values that
12611b00f2d9STeresa Johnson   // are potentially exported to other modules.
126201e32130SMehdi Amini   if (renameModuleForThinLTO(M, *Index, nullptr)) {
12631b00f2d9STeresa Johnson     errs() << "Error renaming module\n";
12641b00f2d9STeresa Johnson     return false;
12651b00f2d9STeresa Johnson   }
12661b00f2d9STeresa Johnson 
126742418abaSMehdi Amini   // Perform the import now.
1268d16c8065SMehdi Amini   auto ModuleLoader = [&M](StringRef Identifier) {
1269d16c8065SMehdi Amini     return loadFile(Identifier, M.getContext());
1270d16c8065SMehdi Amini   };
12719d2bfc48SRafael Espindola   FunctionImporter Importer(*Index, ModuleLoader);
127237e24591SPeter Collingbourne   Expected<bool> Result = Importer.importFunctions(M, ImportList);
12737f00d0a1SPeter Collingbourne 
12747f00d0a1SPeter Collingbourne   // FIXME: Probably need to propagate Errors through the pass manager.
12757f00d0a1SPeter Collingbourne   if (!Result) {
12767f00d0a1SPeter Collingbourne     logAllUnhandledErrors(Result.takeError(), errs(),
12777f00d0a1SPeter Collingbourne                           "Error importing module: ");
12787f00d0a1SPeter Collingbourne     return false;
12797f00d0a1SPeter Collingbourne   }
12807f00d0a1SPeter Collingbourne 
12817f00d0a1SPeter Collingbourne   return *Result;
128221241571STeresa Johnson }
128321241571STeresa Johnson 
128421241571STeresa Johnson namespace {
1285e9ea08a0SEugene Zelenko 
128621241571STeresa Johnson /// Pass that performs cross-module function import provided a summary file.
128721241571STeresa Johnson class FunctionImportLegacyPass : public ModulePass {
128821241571STeresa Johnson public:
128921241571STeresa Johnson   /// Pass identification, replacement for typeid
129021241571STeresa Johnson   static char ID;
129121241571STeresa Johnson 
1292e9ea08a0SEugene Zelenko   explicit FunctionImportLegacyPass() : ModulePass(ID) {}
1293e9ea08a0SEugene Zelenko 
129421241571STeresa Johnson   /// Specify pass name for debug output
1295117296c0SMehdi Amini   StringRef getPassName() const override { return "Function Importing"; }
129621241571STeresa Johnson 
129721241571STeresa Johnson   bool runOnModule(Module &M) override {
129821241571STeresa Johnson     if (skipModule(M))
129921241571STeresa Johnson       return false;
130021241571STeresa Johnson 
1301598bd2a2SPeter Collingbourne     return doImportingForModule(M);
130242418abaSMehdi Amini   }
130342418abaSMehdi Amini };
1304e9ea08a0SEugene Zelenko 
1305e9ea08a0SEugene Zelenko } // end anonymous namespace
130642418abaSMehdi Amini 
130721241571STeresa Johnson PreservedAnalyses FunctionImportPass::run(Module &M,
1308fd03ac6aSSean Silva                                           ModuleAnalysisManager &AM) {
1309598bd2a2SPeter Collingbourne   if (!doImportingForModule(M))
131021241571STeresa Johnson     return PreservedAnalyses::all();
131121241571STeresa Johnson 
131221241571STeresa Johnson   return PreservedAnalyses::none();
131321241571STeresa Johnson }
131421241571STeresa Johnson 
131521241571STeresa Johnson char FunctionImportLegacyPass::ID = 0;
131621241571STeresa Johnson INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
131742418abaSMehdi Amini                 "Summary Based Function Import", false, false)
131842418abaSMehdi Amini 
131942418abaSMehdi Amini namespace llvm {
1320e9ea08a0SEugene Zelenko 
1321598bd2a2SPeter Collingbourne Pass *createFunctionImportPass() {
1322598bd2a2SPeter Collingbourne   return new FunctionImportLegacyPass();
13235fcbdb71STeresa Johnson }
1324e9ea08a0SEugene Zelenko 
1325e9ea08a0SEugene Zelenko } // end namespace llvm
1326