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(
28319e23874SEugene Leviant     const FunctionSummary &Summary, const GVSummaryMapTy &DefinedGVSummaries,
28419e23874SEugene Leviant     FunctionImporter::ImportMapTy &ImportList,
28519e23874SEugene Leviant     StringMap<FunctionImporter::ExportSetTy> *ExportLists) {
28619e23874SEugene Leviant   for (auto &VI : Summary.refs()) {
28719e23874SEugene Leviant     if (DefinedGVSummaries.count(VI.getGUID())) {
288d34e60caSNicola Zaghen       LLVM_DEBUG(
289d34e60caSNicola Zaghen           dbgs() << "Ref ignored! Target already in destination module.\n");
29019e23874SEugene Leviant       continue;
29119e23874SEugene Leviant     }
29219e23874SEugene Leviant 
2937e7b13d0STeresa Johnson     LLVM_DEBUG(dbgs() << " ref -> " << VI << "\n");
29419e23874SEugene Leviant 
29593f99962STeresa Johnson     // If this is a local variable, make sure we import the copy
29693f99962STeresa Johnson     // in the caller's module. The only time a local variable can
29793f99962STeresa Johnson     // share an entry in the index is if there is a local with the same name
29893f99962STeresa Johnson     // in another module that had the same source file name (in a different
29993f99962STeresa Johnson     // directory), where each was compiled in their own directory so there
30093f99962STeresa Johnson     // was not distinguishing path.
30193f99962STeresa Johnson     auto LocalNotInModule = [&](const GlobalValueSummary *RefSummary) -> bool {
30293f99962STeresa Johnson       return GlobalValue::isLocalLinkage(RefSummary->linkage()) &&
30393f99962STeresa Johnson              RefSummary->modulePath() != Summary.modulePath();
30493f99962STeresa Johnson     };
30593f99962STeresa Johnson 
30619e23874SEugene Leviant     for (auto &RefSummary : VI.getSummaryList())
307bf46e741SEugene Leviant       if (isa<GlobalVarSummary>(RefSummary.get()) &&
30893f99962STeresa Johnson           canImportGlobalVar(RefSummary.get()) &&
30993f99962STeresa Johnson           !LocalNotInModule(RefSummary.get())) {
310d2c234a4STeresa Johnson         auto ILI = ImportList[RefSummary->modulePath()].insert(VI.getGUID());
311d2c234a4STeresa Johnson         // Only update stat if we haven't already imported this variable.
312d2c234a4STeresa Johnson         if (ILI.second)
313d2c234a4STeresa Johnson           NumImportedGlobalVarsThinLink++;
31419e23874SEugene Leviant         if (ExportLists)
31519e23874SEugene Leviant           (*ExportLists)[RefSummary->modulePath()].insert(VI.getGUID());
31619e23874SEugene Leviant         break;
31719e23874SEugene Leviant       }
31819e23874SEugene Leviant   }
31919e23874SEugene Leviant }
32019e23874SEugene Leviant 
321cb9a82fcSTeresa Johnson static const char *
322cb9a82fcSTeresa Johnson getFailureName(FunctionImporter::ImportFailureReason Reason) {
323cb9a82fcSTeresa Johnson   switch (Reason) {
324cb9a82fcSTeresa Johnson   case FunctionImporter::ImportFailureReason::None:
325cb9a82fcSTeresa Johnson     return "None";
326cb9a82fcSTeresa Johnson   case FunctionImporter::ImportFailureReason::GlobalVar:
327cb9a82fcSTeresa Johnson     return "GlobalVar";
328cb9a82fcSTeresa Johnson   case FunctionImporter::ImportFailureReason::NotLive:
329cb9a82fcSTeresa Johnson     return "NotLive";
330cb9a82fcSTeresa Johnson   case FunctionImporter::ImportFailureReason::TooLarge:
331cb9a82fcSTeresa Johnson     return "TooLarge";
332cb9a82fcSTeresa Johnson   case FunctionImporter::ImportFailureReason::InterposableLinkage:
333cb9a82fcSTeresa Johnson     return "InterposableLinkage";
334cb9a82fcSTeresa Johnson   case FunctionImporter::ImportFailureReason::LocalLinkageNotInModule:
335cb9a82fcSTeresa Johnson     return "LocalLinkageNotInModule";
336cb9a82fcSTeresa Johnson   case FunctionImporter::ImportFailureReason::NotEligible:
337cb9a82fcSTeresa Johnson     return "NotEligible";
338cb397461STeresa Johnson   case FunctionImporter::ImportFailureReason::NoInline:
339cb397461STeresa Johnson     return "NoInline";
340cb9a82fcSTeresa Johnson   }
341cb9a82fcSTeresa Johnson   llvm_unreachable("invalid reason");
342cb9a82fcSTeresa Johnson }
343cb9a82fcSTeresa Johnson 
34401e32130SMehdi Amini /// Compute the list of functions to import for a given caller. Mark these
34501e32130SMehdi Amini /// imported functions and the symbols they reference in their source module as
34601e32130SMehdi Amini /// exported from their source module.
34701e32130SMehdi Amini static void computeImportForFunction(
3483255eec1STeresa Johnson     const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
349d9830eb7SPiotr Padlewski     const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
35001e32130SMehdi Amini     SmallVectorImpl<EdgeInfo> &Worklist,
3519b490f10SMehdi Amini     FunctionImporter::ImportMapTy &ImportList,
352d68935c5STeresa Johnson     StringMap<FunctionImporter::ExportSetTy> *ExportLists,
353d68935c5STeresa Johnson     FunctionImporter::ImportThresholdsTy &ImportThresholds) {
35419e23874SEugene Leviant   computeImportForReferencedGlobals(Summary, DefinedGVSummaries, ImportList,
35519e23874SEugene Leviant                                     ExportLists);
356974706ebSTeresa Johnson   static int ImportCount = 0;
35701e32130SMehdi Amini   for (auto &Edge : Summary.calls()) {
3589667b91bSPeter Collingbourne     ValueInfo VI = Edge.first;
3597e7b13d0STeresa Johnson     LLVM_DEBUG(dbgs() << " edge -> " << VI << " Threshold:" << Threshold
3607e7b13d0STeresa Johnson                       << "\n");
36101e32130SMehdi Amini 
362974706ebSTeresa Johnson     if (ImportCutoff >= 0 && ImportCount >= ImportCutoff) {
363d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "ignored! import-cutoff value of " << ImportCutoff
364974706ebSTeresa Johnson                         << " reached.\n");
365974706ebSTeresa Johnson       continue;
366974706ebSTeresa Johnson     }
367974706ebSTeresa Johnson 
3681958083dSTeresa Johnson     VI = updateValueInfoForIndirectCalls(Index, VI);
3699667b91bSPeter Collingbourne     if (!VI)
3709667b91bSPeter Collingbourne       continue;
3714a435e08SDehao Chen 
3729667b91bSPeter Collingbourne     if (DefinedGVSummaries.count(VI.getGUID())) {
373d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "ignored! Target already in destination module.\n");
3747e88d0daSMehdi Amini       continue;
375d450da32STeresa Johnson     }
37640641748SMehdi Amini 
377ba72b95fSPiotr Padlewski     auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
378ba72b95fSPiotr Padlewski       if (Hotness == CalleeInfo::HotnessType::Hot)
379ba72b95fSPiotr Padlewski         return ImportHotMultiplier;
380ba72b95fSPiotr Padlewski       if (Hotness == CalleeInfo::HotnessType::Cold)
381ba72b95fSPiotr Padlewski         return ImportColdMultiplier;
38264c46574SDehao Chen       if (Hotness == CalleeInfo::HotnessType::Critical)
38364c46574SDehao Chen         return ImportCriticalMultiplier;
384ba72b95fSPiotr Padlewski       return 1.0;
385ba72b95fSPiotr Padlewski     };
386ba72b95fSPiotr Padlewski 
387d9830eb7SPiotr Padlewski     const auto NewThreshold =
388c73cec84SEaswaran Raman         Threshold * GetBonusMultiplier(Edge.second.getHotness());
389d2869473SPiotr Padlewski 
390cb9a82fcSTeresa Johnson     auto IT = ImportThresholds.insert(std::make_pair(
391cb9a82fcSTeresa Johnson         VI.getGUID(), std::make_tuple(NewThreshold, nullptr, nullptr)));
392d68935c5STeresa Johnson     bool PreviouslyVisited = !IT.second;
393cb9a82fcSTeresa Johnson     auto &ProcessedThreshold = std::get<0>(IT.first->second);
394cb9a82fcSTeresa Johnson     auto &CalleeSummary = std::get<1>(IT.first->second);
395cb9a82fcSTeresa Johnson     auto &FailureInfo = std::get<2>(IT.first->second);
396d68935c5STeresa Johnson 
397d2c234a4STeresa Johnson     bool IsHotCallsite =
398d2c234a4STeresa Johnson         Edge.second.getHotness() == CalleeInfo::HotnessType::Hot;
399d2c234a4STeresa Johnson     bool IsCriticalCallsite =
400d2c234a4STeresa Johnson         Edge.second.getHotness() == CalleeInfo::HotnessType::Critical;
401d2c234a4STeresa Johnson 
402d68935c5STeresa Johnson     const FunctionSummary *ResolvedCalleeSummary = nullptr;
403d68935c5STeresa Johnson     if (CalleeSummary) {
404d68935c5STeresa Johnson       assert(PreviouslyVisited);
405d68935c5STeresa Johnson       // Since the traversal of the call graph is DFS, we can revisit a function
406d68935c5STeresa Johnson       // a second time with a higher threshold. In this case, it is added back
407d68935c5STeresa Johnson       // to the worklist with the new threshold (so that its own callee chains
408d68935c5STeresa Johnson       // can be considered with the higher threshold).
409d68935c5STeresa Johnson       if (NewThreshold <= ProcessedThreshold) {
410d68935c5STeresa Johnson         LLVM_DEBUG(
411d68935c5STeresa Johnson             dbgs() << "ignored! Target was already imported with Threshold "
412d68935c5STeresa Johnson                    << ProcessedThreshold << "\n");
413d68935c5STeresa Johnson         continue;
414d68935c5STeresa Johnson       }
415d68935c5STeresa Johnson       // Update with new larger threshold.
416d68935c5STeresa Johnson       ProcessedThreshold = NewThreshold;
417d68935c5STeresa Johnson       ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
418d68935c5STeresa Johnson     } else {
419d68935c5STeresa Johnson       // If we already rejected importing a callee at the same or higher
420d68935c5STeresa Johnson       // threshold, don't waste time calling selectCallee.
421d68935c5STeresa Johnson       if (PreviouslyVisited && NewThreshold <= ProcessedThreshold) {
422d68935c5STeresa Johnson         LLVM_DEBUG(
423d68935c5STeresa Johnson             dbgs() << "ignored! Target was already rejected with Threshold "
424d68935c5STeresa Johnson             << ProcessedThreshold << "\n");
425cb9a82fcSTeresa Johnson         if (PrintImportFailures) {
426cb9a82fcSTeresa Johnson           assert(FailureInfo &&
427cb9a82fcSTeresa Johnson                  "Expected FailureInfo for previously rejected candidate");
428cb9a82fcSTeresa Johnson           FailureInfo->Attempts++;
429cb9a82fcSTeresa Johnson         }
430d68935c5STeresa Johnson         continue;
431d68935c5STeresa Johnson       }
432d68935c5STeresa Johnson 
433cb9a82fcSTeresa Johnson       FunctionImporter::ImportFailureReason Reason;
434d68935c5STeresa Johnson       CalleeSummary = selectCallee(Index, VI.getSummaryList(), NewThreshold,
435cb9a82fcSTeresa Johnson                                    Summary.modulePath(), Reason, VI.getGUID());
43601e32130SMehdi Amini       if (!CalleeSummary) {
437d68935c5STeresa Johnson         // Update with new larger threshold if this was a retry (otherwise
438cb9a82fcSTeresa Johnson         // we would have already inserted with NewThreshold above). Also
439cb9a82fcSTeresa Johnson         // update failure info if requested.
440cb9a82fcSTeresa Johnson         if (PreviouslyVisited) {
441d68935c5STeresa Johnson           ProcessedThreshold = NewThreshold;
442cb9a82fcSTeresa Johnson           if (PrintImportFailures) {
443cb9a82fcSTeresa Johnson             assert(FailureInfo &&
444cb9a82fcSTeresa Johnson                    "Expected FailureInfo for previously rejected candidate");
445cb9a82fcSTeresa Johnson             FailureInfo->Reason = Reason;
446cb9a82fcSTeresa Johnson             FailureInfo->Attempts++;
447cb9a82fcSTeresa Johnson             FailureInfo->MaxHotness =
448cb9a82fcSTeresa Johnson                 std::max(FailureInfo->MaxHotness, Edge.second.getHotness());
449cb9a82fcSTeresa Johnson           }
450cb9a82fcSTeresa Johnson         } else if (PrintImportFailures) {
451cb9a82fcSTeresa Johnson           assert(!FailureInfo &&
452cb9a82fcSTeresa Johnson                  "Expected no FailureInfo for newly rejected candidate");
4530eaee545SJonas Devlieghere           FailureInfo = std::make_unique<FunctionImporter::ImportFailureInfo>(
454cb9a82fcSTeresa Johnson               VI, Edge.second.getHotness(), Reason, 1);
455cb9a82fcSTeresa Johnson         }
456d34e60caSNicola Zaghen         LLVM_DEBUG(
457d34e60caSNicola Zaghen             dbgs() << "ignored! No qualifying callee with summary found.\n");
4587e88d0daSMehdi Amini         continue;
4597e88d0daSMehdi Amini       }
4602f0cc477SDavid Blaikie 
4612f0cc477SDavid Blaikie       // "Resolve" the summary
462d68935c5STeresa Johnson       CalleeSummary = CalleeSummary->getBaseObject();
463d68935c5STeresa Johnson       ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
4642d28f7aaSMehdi Amini 
465d9830eb7SPiotr Padlewski       assert(ResolvedCalleeSummary->instCount() <= NewThreshold &&
46601e32130SMehdi Amini              "selectCallee() didn't honor the threshold");
46701e32130SMehdi Amini 
4681b859a23STeresa Johnson       auto ExportModulePath = ResolvedCalleeSummary->modulePath();
469d68935c5STeresa Johnson       auto ILI = ImportList[ExportModulePath].insert(VI.getGUID());
470d68935c5STeresa Johnson       // We previously decided to import this GUID definition if it was already
471d68935c5STeresa Johnson       // inserted in the set of imports from the exporting module.
472d68935c5STeresa Johnson       bool PreviouslyImported = !ILI.second;
473d2c234a4STeresa Johnson       if (!PreviouslyImported) {
474d2c234a4STeresa Johnson         NumImportedFunctionsThinLink++;
475d2c234a4STeresa Johnson         if (IsHotCallsite)
476d2c234a4STeresa Johnson           NumImportedHotFunctionsThinLink++;
477d2c234a4STeresa Johnson         if (IsCriticalCallsite)
478d2c234a4STeresa Johnson           NumImportedCriticalFunctionsThinLink++;
479d2c234a4STeresa Johnson       }
480974706ebSTeresa Johnson 
4811b859a23STeresa Johnson       // Make exports in the source module.
4821b859a23STeresa Johnson       if (ExportLists) {
4831b859a23STeresa Johnson         auto &ExportList = (*ExportLists)[ExportModulePath];
4849667b91bSPeter Collingbourne         ExportList.insert(VI.getGUID());
48519f2aa78STeresa Johnson         if (!PreviouslyImported) {
48619f2aa78STeresa Johnson           // This is the first time this function was exported from its source
48719f2aa78STeresa Johnson           // module, so mark all functions and globals it references as exported
4881b859a23STeresa Johnson           // to the outside if they are defined in the same source module.
489edddca22STeresa Johnson           // For efficiency, we unconditionally add all the referenced GUIDs
490edddca22STeresa Johnson           // to the ExportList for this module, and will prune out any not
491edddca22STeresa Johnson           // defined in the module later in a single pass.
4921b859a23STeresa Johnson           for (auto &Edge : ResolvedCalleeSummary->calls()) {
4931b859a23STeresa Johnson             auto CalleeGUID = Edge.first.getGUID();
494edddca22STeresa Johnson             ExportList.insert(CalleeGUID);
4951b859a23STeresa Johnson           }
4961b859a23STeresa Johnson           for (auto &Ref : ResolvedCalleeSummary->refs()) {
4971b859a23STeresa Johnson             auto GUID = Ref.getGUID();
498edddca22STeresa Johnson             ExportList.insert(GUID);
4991b859a23STeresa Johnson           }
5001b859a23STeresa Johnson         }
50119f2aa78STeresa Johnson       }
502d68935c5STeresa Johnson     }
503d68935c5STeresa Johnson 
504d68935c5STeresa Johnson     auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
505d68935c5STeresa Johnson       // Adjust the threshold for next level of imported functions.
506d68935c5STeresa Johnson       // The threshold is different for hot callsites because we can then
507d68935c5STeresa Johnson       // inline chains of hot calls.
508d68935c5STeresa Johnson       if (IsHotCallsite)
509d68935c5STeresa Johnson         return Threshold * ImportHotInstrFactor;
510d68935c5STeresa Johnson       return Threshold * ImportInstrFactor;
511d68935c5STeresa Johnson     };
512d68935c5STeresa Johnson 
513d68935c5STeresa Johnson     const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
514d68935c5STeresa Johnson 
515d68935c5STeresa Johnson     ImportCount++;
516d2869473SPiotr Padlewski 
51701e32130SMehdi Amini     // Insert the newly imported function to the worklist.
5189667b91bSPeter Collingbourne     Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, VI.getGUID());
519d450da32STeresa Johnson   }
520d450da32STeresa Johnson }
521d450da32STeresa Johnson 
52201e32130SMehdi Amini /// Given the list of globals defined in a module, compute the list of imports
52301e32130SMehdi Amini /// as well as the list of "exports", i.e. the list of symbols referenced from
52401e32130SMehdi Amini /// another module (that may require promotion).
52501e32130SMehdi Amini static void ComputeImportForModule(
526c851d216STeresa Johnson     const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
527cb9a82fcSTeresa Johnson     StringRef ModName, FunctionImporter::ImportMapTy &ImportList,
52856584bbfSEvgeniy Stepanov     StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
52901e32130SMehdi Amini   // Worklist contains the list of function imported in this module, for which
53001e32130SMehdi Amini   // we will analyse the callees and may import further down the callgraph.
53101e32130SMehdi Amini   SmallVector<EdgeInfo, 128> Worklist;
532d68935c5STeresa Johnson   FunctionImporter::ImportThresholdsTy ImportThresholds;
53301e32130SMehdi Amini 
53401e32130SMehdi Amini   // Populate the worklist with the import for the functions in the current
53501e32130SMehdi Amini   // module
53628e457bcSTeresa Johnson   for (auto &GVSummary : DefinedGVSummaries) {
5377e7b13d0STeresa Johnson #ifndef NDEBUG
5387e7b13d0STeresa Johnson     // FIXME: Change the GVSummaryMapTy to hold ValueInfo instead of GUID
5397e7b13d0STeresa Johnson     // so this map look up (and possibly others) can be avoided.
5407e7b13d0STeresa Johnson     auto VI = Index.getValueInfo(GVSummary.first);
5417e7b13d0STeresa Johnson #endif
54256584bbfSEvgeniy Stepanov     if (!Index.isGlobalValueLive(GVSummary.second)) {
5437e7b13d0STeresa Johnson       LLVM_DEBUG(dbgs() << "Ignores Dead GUID: " << VI << "\n");
5446c475a75STeresa Johnson       continue;
5456c475a75STeresa Johnson     }
546cfbd0892SPeter Collingbourne     auto *FuncSummary =
547cfbd0892SPeter Collingbourne         dyn_cast<FunctionSummary>(GVSummary.second->getBaseObject());
5481aafabf7SMehdi Amini     if (!FuncSummary)
5491aafabf7SMehdi Amini       // Skip import for global variables
5501aafabf7SMehdi Amini       continue;
5517e7b13d0STeresa Johnson     LLVM_DEBUG(dbgs() << "Initialize import for " << VI << "\n");
5522d28f7aaSMehdi Amini     computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
5539b490f10SMehdi Amini                              DefinedGVSummaries, Worklist, ImportList,
554d68935c5STeresa Johnson                              ExportLists, ImportThresholds);
55501e32130SMehdi Amini   }
55601e32130SMehdi Amini 
557d2869473SPiotr Padlewski   // Process the newly imported functions and add callees to the worklist.
55842418abaSMehdi Amini   while (!Worklist.empty()) {
55901e32130SMehdi Amini     auto FuncInfo = Worklist.pop_back_val();
560475b51a7STeresa Johnson     auto *Summary = std::get<0>(FuncInfo);
561475b51a7STeresa Johnson     auto Threshold = std::get<1>(FuncInfo);
56242418abaSMehdi Amini 
5631aafabf7SMehdi Amini     computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
564d68935c5STeresa Johnson                              Worklist, ImportList, ExportLists,
565d68935c5STeresa Johnson                              ImportThresholds);
566c8c55170SMehdi Amini   }
567cb9a82fcSTeresa Johnson 
568cb9a82fcSTeresa Johnson   // Print stats about functions considered but rejected for importing
569cb9a82fcSTeresa Johnson   // when requested.
570cb9a82fcSTeresa Johnson   if (PrintImportFailures) {
571cb9a82fcSTeresa Johnson     dbgs() << "Missed imports into module " << ModName << "\n";
572cb9a82fcSTeresa Johnson     for (auto &I : ImportThresholds) {
573cb9a82fcSTeresa Johnson       auto &ProcessedThreshold = std::get<0>(I.second);
574cb9a82fcSTeresa Johnson       auto &CalleeSummary = std::get<1>(I.second);
575cb9a82fcSTeresa Johnson       auto &FailureInfo = std::get<2>(I.second);
576cb9a82fcSTeresa Johnson       if (CalleeSummary)
577cb9a82fcSTeresa Johnson         continue; // We are going to import.
578cb9a82fcSTeresa Johnson       assert(FailureInfo);
579cb9a82fcSTeresa Johnson       FunctionSummary *FS = nullptr;
580cb9a82fcSTeresa Johnson       if (!FailureInfo->VI.getSummaryList().empty())
581cb9a82fcSTeresa Johnson         FS = dyn_cast<FunctionSummary>(
582cb9a82fcSTeresa Johnson             FailureInfo->VI.getSummaryList()[0]->getBaseObject());
583cb9a82fcSTeresa Johnson       dbgs() << FailureInfo->VI
584cb9a82fcSTeresa Johnson              << ": Reason = " << getFailureName(FailureInfo->Reason)
585cb9a82fcSTeresa Johnson              << ", Threshold = " << ProcessedThreshold
586cb9a82fcSTeresa Johnson              << ", Size = " << (FS ? (int)FS->instCount() : -1)
587cb9a82fcSTeresa Johnson              << ", MaxHotness = " << getHotnessName(FailureInfo->MaxHotness)
588cb9a82fcSTeresa Johnson              << ", Attempts = " << FailureInfo->Attempts << "\n";
589cb9a82fcSTeresa Johnson     }
590cb9a82fcSTeresa Johnson   }
59142418abaSMehdi Amini }
592ffe2e4aaSMehdi Amini 
59319e23874SEugene Leviant #ifndef NDEBUG
59419e23874SEugene Leviant static bool isGlobalVarSummary(const ModuleSummaryIndex &Index,
59519e23874SEugene Leviant                                GlobalValue::GUID G) {
59619e23874SEugene Leviant   if (const auto &VI = Index.getValueInfo(G)) {
59719e23874SEugene Leviant     auto SL = VI.getSummaryList();
59819e23874SEugene Leviant     if (!SL.empty())
59919e23874SEugene Leviant       return SL[0]->getSummaryKind() == GlobalValueSummary::GlobalVarKind;
60019e23874SEugene Leviant   }
60119e23874SEugene Leviant   return false;
60219e23874SEugene Leviant }
60319e23874SEugene Leviant 
60419e23874SEugene Leviant static GlobalValue::GUID getGUID(GlobalValue::GUID G) { return G; }
60519e23874SEugene Leviant 
60619e23874SEugene Leviant template <class T>
6071fc0da48SBenjamin Kramer static unsigned numGlobalVarSummaries(const ModuleSummaryIndex &Index,
6081fc0da48SBenjamin Kramer                                       T &Cont) {
60919e23874SEugene Leviant   unsigned NumGVS = 0;
61019e23874SEugene Leviant   for (auto &V : Cont)
61119e23874SEugene Leviant     if (isGlobalVarSummary(Index, getGUID(V)))
61219e23874SEugene Leviant       ++NumGVS;
61319e23874SEugene Leviant   return NumGVS;
61419e23874SEugene Leviant }
61519e23874SEugene Leviant #endif
61619e23874SEugene Leviant 
617c86af334STeresa Johnson /// Compute all the import and export for every module using the Index.
61801e32130SMehdi Amini void llvm::ComputeCrossModuleImport(
61901e32130SMehdi Amini     const ModuleSummaryIndex &Index,
620c851d216STeresa Johnson     const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
62101e32130SMehdi Amini     StringMap<FunctionImporter::ImportMapTy> &ImportLists,
62256584bbfSEvgeniy Stepanov     StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
62301e32130SMehdi Amini   // For each module that has function defined, compute the import/export lists.
6241aafabf7SMehdi Amini   for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
6259b490f10SMehdi Amini     auto &ImportList = ImportLists[DefinedGVSummaries.first()];
626d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "Computing import for Module '"
6271aafabf7SMehdi Amini                       << DefinedGVSummaries.first() << "'\n");
628cb9a82fcSTeresa Johnson     ComputeImportForModule(DefinedGVSummaries.second, Index,
629cb9a82fcSTeresa Johnson                            DefinedGVSummaries.first(), ImportList,
63056584bbfSEvgeniy Stepanov                            &ExportLists);
63101e32130SMehdi Amini   }
63201e32130SMehdi Amini 
633edddca22STeresa Johnson   // When computing imports we added all GUIDs referenced by anything
634edddca22STeresa Johnson   // imported from the module to its ExportList. Now we prune each ExportList
635edddca22STeresa Johnson   // of any not defined in that module. This is more efficient than checking
636edddca22STeresa Johnson   // while computing imports because some of the summary lists may be long
637edddca22STeresa Johnson   // due to linkonce (comdat) copies.
638edddca22STeresa Johnson   for (auto &ELI : ExportLists) {
639edddca22STeresa Johnson     const auto &DefinedGVSummaries =
640edddca22STeresa Johnson         ModuleToDefinedGVSummaries.lookup(ELI.first());
641edddca22STeresa Johnson     for (auto EI = ELI.second.begin(); EI != ELI.second.end();) {
642edddca22STeresa Johnson       if (!DefinedGVSummaries.count(*EI))
643edddca22STeresa Johnson         EI = ELI.second.erase(EI);
644edddca22STeresa Johnson       else
645edddca22STeresa Johnson         ++EI;
646edddca22STeresa Johnson     }
647edddca22STeresa Johnson   }
648edddca22STeresa Johnson 
64901e32130SMehdi Amini #ifndef NDEBUG
650d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
65101e32130SMehdi Amini                     << " modules:\n");
65201e32130SMehdi Amini   for (auto &ModuleImports : ImportLists) {
65301e32130SMehdi Amini     auto ModName = ModuleImports.first();
65401e32130SMehdi Amini     auto &Exports = ExportLists[ModName];
65519e23874SEugene Leviant     unsigned NumGVS = numGlobalVarSummaries(Index, Exports);
656d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << "* Module " << ModName << " exports "
65719e23874SEugene Leviant                       << Exports.size() - NumGVS << " functions and " << NumGVS
658d34e60caSNicola Zaghen                       << " vars. Imports from " << ModuleImports.second.size()
659d34e60caSNicola Zaghen                       << " modules.\n");
66001e32130SMehdi Amini     for (auto &Src : ModuleImports.second) {
66101e32130SMehdi Amini       auto SrcModName = Src.first();
66219e23874SEugene Leviant       unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second);
663d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod
66419e23874SEugene Leviant                         << " functions imported from " << SrcModName << "\n");
665d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod
666d34e60caSNicola Zaghen                         << " global vars imported from " << SrcModName << "\n");
66701e32130SMehdi Amini     }
66801e32130SMehdi Amini   }
66901e32130SMehdi Amini #endif
67001e32130SMehdi Amini }
67101e32130SMehdi Amini 
67281bbf742STeresa Johnson #ifndef NDEBUG
67319e23874SEugene Leviant static void dumpImportListForModule(const ModuleSummaryIndex &Index,
67419e23874SEugene Leviant                                     StringRef ModulePath,
67581bbf742STeresa Johnson                                     FunctionImporter::ImportMapTy &ImportList) {
676d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
67781bbf742STeresa Johnson                     << ImportList.size() << " modules.\n");
67881bbf742STeresa Johnson   for (auto &Src : ImportList) {
67981bbf742STeresa Johnson     auto SrcModName = Src.first();
68019e23874SEugene Leviant     unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second);
681d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod
68219e23874SEugene Leviant                       << " functions imported from " << SrcModName << "\n");
683d34e60caSNicola Zaghen     LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod << " vars imported from "
68481bbf742STeresa Johnson                       << SrcModName << "\n");
68581bbf742STeresa Johnson   }
68681bbf742STeresa Johnson }
68769b2de84STeresa Johnson #endif
68881bbf742STeresa Johnson 
689c86af334STeresa Johnson /// Compute all the imports for the given module in the Index.
690c86af334STeresa Johnson void llvm::ComputeCrossModuleImportForModule(
691c86af334STeresa Johnson     StringRef ModulePath, const ModuleSummaryIndex &Index,
692c86af334STeresa Johnson     FunctionImporter::ImportMapTy &ImportList) {
693c86af334STeresa Johnson   // Collect the list of functions this module defines.
694c86af334STeresa Johnson   // GUID -> Summary
695c851d216STeresa Johnson   GVSummaryMapTy FunctionSummaryMap;
69628e457bcSTeresa Johnson   Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
697c86af334STeresa Johnson 
698c86af334STeresa Johnson   // Compute the import list for this module.
699d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
700cb9a82fcSTeresa Johnson   ComputeImportForModule(FunctionSummaryMap, Index, ModulePath, ImportList);
701c86af334STeresa Johnson 
702c86af334STeresa Johnson #ifndef NDEBUG
70319e23874SEugene Leviant   dumpImportListForModule(Index, ModulePath, ImportList);
70481bbf742STeresa Johnson #endif
705c86af334STeresa Johnson }
70681bbf742STeresa Johnson 
70781bbf742STeresa Johnson // Mark all external summaries in Index for import into the given module.
70881bbf742STeresa Johnson // Used for distributed builds using a distributed index.
70981bbf742STeresa Johnson void llvm::ComputeCrossModuleImportForModuleFromIndex(
71081bbf742STeresa Johnson     StringRef ModulePath, const ModuleSummaryIndex &Index,
71181bbf742STeresa Johnson     FunctionImporter::ImportMapTy &ImportList) {
71281bbf742STeresa Johnson   for (auto &GlobalList : Index) {
71381bbf742STeresa Johnson     // Ignore entries for undefined references.
71481bbf742STeresa Johnson     if (GlobalList.second.SummaryList.empty())
71581bbf742STeresa Johnson       continue;
71681bbf742STeresa Johnson 
71781bbf742STeresa Johnson     auto GUID = GlobalList.first;
71881bbf742STeresa Johnson     assert(GlobalList.second.SummaryList.size() == 1 &&
71981bbf742STeresa Johnson            "Expected individual combined index to have one summary per GUID");
72081bbf742STeresa Johnson     auto &Summary = GlobalList.second.SummaryList[0];
72181bbf742STeresa Johnson     // Skip the summaries for the importing module. These are included to
72281bbf742STeresa Johnson     // e.g. record required linkage changes.
72381bbf742STeresa Johnson     if (Summary->modulePath() == ModulePath)
72481bbf742STeresa Johnson       continue;
725d68935c5STeresa Johnson     // Add an entry to provoke importing by thinBackend.
726d68935c5STeresa Johnson     ImportList[Summary->modulePath()].insert(GUID);
72781bbf742STeresa Johnson   }
72881bbf742STeresa Johnson #ifndef NDEBUG
72919e23874SEugene Leviant   dumpImportListForModule(Index, ModulePath, ImportList);
730c86af334STeresa Johnson #endif
731c86af334STeresa Johnson }
732c86af334STeresa Johnson 
73356584bbfSEvgeniy Stepanov void llvm::computeDeadSymbols(
73456584bbfSEvgeniy Stepanov     ModuleSummaryIndex &Index,
735eaf5172cSGeorge Rimar     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
736eaf5172cSGeorge Rimar     function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing) {
73756584bbfSEvgeniy Stepanov   assert(!Index.withGlobalValueDeadStripping());
7386c475a75STeresa Johnson   if (!ComputeDead)
73956584bbfSEvgeniy Stepanov     return;
7406c475a75STeresa Johnson   if (GUIDPreservedSymbols.empty())
7416c475a75STeresa Johnson     // Don't do anything when nothing is live, this is friendly with tests.
74256584bbfSEvgeniy Stepanov     return;
74356584bbfSEvgeniy Stepanov   unsigned LiveSymbols = 0;
7449667b91bSPeter Collingbourne   SmallVector<ValueInfo, 128> Worklist;
7459667b91bSPeter Collingbourne   Worklist.reserve(GUIDPreservedSymbols.size() * 2);
7469667b91bSPeter Collingbourne   for (auto GUID : GUIDPreservedSymbols) {
7479667b91bSPeter Collingbourne     ValueInfo VI = Index.getValueInfo(GUID);
7489667b91bSPeter Collingbourne     if (!VI)
7499667b91bSPeter Collingbourne       continue;
75056584bbfSEvgeniy Stepanov     for (auto &S : VI.getSummaryList())
75156584bbfSEvgeniy Stepanov       S->setLive(true);
7526c475a75STeresa Johnson   }
75356584bbfSEvgeniy Stepanov 
7546c475a75STeresa Johnson   // Add values flagged in the index as live roots to the worklist.
7557e7b13d0STeresa Johnson   for (const auto &Entry : Index) {
7567e7b13d0STeresa Johnson     auto VI = Index.getValueInfo(Entry);
75756584bbfSEvgeniy Stepanov     for (auto &S : Entry.second.SummaryList)
75856584bbfSEvgeniy Stepanov       if (S->isLive()) {
7597e7b13d0STeresa Johnson         LLVM_DEBUG(dbgs() << "Live root: " << VI << "\n");
7607e7b13d0STeresa Johnson         Worklist.push_back(VI);
76156584bbfSEvgeniy Stepanov         ++LiveSymbols;
76256584bbfSEvgeniy Stepanov         break;
7636c475a75STeresa Johnson       }
7647e7b13d0STeresa Johnson   }
7656c475a75STeresa Johnson 
76656584bbfSEvgeniy Stepanov   // Make value live and add it to the worklist if it was not live before.
767*ea314fd4STeresa Johnson   auto visit = [&](ValueInfo VI, bool IsAliasee) {
7681958083dSTeresa Johnson     // FIXME: If we knew which edges were created for indirect call profiles,
7691958083dSTeresa Johnson     // we could skip them here. Any that are live should be reached via
7701958083dSTeresa Johnson     // other edges, e.g. reference edges. Otherwise, using a profile collected
7711958083dSTeresa Johnson     // on a slightly different binary might provoke preserving, importing
7721958083dSTeresa Johnson     // and ultimately promoting calls to functions not linked into this
7731958083dSTeresa Johnson     // binary, which increases the binary size unnecessarily. Note that
7741958083dSTeresa Johnson     // if this code changes, the importer needs to change so that edges
7751958083dSTeresa Johnson     // to functions marked dead are skipped.
7761958083dSTeresa Johnson     VI = updateValueInfoForIndirectCalls(Index, VI);
7771958083dSTeresa Johnson     if (!VI)
7781958083dSTeresa Johnson       return;
77933e3b4b9SXin Tong 
7805b2f6a1bSTeresa Johnson     if (llvm::any_of(VI.getSummaryList(),
78133e3b4b9SXin Tong                      [](const std::unique_ptr<llvm::GlobalValueSummary> &S) {
78233e3b4b9SXin Tong                        return S->isLive();
78333e3b4b9SXin Tong                      }))
784f625118eSTeresa Johnson       return;
785eaf5172cSGeorge Rimar 
786aab60006SVlad Tsyrklevich     // We only keep live symbols that are known to be non-prevailing if any are
787bfdad33bSXin Tong     // available_externally, linkonceodr, weakodr. Those symbols are discarded
788bfdad33bSXin Tong     // later in the EliminateAvailableExternally pass and setting them to
789bfdad33bSXin Tong     // not-live could break downstreams users of liveness information (PR36483)
790bfdad33bSXin Tong     // or limit optimization opportunities.
791aab60006SVlad Tsyrklevich     if (isPrevailing(VI.getGUID()) == PrevailingType::No) {
792bfdad33bSXin Tong       bool KeepAliveLinkage = false;
793aab60006SVlad Tsyrklevich       bool Interposable = false;
794aab60006SVlad Tsyrklevich       for (auto &S : VI.getSummaryList()) {
795bfdad33bSXin Tong         if (S->linkage() == GlobalValue::AvailableExternallyLinkage ||
796bfdad33bSXin Tong             S->linkage() == GlobalValue::WeakODRLinkage ||
797bfdad33bSXin Tong             S->linkage() == GlobalValue::LinkOnceODRLinkage)
798bfdad33bSXin Tong           KeepAliveLinkage = true;
799aab60006SVlad Tsyrklevich         else if (GlobalValue::isInterposableLinkage(S->linkage()))
800aab60006SVlad Tsyrklevich           Interposable = true;
801aab60006SVlad Tsyrklevich       }
802aab60006SVlad Tsyrklevich 
803*ea314fd4STeresa Johnson       if (!IsAliasee) {
804bfdad33bSXin Tong         if (!KeepAliveLinkage)
805eaf5172cSGeorge Rimar           return;
806eaf5172cSGeorge Rimar 
807aab60006SVlad Tsyrklevich         if (Interposable)
808bfdad33bSXin Tong           report_fatal_error(
809*ea314fd4STeresa Johnson               "Interposable and available_externally/linkonce_odr/weak_odr "
810*ea314fd4STeresa Johnson               "symbol");
811*ea314fd4STeresa Johnson       }
812aab60006SVlad Tsyrklevich     }
813aab60006SVlad Tsyrklevich 
814f625118eSTeresa Johnson     for (auto &S : VI.getSummaryList())
81556584bbfSEvgeniy Stepanov       S->setLive(true);
81656584bbfSEvgeniy Stepanov     ++LiveSymbols;
81756584bbfSEvgeniy Stepanov     Worklist.push_back(VI);
81856584bbfSEvgeniy Stepanov   };
81956584bbfSEvgeniy Stepanov 
8206c475a75STeresa Johnson   while (!Worklist.empty()) {
8219667b91bSPeter Collingbourne     auto VI = Worklist.pop_back_val();
8229667b91bSPeter Collingbourne     for (auto &Summary : VI.getSummaryList()) {
8235b2f6a1bSTeresa Johnson       if (auto *AS = dyn_cast<AliasSummary>(Summary.get())) {
8245b2f6a1bSTeresa Johnson         // If this is an alias, visit the aliasee VI to ensure that all copies
8255b2f6a1bSTeresa Johnson         // are marked live and it is added to the worklist for further
8265b2f6a1bSTeresa Johnson         // processing of its references.
827*ea314fd4STeresa Johnson         visit(AS->getAliaseeVI(), true);
8285b2f6a1bSTeresa Johnson         continue;
8295b2f6a1bSTeresa Johnson       }
8305b2f6a1bSTeresa Johnson 
8315b2f6a1bSTeresa Johnson       Summary->setLive(true);
8325b2f6a1bSTeresa Johnson       for (auto Ref : Summary->refs())
833*ea314fd4STeresa Johnson         visit(Ref, false);
8345b2f6a1bSTeresa Johnson       if (auto *FS = dyn_cast<FunctionSummary>(Summary.get()))
83556584bbfSEvgeniy Stepanov         for (auto Call : FS->calls())
836*ea314fd4STeresa Johnson           visit(Call.first, false);
8376c475a75STeresa Johnson     }
8386c475a75STeresa Johnson   }
83956584bbfSEvgeniy Stepanov   Index.setWithGlobalValueDeadStripping();
84056584bbfSEvgeniy Stepanov 
84156584bbfSEvgeniy Stepanov   unsigned DeadSymbols = Index.size() - LiveSymbols;
842d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols
84356584bbfSEvgeniy Stepanov                     << " symbols Dead \n");
84456584bbfSEvgeniy Stepanov   NumDeadSymbols += DeadSymbols;
84556584bbfSEvgeniy Stepanov   NumLiveSymbols += LiveSymbols;
8466c475a75STeresa Johnson }
8476c475a75STeresa Johnson 
848bf46e741SEugene Leviant // Compute dead symbols and propagate constants in combined index.
849bf46e741SEugene Leviant void llvm::computeDeadSymbolsWithConstProp(
850bf46e741SEugene Leviant     ModuleSummaryIndex &Index,
851bf46e741SEugene Leviant     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
852bf46e741SEugene Leviant     function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing,
853bf46e741SEugene Leviant     bool ImportEnabled) {
854bf46e741SEugene Leviant   computeDeadSymbols(Index, GUIDPreservedSymbols, isPrevailing);
855bf46e741SEugene Leviant   if (ImportEnabled) {
8563aef3528SEugene Leviant     Index.propagateAttributes(GUIDPreservedSymbols);
857bf46e741SEugene Leviant   } else {
8583aef3528SEugene Leviant     // If import is disabled we should drop read/write-only attribute
859bf46e741SEugene Leviant     // from all summaries to prevent internalization.
860bf46e741SEugene Leviant     for (auto &P : Index)
861bf46e741SEugene Leviant       for (auto &S : P.second.SummaryList)
8623aef3528SEugene Leviant         if (auto *GVS = dyn_cast<GlobalVarSummary>(S.get())) {
863bf46e741SEugene Leviant           GVS->setReadOnly(false);
8643aef3528SEugene Leviant           GVS->setWriteOnly(false);
8653aef3528SEugene Leviant         }
866bf46e741SEugene Leviant   }
867bf46e741SEugene Leviant }
868bf46e741SEugene Leviant 
86984174c37STeresa Johnson /// Compute the set of summaries needed for a ThinLTO backend compilation of
87084174c37STeresa Johnson /// \p ModulePath.
87184174c37STeresa Johnson void llvm::gatherImportedSummariesForModule(
87284174c37STeresa Johnson     StringRef ModulePath,
87384174c37STeresa Johnson     const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
874cdbcbf74SMehdi Amini     const FunctionImporter::ImportMapTy &ImportList,
87584174c37STeresa Johnson     std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
87684174c37STeresa Johnson   // Include all summaries from the importing module.
87784174c37STeresa Johnson   ModuleToSummariesForIndex[ModulePath] =
87884174c37STeresa Johnson       ModuleToDefinedGVSummaries.lookup(ModulePath);
87984174c37STeresa Johnson   // Include summaries for imports.
88088c491ddSMehdi Amini   for (auto &ILI : ImportList) {
88184174c37STeresa Johnson     auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
88284174c37STeresa Johnson     const auto &DefinedGVSummaries =
88384174c37STeresa Johnson         ModuleToDefinedGVSummaries.lookup(ILI.first());
88484174c37STeresa Johnson     for (auto &GI : ILI.second) {
885d68935c5STeresa Johnson       const auto &DS = DefinedGVSummaries.find(GI);
88684174c37STeresa Johnson       assert(DS != DefinedGVSummaries.end() &&
88784174c37STeresa Johnson              "Expected a defined summary for imported global value");
888d68935c5STeresa Johnson       SummariesForIndex[GI] = DS->second;
88984174c37STeresa Johnson     }
89084174c37STeresa Johnson   }
89184174c37STeresa Johnson }
89284174c37STeresa Johnson 
8938570fe47STeresa Johnson /// Emit the files \p ModulePath will import from into \p OutputFilename.
894c0320ef4STeresa Johnson std::error_code llvm::EmitImportsFiles(
895c0320ef4STeresa Johnson     StringRef ModulePath, StringRef OutputFilename,
896c0320ef4STeresa Johnson     const std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
8978570fe47STeresa Johnson   std::error_code EC;
898d9b948b6SFangrui Song   raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::OF_None);
8998570fe47STeresa Johnson   if (EC)
9008570fe47STeresa Johnson     return EC;
901c0320ef4STeresa Johnson   for (auto &ILI : ModuleToSummariesForIndex)
902c0320ef4STeresa Johnson     // The ModuleToSummariesForIndex map includes an entry for the current
903c0320ef4STeresa Johnson     // Module (needed for writing out the index files). We don't want to
904c0320ef4STeresa Johnson     // include it in the imports file, however, so filter it out.
905c0320ef4STeresa Johnson     if (ILI.first != ModulePath)
906c0320ef4STeresa Johnson       ImportsOS << ILI.first << "\n";
9078570fe47STeresa Johnson   return std::error_code();
9088570fe47STeresa Johnson }
9098570fe47STeresa Johnson 
9105a95c477STeresa Johnson bool llvm::convertToDeclaration(GlobalValue &GV) {
911d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName()
912d34e60caSNicola Zaghen                     << "\n");
9134566c6dbSTeresa Johnson   if (Function *F = dyn_cast<Function>(&GV)) {
9144566c6dbSTeresa Johnson     F->deleteBody();
9154566c6dbSTeresa Johnson     F->clearMetadata();
9167873669bSPeter Collingbourne     F->setComdat(nullptr);
9174566c6dbSTeresa Johnson   } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
9184566c6dbSTeresa Johnson     V->setInitializer(nullptr);
9194566c6dbSTeresa Johnson     V->setLinkage(GlobalValue::ExternalLinkage);
9204566c6dbSTeresa Johnson     V->clearMetadata();
9217873669bSPeter Collingbourne     V->setComdat(nullptr);
9225a95c477STeresa Johnson   } else {
9235a95c477STeresa Johnson     GlobalValue *NewGV;
9245a95c477STeresa Johnson     if (GV.getValueType()->isFunctionTy())
9255a95c477STeresa Johnson       NewGV =
9265a95c477STeresa Johnson           Function::Create(cast<FunctionType>(GV.getValueType()),
927f920da00SDylan McKay                            GlobalValue::ExternalLinkage, GV.getAddressSpace(),
928f920da00SDylan McKay                            "", GV.getParent());
9295a95c477STeresa Johnson     else
9305a95c477STeresa Johnson       NewGV =
9315a95c477STeresa Johnson           new GlobalVariable(*GV.getParent(), GV.getValueType(),
9325a95c477STeresa Johnson                              /*isConstant*/ false, GlobalValue::ExternalLinkage,
9335a95c477STeresa Johnson                              /*init*/ nullptr, "",
9345a95c477STeresa Johnson                              /*insertbefore*/ nullptr, GV.getThreadLocalMode(),
9355a95c477STeresa Johnson                              GV.getType()->getAddressSpace());
9365a95c477STeresa Johnson     NewGV->takeName(&GV);
9375a95c477STeresa Johnson     GV.replaceAllUsesWith(NewGV);
9385a95c477STeresa Johnson     return false;
9395a95c477STeresa Johnson   }
9405a95c477STeresa Johnson   return true;
941eaf5172cSGeorge Rimar }
9424566c6dbSTeresa Johnson 
943e61652a3SPirama Arumuga Nainar /// Fixup prevailing symbol linkages in \p TheModule based on summary analysis.
944e61652a3SPirama Arumuga Nainar void llvm::thinLTOResolvePrevailingInModule(
945eaf5172cSGeorge Rimar     Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
94604c9a2d6STeresa Johnson   auto updateLinkage = [&](GlobalValue &GV) {
94704c9a2d6STeresa Johnson     // See if the global summary analysis computed a new resolved linkage.
94804c9a2d6STeresa Johnson     const auto &GS = DefinedGlobals.find(GV.getGUID());
94904c9a2d6STeresa Johnson     if (GS == DefinedGlobals.end())
95004c9a2d6STeresa Johnson       return;
95104c9a2d6STeresa Johnson     auto NewLinkage = GS->second->linkage();
95204c9a2d6STeresa Johnson     if (NewLinkage == GV.getLinkage())
95304c9a2d6STeresa Johnson       return;
954e61652a3SPirama Arumuga Nainar     if (GlobalValue::isLocalLinkage(GV.getLinkage()) ||
955e61652a3SPirama Arumuga Nainar         // In case it was dead and already converted to declaration.
956e61652a3SPirama Arumuga Nainar         GV.isDeclaration())
9576a5fbe52SDavide Italiano       return;
958*ea314fd4STeresa Johnson 
9594566c6dbSTeresa Johnson     // Check for a non-prevailing def that has interposable linkage
9604566c6dbSTeresa Johnson     // (e.g. non-odr weak or linkonce). In that case we can't simply
9614566c6dbSTeresa Johnson     // convert to available_externally, since it would lose the
9624566c6dbSTeresa Johnson     // interposable property and possibly get inlined. Simply drop
9634566c6dbSTeresa Johnson     // the definition in that case.
9644566c6dbSTeresa Johnson     if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) &&
9655a95c477STeresa Johnson         GlobalValue::isInterposableLinkage(GV.getLinkage())) {
9665a95c477STeresa Johnson       if (!convertToDeclaration(GV))
9675a95c477STeresa Johnson         // FIXME: Change this to collect replaced GVs and later erase
968e61652a3SPirama Arumuga Nainar         // them from the parent module once thinLTOResolvePrevailingGUID is
9695a95c477STeresa Johnson         // changed to enable this for aliases.
9705a95c477STeresa Johnson         llvm_unreachable("Expected GV to be converted");
9715a95c477STeresa Johnson     } else {
97237b80122STeresa Johnson       // If all copies of the original symbol had global unnamed addr and
97337b80122STeresa Johnson       // linkonce_odr linkage, it should be an auto hide symbol. In that case
97437b80122STeresa Johnson       // the thin link would have marked it as CanAutoHide. Add hidden visibility
97537b80122STeresa Johnson       // to the symbol to preserve the property.
97637b80122STeresa Johnson       if (NewLinkage == GlobalValue::WeakODRLinkage &&
97737b80122STeresa Johnson           GS->second->canAutoHide()) {
97837b80122STeresa Johnson         assert(GV.hasLinkOnceODRLinkage() && GV.hasGlobalUnnamedAddr());
97933ba93c2SSteven Wu         GV.setVisibility(GlobalValue::HiddenVisibility);
98037b80122STeresa Johnson       }
98133ba93c2SSteven Wu 
982d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName()
983d34e60caSNicola Zaghen                         << "` from " << GV.getLinkage() << " to " << NewLinkage
984d34e60caSNicola Zaghen                         << "\n");
98504c9a2d6STeresa Johnson       GV.setLinkage(NewLinkage);
9864566c6dbSTeresa Johnson     }
9874566c6dbSTeresa Johnson     // Remove declarations from comdats, including available_externally
9886107a419STeresa Johnson     // as this is a declaration for the linker, and will be dropped eventually.
9896107a419STeresa Johnson     // It is illegal for comdats to contain declarations.
9906107a419STeresa Johnson     auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
9914566c6dbSTeresa Johnson     if (GO && GO->isDeclarationForLinker() && GO->hasComdat())
9926107a419STeresa Johnson       GO->setComdat(nullptr);
99304c9a2d6STeresa Johnson   };
99404c9a2d6STeresa Johnson 
99504c9a2d6STeresa Johnson   // Process functions and global now
99604c9a2d6STeresa Johnson   for (auto &GV : TheModule)
99704c9a2d6STeresa Johnson     updateLinkage(GV);
99804c9a2d6STeresa Johnson   for (auto &GV : TheModule.globals())
99904c9a2d6STeresa Johnson     updateLinkage(GV);
100004c9a2d6STeresa Johnson   for (auto &GV : TheModule.aliases())
100104c9a2d6STeresa Johnson     updateLinkage(GV);
100204c9a2d6STeresa Johnson }
100304c9a2d6STeresa Johnson 
100404c9a2d6STeresa Johnson /// Run internalization on \p TheModule based on symmary analysis.
100504c9a2d6STeresa Johnson void llvm::thinLTOInternalizeModule(Module &TheModule,
100604c9a2d6STeresa Johnson                                     const GVSummaryMapTy &DefinedGlobals) {
100704c9a2d6STeresa Johnson   // Declare a callback for the internalize pass that will ask for every
100804c9a2d6STeresa Johnson   // candidate GlobalValue if it can be internalized or not.
100904c9a2d6STeresa Johnson   auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
101004c9a2d6STeresa Johnson     // Lookup the linkage recorded in the summaries during global analysis.
1011c3d677f9SPeter Collingbourne     auto GS = DefinedGlobals.find(GV.getGUID());
101204c9a2d6STeresa Johnson     if (GS == DefinedGlobals.end()) {
101304c9a2d6STeresa Johnson       // Must have been promoted (possibly conservatively). Find original
101404c9a2d6STeresa Johnson       // name so that we can access the correct summary and see if it can
101504c9a2d6STeresa Johnson       // be internalized again.
101604c9a2d6STeresa Johnson       // FIXME: Eventually we should control promotion instead of promoting
101704c9a2d6STeresa Johnson       // and internalizing again.
101804c9a2d6STeresa Johnson       StringRef OrigName =
101904c9a2d6STeresa Johnson           ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
102004c9a2d6STeresa Johnson       std::string OrigId = GlobalValue::getGlobalIdentifier(
102104c9a2d6STeresa Johnson           OrigName, GlobalValue::InternalLinkage,
102204c9a2d6STeresa Johnson           TheModule.getSourceFileName());
1023c3d677f9SPeter Collingbourne       GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
10247ab1f692STeresa Johnson       if (GS == DefinedGlobals.end()) {
10257ab1f692STeresa Johnson         // Also check the original non-promoted non-globalized name. In some
10267ab1f692STeresa Johnson         // cases a preempted weak value is linked in as a local copy because
10277ab1f692STeresa Johnson         // it is referenced by an alias (IRLinker::linkGlobalValueProto).
10287ab1f692STeresa Johnson         // In that case, since it was originally not a local value, it was
10297ab1f692STeresa Johnson         // recorded in the index using the original name.
10307ab1f692STeresa Johnson         // FIXME: This may not be needed once PR27866 is fixed.
1031c3d677f9SPeter Collingbourne         GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
103204c9a2d6STeresa Johnson         assert(GS != DefinedGlobals.end());
10337ab1f692STeresa Johnson       }
1034c3d677f9SPeter Collingbourne     }
1035c3d677f9SPeter Collingbourne     return !GlobalValue::isLocalLinkage(GS->second->linkage());
103604c9a2d6STeresa Johnson   };
103704c9a2d6STeresa Johnson 
103804c9a2d6STeresa Johnson   // FIXME: See if we can just internalize directly here via linkage changes
103904c9a2d6STeresa Johnson   // based on the index, rather than invoking internalizeModule.
1040e9ea08a0SEugene Zelenko   internalizeModule(TheModule, MustPreserveGV);
104104c9a2d6STeresa Johnson }
104204c9a2d6STeresa Johnson 
104381bbf742STeresa Johnson /// Make alias a clone of its aliasee.
104481bbf742STeresa Johnson static Function *replaceAliasWithAliasee(Module *SrcModule, GlobalAlias *GA) {
104581bbf742STeresa Johnson   Function *Fn = cast<Function>(GA->getBaseObject());
104681bbf742STeresa Johnson 
104781bbf742STeresa Johnson   ValueToValueMapTy VMap;
104881bbf742STeresa Johnson   Function *NewFn = CloneFunction(Fn, VMap);
10495b2088d1STeresa Johnson   // Clone should use the original alias's linkage, visibility and name, and we
10505b2088d1STeresa Johnson   // ensure all uses of alias instead use the new clone (casted if necessary).
105181bbf742STeresa Johnson   NewFn->setLinkage(GA->getLinkage());
10525b2088d1STeresa Johnson   NewFn->setVisibility(GA->getVisibility());
105381bbf742STeresa Johnson   GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewFn, GA->getType()));
105481bbf742STeresa Johnson   NewFn->takeName(GA);
105581bbf742STeresa Johnson   return NewFn;
105681bbf742STeresa Johnson }
105781bbf742STeresa Johnson 
1058bf46e741SEugene Leviant // Internalize values that we marked with specific attribute
1059bf46e741SEugene Leviant // in processGlobalForThinLTO.
10603aef3528SEugene Leviant static void internalizeGVsAfterImport(Module &M) {
1061bf46e741SEugene Leviant   for (auto &GV : M.globals())
1062bf46e741SEugene Leviant     // Skip GVs which have been converted to declarations
1063bf46e741SEugene Leviant     // by dropDeadSymbols.
1064bf46e741SEugene Leviant     if (!GV.isDeclaration() && GV.hasAttribute("thinlto-internalize")) {
1065bf46e741SEugene Leviant       GV.setLinkage(GlobalValue::InternalLinkage);
1066bf46e741SEugene Leviant       GV.setVisibility(GlobalValue::DefaultVisibility);
1067bf46e741SEugene Leviant     }
1068bf46e741SEugene Leviant }
1069bf46e741SEugene Leviant 
1070c8c55170SMehdi Amini // Automatically import functions in Module \p DestModule based on the summaries
1071c8c55170SMehdi Amini // index.
10727f00d0a1SPeter Collingbourne Expected<bool> FunctionImporter::importFunctions(
107366043797SAdrian Prantl     Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
1074d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Starting import for Module "
1075311fef6eSMehdi Amini                     << DestModule.getModuleIdentifier() << "\n");
107619e23874SEugene Leviant   unsigned ImportedCount = 0, ImportedGVCount = 0;
1077c8c55170SMehdi Amini 
10786d8f817fSPeter Collingbourne   IRMover Mover(DestModule);
10797e88d0daSMehdi Amini   // Do the actual import of functions now, one Module at a time
108001e32130SMehdi Amini   std::set<StringRef> ModuleNameOrderedList;
108101e32130SMehdi Amini   for (auto &FunctionsToImportPerModule : ImportList) {
108201e32130SMehdi Amini     ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
108301e32130SMehdi Amini   }
108401e32130SMehdi Amini   for (auto &Name : ModuleNameOrderedList) {
10857e88d0daSMehdi Amini     // Get the module for the import
108601e32130SMehdi Amini     const auto &FunctionsToImportPerModule = ImportList.find(Name);
108701e32130SMehdi Amini     assert(FunctionsToImportPerModule != ImportList.end());
1088d9445c49SPeter Collingbourne     Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
1089d9445c49SPeter Collingbourne     if (!SrcModuleOrErr)
1090d9445c49SPeter Collingbourne       return SrcModuleOrErr.takeError();
1091d9445c49SPeter Collingbourne     std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
10927e88d0daSMehdi Amini     assert(&DestModule.getContext() == &SrcModule->getContext() &&
10937e88d0daSMehdi Amini            "Context mismatch");
10947e88d0daSMehdi Amini 
10956cba37ceSTeresa Johnson     // If modules were created with lazy metadata loading, materialize it
10966cba37ceSTeresa Johnson     // now, before linking it (otherwise this will be a noop).
10977f00d0a1SPeter Collingbourne     if (Error Err = SrcModule->materializeMetadata())
10987f00d0a1SPeter Collingbourne       return std::move(Err);
1099e5a61917STeresa Johnson 
110001e32130SMehdi Amini     auto &ImportGUIDs = FunctionsToImportPerModule->second;
110101e32130SMehdi Amini     // Find the globals to import
11026d8f817fSPeter Collingbourne     SetVector<GlobalValue *> GlobalsToImport;
11031f685e01SPiotr Padlewski     for (Function &F : *SrcModule) {
11041f685e01SPiotr Padlewski       if (!F.hasName())
11050beb858eSTeresa Johnson         continue;
11061f685e01SPiotr Padlewski       auto GUID = F.getGUID();
11070beb858eSTeresa Johnson       auto Import = ImportGUIDs.count(GUID);
1108d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function "
1109d34e60caSNicola Zaghen                         << GUID << " " << F.getName() << " from "
1110aeb1e59bSMehdi Amini                         << SrcModule->getSourceFileName() << "\n");
11110beb858eSTeresa Johnson       if (Import) {
11127f00d0a1SPeter Collingbourne         if (Error Err = F.materialize())
11137f00d0a1SPeter Collingbourne           return std::move(Err);
11143b776128SPiotr Padlewski         if (EnableImportMetadata) {
11156deaa6afSPiotr Padlewski           // Add 'thinlto_src_module' metadata for statistics and debugging.
11163b776128SPiotr Padlewski           F.setMetadata(
11173b776128SPiotr Padlewski               "thinlto_src_module",
1118e9ea08a0SEugene Zelenko               MDNode::get(DestModule.getContext(),
1119e9ea08a0SEugene Zelenko                           {MDString::get(DestModule.getContext(),
11206deaa6afSPiotr Padlewski                                          SrcModule->getSourceFileName())}));
11213b776128SPiotr Padlewski         }
11221f685e01SPiotr Padlewski         GlobalsToImport.insert(&F);
112301e32130SMehdi Amini       }
112401e32130SMehdi Amini     }
11251f685e01SPiotr Padlewski     for (GlobalVariable &GV : SrcModule->globals()) {
11262d28f7aaSMehdi Amini       if (!GV.hasName())
11272d28f7aaSMehdi Amini         continue;
11282d28f7aaSMehdi Amini       auto GUID = GV.getGUID();
11292d28f7aaSMehdi Amini       auto Import = ImportGUIDs.count(GUID);
1130d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global "
1131d34e60caSNicola Zaghen                         << GUID << " " << GV.getName() << " from "
1132aeb1e59bSMehdi Amini                         << SrcModule->getSourceFileName() << "\n");
11332d28f7aaSMehdi Amini       if (Import) {
11347f00d0a1SPeter Collingbourne         if (Error Err = GV.materialize())
11357f00d0a1SPeter Collingbourne           return std::move(Err);
113619e23874SEugene Leviant         ImportedGVCount += GlobalsToImport.insert(&GV);
11372d28f7aaSMehdi Amini       }
11382d28f7aaSMehdi Amini     }
11391f685e01SPiotr Padlewski     for (GlobalAlias &GA : SrcModule->aliases()) {
11401f685e01SPiotr Padlewski       if (!GA.hasName())
114101e32130SMehdi Amini         continue;
11421f685e01SPiotr Padlewski       auto GUID = GA.getGUID();
114381bbf742STeresa Johnson       auto Import = ImportGUIDs.count(GUID);
1144d34e60caSNicola Zaghen       LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias "
1145d34e60caSNicola Zaghen                         << GUID << " " << GA.getName() << " from "
1146aeb1e59bSMehdi Amini                         << SrcModule->getSourceFileName() << "\n");
114781bbf742STeresa Johnson       if (Import) {
114881bbf742STeresa Johnson         if (Error Err = GA.materialize())
114981bbf742STeresa Johnson           return std::move(Err);
115081bbf742STeresa Johnson         // Import alias as a copy of its aliasee.
115181bbf742STeresa Johnson         GlobalObject *Base = GA.getBaseObject();
115281bbf742STeresa Johnson         if (Error Err = Base->materialize())
115381bbf742STeresa Johnson           return std::move(Err);
115481bbf742STeresa Johnson         auto *Fn = replaceAliasWithAliasee(SrcModule.get(), &GA);
1155d34e60caSNicola Zaghen         LLVM_DEBUG(dbgs() << "Is importing aliasee fn " << Base->getGUID()
115681bbf742STeresa Johnson                           << " " << Base->getName() << " from "
115781bbf742STeresa Johnson                           << SrcModule->getSourceFileName() << "\n");
115881bbf742STeresa Johnson         if (EnableImportMetadata) {
115981bbf742STeresa Johnson           // Add 'thinlto_src_module' metadata for statistics and debugging.
116081bbf742STeresa Johnson           Fn->setMetadata(
116181bbf742STeresa Johnson               "thinlto_src_module",
116281bbf742STeresa Johnson               MDNode::get(DestModule.getContext(),
116381bbf742STeresa Johnson                           {MDString::get(DestModule.getContext(),
116481bbf742STeresa Johnson                                          SrcModule->getSourceFileName())}));
116501e32130SMehdi Amini         }
116681bbf742STeresa Johnson         GlobalsToImport.insert(Fn);
116781bbf742STeresa Johnson       }
116881bbf742STeresa Johnson     }
116901e32130SMehdi Amini 
117019ef4fadSMehdi Amini     // Upgrade debug info after we're done materializing all the globals and we
117119ef4fadSMehdi Amini     // have loaded all the required metadata!
117219ef4fadSMehdi Amini     UpgradeDebugInfo(*SrcModule);
117319ef4fadSMehdi Amini 
11747e88d0daSMehdi Amini     // Link in the specified functions.
117501e32130SMehdi Amini     if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
11768d05185aSMehdi Amini       return true;
11778d05185aSMehdi Amini 
1178d29478f7STeresa Johnson     if (PrintImports) {
1179d29478f7STeresa Johnson       for (const auto *GV : GlobalsToImport)
1180d29478f7STeresa Johnson         dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
1181d29478f7STeresa Johnson                << " from " << SrcModule->getSourceFileName() << "\n";
1182d29478f7STeresa Johnson     }
1183d29478f7STeresa Johnson 
11846d8f817fSPeter Collingbourne     if (Mover.move(std::move(SrcModule), GlobalsToImport.getArrayRef(),
11856d8f817fSPeter Collingbourne                    [](GlobalValue &, IRMover::ValueAdder) {},
1186e6fd9ff9SPeter Collingbourne                    /*IsPerformingImport=*/true))
11877e88d0daSMehdi Amini       report_fatal_error("Function Import: link error");
11887e88d0daSMehdi Amini 
118901e32130SMehdi Amini     ImportedCount += GlobalsToImport.size();
11906c475a75STeresa Johnson     NumImportedModules++;
11917e88d0daSMehdi Amini   }
1192e5a61917STeresa Johnson 
11933aef3528SEugene Leviant   internalizeGVsAfterImport(DestModule);
1194bf46e741SEugene Leviant 
119519e23874SEugene Leviant   NumImportedFunctions += (ImportedCount - ImportedGVCount);
119619e23874SEugene Leviant   NumImportedGlobalVars += ImportedGVCount;
1197d29478f7STeresa Johnson 
1198d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Imported " << ImportedCount - ImportedGVCount
1199d34e60caSNicola Zaghen                     << " functions for Module "
1200d34e60caSNicola Zaghen                     << DestModule.getModuleIdentifier() << "\n");
1201d34e60caSNicola Zaghen   LLVM_DEBUG(dbgs() << "Imported " << ImportedGVCount
120219e23874SEugene Leviant                     << " global variables for Module "
1203c8c55170SMehdi Amini                     << DestModule.getModuleIdentifier() << "\n");
1204c8c55170SMehdi Amini   return ImportedCount;
120542418abaSMehdi Amini }
120642418abaSMehdi Amini 
1207598bd2a2SPeter Collingbourne static bool doImportingForModule(Module &M) {
1208598bd2a2SPeter Collingbourne   if (SummaryFile.empty())
1209598bd2a2SPeter Collingbourne     report_fatal_error("error: -function-import requires -summary-file\n");
12106de481a3SPeter Collingbourne   Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
12116de481a3SPeter Collingbourne       getModuleSummaryIndexForFile(SummaryFile);
12126de481a3SPeter Collingbourne   if (!IndexPtrOrErr) {
12136de481a3SPeter Collingbourne     logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
12146de481a3SPeter Collingbourne                           "Error loading file '" + SummaryFile + "': ");
121542418abaSMehdi Amini     return false;
121642418abaSMehdi Amini   }
1217598bd2a2SPeter Collingbourne   std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
121842418abaSMehdi Amini 
1219c86af334STeresa Johnson   // First step is collecting the import list.
1220c86af334STeresa Johnson   FunctionImporter::ImportMapTy ImportList;
122181bbf742STeresa Johnson   // If requested, simply import all functions in the index. This is used
122281bbf742STeresa Johnson   // when testing distributed backend handling via the opt tool, when
122381bbf742STeresa Johnson   // we have distributed indexes containing exactly the summaries to import.
122481bbf742STeresa Johnson   if (ImportAllIndex)
122581bbf742STeresa Johnson     ComputeCrossModuleImportForModuleFromIndex(M.getModuleIdentifier(), *Index,
122681bbf742STeresa Johnson                                                ImportList);
122781bbf742STeresa Johnson   else
1228c86af334STeresa Johnson     ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
1229c86af334STeresa Johnson                                       ImportList);
123001e32130SMehdi Amini 
12314fef68cbSTeresa Johnson   // Conservatively mark all internal values as promoted. This interface is
12324fef68cbSTeresa Johnson   // only used when doing importing via the function importing pass. The pass
12334fef68cbSTeresa Johnson   // is only enabled when testing importing via the 'opt' tool, which does
12344fef68cbSTeresa Johnson   // not do the ThinLink that would normally determine what values to promote.
12354fef68cbSTeresa Johnson   for (auto &I : *Index) {
12369667b91bSPeter Collingbourne     for (auto &S : I.second.SummaryList) {
12374fef68cbSTeresa Johnson       if (GlobalValue::isLocalLinkage(S->linkage()))
12384fef68cbSTeresa Johnson         S->setLinkage(GlobalValue::ExternalLinkage);
12394fef68cbSTeresa Johnson     }
12404fef68cbSTeresa Johnson   }
12414fef68cbSTeresa Johnson 
124201e32130SMehdi Amini   // Next we need to promote to global scope and rename any local values that
12431b00f2d9STeresa Johnson   // are potentially exported to other modules.
124401e32130SMehdi Amini   if (renameModuleForThinLTO(M, *Index, nullptr)) {
12451b00f2d9STeresa Johnson     errs() << "Error renaming module\n";
12461b00f2d9STeresa Johnson     return false;
12471b00f2d9STeresa Johnson   }
12481b00f2d9STeresa Johnson 
124942418abaSMehdi Amini   // Perform the import now.
1250d16c8065SMehdi Amini   auto ModuleLoader = [&M](StringRef Identifier) {
1251d16c8065SMehdi Amini     return loadFile(Identifier, M.getContext());
1252d16c8065SMehdi Amini   };
12539d2bfc48SRafael Espindola   FunctionImporter Importer(*Index, ModuleLoader);
125437e24591SPeter Collingbourne   Expected<bool> Result = Importer.importFunctions(M, ImportList);
12557f00d0a1SPeter Collingbourne 
12567f00d0a1SPeter Collingbourne   // FIXME: Probably need to propagate Errors through the pass manager.
12577f00d0a1SPeter Collingbourne   if (!Result) {
12587f00d0a1SPeter Collingbourne     logAllUnhandledErrors(Result.takeError(), errs(),
12597f00d0a1SPeter Collingbourne                           "Error importing module: ");
12607f00d0a1SPeter Collingbourne     return false;
12617f00d0a1SPeter Collingbourne   }
12627f00d0a1SPeter Collingbourne 
12637f00d0a1SPeter Collingbourne   return *Result;
126421241571STeresa Johnson }
126521241571STeresa Johnson 
126621241571STeresa Johnson namespace {
1267e9ea08a0SEugene Zelenko 
126821241571STeresa Johnson /// Pass that performs cross-module function import provided a summary file.
126921241571STeresa Johnson class FunctionImportLegacyPass : public ModulePass {
127021241571STeresa Johnson public:
127121241571STeresa Johnson   /// Pass identification, replacement for typeid
127221241571STeresa Johnson   static char ID;
127321241571STeresa Johnson 
1274e9ea08a0SEugene Zelenko   explicit FunctionImportLegacyPass() : ModulePass(ID) {}
1275e9ea08a0SEugene Zelenko 
127621241571STeresa Johnson   /// Specify pass name for debug output
1277117296c0SMehdi Amini   StringRef getPassName() const override { return "Function Importing"; }
127821241571STeresa Johnson 
127921241571STeresa Johnson   bool runOnModule(Module &M) override {
128021241571STeresa Johnson     if (skipModule(M))
128121241571STeresa Johnson       return false;
128221241571STeresa Johnson 
1283598bd2a2SPeter Collingbourne     return doImportingForModule(M);
128442418abaSMehdi Amini   }
128542418abaSMehdi Amini };
1286e9ea08a0SEugene Zelenko 
1287e9ea08a0SEugene Zelenko } // end anonymous namespace
128842418abaSMehdi Amini 
128921241571STeresa Johnson PreservedAnalyses FunctionImportPass::run(Module &M,
1290fd03ac6aSSean Silva                                           ModuleAnalysisManager &AM) {
1291598bd2a2SPeter Collingbourne   if (!doImportingForModule(M))
129221241571STeresa Johnson     return PreservedAnalyses::all();
129321241571STeresa Johnson 
129421241571STeresa Johnson   return PreservedAnalyses::none();
129521241571STeresa Johnson }
129621241571STeresa Johnson 
129721241571STeresa Johnson char FunctionImportLegacyPass::ID = 0;
129821241571STeresa Johnson INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
129942418abaSMehdi Amini                 "Summary Based Function Import", false, false)
130042418abaSMehdi Amini 
130142418abaSMehdi Amini namespace llvm {
1302e9ea08a0SEugene Zelenko 
1303598bd2a2SPeter Collingbourne Pass *createFunctionImportPass() {
1304598bd2a2SPeter Collingbourne   return new FunctionImportLegacyPass();
13055fcbdb71STeresa Johnson }
1306e9ea08a0SEugene Zelenko 
1307e9ea08a0SEugene Zelenko } // end namespace llvm
1308