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"
34*05da2fe5SReid Kleckner #include "llvm/InitializePasses.h"
35e9ea08a0SEugene Zelenko #include "llvm/Linker/IRMover.h"
36e9ea08a0SEugene Zelenko #include "llvm/Object/ModuleSymbolTable.h"
37e9ea08a0SEugene Zelenko #include "llvm/Object/SymbolicFile.h"
38e9ea08a0SEugene Zelenko #include "llvm/Pass.h"
39e9ea08a0SEugene Zelenko #include "llvm/Support/Casting.h"
4042418abaSMehdi Amini #include "llvm/Support/CommandLine.h"
4142418abaSMehdi Amini #include "llvm/Support/Debug.h"
42e9ea08a0SEugene Zelenko #include "llvm/Support/Error.h"
43e9ea08a0SEugene Zelenko #include "llvm/Support/ErrorHandling.h"
44e9ea08a0SEugene Zelenko #include "llvm/Support/FileSystem.h"
4542418abaSMehdi Amini #include "llvm/Support/SourceMgr.h"
46e9ea08a0SEugene Zelenko #include "llvm/Support/raw_ostream.h"
4704c9a2d6STeresa Johnson #include "llvm/Transforms/IPO/Internalize.h"
4881bbf742STeresa Johnson #include "llvm/Transforms/Utils/Cloning.h"
49488a800aSTeresa Johnson #include "llvm/Transforms/Utils/FunctionImportUtils.h"
5081bbf742STeresa Johnson #include "llvm/Transforms/Utils/ValueMapper.h"
51e9ea08a0SEugene Zelenko #include <cassert>
52e9ea08a0SEugene Zelenko #include <memory>
53e9ea08a0SEugene Zelenko #include <set>
54e9ea08a0SEugene Zelenko #include <string>
55e9ea08a0SEugene Zelenko #include <system_error>
56e9ea08a0SEugene Zelenko #include <tuple>
57e9ea08a0SEugene Zelenko #include <utility>
587e88d0daSMehdi Amini 
5942418abaSMehdi Amini using namespace llvm;
6042418abaSMehdi Amini 
61e9ea08a0SEugene Zelenko #define DEBUG_TYPE "function-import"
62e9ea08a0SEugene Zelenko 
63d2c234a4STeresa Johnson STATISTIC(NumImportedFunctionsThinLink,
64d2c234a4STeresa Johnson           "Number of functions thin link decided to import");
65d2c234a4STeresa Johnson STATISTIC(NumImportedHotFunctionsThinLink,
66d2c234a4STeresa Johnson           "Number of hot functions thin link decided to import");
67d2c234a4STeresa Johnson STATISTIC(NumImportedCriticalFunctionsThinLink,
68d2c234a4STeresa Johnson           "Number of critical functions thin link decided to import");
69d2c234a4STeresa Johnson STATISTIC(NumImportedGlobalVarsThinLink,
70d2c234a4STeresa Johnson           "Number of global variables thin link decided to import");
71d2c234a4STeresa Johnson STATISTIC(NumImportedFunctions, "Number of functions imported in backend");
72d2c234a4STeresa Johnson STATISTIC(NumImportedGlobalVars,
73d2c234a4STeresa Johnson           "Number of global variables imported in backend");
746c475a75STeresa Johnson STATISTIC(NumImportedModules, "Number of modules imported from");
756c475a75STeresa Johnson STATISTIC(NumDeadSymbols, "Number of dead stripped symbols in index");
766c475a75STeresa Johnson STATISTIC(NumLiveSymbols, "Number of live symbols in index");
77d29478f7STeresa Johnson 
7839303619STeresa Johnson /// Limit on instruction count of imported functions.
7939303619STeresa Johnson static cl::opt<unsigned> ImportInstrLimit(
8039303619STeresa Johnson     "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
8139303619STeresa Johnson     cl::desc("Only import functions with less than N instructions"));
8239303619STeresa Johnson 
83974706ebSTeresa Johnson static cl::opt<int> ImportCutoff(
84974706ebSTeresa Johnson     "import-cutoff", cl::init(-1), cl::Hidden, cl::value_desc("N"),
85974706ebSTeresa Johnson     cl::desc("Only import first N functions if N>=0 (default -1)"));
86974706ebSTeresa Johnson 
8740641748SMehdi Amini static cl::opt<float>
8840641748SMehdi Amini     ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7),
8940641748SMehdi Amini                       cl::Hidden, cl::value_desc("x"),
9040641748SMehdi Amini                       cl::desc("As we import functions, multiply the "
9140641748SMehdi Amini                                "`import-instr-limit` threshold by this factor "
9240641748SMehdi Amini                                "before processing newly imported functions"));
93ba72b95fSPiotr Padlewski 
94d2869473SPiotr Padlewski static cl::opt<float> ImportHotInstrFactor(
95d2869473SPiotr Padlewski     "import-hot-evolution-factor", cl::init(1.0), cl::Hidden,
96d2869473SPiotr Padlewski     cl::value_desc("x"),
97d2869473SPiotr Padlewski     cl::desc("As we import functions called from hot callsite, multiply the "
98d2869473SPiotr Padlewski              "`import-instr-limit` threshold by this factor "
99d2869473SPiotr Padlewski              "before processing newly imported functions"));
100d2869473SPiotr Padlewski 
101d9830eb7SPiotr Padlewski static cl::opt<float> ImportHotMultiplier(
1028260d665SDehao Chen     "import-hot-multiplier", cl::init(10.0), cl::Hidden, cl::value_desc("x"),
103ba72b95fSPiotr Padlewski     cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"));
104ba72b95fSPiotr Padlewski 
10564c46574SDehao Chen static cl::opt<float> ImportCriticalMultiplier(
10664c46574SDehao Chen     "import-critical-multiplier", cl::init(100.0), cl::Hidden,
10764c46574SDehao Chen     cl::value_desc("x"),
10864c46574SDehao Chen     cl::desc(
10964c46574SDehao Chen         "Multiply the `import-instr-limit` threshold for critical callsites"));
11064c46574SDehao Chen 
111ba72b95fSPiotr Padlewski // FIXME: This multiplier was not really tuned up.
112ba72b95fSPiotr Padlewski static cl::opt<float> ImportColdMultiplier(
113ba72b95fSPiotr Padlewski     "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"),
114ba72b95fSPiotr Padlewski     cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"));
11540641748SMehdi Amini 
116d29478f7STeresa Johnson static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
117d29478f7STeresa Johnson                                   cl::desc("Print imported functions"));
118d29478f7STeresa Johnson 
119cb9a82fcSTeresa Johnson static cl::opt<bool> PrintImportFailures(
120cb9a82fcSTeresa Johnson     "print-import-failures", cl::init(false), cl::Hidden,
121cb9a82fcSTeresa Johnson     cl::desc("Print information for functions rejected for importing"));
122cb9a82fcSTeresa Johnson 
1236c475a75STeresa Johnson static cl::opt<bool> ComputeDead("compute-dead", cl::init(true), cl::Hidden,
1246c475a75STeresa Johnson                                  cl::desc("Compute dead symbols"));
1256c475a75STeresa Johnson 
1263b776128SPiotr Padlewski static cl::opt<bool> EnableImportMetadata(
1273b776128SPiotr Padlewski     "enable-import-metadata", cl::init(
1283b776128SPiotr Padlewski #if !defined(NDEBUG)
1293b776128SPiotr Padlewski                                   true /*Enabled with asserts.*/
1303b776128SPiotr Padlewski #else
1313b776128SPiotr Padlewski                                   false
1323b776128SPiotr Padlewski #endif
1333b776128SPiotr Padlewski                                   ),
1343b776128SPiotr Padlewski     cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'"));
1353b776128SPiotr Padlewski 
136e9ea08a0SEugene Zelenko /// Summary file to use for function importing when using -function-import from
137e9ea08a0SEugene Zelenko /// the command line.
138e9ea08a0SEugene Zelenko static cl::opt<std::string>
139e9ea08a0SEugene Zelenko     SummaryFile("summary-file",
140e9ea08a0SEugene Zelenko                 cl::desc("The summary file to use for function importing."));
141e9ea08a0SEugene Zelenko 
14281bbf742STeresa Johnson /// Used when testing importing from distributed indexes via opt
14381bbf742STeresa Johnson // -function-import.
14481bbf742STeresa Johnson static cl::opt<bool>
14581bbf742STeresa Johnson     ImportAllIndex("import-all-index",
14681bbf742STeresa Johnson                    cl::desc("Import all external functions in index."));
14781bbf742STeresa Johnson 
14842418abaSMehdi Amini // Load lazily a module from \p FileName in \p Context.
14942418abaSMehdi Amini static std::unique_ptr<Module> loadFile(const std::string &FileName,
15042418abaSMehdi Amini                                         LLVMContext &Context) {
15142418abaSMehdi Amini   SMDiagnostic Err;
152d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Loading '" << FileName << "'\n");
1536cba37ceSTeresa Johnson   // Metadata isn't loaded until functions are imported, to minimize
1546cba37ceSTeresa Johnson   // the memory overhead.
155a1080ee6STeresa Johnson   std::unique_ptr<Module> Result =
156a1080ee6STeresa Johnson       getLazyIRFileModule(FileName, Err, Context,
157a1080ee6STeresa Johnson                           /* ShouldLazyLoadMetadata = */ true);
15842418abaSMehdi Amini   if (!Result) {
15942418abaSMehdi Amini     Err.print("function-import", errs());
160d7ad221cSMehdi Amini     report_fatal_error("Abort");
16142418abaSMehdi Amini   }
16242418abaSMehdi Amini 
16342418abaSMehdi Amini   return Result;
16442418abaSMehdi Amini }
16542418abaSMehdi Amini 
16601e32130SMehdi Amini /// Given a list of possible callee implementation for a call site, select one
16701e32130SMehdi Amini /// that fits the \p Threshold.
16801e32130SMehdi Amini ///
16901e32130SMehdi Amini /// FIXME: select "best" instead of first that fits. But what is "best"?
17001e32130SMehdi Amini /// - The smallest: more likely to be inlined.
17101e32130SMehdi Amini /// - The one with the least outgoing edges (already well optimized).
17201e32130SMehdi Amini /// - One from a module already being imported from in order to reduce the
17301e32130SMehdi Amini ///   number of source modules parsed/linked.
17401e32130SMehdi Amini /// - One that has PGO data attached.
17501e32130SMehdi Amini /// - [insert you fancy metric here]
1762d28f7aaSMehdi Amini static const GlobalValueSummary *
177b4e1e829SMehdi Amini selectCallee(const ModuleSummaryIndex &Index,
1789667b91bSPeter Collingbourne              ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
179cb9a82fcSTeresa Johnson              unsigned Threshold, StringRef CallerModulePath,
180cb9a82fcSTeresa Johnson              FunctionImporter::ImportFailureReason &Reason,
181cb9a82fcSTeresa Johnson              GlobalValue::GUID GUID) {
182cb9a82fcSTeresa Johnson   Reason = FunctionImporter::ImportFailureReason::None;
18301e32130SMehdi Amini   auto It = llvm::find_if(
18428e457bcSTeresa Johnson       CalleeSummaryList,
18528e457bcSTeresa Johnson       [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
18628e457bcSTeresa Johnson         auto *GVSummary = SummaryPtr.get();
187cb9a82fcSTeresa Johnson         if (!Index.isGlobalValueLive(GVSummary)) {
188cb9a82fcSTeresa Johnson           Reason = FunctionImporter::ImportFailureReason::NotLive;
189eaf5172cSGeorge Rimar           return false;
190cb9a82fcSTeresa Johnson         }
191eaf5172cSGeorge Rimar 
19273305f82STeresa Johnson         // For SamplePGO, in computeImportForFunction the OriginalId
19373305f82STeresa Johnson         // may have been used to locate the callee summary list (See
19473305f82STeresa Johnson         // comment there).
19573305f82STeresa Johnson         // The mapping from OriginalId to GUID may return a GUID
19673305f82STeresa Johnson         // that corresponds to a static variable. Filter it out here.
19773305f82STeresa Johnson         // This can happen when
19873305f82STeresa Johnson         // 1) There is a call to a library function which is not defined
19973305f82STeresa Johnson         // in the index.
20073305f82STeresa Johnson         // 2) There is a static variable with the  OriginalGUID identical
20173305f82STeresa Johnson         // to the GUID of the library function in 1);
20273305f82STeresa Johnson         // When this happens, the logic for SamplePGO kicks in and
20373305f82STeresa Johnson         // the static variable in 2) will be found, which needs to be
20473305f82STeresa Johnson         // filtered out.
205cb9a82fcSTeresa Johnson         if (GVSummary->getSummaryKind() == GlobalValueSummary::GlobalVarKind) {
206cb9a82fcSTeresa Johnson           Reason = FunctionImporter::ImportFailureReason::GlobalVar;
20773305f82STeresa Johnson           return false;
208cb9a82fcSTeresa Johnson         }
209cb9a82fcSTeresa Johnson         if (GlobalValue::isInterposableLinkage(GVSummary->linkage())) {
210cb9a82fcSTeresa Johnson           Reason = FunctionImporter::ImportFailureReason::InterposableLinkage;
2115b85d8d6SMehdi Amini           // There is no point in importing these, we can't inline them
21201e32130SMehdi Amini           return false;
213cb9a82fcSTeresa Johnson         }
2142c719cc1SMehdi Amini 
21581bbf742STeresa Johnson         auto *Summary = cast<FunctionSummary>(GVSummary->getBaseObject());
2167e88d0daSMehdi Amini 
21783aaf358STeresa Johnson         // If this is a local function, make sure we import the copy
21883aaf358STeresa Johnson         // in the caller's module. The only time a local function can
21983aaf358STeresa Johnson         // share an entry in the index is if there is a local with the same name
22083aaf358STeresa Johnson         // in another module that had the same source file name (in a different
22183aaf358STeresa Johnson         // directory), where each was compiled in their own directory so there
22283aaf358STeresa Johnson         // was not distinguishing path.
22383aaf358STeresa Johnson         // However, do the import from another module if there is only one
22483aaf358STeresa Johnson         // entry in the list - in that case this must be a reference due
22583aaf358STeresa Johnson         // to indirect call profile data, since a function pointer can point to
22683aaf358STeresa Johnson         // a local in another module.
22783aaf358STeresa Johnson         if (GlobalValue::isLocalLinkage(Summary->linkage()) &&
22883aaf358STeresa Johnson             CalleeSummaryList.size() > 1 &&
229cb9a82fcSTeresa Johnson             Summary->modulePath() != CallerModulePath) {
230cb9a82fcSTeresa Johnson           Reason =
231cb9a82fcSTeresa Johnson               FunctionImporter::ImportFailureReason::LocalLinkageNotInModule;
23283aaf358STeresa Johnson           return false;
233cb9a82fcSTeresa Johnson         }
23483aaf358STeresa Johnson 
235b11391bbSTeresa Johnson         if ((Summary->instCount() > Threshold) &&
236b11391bbSTeresa Johnson             !Summary->fflags().AlwaysInline) {
237cb9a82fcSTeresa Johnson           Reason = FunctionImporter::ImportFailureReason::TooLarge;
238f9dc3deaSTeresa Johnson           return false;
239cb9a82fcSTeresa Johnson         }
240f9dc3deaSTeresa Johnson 
241cb397461STeresa Johnson         // Skip if it isn't legal to import (e.g. may reference unpromotable
242cb397461STeresa Johnson         // locals).
243cb9a82fcSTeresa Johnson         if (Summary->notEligibleToImport()) {
244cb9a82fcSTeresa Johnson           Reason = FunctionImporter::ImportFailureReason::NotEligible;
245b4e1e829SMehdi Amini           return false;
246cb9a82fcSTeresa Johnson         }
247b4e1e829SMehdi Amini 
248cb397461STeresa Johnson         // Don't bother importing if we can't inline it anyway.
249cb397461STeresa Johnson         if (Summary->fflags().NoInline) {
250cb397461STeresa Johnson           Reason = FunctionImporter::ImportFailureReason::NoInline;
251cb397461STeresa Johnson           return false;
252cb397461STeresa Johnson         }
253cb397461STeresa Johnson 
25401e32130SMehdi Amini         return true;
25501e32130SMehdi Amini       });
25628e457bcSTeresa Johnson   if (It == CalleeSummaryList.end())
25701e32130SMehdi Amini     return nullptr;
2587e88d0daSMehdi Amini 
259f9dc3deaSTeresa Johnson   return cast<GlobalValueSummary>(It->get());
260434e9561SRafael Espindola }
2617e88d0daSMehdi Amini 
262e9ea08a0SEugene Zelenko namespace {
263e9ea08a0SEugene Zelenko 
264475b51a7STeresa Johnson using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */,
265475b51a7STeresa Johnson                             GlobalValue::GUID>;
26601e32130SMehdi Amini 
267e9ea08a0SEugene Zelenko } // anonymous namespace
268e9ea08a0SEugene Zelenko 
2691958083dSTeresa Johnson static ValueInfo
2701958083dSTeresa Johnson updateValueInfoForIndirectCalls(const ModuleSummaryIndex &Index, ValueInfo VI) {
2711958083dSTeresa Johnson   if (!VI.getSummaryList().empty())
2721958083dSTeresa Johnson     return VI;
2731958083dSTeresa Johnson   // For SamplePGO, the indirect call targets for local functions will
2741958083dSTeresa Johnson   // have its original name annotated in profile. We try to find the
2751958083dSTeresa Johnson   // corresponding PGOFuncName as the GUID.
2761958083dSTeresa Johnson   // FIXME: Consider updating the edges in the graph after building
2771958083dSTeresa Johnson   // it, rather than needing to perform this mapping on each walk.
2781958083dSTeresa Johnson   auto GUID = Index.getGUIDFromOriginalID(VI.getGUID());
2791958083dSTeresa Johnson   if (GUID == 0)
28028d8a49fSEugene Leviant     return ValueInfo();
2811958083dSTeresa Johnson   return Index.getValueInfo(GUID);
2821958083dSTeresa Johnson }
2831958083dSTeresa Johnson 
28419e23874SEugene Leviant static void computeImportForReferencedGlobals(
285dde58938Sevgeny     const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
286dde58938Sevgeny     const GVSummaryMapTy &DefinedGVSummaries,
28719e23874SEugene Leviant     FunctionImporter::ImportMapTy &ImportList,
28819e23874SEugene Leviant     StringMap<FunctionImporter::ExportSetTy> *ExportLists) {
28919e23874SEugene Leviant   for (auto &VI : Summary.refs()) {
29019e23874SEugene Leviant     if (DefinedGVSummaries.count(VI.getGUID())) {
291d34e60caSNicola Zaghen       LLVM_DEBUG(
292d34e60caSNicola Zaghen           dbgs() << "Ref ignored! Target already in destination module.\n");
29319e23874SEugene Leviant       continue;
29419e23874SEugene Leviant     }
29519e23874SEugene Leviant 
2967e7b13d0STeresa Johnson     LLVM_DEBUG(dbgs() << " ref -> " << VI << "\n");
29719e23874SEugene Leviant 
29893f99962STeresa Johnson     // If this is a local variable, make sure we import the copy
29993f99962STeresa Johnson     // in the caller's module. The only time a local variable can
30093f99962STeresa Johnson     // share an entry in the index is if there is a local with the same name
30193f99962STeresa Johnson     // in another module that had the same source file name (in a different
30293f99962STeresa Johnson     // directory), where each was compiled in their own directory so there
30393f99962STeresa Johnson     // was not distinguishing path.
30493f99962STeresa Johnson     auto LocalNotInModule = [&](const GlobalValueSummary *RefSummary) -> bool {
30593f99962STeresa Johnson       return GlobalValue::isLocalLinkage(RefSummary->linkage()) &&
30693f99962STeresa Johnson              RefSummary->modulePath() != Summary.modulePath();
30793f99962STeresa Johnson     };
30893f99962STeresa Johnson 
309dde58938Sevgeny     auto MarkExported = [&](const ValueInfo &VI, const GlobalValueSummary *S) {
310dde58938Sevgeny       if (ExportLists)
311dde58938Sevgeny         (*ExportLists)[S->modulePath()].insert(VI.getGUID());
312dde58938Sevgeny     };
313dde58938Sevgeny 
31419e23874SEugene Leviant     for (auto &RefSummary : VI.getSummaryList())
315bf46e741SEugene Leviant       if (isa<GlobalVarSummary>(RefSummary.get()) &&
316dde58938Sevgeny           Index.canImportGlobalVar(RefSummary.get(), /* AnalyzeRefs */ true) &&
31793f99962STeresa Johnson           !LocalNotInModule(RefSummary.get())) {
318d2c234a4STeresa Johnson         auto ILI = ImportList[RefSummary->modulePath()].insert(VI.getGUID());
319d2c234a4STeresa Johnson         // Only update stat if we haven't already imported this variable.
320d2c234a4STeresa Johnson         if (ILI.second)
321d2c234a4STeresa Johnson           NumImportedGlobalVarsThinLink++;
322dde58938Sevgeny         MarkExported(VI, RefSummary.get());
3237f92d66fSevgeny         // Promote referenced functions and variables. We don't promote
3247f92d66fSevgeny         // objects referenced by writeonly variable initializer, because
3257f92d66fSevgeny         // we convert such variables initializers to "zeroinitializer".
3267f92d66fSevgeny         // See processGlobalForThinLTO.
3277f92d66fSevgeny         if (!Index.isWriteOnly(cast<GlobalVarSummary>(RefSummary.get())))
328dde58938Sevgeny           for (const auto &VI : RefSummary->refs())
329dde58938Sevgeny             for (const auto &RefFn : VI.getSummaryList())
330dde58938Sevgeny               MarkExported(VI, RefFn.get());
33119e23874SEugene Leviant         break;
33219e23874SEugene Leviant       }
33319e23874SEugene Leviant   }
33419e23874SEugene Leviant }
33519e23874SEugene Leviant 
336cb9a82fcSTeresa Johnson static const char *
337cb9a82fcSTeresa Johnson getFailureName(FunctionImporter::ImportFailureReason Reason) {
338cb9a82fcSTeresa Johnson   switch (Reason) {
339cb9a82fcSTeresa Johnson   case FunctionImporter::ImportFailureReason::None:
340cb9a82fcSTeresa Johnson     return "None";
341cb9a82fcSTeresa Johnson   case FunctionImporter::ImportFailureReason::GlobalVar:
342cb9a82fcSTeresa Johnson     return "GlobalVar";
343cb9a82fcSTeresa Johnson   case FunctionImporter::ImportFailureReason::NotLive:
344cb9a82fcSTeresa Johnson     return "NotLive";
345cb9a82fcSTeresa Johnson   case FunctionImporter::ImportFailureReason::TooLarge:
346cb9a82fcSTeresa Johnson     return "TooLarge";
347cb9a82fcSTeresa Johnson   case FunctionImporter::ImportFailureReason::InterposableLinkage:
348cb9a82fcSTeresa Johnson     return "InterposableLinkage";
349cb9a82fcSTeresa Johnson   case FunctionImporter::ImportFailureReason::LocalLinkageNotInModule:
350cb9a82fcSTeresa Johnson     return "LocalLinkageNotInModule";
351cb9a82fcSTeresa Johnson   case FunctionImporter::ImportFailureReason::NotEligible:
352cb9a82fcSTeresa Johnson     return "NotEligible";
353cb397461STeresa Johnson   case FunctionImporter::ImportFailureReason::NoInline:
354cb397461STeresa Johnson     return "NoInline";
355cb9a82fcSTeresa Johnson   }
356cb9a82fcSTeresa Johnson   llvm_unreachable("invalid reason");
357cb9a82fcSTeresa Johnson }
358cb9a82fcSTeresa Johnson 
35901e32130SMehdi Amini /// Compute the list of functions to import for a given caller. Mark these
36001e32130SMehdi Amini /// imported functions and the symbols they reference in their source module as
36101e32130SMehdi Amini /// exported from their source module.
36201e32130SMehdi Amini static void computeImportForFunction(
3633255eec1STeresa Johnson     const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
364d9830eb7SPiotr Padlewski     const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
36501e32130SMehdi Amini     SmallVectorImpl<EdgeInfo> &Worklist,
3669b490f10SMehdi Amini     FunctionImporter::ImportMapTy &ImportList,
367d68935c5STeresa Johnson     StringMap<FunctionImporter::ExportSetTy> *ExportLists,
368d68935c5STeresa Johnson     FunctionImporter::ImportThresholdsTy &ImportThresholds) {
369dde58938Sevgeny   computeImportForReferencedGlobals(Summary, Index, DefinedGVSummaries,
370dde58938Sevgeny                                     ImportList, ExportLists);
371974706ebSTeresa Johnson   static int ImportCount = 0;
37201e32130SMehdi Amini   for (auto &Edge : Summary.calls()) {
3739667b91bSPeter Collingbourne     ValueInfo VI = Edge.first;
3747e7b13d0STeresa Johnson     LLVM_DEBUG(dbgs() << " edge -> " << VI << " Threshold:" << Threshold
3757e7b13d0STeresa Johnson                       << "\n");
37601e32130SMehdi Amini 
377974706ebSTeresa Johnson     if (ImportCutoff >= 0 && ImportCount >= ImportCutoff) {
378d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "ignored! import-cutoff value of " << ImportCutoff
379974706ebSTeresa Johnson                         << " reached.\n");
380974706ebSTeresa Johnson       continue;
381974706ebSTeresa Johnson     }
382974706ebSTeresa Johnson 
3831958083dSTeresa Johnson     VI = updateValueInfoForIndirectCalls(Index, VI);
3849667b91bSPeter Collingbourne     if (!VI)
3859667b91bSPeter Collingbourne       continue;
3864a435e08SDehao Chen 
3879667b91bSPeter Collingbourne     if (DefinedGVSummaries.count(VI.getGUID())) {
388d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "ignored! Target already in destination module.\n");
3897e88d0daSMehdi Amini       continue;
390d450da32STeresa Johnson     }
39140641748SMehdi Amini 
392ba72b95fSPiotr Padlewski     auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
393ba72b95fSPiotr Padlewski       if (Hotness == CalleeInfo::HotnessType::Hot)
394ba72b95fSPiotr Padlewski         return ImportHotMultiplier;
395ba72b95fSPiotr Padlewski       if (Hotness == CalleeInfo::HotnessType::Cold)
396ba72b95fSPiotr Padlewski         return ImportColdMultiplier;
39764c46574SDehao Chen       if (Hotness == CalleeInfo::HotnessType::Critical)
39864c46574SDehao Chen         return ImportCriticalMultiplier;
399ba72b95fSPiotr Padlewski       return 1.0;
400ba72b95fSPiotr Padlewski     };
401ba72b95fSPiotr Padlewski 
402d9830eb7SPiotr Padlewski     const auto NewThreshold =
403c73cec84SEaswaran Raman         Threshold * GetBonusMultiplier(Edge.second.getHotness());
404d2869473SPiotr Padlewski 
405cb9a82fcSTeresa Johnson     auto IT = ImportThresholds.insert(std::make_pair(
406cb9a82fcSTeresa Johnson         VI.getGUID(), std::make_tuple(NewThreshold, nullptr, nullptr)));
407d68935c5STeresa Johnson     bool PreviouslyVisited = !IT.second;
408cb9a82fcSTeresa Johnson     auto &ProcessedThreshold = std::get<0>(IT.first->second);
409cb9a82fcSTeresa Johnson     auto &CalleeSummary = std::get<1>(IT.first->second);
410cb9a82fcSTeresa Johnson     auto &FailureInfo = std::get<2>(IT.first->second);
411d68935c5STeresa Johnson 
412d2c234a4STeresa Johnson     bool IsHotCallsite =
413d2c234a4STeresa Johnson         Edge.second.getHotness() == CalleeInfo::HotnessType::Hot;
414d2c234a4STeresa Johnson     bool IsCriticalCallsite =
415d2c234a4STeresa Johnson         Edge.second.getHotness() == CalleeInfo::HotnessType::Critical;
416d2c234a4STeresa Johnson 
417d68935c5STeresa Johnson     const FunctionSummary *ResolvedCalleeSummary = nullptr;
418d68935c5STeresa Johnson     if (CalleeSummary) {
419d68935c5STeresa Johnson       assert(PreviouslyVisited);
420d68935c5STeresa Johnson       // Since the traversal of the call graph is DFS, we can revisit a function
421d68935c5STeresa Johnson       // a second time with a higher threshold. In this case, it is added back
422d68935c5STeresa Johnson       // to the worklist with the new threshold (so that its own callee chains
423d68935c5STeresa Johnson       // can be considered with the higher threshold).
424d68935c5STeresa Johnson       if (NewThreshold <= ProcessedThreshold) {
425d68935c5STeresa Johnson         LLVM_DEBUG(
426d68935c5STeresa Johnson             dbgs() << "ignored! Target was already imported with Threshold "
427d68935c5STeresa Johnson                    << ProcessedThreshold << "\n");
428d68935c5STeresa Johnson         continue;
429d68935c5STeresa Johnson       }
430d68935c5STeresa Johnson       // Update with new larger threshold.
431d68935c5STeresa Johnson       ProcessedThreshold = NewThreshold;
432d68935c5STeresa Johnson       ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
433d68935c5STeresa Johnson     } else {
434d68935c5STeresa Johnson       // If we already rejected importing a callee at the same or higher
435d68935c5STeresa Johnson       // threshold, don't waste time calling selectCallee.
436d68935c5STeresa Johnson       if (PreviouslyVisited && NewThreshold <= ProcessedThreshold) {
437d68935c5STeresa Johnson         LLVM_DEBUG(
438d68935c5STeresa Johnson             dbgs() << "ignored! Target was already rejected with Threshold "
439d68935c5STeresa Johnson             << ProcessedThreshold << "\n");
440cb9a82fcSTeresa Johnson         if (PrintImportFailures) {
441cb9a82fcSTeresa Johnson           assert(FailureInfo &&
442cb9a82fcSTeresa Johnson                  "Expected FailureInfo for previously rejected candidate");
443cb9a82fcSTeresa Johnson           FailureInfo->Attempts++;
444cb9a82fcSTeresa Johnson         }
445d68935c5STeresa Johnson         continue;
446d68935c5STeresa Johnson       }
447d68935c5STeresa Johnson 
448cb9a82fcSTeresa Johnson       FunctionImporter::ImportFailureReason Reason;
449d68935c5STeresa Johnson       CalleeSummary = selectCallee(Index, VI.getSummaryList(), NewThreshold,
450cb9a82fcSTeresa Johnson                                    Summary.modulePath(), Reason, VI.getGUID());
45101e32130SMehdi Amini       if (!CalleeSummary) {
452d68935c5STeresa Johnson         // Update with new larger threshold if this was a retry (otherwise
453cb9a82fcSTeresa Johnson         // we would have already inserted with NewThreshold above). Also
454cb9a82fcSTeresa Johnson         // update failure info if requested.
455cb9a82fcSTeresa Johnson         if (PreviouslyVisited) {
456d68935c5STeresa Johnson           ProcessedThreshold = NewThreshold;
457cb9a82fcSTeresa Johnson           if (PrintImportFailures) {
458cb9a82fcSTeresa Johnson             assert(FailureInfo &&
459cb9a82fcSTeresa Johnson                    "Expected FailureInfo for previously rejected candidate");
460cb9a82fcSTeresa Johnson             FailureInfo->Reason = Reason;
461cb9a82fcSTeresa Johnson             FailureInfo->Attempts++;
462cb9a82fcSTeresa Johnson             FailureInfo->MaxHotness =
463cb9a82fcSTeresa Johnson                 std::max(FailureInfo->MaxHotness, Edge.second.getHotness());
464cb9a82fcSTeresa Johnson           }
465cb9a82fcSTeresa Johnson         } else if (PrintImportFailures) {
466cb9a82fcSTeresa Johnson           assert(!FailureInfo &&
467cb9a82fcSTeresa Johnson                  "Expected no FailureInfo for newly rejected candidate");
4680eaee545SJonas Devlieghere           FailureInfo = std::make_unique<FunctionImporter::ImportFailureInfo>(
469cb9a82fcSTeresa Johnson               VI, Edge.second.getHotness(), Reason, 1);
470cb9a82fcSTeresa Johnson         }
471d34e60caSNicola Zaghen         LLVM_DEBUG(
472d34e60caSNicola Zaghen             dbgs() << "ignored! No qualifying callee with summary found.\n");
4737e88d0daSMehdi Amini         continue;
4747e88d0daSMehdi Amini       }
4752f0cc477SDavid Blaikie 
4762f0cc477SDavid Blaikie       // "Resolve" the summary
477d68935c5STeresa Johnson       CalleeSummary = CalleeSummary->getBaseObject();
478d68935c5STeresa Johnson       ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
4792d28f7aaSMehdi Amini 
480b11391bbSTeresa Johnson       assert((ResolvedCalleeSummary->fflags().AlwaysInline ||
481b11391bbSTeresa Johnson 	     (ResolvedCalleeSummary->instCount() <= NewThreshold)) &&
48201e32130SMehdi Amini              "selectCallee() didn't honor the threshold");
48301e32130SMehdi Amini 
4841b859a23STeresa Johnson       auto ExportModulePath = ResolvedCalleeSummary->modulePath();
485d68935c5STeresa Johnson       auto ILI = ImportList[ExportModulePath].insert(VI.getGUID());
486d68935c5STeresa Johnson       // We previously decided to import this GUID definition if it was already
487d68935c5STeresa Johnson       // inserted in the set of imports from the exporting module.
488d68935c5STeresa Johnson       bool PreviouslyImported = !ILI.second;
489d2c234a4STeresa Johnson       if (!PreviouslyImported) {
490d2c234a4STeresa Johnson         NumImportedFunctionsThinLink++;
491d2c234a4STeresa Johnson         if (IsHotCallsite)
492d2c234a4STeresa Johnson           NumImportedHotFunctionsThinLink++;
493d2c234a4STeresa Johnson         if (IsCriticalCallsite)
494d2c234a4STeresa Johnson           NumImportedCriticalFunctionsThinLink++;
495d2c234a4STeresa Johnson       }
496974706ebSTeresa Johnson 
4971b859a23STeresa Johnson       // Make exports in the source module.
4981b859a23STeresa Johnson       if (ExportLists) {
4991b859a23STeresa Johnson         auto &ExportList = (*ExportLists)[ExportModulePath];
5009667b91bSPeter Collingbourne         ExportList.insert(VI.getGUID());
50119f2aa78STeresa Johnson         if (!PreviouslyImported) {
50219f2aa78STeresa Johnson           // This is the first time this function was exported from its source
50319f2aa78STeresa Johnson           // module, so mark all functions and globals it references as exported
5041b859a23STeresa Johnson           // to the outside if they are defined in the same source module.
505edddca22STeresa Johnson           // For efficiency, we unconditionally add all the referenced GUIDs
506edddca22STeresa Johnson           // to the ExportList for this module, and will prune out any not
507edddca22STeresa Johnson           // defined in the module later in a single pass.
5081b859a23STeresa Johnson           for (auto &Edge : ResolvedCalleeSummary->calls()) {
5091b859a23STeresa Johnson             auto CalleeGUID = Edge.first.getGUID();
510edddca22STeresa Johnson             ExportList.insert(CalleeGUID);
5111b859a23STeresa Johnson           }
5121b859a23STeresa Johnson           for (auto &Ref : ResolvedCalleeSummary->refs()) {
5131b859a23STeresa Johnson             auto GUID = Ref.getGUID();
514edddca22STeresa Johnson             ExportList.insert(GUID);
5151b859a23STeresa Johnson           }
5161b859a23STeresa Johnson         }
51719f2aa78STeresa Johnson       }
518d68935c5STeresa Johnson     }
519d68935c5STeresa Johnson 
520d68935c5STeresa Johnson     auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
521d68935c5STeresa Johnson       // Adjust the threshold for next level of imported functions.
522d68935c5STeresa Johnson       // The threshold is different for hot callsites because we can then
523d68935c5STeresa Johnson       // inline chains of hot calls.
524d68935c5STeresa Johnson       if (IsHotCallsite)
525d68935c5STeresa Johnson         return Threshold * ImportHotInstrFactor;
526d68935c5STeresa Johnson       return Threshold * ImportInstrFactor;
527d68935c5STeresa Johnson     };
528d68935c5STeresa Johnson 
529d68935c5STeresa Johnson     const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
530d68935c5STeresa Johnson 
531d68935c5STeresa Johnson     ImportCount++;
532d2869473SPiotr Padlewski 
53301e32130SMehdi Amini     // Insert the newly imported function to the worklist.
5349667b91bSPeter Collingbourne     Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, VI.getGUID());
535d450da32STeresa Johnson   }
536d450da32STeresa Johnson }
537d450da32STeresa Johnson 
53801e32130SMehdi Amini /// Given the list of globals defined in a module, compute the list of imports
53901e32130SMehdi Amini /// as well as the list of "exports", i.e. the list of symbols referenced from
54001e32130SMehdi Amini /// another module (that may require promotion).
54101e32130SMehdi Amini static void ComputeImportForModule(
542c851d216STeresa Johnson     const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
543cb9a82fcSTeresa Johnson     StringRef ModName, FunctionImporter::ImportMapTy &ImportList,
54456584bbfSEvgeniy Stepanov     StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
54501e32130SMehdi Amini   // Worklist contains the list of function imported in this module, for which
54601e32130SMehdi Amini   // we will analyse the callees and may import further down the callgraph.
54701e32130SMehdi Amini   SmallVector<EdgeInfo, 128> Worklist;
548d68935c5STeresa Johnson   FunctionImporter::ImportThresholdsTy ImportThresholds;
54901e32130SMehdi Amini 
55001e32130SMehdi Amini   // Populate the worklist with the import for the functions in the current
55101e32130SMehdi Amini   // module
55228e457bcSTeresa Johnson   for (auto &GVSummary : DefinedGVSummaries) {
5537e7b13d0STeresa Johnson #ifndef NDEBUG
5547e7b13d0STeresa Johnson     // FIXME: Change the GVSummaryMapTy to hold ValueInfo instead of GUID
5557e7b13d0STeresa Johnson     // so this map look up (and possibly others) can be avoided.
5567e7b13d0STeresa Johnson     auto VI = Index.getValueInfo(GVSummary.first);
5577e7b13d0STeresa Johnson #endif
55856584bbfSEvgeniy Stepanov     if (!Index.isGlobalValueLive(GVSummary.second)) {
5597e7b13d0STeresa Johnson       LLVM_DEBUG(dbgs() << "Ignores Dead GUID: " << VI << "\n");
5606c475a75STeresa Johnson       continue;
5616c475a75STeresa Johnson     }
562cfbd0892SPeter Collingbourne     auto *FuncSummary =
563cfbd0892SPeter Collingbourne         dyn_cast<FunctionSummary>(GVSummary.second->getBaseObject());
5641aafabf7SMehdi Amini     if (!FuncSummary)
5651aafabf7SMehdi Amini       // Skip import for global variables
5661aafabf7SMehdi Amini       continue;
5677e7b13d0STeresa Johnson     LLVM_DEBUG(dbgs() << "Initialize import for " << VI << "\n");
5682d28f7aaSMehdi Amini     computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
5699b490f10SMehdi Amini                              DefinedGVSummaries, Worklist, ImportList,
570d68935c5STeresa Johnson                              ExportLists, ImportThresholds);
57101e32130SMehdi Amini   }
57201e32130SMehdi Amini 
573d2869473SPiotr Padlewski   // Process the newly imported functions and add callees to the worklist.
57442418abaSMehdi Amini   while (!Worklist.empty()) {
57501e32130SMehdi Amini     auto FuncInfo = Worklist.pop_back_val();
576475b51a7STeresa Johnson     auto *Summary = std::get<0>(FuncInfo);
577475b51a7STeresa Johnson     auto Threshold = std::get<1>(FuncInfo);
57842418abaSMehdi Amini 
5791aafabf7SMehdi Amini     computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
580d68935c5STeresa Johnson                              Worklist, ImportList, ExportLists,
581d68935c5STeresa Johnson                              ImportThresholds);
582c8c55170SMehdi Amini   }
583cb9a82fcSTeresa Johnson 
584cb9a82fcSTeresa Johnson   // Print stats about functions considered but rejected for importing
585cb9a82fcSTeresa Johnson   // when requested.
586cb9a82fcSTeresa Johnson   if (PrintImportFailures) {
587cb9a82fcSTeresa Johnson     dbgs() << "Missed imports into module " << ModName << "\n";
588cb9a82fcSTeresa Johnson     for (auto &I : ImportThresholds) {
589cb9a82fcSTeresa Johnson       auto &ProcessedThreshold = std::get<0>(I.second);
590cb9a82fcSTeresa Johnson       auto &CalleeSummary = std::get<1>(I.second);
591cb9a82fcSTeresa Johnson       auto &FailureInfo = std::get<2>(I.second);
592cb9a82fcSTeresa Johnson       if (CalleeSummary)
593cb9a82fcSTeresa Johnson         continue; // We are going to import.
594cb9a82fcSTeresa Johnson       assert(FailureInfo);
595cb9a82fcSTeresa Johnson       FunctionSummary *FS = nullptr;
596cb9a82fcSTeresa Johnson       if (!FailureInfo->VI.getSummaryList().empty())
597cb9a82fcSTeresa Johnson         FS = dyn_cast<FunctionSummary>(
598cb9a82fcSTeresa Johnson             FailureInfo->VI.getSummaryList()[0]->getBaseObject());
599cb9a82fcSTeresa Johnson       dbgs() << FailureInfo->VI
600cb9a82fcSTeresa Johnson              << ": Reason = " << getFailureName(FailureInfo->Reason)
601cb9a82fcSTeresa Johnson              << ", Threshold = " << ProcessedThreshold
602cb9a82fcSTeresa Johnson              << ", Size = " << (FS ? (int)FS->instCount() : -1)
603cb9a82fcSTeresa Johnson              << ", MaxHotness = " << getHotnessName(FailureInfo->MaxHotness)
604cb9a82fcSTeresa Johnson              << ", Attempts = " << FailureInfo->Attempts << "\n";
605cb9a82fcSTeresa Johnson     }
606cb9a82fcSTeresa Johnson   }
60742418abaSMehdi Amini }
608ffe2e4aaSMehdi Amini 
60919e23874SEugene Leviant #ifndef NDEBUG
61019e23874SEugene Leviant static bool isGlobalVarSummary(const ModuleSummaryIndex &Index,
61119e23874SEugene Leviant                                GlobalValue::GUID G) {
61219e23874SEugene Leviant   if (const auto &VI = Index.getValueInfo(G)) {
61319e23874SEugene Leviant     auto SL = VI.getSummaryList();
61419e23874SEugene Leviant     if (!SL.empty())
61519e23874SEugene Leviant       return SL[0]->getSummaryKind() == GlobalValueSummary::GlobalVarKind;
61619e23874SEugene Leviant   }
61719e23874SEugene Leviant   return false;
61819e23874SEugene Leviant }
61919e23874SEugene Leviant 
62019e23874SEugene Leviant static GlobalValue::GUID getGUID(GlobalValue::GUID G) { return G; }
62119e23874SEugene Leviant 
62219e23874SEugene Leviant template <class T>
6231fc0da48SBenjamin Kramer static unsigned numGlobalVarSummaries(const ModuleSummaryIndex &Index,
6241fc0da48SBenjamin Kramer                                       T &Cont) {
62519e23874SEugene Leviant   unsigned NumGVS = 0;
62619e23874SEugene Leviant   for (auto &V : Cont)
62719e23874SEugene Leviant     if (isGlobalVarSummary(Index, getGUID(V)))
62819e23874SEugene Leviant       ++NumGVS;
62919e23874SEugene Leviant   return NumGVS;
63019e23874SEugene Leviant }
63119e23874SEugene Leviant #endif
63219e23874SEugene Leviant 
633c86af334STeresa Johnson /// Compute all the import and export for every module using the Index.
63401e32130SMehdi Amini void llvm::ComputeCrossModuleImport(
63501e32130SMehdi Amini     const ModuleSummaryIndex &Index,
636c851d216STeresa Johnson     const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
63701e32130SMehdi Amini     StringMap<FunctionImporter::ImportMapTy> &ImportLists,
63856584bbfSEvgeniy Stepanov     StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
63901e32130SMehdi Amini   // For each module that has function defined, compute the import/export lists.
6401aafabf7SMehdi Amini   for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
6419b490f10SMehdi Amini     auto &ImportList = ImportLists[DefinedGVSummaries.first()];
642d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Computing import for Module '"
6431aafabf7SMehdi Amini                       << DefinedGVSummaries.first() << "'\n");
644cb9a82fcSTeresa Johnson     ComputeImportForModule(DefinedGVSummaries.second, Index,
645cb9a82fcSTeresa Johnson                            DefinedGVSummaries.first(), ImportList,
64656584bbfSEvgeniy Stepanov                            &ExportLists);
64701e32130SMehdi Amini   }
64801e32130SMehdi Amini 
649edddca22STeresa Johnson   // When computing imports we added all GUIDs referenced by anything
650edddca22STeresa Johnson   // imported from the module to its ExportList. Now we prune each ExportList
651edddca22STeresa Johnson   // of any not defined in that module. This is more efficient than checking
652edddca22STeresa Johnson   // while computing imports because some of the summary lists may be long
653edddca22STeresa Johnson   // due to linkonce (comdat) copies.
654edddca22STeresa Johnson   for (auto &ELI : ExportLists) {
655edddca22STeresa Johnson     const auto &DefinedGVSummaries =
656edddca22STeresa Johnson         ModuleToDefinedGVSummaries.lookup(ELI.first());
657edddca22STeresa Johnson     for (auto EI = ELI.second.begin(); EI != ELI.second.end();) {
658edddca22STeresa Johnson       if (!DefinedGVSummaries.count(*EI))
659edddca22STeresa Johnson         EI = ELI.second.erase(EI);
660edddca22STeresa Johnson       else
661edddca22STeresa Johnson         ++EI;
662edddca22STeresa Johnson     }
663edddca22STeresa Johnson   }
664edddca22STeresa Johnson 
66501e32130SMehdi Amini #ifndef NDEBUG
666d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
66701e32130SMehdi Amini                     << " modules:\n");
66801e32130SMehdi Amini   for (auto &ModuleImports : ImportLists) {
66901e32130SMehdi Amini     auto ModName = ModuleImports.first();
67001e32130SMehdi Amini     auto &Exports = ExportLists[ModName];
67119e23874SEugene Leviant     unsigned NumGVS = numGlobalVarSummaries(Index, Exports);
672d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "* Module " << ModName << " exports "
67319e23874SEugene Leviant                       << Exports.size() - NumGVS << " functions and " << NumGVS
674d34e60caSNicola Zaghen                       << " vars. Imports from " << ModuleImports.second.size()
675d34e60caSNicola Zaghen                       << " modules.\n");
67601e32130SMehdi Amini     for (auto &Src : ModuleImports.second) {
67701e32130SMehdi Amini       auto SrcModName = Src.first();
67819e23874SEugene Leviant       unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second);
679d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod
68019e23874SEugene Leviant                         << " functions imported from " << SrcModName << "\n");
681d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod
682d34e60caSNicola Zaghen                         << " global vars imported from " << SrcModName << "\n");
68301e32130SMehdi Amini     }
68401e32130SMehdi Amini   }
68501e32130SMehdi Amini #endif
68601e32130SMehdi Amini }
68701e32130SMehdi Amini 
68881bbf742STeresa Johnson #ifndef NDEBUG
68919e23874SEugene Leviant static void dumpImportListForModule(const ModuleSummaryIndex &Index,
69019e23874SEugene Leviant                                     StringRef ModulePath,
69181bbf742STeresa Johnson                                     FunctionImporter::ImportMapTy &ImportList) {
692d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
69381bbf742STeresa Johnson                     << ImportList.size() << " modules.\n");
69481bbf742STeresa Johnson   for (auto &Src : ImportList) {
69581bbf742STeresa Johnson     auto SrcModName = Src.first();
69619e23874SEugene Leviant     unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second);
697d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod
69819e23874SEugene Leviant                       << " functions imported from " << SrcModName << "\n");
699d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod << " vars imported from "
70081bbf742STeresa Johnson                       << SrcModName << "\n");
70181bbf742STeresa Johnson   }
70281bbf742STeresa Johnson }
70369b2de84STeresa Johnson #endif
70481bbf742STeresa Johnson 
705c86af334STeresa Johnson /// Compute all the imports for the given module in the Index.
706c86af334STeresa Johnson void llvm::ComputeCrossModuleImportForModule(
707c86af334STeresa Johnson     StringRef ModulePath, const ModuleSummaryIndex &Index,
708c86af334STeresa Johnson     FunctionImporter::ImportMapTy &ImportList) {
709c86af334STeresa Johnson   // Collect the list of functions this module defines.
710c86af334STeresa Johnson   // GUID -> Summary
711c851d216STeresa Johnson   GVSummaryMapTy FunctionSummaryMap;
71228e457bcSTeresa Johnson   Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
713c86af334STeresa Johnson 
714c86af334STeresa Johnson   // Compute the import list for this module.
715d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
716cb9a82fcSTeresa Johnson   ComputeImportForModule(FunctionSummaryMap, Index, ModulePath, ImportList);
717c86af334STeresa Johnson 
718c86af334STeresa Johnson #ifndef NDEBUG
71919e23874SEugene Leviant   dumpImportListForModule(Index, ModulePath, ImportList);
72081bbf742STeresa Johnson #endif
721c86af334STeresa Johnson }
72281bbf742STeresa Johnson 
72381bbf742STeresa Johnson // Mark all external summaries in Index for import into the given module.
72481bbf742STeresa Johnson // Used for distributed builds using a distributed index.
72581bbf742STeresa Johnson void llvm::ComputeCrossModuleImportForModuleFromIndex(
72681bbf742STeresa Johnson     StringRef ModulePath, const ModuleSummaryIndex &Index,
72781bbf742STeresa Johnson     FunctionImporter::ImportMapTy &ImportList) {
72881bbf742STeresa Johnson   for (auto &GlobalList : Index) {
72981bbf742STeresa Johnson     // Ignore entries for undefined references.
73081bbf742STeresa Johnson     if (GlobalList.second.SummaryList.empty())
73181bbf742STeresa Johnson       continue;
73281bbf742STeresa Johnson 
73381bbf742STeresa Johnson     auto GUID = GlobalList.first;
73481bbf742STeresa Johnson     assert(GlobalList.second.SummaryList.size() == 1 &&
73581bbf742STeresa Johnson            "Expected individual combined index to have one summary per GUID");
73681bbf742STeresa Johnson     auto &Summary = GlobalList.second.SummaryList[0];
73781bbf742STeresa Johnson     // Skip the summaries for the importing module. These are included to
73881bbf742STeresa Johnson     // e.g. record required linkage changes.
73981bbf742STeresa Johnson     if (Summary->modulePath() == ModulePath)
74081bbf742STeresa Johnson       continue;
741d68935c5STeresa Johnson     // Add an entry to provoke importing by thinBackend.
742d68935c5STeresa Johnson     ImportList[Summary->modulePath()].insert(GUID);
74381bbf742STeresa Johnson   }
74481bbf742STeresa Johnson #ifndef NDEBUG
74519e23874SEugene Leviant   dumpImportListForModule(Index, ModulePath, ImportList);
746c86af334STeresa Johnson #endif
747c86af334STeresa Johnson }
748c86af334STeresa Johnson 
74956584bbfSEvgeniy Stepanov void llvm::computeDeadSymbols(
75056584bbfSEvgeniy Stepanov     ModuleSummaryIndex &Index,
751eaf5172cSGeorge Rimar     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
752eaf5172cSGeorge Rimar     function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing) {
75356584bbfSEvgeniy Stepanov   assert(!Index.withGlobalValueDeadStripping());
7546c475a75STeresa Johnson   if (!ComputeDead)
75556584bbfSEvgeniy Stepanov     return;
7566c475a75STeresa Johnson   if (GUIDPreservedSymbols.empty())
7576c475a75STeresa Johnson     // Don't do anything when nothing is live, this is friendly with tests.
75856584bbfSEvgeniy Stepanov     return;
75956584bbfSEvgeniy Stepanov   unsigned LiveSymbols = 0;
7609667b91bSPeter Collingbourne   SmallVector<ValueInfo, 128> Worklist;
7619667b91bSPeter Collingbourne   Worklist.reserve(GUIDPreservedSymbols.size() * 2);
7629667b91bSPeter Collingbourne   for (auto GUID : GUIDPreservedSymbols) {
7639667b91bSPeter Collingbourne     ValueInfo VI = Index.getValueInfo(GUID);
7649667b91bSPeter Collingbourne     if (!VI)
7659667b91bSPeter Collingbourne       continue;
76656584bbfSEvgeniy Stepanov     for (auto &S : VI.getSummaryList())
76756584bbfSEvgeniy Stepanov       S->setLive(true);
7686c475a75STeresa Johnson   }
76956584bbfSEvgeniy Stepanov 
7706c475a75STeresa Johnson   // Add values flagged in the index as live roots to the worklist.
7717e7b13d0STeresa Johnson   for (const auto &Entry : Index) {
7727e7b13d0STeresa Johnson     auto VI = Index.getValueInfo(Entry);
77356584bbfSEvgeniy Stepanov     for (auto &S : Entry.second.SummaryList)
77456584bbfSEvgeniy Stepanov       if (S->isLive()) {
7757e7b13d0STeresa Johnson         LLVM_DEBUG(dbgs() << "Live root: " << VI << "\n");
7767e7b13d0STeresa Johnson         Worklist.push_back(VI);
77756584bbfSEvgeniy Stepanov         ++LiveSymbols;
77856584bbfSEvgeniy Stepanov         break;
7796c475a75STeresa Johnson       }
7807e7b13d0STeresa Johnson   }
7816c475a75STeresa Johnson 
78256584bbfSEvgeniy Stepanov   // Make value live and add it to the worklist if it was not live before.
783ea314fd4STeresa Johnson   auto visit = [&](ValueInfo VI, bool IsAliasee) {
7841958083dSTeresa Johnson     // FIXME: If we knew which edges were created for indirect call profiles,
7851958083dSTeresa Johnson     // we could skip them here. Any that are live should be reached via
7861958083dSTeresa Johnson     // other edges, e.g. reference edges. Otherwise, using a profile collected
7871958083dSTeresa Johnson     // on a slightly different binary might provoke preserving, importing
7881958083dSTeresa Johnson     // and ultimately promoting calls to functions not linked into this
7891958083dSTeresa Johnson     // binary, which increases the binary size unnecessarily. Note that
7901958083dSTeresa Johnson     // if this code changes, the importer needs to change so that edges
7911958083dSTeresa Johnson     // to functions marked dead are skipped.
7921958083dSTeresa Johnson     VI = updateValueInfoForIndirectCalls(Index, VI);
7931958083dSTeresa Johnson     if (!VI)
7941958083dSTeresa Johnson       return;
79533e3b4b9SXin Tong 
7965b2f6a1bSTeresa Johnson     if (llvm::any_of(VI.getSummaryList(),
79733e3b4b9SXin Tong                      [](const std::unique_ptr<llvm::GlobalValueSummary> &S) {
79833e3b4b9SXin Tong                        return S->isLive();
79933e3b4b9SXin Tong                      }))
800f625118eSTeresa Johnson       return;
801eaf5172cSGeorge Rimar 
802aab60006SVlad Tsyrklevich     // We only keep live symbols that are known to be non-prevailing if any are
803bfdad33bSXin Tong     // available_externally, linkonceodr, weakodr. Those symbols are discarded
804bfdad33bSXin Tong     // later in the EliminateAvailableExternally pass and setting them to
805bfdad33bSXin Tong     // not-live could break downstreams users of liveness information (PR36483)
806bfdad33bSXin Tong     // or limit optimization opportunities.
807aab60006SVlad Tsyrklevich     if (isPrevailing(VI.getGUID()) == PrevailingType::No) {
808bfdad33bSXin Tong       bool KeepAliveLinkage = false;
809aab60006SVlad Tsyrklevich       bool Interposable = false;
810aab60006SVlad Tsyrklevich       for (auto &S : VI.getSummaryList()) {
811bfdad33bSXin Tong         if (S->linkage() == GlobalValue::AvailableExternallyLinkage ||
812bfdad33bSXin Tong             S->linkage() == GlobalValue::WeakODRLinkage ||
813bfdad33bSXin Tong             S->linkage() == GlobalValue::LinkOnceODRLinkage)
814bfdad33bSXin Tong           KeepAliveLinkage = true;
815aab60006SVlad Tsyrklevich         else if (GlobalValue::isInterposableLinkage(S->linkage()))
816aab60006SVlad Tsyrklevich           Interposable = true;
817aab60006SVlad Tsyrklevich       }
818aab60006SVlad Tsyrklevich 
819ea314fd4STeresa Johnson       if (!IsAliasee) {
820bfdad33bSXin Tong         if (!KeepAliveLinkage)
821eaf5172cSGeorge Rimar           return;
822eaf5172cSGeorge Rimar 
823aab60006SVlad Tsyrklevich         if (Interposable)
824bfdad33bSXin Tong           report_fatal_error(
825ea314fd4STeresa Johnson               "Interposable and available_externally/linkonce_odr/weak_odr "
826ea314fd4STeresa Johnson               "symbol");
827ea314fd4STeresa Johnson       }
828aab60006SVlad Tsyrklevich     }
829aab60006SVlad Tsyrklevich 
830f625118eSTeresa Johnson     for (auto &S : VI.getSummaryList())
83156584bbfSEvgeniy Stepanov       S->setLive(true);
83256584bbfSEvgeniy Stepanov     ++LiveSymbols;
83356584bbfSEvgeniy Stepanov     Worklist.push_back(VI);
83456584bbfSEvgeniy Stepanov   };
83556584bbfSEvgeniy Stepanov 
8366c475a75STeresa Johnson   while (!Worklist.empty()) {
8379667b91bSPeter Collingbourne     auto VI = Worklist.pop_back_val();
8389667b91bSPeter Collingbourne     for (auto &Summary : VI.getSummaryList()) {
8395b2f6a1bSTeresa Johnson       if (auto *AS = dyn_cast<AliasSummary>(Summary.get())) {
8405b2f6a1bSTeresa Johnson         // If this is an alias, visit the aliasee VI to ensure that all copies
8415b2f6a1bSTeresa Johnson         // are marked live and it is added to the worklist for further
8425b2f6a1bSTeresa Johnson         // processing of its references.
843ea314fd4STeresa Johnson         visit(AS->getAliaseeVI(), true);
8445b2f6a1bSTeresa Johnson         continue;
8455b2f6a1bSTeresa Johnson       }
8465b2f6a1bSTeresa Johnson 
8475b2f6a1bSTeresa Johnson       Summary->setLive(true);
8485b2f6a1bSTeresa Johnson       for (auto Ref : Summary->refs())
849ea314fd4STeresa Johnson         visit(Ref, false);
8505b2f6a1bSTeresa Johnson       if (auto *FS = dyn_cast<FunctionSummary>(Summary.get()))
85156584bbfSEvgeniy Stepanov         for (auto Call : FS->calls())
852ea314fd4STeresa Johnson           visit(Call.first, false);
8536c475a75STeresa Johnson     }
8546c475a75STeresa Johnson   }
85556584bbfSEvgeniy Stepanov   Index.setWithGlobalValueDeadStripping();
85656584bbfSEvgeniy Stepanov 
85756584bbfSEvgeniy Stepanov   unsigned DeadSymbols = Index.size() - LiveSymbols;
858d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols
85956584bbfSEvgeniy Stepanov                     << " symbols Dead \n");
86056584bbfSEvgeniy Stepanov   NumDeadSymbols += DeadSymbols;
86156584bbfSEvgeniy Stepanov   NumLiveSymbols += LiveSymbols;
8626c475a75STeresa Johnson }
8636c475a75STeresa Johnson 
864bf46e741SEugene Leviant // Compute dead symbols and propagate constants in combined index.
865bf46e741SEugene Leviant void llvm::computeDeadSymbolsWithConstProp(
866bf46e741SEugene Leviant     ModuleSummaryIndex &Index,
867bf46e741SEugene Leviant     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
868bf46e741SEugene Leviant     function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing,
869bf46e741SEugene Leviant     bool ImportEnabled) {
870bf46e741SEugene Leviant   computeDeadSymbols(Index, GUIDPreservedSymbols, isPrevailing);
871bf46e741SEugene Leviant   if (ImportEnabled) {
8723aef3528SEugene Leviant     Index.propagateAttributes(GUIDPreservedSymbols);
873bf46e741SEugene Leviant   } else {
8743aef3528SEugene Leviant     // If import is disabled we should drop read/write-only attribute
875bf46e741SEugene Leviant     // from all summaries to prevent internalization.
876bf46e741SEugene Leviant     for (auto &P : Index)
877bf46e741SEugene Leviant       for (auto &S : P.second.SummaryList)
8783aef3528SEugene Leviant         if (auto *GVS = dyn_cast<GlobalVarSummary>(S.get())) {
879bf46e741SEugene Leviant           GVS->setReadOnly(false);
8803aef3528SEugene Leviant           GVS->setWriteOnly(false);
8813aef3528SEugene Leviant         }
882bf46e741SEugene Leviant   }
883dde58938Sevgeny   Index.setWithAttributePropagation();
884bf46e741SEugene Leviant }
885bf46e741SEugene Leviant 
88684174c37STeresa Johnson /// Compute the set of summaries needed for a ThinLTO backend compilation of
88784174c37STeresa Johnson /// \p ModulePath.
88884174c37STeresa Johnson void llvm::gatherImportedSummariesForModule(
88984174c37STeresa Johnson     StringRef ModulePath,
89084174c37STeresa Johnson     const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
891cdbcbf74SMehdi Amini     const FunctionImporter::ImportMapTy &ImportList,
89284174c37STeresa Johnson     std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
89384174c37STeresa Johnson   // Include all summaries from the importing module.
89484174c37STeresa Johnson   ModuleToSummariesForIndex[ModulePath] =
89584174c37STeresa Johnson       ModuleToDefinedGVSummaries.lookup(ModulePath);
89684174c37STeresa Johnson   // Include summaries for imports.
89788c491ddSMehdi Amini   for (auto &ILI : ImportList) {
89884174c37STeresa Johnson     auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
89984174c37STeresa Johnson     const auto &DefinedGVSummaries =
90084174c37STeresa Johnson         ModuleToDefinedGVSummaries.lookup(ILI.first());
90184174c37STeresa Johnson     for (auto &GI : ILI.second) {
902d68935c5STeresa Johnson       const auto &DS = DefinedGVSummaries.find(GI);
90384174c37STeresa Johnson       assert(DS != DefinedGVSummaries.end() &&
90484174c37STeresa Johnson              "Expected a defined summary for imported global value");
905d68935c5STeresa Johnson       SummariesForIndex[GI] = DS->second;
90684174c37STeresa Johnson     }
90784174c37STeresa Johnson   }
90884174c37STeresa Johnson }
90984174c37STeresa Johnson 
9108570fe47STeresa Johnson /// Emit the files \p ModulePath will import from into \p OutputFilename.
911c0320ef4STeresa Johnson std::error_code llvm::EmitImportsFiles(
912c0320ef4STeresa Johnson     StringRef ModulePath, StringRef OutputFilename,
913c0320ef4STeresa Johnson     const std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
9148570fe47STeresa Johnson   std::error_code EC;
915d9b948b6SFangrui Song   raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::OF_None);
9168570fe47STeresa Johnson   if (EC)
9178570fe47STeresa Johnson     return EC;
918c0320ef4STeresa Johnson   for (auto &ILI : ModuleToSummariesForIndex)
919c0320ef4STeresa Johnson     // The ModuleToSummariesForIndex map includes an entry for the current
920c0320ef4STeresa Johnson     // Module (needed for writing out the index files). We don't want to
921c0320ef4STeresa Johnson     // include it in the imports file, however, so filter it out.
922c0320ef4STeresa Johnson     if (ILI.first != ModulePath)
923c0320ef4STeresa Johnson       ImportsOS << ILI.first << "\n";
9248570fe47STeresa Johnson   return std::error_code();
9258570fe47STeresa Johnson }
9268570fe47STeresa Johnson 
9275a95c477STeresa Johnson bool llvm::convertToDeclaration(GlobalValue &GV) {
928d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName()
929d34e60caSNicola Zaghen                     << "\n");
9304566c6dbSTeresa Johnson   if (Function *F = dyn_cast<Function>(&GV)) {
9314566c6dbSTeresa Johnson     F->deleteBody();
9324566c6dbSTeresa Johnson     F->clearMetadata();
9337873669bSPeter Collingbourne     F->setComdat(nullptr);
9344566c6dbSTeresa Johnson   } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
9354566c6dbSTeresa Johnson     V->setInitializer(nullptr);
9364566c6dbSTeresa Johnson     V->setLinkage(GlobalValue::ExternalLinkage);
9374566c6dbSTeresa Johnson     V->clearMetadata();
9387873669bSPeter Collingbourne     V->setComdat(nullptr);
9395a95c477STeresa Johnson   } else {
9405a95c477STeresa Johnson     GlobalValue *NewGV;
9415a95c477STeresa Johnson     if (GV.getValueType()->isFunctionTy())
9425a95c477STeresa Johnson       NewGV =
9435a95c477STeresa Johnson           Function::Create(cast<FunctionType>(GV.getValueType()),
944f920da00SDylan McKay                            GlobalValue::ExternalLinkage, GV.getAddressSpace(),
945f920da00SDylan McKay                            "", GV.getParent());
9465a95c477STeresa Johnson     else
9475a95c477STeresa Johnson       NewGV =
9485a95c477STeresa Johnson           new GlobalVariable(*GV.getParent(), GV.getValueType(),
9495a95c477STeresa Johnson                              /*isConstant*/ false, GlobalValue::ExternalLinkage,
9505a95c477STeresa Johnson                              /*init*/ nullptr, "",
9515a95c477STeresa Johnson                              /*insertbefore*/ nullptr, GV.getThreadLocalMode(),
9525a95c477STeresa Johnson                              GV.getType()->getAddressSpace());
9535a95c477STeresa Johnson     NewGV->takeName(&GV);
9545a95c477STeresa Johnson     GV.replaceAllUsesWith(NewGV);
9555a95c477STeresa Johnson     return false;
9565a95c477STeresa Johnson   }
9575a95c477STeresa Johnson   return true;
958eaf5172cSGeorge Rimar }
9594566c6dbSTeresa Johnson 
960e61652a3SPirama Arumuga Nainar /// Fixup prevailing symbol linkages in \p TheModule based on summary analysis.
961e61652a3SPirama Arumuga Nainar void llvm::thinLTOResolvePrevailingInModule(
962eaf5172cSGeorge Rimar     Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
96304c9a2d6STeresa Johnson   auto updateLinkage = [&](GlobalValue &GV) {
96404c9a2d6STeresa Johnson     // See if the global summary analysis computed a new resolved linkage.
96504c9a2d6STeresa Johnson     const auto &GS = DefinedGlobals.find(GV.getGUID());
96604c9a2d6STeresa Johnson     if (GS == DefinedGlobals.end())
96704c9a2d6STeresa Johnson       return;
96804c9a2d6STeresa Johnson     auto NewLinkage = GS->second->linkage();
96904c9a2d6STeresa Johnson     if (NewLinkage == GV.getLinkage())
97004c9a2d6STeresa Johnson       return;
971e61652a3SPirama Arumuga Nainar     if (GlobalValue::isLocalLinkage(GV.getLinkage()) ||
972e5dd30f7SEugene Leviant         // Don't internalize anything here, because the code below
973e5dd30f7SEugene Leviant         // lacks necessary correctness checks. Leave this job to
974e5dd30f7SEugene Leviant         // LLVM 'internalize' pass.
9750f418677SEugene Leviant         GlobalValue::isLocalLinkage(NewLinkage) ||
976e61652a3SPirama Arumuga Nainar         // In case it was dead and already converted to declaration.
977e61652a3SPirama Arumuga Nainar         GV.isDeclaration())
9786a5fbe52SDavide Italiano       return;
979ea314fd4STeresa Johnson 
9804566c6dbSTeresa Johnson     // Check for a non-prevailing def that has interposable linkage
9814566c6dbSTeresa Johnson     // (e.g. non-odr weak or linkonce). In that case we can't simply
9824566c6dbSTeresa Johnson     // convert to available_externally, since it would lose the
9834566c6dbSTeresa Johnson     // interposable property and possibly get inlined. Simply drop
9844566c6dbSTeresa Johnson     // the definition in that case.
9854566c6dbSTeresa Johnson     if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) &&
9865a95c477STeresa Johnson         GlobalValue::isInterposableLinkage(GV.getLinkage())) {
9875a95c477STeresa Johnson       if (!convertToDeclaration(GV))
9885a95c477STeresa Johnson         // FIXME: Change this to collect replaced GVs and later erase
989e61652a3SPirama Arumuga Nainar         // them from the parent module once thinLTOResolvePrevailingGUID is
9905a95c477STeresa Johnson         // changed to enable this for aliases.
9915a95c477STeresa Johnson         llvm_unreachable("Expected GV to be converted");
9925a95c477STeresa Johnson     } else {
99337b80122STeresa Johnson       // If all copies of the original symbol had global unnamed addr and
99437b80122STeresa Johnson       // linkonce_odr linkage, it should be an auto hide symbol. In that case
99537b80122STeresa Johnson       // the thin link would have marked it as CanAutoHide. Add hidden visibility
99637b80122STeresa Johnson       // to the symbol to preserve the property.
99737b80122STeresa Johnson       if (NewLinkage == GlobalValue::WeakODRLinkage &&
99837b80122STeresa Johnson           GS->second->canAutoHide()) {
99937b80122STeresa Johnson         assert(GV.hasLinkOnceODRLinkage() && GV.hasGlobalUnnamedAddr());
100033ba93c2SSteven Wu         GV.setVisibility(GlobalValue::HiddenVisibility);
100137b80122STeresa Johnson       }
100233ba93c2SSteven Wu 
1003d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName()
1004d34e60caSNicola Zaghen                         << "` from " << GV.getLinkage() << " to " << NewLinkage
1005d34e60caSNicola Zaghen                         << "\n");
100604c9a2d6STeresa Johnson       GV.setLinkage(NewLinkage);
10074566c6dbSTeresa Johnson     }
10084566c6dbSTeresa Johnson     // Remove declarations from comdats, including available_externally
10096107a419STeresa Johnson     // as this is a declaration for the linker, and will be dropped eventually.
10106107a419STeresa Johnson     // It is illegal for comdats to contain declarations.
10116107a419STeresa Johnson     auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
10124566c6dbSTeresa Johnson     if (GO && GO->isDeclarationForLinker() && GO->hasComdat())
10136107a419STeresa Johnson       GO->setComdat(nullptr);
101404c9a2d6STeresa Johnson   };
101504c9a2d6STeresa Johnson 
101604c9a2d6STeresa Johnson   // Process functions and global now
101704c9a2d6STeresa Johnson   for (auto &GV : TheModule)
101804c9a2d6STeresa Johnson     updateLinkage(GV);
101904c9a2d6STeresa Johnson   for (auto &GV : TheModule.globals())
102004c9a2d6STeresa Johnson     updateLinkage(GV);
102104c9a2d6STeresa Johnson   for (auto &GV : TheModule.aliases())
102204c9a2d6STeresa Johnson     updateLinkage(GV);
102304c9a2d6STeresa Johnson }
102404c9a2d6STeresa Johnson 
102504c9a2d6STeresa Johnson /// Run internalization on \p TheModule based on symmary analysis.
102604c9a2d6STeresa Johnson void llvm::thinLTOInternalizeModule(Module &TheModule,
102704c9a2d6STeresa Johnson                                     const GVSummaryMapTy &DefinedGlobals) {
102804c9a2d6STeresa Johnson   // Declare a callback for the internalize pass that will ask for every
102904c9a2d6STeresa Johnson   // candidate GlobalValue if it can be internalized or not.
103004c9a2d6STeresa Johnson   auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
103104c9a2d6STeresa Johnson     // Lookup the linkage recorded in the summaries during global analysis.
1032c3d677f9SPeter Collingbourne     auto GS = DefinedGlobals.find(GV.getGUID());
103304c9a2d6STeresa Johnson     if (GS == DefinedGlobals.end()) {
103404c9a2d6STeresa Johnson       // Must have been promoted (possibly conservatively). Find original
103504c9a2d6STeresa Johnson       // name so that we can access the correct summary and see if it can
103604c9a2d6STeresa Johnson       // be internalized again.
103704c9a2d6STeresa Johnson       // FIXME: Eventually we should control promotion instead of promoting
103804c9a2d6STeresa Johnson       // and internalizing again.
103904c9a2d6STeresa Johnson       StringRef OrigName =
104004c9a2d6STeresa Johnson           ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
104104c9a2d6STeresa Johnson       std::string OrigId = GlobalValue::getGlobalIdentifier(
104204c9a2d6STeresa Johnson           OrigName, GlobalValue::InternalLinkage,
104304c9a2d6STeresa Johnson           TheModule.getSourceFileName());
1044c3d677f9SPeter Collingbourne       GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
10457ab1f692STeresa Johnson       if (GS == DefinedGlobals.end()) {
10467ab1f692STeresa Johnson         // Also check the original non-promoted non-globalized name. In some
10477ab1f692STeresa Johnson         // cases a preempted weak value is linked in as a local copy because
10487ab1f692STeresa Johnson         // it is referenced by an alias (IRLinker::linkGlobalValueProto).
10497ab1f692STeresa Johnson         // In that case, since it was originally not a local value, it was
10507ab1f692STeresa Johnson         // recorded in the index using the original name.
10517ab1f692STeresa Johnson         // FIXME: This may not be needed once PR27866 is fixed.
1052c3d677f9SPeter Collingbourne         GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
105304c9a2d6STeresa Johnson         assert(GS != DefinedGlobals.end());
10547ab1f692STeresa Johnson       }
1055c3d677f9SPeter Collingbourne     }
1056c3d677f9SPeter Collingbourne     return !GlobalValue::isLocalLinkage(GS->second->linkage());
105704c9a2d6STeresa Johnson   };
105804c9a2d6STeresa Johnson 
105904c9a2d6STeresa Johnson   // FIXME: See if we can just internalize directly here via linkage changes
106004c9a2d6STeresa Johnson   // based on the index, rather than invoking internalizeModule.
1061e9ea08a0SEugene Zelenko   internalizeModule(TheModule, MustPreserveGV);
106204c9a2d6STeresa Johnson }
106304c9a2d6STeresa Johnson 
106481bbf742STeresa Johnson /// Make alias a clone of its aliasee.
106581bbf742STeresa Johnson static Function *replaceAliasWithAliasee(Module *SrcModule, GlobalAlias *GA) {
106681bbf742STeresa Johnson   Function *Fn = cast<Function>(GA->getBaseObject());
106781bbf742STeresa Johnson 
106881bbf742STeresa Johnson   ValueToValueMapTy VMap;
106981bbf742STeresa Johnson   Function *NewFn = CloneFunction(Fn, VMap);
10705b2088d1STeresa Johnson   // Clone should use the original alias's linkage, visibility and name, and we
10715b2088d1STeresa Johnson   // ensure all uses of alias instead use the new clone (casted if necessary).
107281bbf742STeresa Johnson   NewFn->setLinkage(GA->getLinkage());
10735b2088d1STeresa Johnson   NewFn->setVisibility(GA->getVisibility());
107481bbf742STeresa Johnson   GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewFn, GA->getType()));
107581bbf742STeresa Johnson   NewFn->takeName(GA);
107681bbf742STeresa Johnson   return NewFn;
107781bbf742STeresa Johnson }
107881bbf742STeresa Johnson 
1079bf46e741SEugene Leviant // Internalize values that we marked with specific attribute
1080bf46e741SEugene Leviant // in processGlobalForThinLTO.
10813aef3528SEugene Leviant static void internalizeGVsAfterImport(Module &M) {
1082bf46e741SEugene Leviant   for (auto &GV : M.globals())
1083bf46e741SEugene Leviant     // Skip GVs which have been converted to declarations
1084bf46e741SEugene Leviant     // by dropDeadSymbols.
1085bf46e741SEugene Leviant     if (!GV.isDeclaration() && GV.hasAttribute("thinlto-internalize")) {
1086bf46e741SEugene Leviant       GV.setLinkage(GlobalValue::InternalLinkage);
1087bf46e741SEugene Leviant       GV.setVisibility(GlobalValue::DefaultVisibility);
1088bf46e741SEugene Leviant     }
1089bf46e741SEugene Leviant }
1090bf46e741SEugene Leviant 
1091c8c55170SMehdi Amini // Automatically import functions in Module \p DestModule based on the summaries
1092c8c55170SMehdi Amini // index.
10937f00d0a1SPeter Collingbourne Expected<bool> FunctionImporter::importFunctions(
109466043797SAdrian Prantl     Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
1095d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Starting import for Module "
1096311fef6eSMehdi Amini                     << DestModule.getModuleIdentifier() << "\n");
109719e23874SEugene Leviant   unsigned ImportedCount = 0, ImportedGVCount = 0;
1098c8c55170SMehdi Amini 
10996d8f817fSPeter Collingbourne   IRMover Mover(DestModule);
11007e88d0daSMehdi Amini   // Do the actual import of functions now, one Module at a time
110101e32130SMehdi Amini   std::set<StringRef> ModuleNameOrderedList;
110201e32130SMehdi Amini   for (auto &FunctionsToImportPerModule : ImportList) {
110301e32130SMehdi Amini     ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
110401e32130SMehdi Amini   }
110501e32130SMehdi Amini   for (auto &Name : ModuleNameOrderedList) {
11067e88d0daSMehdi Amini     // Get the module for the import
110701e32130SMehdi Amini     const auto &FunctionsToImportPerModule = ImportList.find(Name);
110801e32130SMehdi Amini     assert(FunctionsToImportPerModule != ImportList.end());
1109d9445c49SPeter Collingbourne     Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
1110d9445c49SPeter Collingbourne     if (!SrcModuleOrErr)
1111d9445c49SPeter Collingbourne       return SrcModuleOrErr.takeError();
1112d9445c49SPeter Collingbourne     std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
11137e88d0daSMehdi Amini     assert(&DestModule.getContext() == &SrcModule->getContext() &&
11147e88d0daSMehdi Amini            "Context mismatch");
11157e88d0daSMehdi Amini 
11166cba37ceSTeresa Johnson     // If modules were created with lazy metadata loading, materialize it
11176cba37ceSTeresa Johnson     // now, before linking it (otherwise this will be a noop).
11187f00d0a1SPeter Collingbourne     if (Error Err = SrcModule->materializeMetadata())
11197f00d0a1SPeter Collingbourne       return std::move(Err);
1120e5a61917STeresa Johnson 
112101e32130SMehdi Amini     auto &ImportGUIDs = FunctionsToImportPerModule->second;
112201e32130SMehdi Amini     // Find the globals to import
11236d8f817fSPeter Collingbourne     SetVector<GlobalValue *> GlobalsToImport;
11241f685e01SPiotr Padlewski     for (Function &F : *SrcModule) {
11251f685e01SPiotr Padlewski       if (!F.hasName())
11260beb858eSTeresa Johnson         continue;
11271f685e01SPiotr Padlewski       auto GUID = F.getGUID();
11280beb858eSTeresa Johnson       auto Import = ImportGUIDs.count(GUID);
1129d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function "
1130d34e60caSNicola Zaghen                         << GUID << " " << F.getName() << " from "
1131aeb1e59bSMehdi Amini                         << SrcModule->getSourceFileName() << "\n");
11320beb858eSTeresa Johnson       if (Import) {
11337f00d0a1SPeter Collingbourne         if (Error Err = F.materialize())
11347f00d0a1SPeter Collingbourne           return std::move(Err);
11353b776128SPiotr Padlewski         if (EnableImportMetadata) {
11366deaa6afSPiotr Padlewski           // Add 'thinlto_src_module' metadata for statistics and debugging.
11373b776128SPiotr Padlewski           F.setMetadata(
11383b776128SPiotr Padlewski               "thinlto_src_module",
1139e9ea08a0SEugene Zelenko               MDNode::get(DestModule.getContext(),
1140e9ea08a0SEugene Zelenko                           {MDString::get(DestModule.getContext(),
11416deaa6afSPiotr Padlewski                                          SrcModule->getSourceFileName())}));
11423b776128SPiotr Padlewski         }
11431f685e01SPiotr Padlewski         GlobalsToImport.insert(&F);
114401e32130SMehdi Amini       }
114501e32130SMehdi Amini     }
11461f685e01SPiotr Padlewski     for (GlobalVariable &GV : SrcModule->globals()) {
11472d28f7aaSMehdi Amini       if (!GV.hasName())
11482d28f7aaSMehdi Amini         continue;
11492d28f7aaSMehdi Amini       auto GUID = GV.getGUID();
11502d28f7aaSMehdi Amini       auto Import = ImportGUIDs.count(GUID);
1151d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global "
1152d34e60caSNicola Zaghen                         << GUID << " " << GV.getName() << " from "
1153aeb1e59bSMehdi Amini                         << SrcModule->getSourceFileName() << "\n");
11542d28f7aaSMehdi Amini       if (Import) {
11557f00d0a1SPeter Collingbourne         if (Error Err = GV.materialize())
11567f00d0a1SPeter Collingbourne           return std::move(Err);
115719e23874SEugene Leviant         ImportedGVCount += GlobalsToImport.insert(&GV);
11582d28f7aaSMehdi Amini       }
11592d28f7aaSMehdi Amini     }
11601f685e01SPiotr Padlewski     for (GlobalAlias &GA : SrcModule->aliases()) {
11611f685e01SPiotr Padlewski       if (!GA.hasName())
116201e32130SMehdi Amini         continue;
11631f685e01SPiotr Padlewski       auto GUID = GA.getGUID();
116481bbf742STeresa Johnson       auto Import = ImportGUIDs.count(GUID);
1165d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias "
1166d34e60caSNicola Zaghen                         << GUID << " " << GA.getName() << " from "
1167aeb1e59bSMehdi Amini                         << SrcModule->getSourceFileName() << "\n");
116881bbf742STeresa Johnson       if (Import) {
116981bbf742STeresa Johnson         if (Error Err = GA.materialize())
117081bbf742STeresa Johnson           return std::move(Err);
117181bbf742STeresa Johnson         // Import alias as a copy of its aliasee.
117281bbf742STeresa Johnson         GlobalObject *Base = GA.getBaseObject();
117381bbf742STeresa Johnson         if (Error Err = Base->materialize())
117481bbf742STeresa Johnson           return std::move(Err);
117581bbf742STeresa Johnson         auto *Fn = replaceAliasWithAliasee(SrcModule.get(), &GA);
1176d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "Is importing aliasee fn " << Base->getGUID()
117781bbf742STeresa Johnson                           << " " << Base->getName() << " from "
117881bbf742STeresa Johnson                           << SrcModule->getSourceFileName() << "\n");
117981bbf742STeresa Johnson         if (EnableImportMetadata) {
118081bbf742STeresa Johnson           // Add 'thinlto_src_module' metadata for statistics and debugging.
118181bbf742STeresa Johnson           Fn->setMetadata(
118281bbf742STeresa Johnson               "thinlto_src_module",
118381bbf742STeresa Johnson               MDNode::get(DestModule.getContext(),
118481bbf742STeresa Johnson                           {MDString::get(DestModule.getContext(),
118581bbf742STeresa Johnson                                          SrcModule->getSourceFileName())}));
118601e32130SMehdi Amini         }
118781bbf742STeresa Johnson         GlobalsToImport.insert(Fn);
118881bbf742STeresa Johnson       }
118981bbf742STeresa Johnson     }
119001e32130SMehdi Amini 
119119ef4fadSMehdi Amini     // Upgrade debug info after we're done materializing all the globals and we
119219ef4fadSMehdi Amini     // have loaded all the required metadata!
119319ef4fadSMehdi Amini     UpgradeDebugInfo(*SrcModule);
119419ef4fadSMehdi Amini 
11957e88d0daSMehdi Amini     // Link in the specified functions.
119601e32130SMehdi Amini     if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
11978d05185aSMehdi Amini       return true;
11988d05185aSMehdi Amini 
1199d29478f7STeresa Johnson     if (PrintImports) {
1200d29478f7STeresa Johnson       for (const auto *GV : GlobalsToImport)
1201d29478f7STeresa Johnson         dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
1202d29478f7STeresa Johnson                << " from " << SrcModule->getSourceFileName() << "\n";
1203d29478f7STeresa Johnson     }
1204d29478f7STeresa Johnson 
12056d8f817fSPeter Collingbourne     if (Mover.move(std::move(SrcModule), GlobalsToImport.getArrayRef(),
12066d8f817fSPeter Collingbourne                    [](GlobalValue &, IRMover::ValueAdder) {},
1207e6fd9ff9SPeter Collingbourne                    /*IsPerformingImport=*/true))
12087e88d0daSMehdi Amini       report_fatal_error("Function Import: link error");
12097e88d0daSMehdi Amini 
121001e32130SMehdi Amini     ImportedCount += GlobalsToImport.size();
12116c475a75STeresa Johnson     NumImportedModules++;
12127e88d0daSMehdi Amini   }
1213e5a61917STeresa Johnson 
12143aef3528SEugene Leviant   internalizeGVsAfterImport(DestModule);
1215bf46e741SEugene Leviant 
121619e23874SEugene Leviant   NumImportedFunctions += (ImportedCount - ImportedGVCount);
121719e23874SEugene Leviant   NumImportedGlobalVars += ImportedGVCount;
1218d29478f7STeresa Johnson 
1219d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Imported " << ImportedCount - ImportedGVCount
1220d34e60caSNicola Zaghen                     << " functions for Module "
1221d34e60caSNicola Zaghen                     << DestModule.getModuleIdentifier() << "\n");
1222d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Imported " << ImportedGVCount
122319e23874SEugene Leviant                     << " global variables for Module "
1224c8c55170SMehdi Amini                     << DestModule.getModuleIdentifier() << "\n");
1225c8c55170SMehdi Amini   return ImportedCount;
122642418abaSMehdi Amini }
122742418abaSMehdi Amini 
1228598bd2a2SPeter Collingbourne static bool doImportingForModule(Module &M) {
1229598bd2a2SPeter Collingbourne   if (SummaryFile.empty())
1230598bd2a2SPeter Collingbourne     report_fatal_error("error: -function-import requires -summary-file\n");
12316de481a3SPeter Collingbourne   Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
12326de481a3SPeter Collingbourne       getModuleSummaryIndexForFile(SummaryFile);
12336de481a3SPeter Collingbourne   if (!IndexPtrOrErr) {
12346de481a3SPeter Collingbourne     logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
12356de481a3SPeter Collingbourne                           "Error loading file '" + SummaryFile + "': ");
123642418abaSMehdi Amini     return false;
123742418abaSMehdi Amini   }
1238598bd2a2SPeter Collingbourne   std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
123942418abaSMehdi Amini 
1240c86af334STeresa Johnson   // First step is collecting the import list.
1241c86af334STeresa Johnson   FunctionImporter::ImportMapTy ImportList;
124281bbf742STeresa Johnson   // If requested, simply import all functions in the index. This is used
124381bbf742STeresa Johnson   // when testing distributed backend handling via the opt tool, when
124481bbf742STeresa Johnson   // we have distributed indexes containing exactly the summaries to import.
124581bbf742STeresa Johnson   if (ImportAllIndex)
124681bbf742STeresa Johnson     ComputeCrossModuleImportForModuleFromIndex(M.getModuleIdentifier(), *Index,
124781bbf742STeresa Johnson                                                ImportList);
124881bbf742STeresa Johnson   else
1249c86af334STeresa Johnson     ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
1250c86af334STeresa Johnson                                       ImportList);
125101e32130SMehdi Amini 
12524fef68cbSTeresa Johnson   // Conservatively mark all internal values as promoted. This interface is
12534fef68cbSTeresa Johnson   // only used when doing importing via the function importing pass. The pass
12544fef68cbSTeresa Johnson   // is only enabled when testing importing via the 'opt' tool, which does
12554fef68cbSTeresa Johnson   // not do the ThinLink that would normally determine what values to promote.
12564fef68cbSTeresa Johnson   for (auto &I : *Index) {
12579667b91bSPeter Collingbourne     for (auto &S : I.second.SummaryList) {
12584fef68cbSTeresa Johnson       if (GlobalValue::isLocalLinkage(S->linkage()))
12594fef68cbSTeresa Johnson         S->setLinkage(GlobalValue::ExternalLinkage);
12604fef68cbSTeresa Johnson     }
12614fef68cbSTeresa Johnson   }
12624fef68cbSTeresa Johnson 
126301e32130SMehdi Amini   // Next we need to promote to global scope and rename any local values that
12641b00f2d9STeresa Johnson   // are potentially exported to other modules.
126501e32130SMehdi Amini   if (renameModuleForThinLTO(M, *Index, nullptr)) {
12661b00f2d9STeresa Johnson     errs() << "Error renaming module\n";
12671b00f2d9STeresa Johnson     return false;
12681b00f2d9STeresa Johnson   }
12691b00f2d9STeresa Johnson 
127042418abaSMehdi Amini   // Perform the import now.
1271d16c8065SMehdi Amini   auto ModuleLoader = [&M](StringRef Identifier) {
1272d16c8065SMehdi Amini     return loadFile(Identifier, M.getContext());
1273d16c8065SMehdi Amini   };
12749d2bfc48SRafael Espindola   FunctionImporter Importer(*Index, ModuleLoader);
127537e24591SPeter Collingbourne   Expected<bool> Result = Importer.importFunctions(M, ImportList);
12767f00d0a1SPeter Collingbourne 
12777f00d0a1SPeter Collingbourne   // FIXME: Probably need to propagate Errors through the pass manager.
12787f00d0a1SPeter Collingbourne   if (!Result) {
12797f00d0a1SPeter Collingbourne     logAllUnhandledErrors(Result.takeError(), errs(),
12807f00d0a1SPeter Collingbourne                           "Error importing module: ");
12817f00d0a1SPeter Collingbourne     return false;
12827f00d0a1SPeter Collingbourne   }
12837f00d0a1SPeter Collingbourne 
12847f00d0a1SPeter Collingbourne   return *Result;
128521241571STeresa Johnson }
128621241571STeresa Johnson 
128721241571STeresa Johnson namespace {
1288e9ea08a0SEugene Zelenko 
128921241571STeresa Johnson /// Pass that performs cross-module function import provided a summary file.
129021241571STeresa Johnson class FunctionImportLegacyPass : public ModulePass {
129121241571STeresa Johnson public:
129221241571STeresa Johnson   /// Pass identification, replacement for typeid
129321241571STeresa Johnson   static char ID;
129421241571STeresa Johnson 
1295e9ea08a0SEugene Zelenko   explicit FunctionImportLegacyPass() : ModulePass(ID) {}
1296e9ea08a0SEugene Zelenko 
129721241571STeresa Johnson   /// Specify pass name for debug output
1298117296c0SMehdi Amini   StringRef getPassName() const override { return "Function Importing"; }
129921241571STeresa Johnson 
130021241571STeresa Johnson   bool runOnModule(Module &M) override {
130121241571STeresa Johnson     if (skipModule(M))
130221241571STeresa Johnson       return false;
130321241571STeresa Johnson 
1304598bd2a2SPeter Collingbourne     return doImportingForModule(M);
130542418abaSMehdi Amini   }
130642418abaSMehdi Amini };
1307e9ea08a0SEugene Zelenko 
1308e9ea08a0SEugene Zelenko } // end anonymous namespace
130942418abaSMehdi Amini 
131021241571STeresa Johnson PreservedAnalyses FunctionImportPass::run(Module &M,
1311fd03ac6aSSean Silva                                           ModuleAnalysisManager &AM) {
1312598bd2a2SPeter Collingbourne   if (!doImportingForModule(M))
131321241571STeresa Johnson     return PreservedAnalyses::all();
131421241571STeresa Johnson 
131521241571STeresa Johnson   return PreservedAnalyses::none();
131621241571STeresa Johnson }
131721241571STeresa Johnson 
131821241571STeresa Johnson char FunctionImportLegacyPass::ID = 0;
131921241571STeresa Johnson INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
132042418abaSMehdi Amini                 "Summary Based Function Import", false, false)
132142418abaSMehdi Amini 
132242418abaSMehdi Amini namespace llvm {
1323e9ea08a0SEugene Zelenko 
1324598bd2a2SPeter Collingbourne Pass *createFunctionImportPass() {
1325598bd2a2SPeter Collingbourne   return new FunctionImportLegacyPass();
13265fcbdb71STeresa Johnson }
1327e9ea08a0SEugene Zelenko 
1328e9ea08a0SEugene Zelenko } // end namespace llvm
1329