142418abaSMehdi Amini //===- FunctionImport.cpp - ThinLTO Summary-based Function Import ---------===//
242418abaSMehdi Amini //
342418abaSMehdi Amini //                     The LLVM Compiler Infrastructure
442418abaSMehdi Amini //
542418abaSMehdi Amini // This file is distributed under the University of Illinois Open Source
642418abaSMehdi Amini // License. See LICENSE.TXT for details.
742418abaSMehdi Amini //
842418abaSMehdi Amini //===----------------------------------------------------------------------===//
942418abaSMehdi Amini //
1042418abaSMehdi Amini // This file implements Function import based on summaries.
1142418abaSMehdi Amini //
1242418abaSMehdi Amini //===----------------------------------------------------------------------===//
1342418abaSMehdi Amini 
1442418abaSMehdi Amini #include "llvm/Transforms/IPO/FunctionImport.h"
15e9ea08a0SEugene Zelenko #include "llvm/ADT/ArrayRef.h"
16e9ea08a0SEugene Zelenko #include "llvm/ADT/STLExtras.h"
17e9ea08a0SEugene Zelenko #include "llvm/ADT/SetVector.h"
1801e32130SMehdi Amini #include "llvm/ADT/SmallVector.h"
19d29478f7STeresa Johnson #include "llvm/ADT/Statistic.h"
20e9ea08a0SEugene Zelenko #include "llvm/ADT/StringMap.h"
21d3e7d19fSCharles Saternos #include "llvm/ADT/StringSet.h"
22*2ad768bbSVolodymyr Sapsai #include "llvm/ADT/StringRef.h"
23c15d60b7SPeter Collingbourne #include "llvm/Bitcode/BitcodeReader.h"
2442418abaSMehdi Amini #include "llvm/IR/AutoUpgrade.h"
2581bbf742STeresa Johnson #include "llvm/IR/Constants.h"
26e9ea08a0SEugene Zelenko #include "llvm/IR/Function.h"
27e9ea08a0SEugene Zelenko #include "llvm/IR/GlobalAlias.h"
28e9ea08a0SEugene Zelenko #include "llvm/IR/GlobalObject.h"
29e9ea08a0SEugene Zelenko #include "llvm/IR/GlobalValue.h"
30e9ea08a0SEugene Zelenko #include "llvm/IR/GlobalVariable.h"
31e9ea08a0SEugene Zelenko #include "llvm/IR/Metadata.h"
3242418abaSMehdi Amini #include "llvm/IR/Module.h"
33e9ea08a0SEugene Zelenko #include "llvm/IR/ModuleSummaryIndex.h"
3442418abaSMehdi Amini #include "llvm/IRReader/IRReader.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 
636c475a75STeresa Johnson STATISTIC(NumImportedFunctions, "Number of functions imported");
646c475a75STeresa Johnson STATISTIC(NumImportedModules, "Number of modules imported from");
656c475a75STeresa Johnson STATISTIC(NumDeadSymbols, "Number of dead stripped symbols in index");
666c475a75STeresa Johnson STATISTIC(NumLiveSymbols, "Number of live symbols in index");
67d29478f7STeresa Johnson 
6839303619STeresa Johnson /// Limit on instruction count of imported functions.
6939303619STeresa Johnson static cl::opt<unsigned> ImportInstrLimit(
7039303619STeresa Johnson     "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
7139303619STeresa Johnson     cl::desc("Only import functions with less than N instructions"));
7239303619STeresa Johnson 
7340641748SMehdi Amini static cl::opt<float>
7440641748SMehdi Amini     ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7),
7540641748SMehdi Amini                       cl::Hidden, cl::value_desc("x"),
7640641748SMehdi Amini                       cl::desc("As we import functions, multiply the "
7740641748SMehdi Amini                                "`import-instr-limit` threshold by this factor "
7840641748SMehdi Amini                                "before processing newly imported functions"));
79ba72b95fSPiotr Padlewski 
80d2869473SPiotr Padlewski static cl::opt<float> ImportHotInstrFactor(
81d2869473SPiotr Padlewski     "import-hot-evolution-factor", cl::init(1.0), cl::Hidden,
82d2869473SPiotr Padlewski     cl::value_desc("x"),
83d2869473SPiotr Padlewski     cl::desc("As we import functions called from hot callsite, multiply the "
84d2869473SPiotr Padlewski              "`import-instr-limit` threshold by this factor "
85d2869473SPiotr Padlewski              "before processing newly imported functions"));
86d2869473SPiotr Padlewski 
87d9830eb7SPiotr Padlewski static cl::opt<float> ImportHotMultiplier(
888260d665SDehao Chen     "import-hot-multiplier", cl::init(10.0), cl::Hidden, cl::value_desc("x"),
89ba72b95fSPiotr Padlewski     cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"));
90ba72b95fSPiotr Padlewski 
9164c46574SDehao Chen static cl::opt<float> ImportCriticalMultiplier(
9264c46574SDehao Chen     "import-critical-multiplier", cl::init(100.0), cl::Hidden,
9364c46574SDehao Chen     cl::value_desc("x"),
9464c46574SDehao Chen     cl::desc(
9564c46574SDehao Chen         "Multiply the `import-instr-limit` threshold for critical callsites"));
9664c46574SDehao Chen 
97ba72b95fSPiotr Padlewski // FIXME: This multiplier was not really tuned up.
98ba72b95fSPiotr Padlewski static cl::opt<float> ImportColdMultiplier(
99ba72b95fSPiotr Padlewski     "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"),
100ba72b95fSPiotr Padlewski     cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"));
10140641748SMehdi Amini 
102d29478f7STeresa Johnson static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
103d29478f7STeresa Johnson                                   cl::desc("Print imported functions"));
104d29478f7STeresa Johnson 
1056c475a75STeresa Johnson static cl::opt<bool> ComputeDead("compute-dead", cl::init(true), cl::Hidden,
1066c475a75STeresa Johnson                                  cl::desc("Compute dead symbols"));
1076c475a75STeresa Johnson 
1083b776128SPiotr Padlewski static cl::opt<bool> EnableImportMetadata(
1093b776128SPiotr Padlewski     "enable-import-metadata", cl::init(
1103b776128SPiotr Padlewski #if !defined(NDEBUG)
1113b776128SPiotr Padlewski                                   true /*Enabled with asserts.*/
1123b776128SPiotr Padlewski #else
1133b776128SPiotr Padlewski                                   false
1143b776128SPiotr Padlewski #endif
1153b776128SPiotr Padlewski                                   ),
1163b776128SPiotr Padlewski     cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'"));
1173b776128SPiotr Padlewski 
118e9ea08a0SEugene Zelenko /// Summary file to use for function importing when using -function-import from
119e9ea08a0SEugene Zelenko /// the command line.
120e9ea08a0SEugene Zelenko static cl::opt<std::string>
121e9ea08a0SEugene Zelenko     SummaryFile("summary-file",
122e9ea08a0SEugene Zelenko                 cl::desc("The summary file to use for function importing."));
123e9ea08a0SEugene Zelenko 
12481bbf742STeresa Johnson /// Used when testing importing from distributed indexes via opt
12581bbf742STeresa Johnson // -function-import.
12681bbf742STeresa Johnson static cl::opt<bool>
12781bbf742STeresa Johnson     ImportAllIndex("import-all-index",
12881bbf742STeresa Johnson                    cl::desc("Import all external functions in index."));
12981bbf742STeresa Johnson 
13042418abaSMehdi Amini // Load lazily a module from \p FileName in \p Context.
13142418abaSMehdi Amini static std::unique_ptr<Module> loadFile(const std::string &FileName,
13242418abaSMehdi Amini                                         LLVMContext &Context) {
13342418abaSMehdi Amini   SMDiagnostic Err;
13442418abaSMehdi Amini   DEBUG(dbgs() << "Loading '" << FileName << "'\n");
1356cba37ceSTeresa Johnson   // Metadata isn't loaded until functions are imported, to minimize
1366cba37ceSTeresa Johnson   // the memory overhead.
137a1080ee6STeresa Johnson   std::unique_ptr<Module> Result =
138a1080ee6STeresa Johnson       getLazyIRFileModule(FileName, Err, Context,
139a1080ee6STeresa Johnson                           /* ShouldLazyLoadMetadata = */ true);
14042418abaSMehdi Amini   if (!Result) {
14142418abaSMehdi Amini     Err.print("function-import", errs());
142d7ad221cSMehdi Amini     report_fatal_error("Abort");
14342418abaSMehdi Amini   }
14442418abaSMehdi Amini 
14542418abaSMehdi Amini   return Result;
14642418abaSMehdi Amini }
14742418abaSMehdi Amini 
14801e32130SMehdi Amini /// Given a list of possible callee implementation for a call site, select one
14901e32130SMehdi Amini /// that fits the \p Threshold.
15001e32130SMehdi Amini ///
15101e32130SMehdi Amini /// FIXME: select "best" instead of first that fits. But what is "best"?
15201e32130SMehdi Amini /// - The smallest: more likely to be inlined.
15301e32130SMehdi Amini /// - The one with the least outgoing edges (already well optimized).
15401e32130SMehdi Amini /// - One from a module already being imported from in order to reduce the
15501e32130SMehdi Amini ///   number of source modules parsed/linked.
15601e32130SMehdi Amini /// - One that has PGO data attached.
15701e32130SMehdi Amini /// - [insert you fancy metric here]
1582d28f7aaSMehdi Amini static const GlobalValueSummary *
159b4e1e829SMehdi Amini selectCallee(const ModuleSummaryIndex &Index,
1609667b91bSPeter Collingbourne              ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
16183aaf358STeresa Johnson              unsigned Threshold, StringRef CallerModulePath) {
16201e32130SMehdi Amini   auto It = llvm::find_if(
16328e457bcSTeresa Johnson       CalleeSummaryList,
16428e457bcSTeresa Johnson       [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
16528e457bcSTeresa Johnson         auto *GVSummary = SummaryPtr.get();
166eaf5172cSGeorge Rimar         if (!Index.isGlobalValueLive(GVSummary))
167eaf5172cSGeorge Rimar           return false;
168eaf5172cSGeorge Rimar 
16973305f82STeresa Johnson         // For SamplePGO, in computeImportForFunction the OriginalId
17073305f82STeresa Johnson         // may have been used to locate the callee summary list (See
17173305f82STeresa Johnson         // comment there).
17273305f82STeresa Johnson         // The mapping from OriginalId to GUID may return a GUID
17373305f82STeresa Johnson         // that corresponds to a static variable. Filter it out here.
17473305f82STeresa Johnson         // This can happen when
17573305f82STeresa Johnson         // 1) There is a call to a library function which is not defined
17673305f82STeresa Johnson         // in the index.
17773305f82STeresa Johnson         // 2) There is a static variable with the  OriginalGUID identical
17873305f82STeresa Johnson         // to the GUID of the library function in 1);
17973305f82STeresa Johnson         // When this happens, the logic for SamplePGO kicks in and
18073305f82STeresa Johnson         // the static variable in 2) will be found, which needs to be
18173305f82STeresa Johnson         // filtered out.
18273305f82STeresa Johnson         if (GVSummary->getSummaryKind() == GlobalValueSummary::GlobalVarKind)
18373305f82STeresa Johnson           return false;
184f329be83SRafael Espindola         if (GlobalValue::isInterposableLinkage(GVSummary->linkage()))
1855b85d8d6SMehdi Amini           // There is no point in importing these, we can't inline them
18601e32130SMehdi Amini           return false;
1872c719cc1SMehdi Amini 
18881bbf742STeresa Johnson         auto *Summary = cast<FunctionSummary>(GVSummary->getBaseObject());
1897e88d0daSMehdi Amini 
19083aaf358STeresa Johnson         // If this is a local function, make sure we import the copy
19183aaf358STeresa Johnson         // in the caller's module. The only time a local function can
19283aaf358STeresa Johnson         // share an entry in the index is if there is a local with the same name
19383aaf358STeresa Johnson         // in another module that had the same source file name (in a different
19483aaf358STeresa Johnson         // directory), where each was compiled in their own directory so there
19583aaf358STeresa Johnson         // was not distinguishing path.
19683aaf358STeresa Johnson         // However, do the import from another module if there is only one
19783aaf358STeresa Johnson         // entry in the list - in that case this must be a reference due
19883aaf358STeresa Johnson         // to indirect call profile data, since a function pointer can point to
19983aaf358STeresa Johnson         // a local in another module.
20083aaf358STeresa Johnson         if (GlobalValue::isLocalLinkage(Summary->linkage()) &&
20183aaf358STeresa Johnson             CalleeSummaryList.size() > 1 &&
20283aaf358STeresa Johnson             Summary->modulePath() != CallerModulePath)
20383aaf358STeresa Johnson           return false;
20483aaf358STeresa Johnson 
205f9dc3deaSTeresa Johnson         if (Summary->instCount() > Threshold)
206f9dc3deaSTeresa Johnson           return false;
207f9dc3deaSTeresa Johnson 
208519465b9STeresa Johnson         if (Summary->notEligibleToImport())
209b4e1e829SMehdi Amini           return false;
210b4e1e829SMehdi Amini 
21101e32130SMehdi Amini         return true;
21201e32130SMehdi Amini       });
21328e457bcSTeresa Johnson   if (It == CalleeSummaryList.end())
21401e32130SMehdi Amini     return nullptr;
2157e88d0daSMehdi Amini 
216f9dc3deaSTeresa Johnson   return cast<GlobalValueSummary>(It->get());
217434e9561SRafael Espindola }
2187e88d0daSMehdi Amini 
219e9ea08a0SEugene Zelenko namespace {
220e9ea08a0SEugene Zelenko 
221475b51a7STeresa Johnson using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */,
222475b51a7STeresa Johnson                             GlobalValue::GUID>;
22301e32130SMehdi Amini 
224e9ea08a0SEugene Zelenko } // anonymous namespace
225e9ea08a0SEugene Zelenko 
2261958083dSTeresa Johnson static ValueInfo
2271958083dSTeresa Johnson updateValueInfoForIndirectCalls(const ModuleSummaryIndex &Index, ValueInfo VI) {
2281958083dSTeresa Johnson   if (!VI.getSummaryList().empty())
2291958083dSTeresa Johnson     return VI;
2301958083dSTeresa Johnson   // For SamplePGO, the indirect call targets for local functions will
2311958083dSTeresa Johnson   // have its original name annotated in profile. We try to find the
2321958083dSTeresa Johnson   // corresponding PGOFuncName as the GUID.
2331958083dSTeresa Johnson   // FIXME: Consider updating the edges in the graph after building
2341958083dSTeresa Johnson   // it, rather than needing to perform this mapping on each walk.
2351958083dSTeresa Johnson   auto GUID = Index.getGUIDFromOriginalID(VI.getGUID());
2361958083dSTeresa Johnson   if (GUID == 0)
23728d8a49fSEugene Leviant     return ValueInfo();
2381958083dSTeresa Johnson   return Index.getValueInfo(GUID);
2391958083dSTeresa Johnson }
2401958083dSTeresa Johnson 
24101e32130SMehdi Amini /// Compute the list of functions to import for a given caller. Mark these
24201e32130SMehdi Amini /// imported functions and the symbols they reference in their source module as
24301e32130SMehdi Amini /// exported from their source module.
24401e32130SMehdi Amini static void computeImportForFunction(
2453255eec1STeresa Johnson     const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
246d9830eb7SPiotr Padlewski     const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
24701e32130SMehdi Amini     SmallVectorImpl<EdgeInfo> &Worklist,
2489b490f10SMehdi Amini     FunctionImporter::ImportMapTy &ImportList,
249c86af334STeresa Johnson     StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
25001e32130SMehdi Amini   for (auto &Edge : Summary.calls()) {
2519667b91bSPeter Collingbourne     ValueInfo VI = Edge.first;
2529667b91bSPeter Collingbourne     DEBUG(dbgs() << " edge -> " << VI.getGUID() << " Threshold:" << Threshold
2539667b91bSPeter Collingbourne                  << "\n");
25401e32130SMehdi Amini 
2551958083dSTeresa Johnson     VI = updateValueInfoForIndirectCalls(Index, VI);
2569667b91bSPeter Collingbourne     if (!VI)
2579667b91bSPeter Collingbourne       continue;
2584a435e08SDehao Chen 
2599667b91bSPeter Collingbourne     if (DefinedGVSummaries.count(VI.getGUID())) {
26001e32130SMehdi Amini       DEBUG(dbgs() << "ignored! Target already in destination module.\n");
2617e88d0daSMehdi Amini       continue;
262d450da32STeresa Johnson     }
26340641748SMehdi Amini 
264ba72b95fSPiotr Padlewski     auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
265ba72b95fSPiotr Padlewski       if (Hotness == CalleeInfo::HotnessType::Hot)
266ba72b95fSPiotr Padlewski         return ImportHotMultiplier;
267ba72b95fSPiotr Padlewski       if (Hotness == CalleeInfo::HotnessType::Cold)
268ba72b95fSPiotr Padlewski         return ImportColdMultiplier;
26964c46574SDehao Chen       if (Hotness == CalleeInfo::HotnessType::Critical)
27064c46574SDehao Chen         return ImportCriticalMultiplier;
271ba72b95fSPiotr Padlewski       return 1.0;
272ba72b95fSPiotr Padlewski     };
273ba72b95fSPiotr Padlewski 
274d9830eb7SPiotr Padlewski     const auto NewThreshold =
275c73cec84SEaswaran Raman         Threshold * GetBonusMultiplier(Edge.second.getHotness());
276d2869473SPiotr Padlewski 
2779667b91bSPeter Collingbourne     auto *CalleeSummary = selectCallee(Index, VI.getSummaryList(), NewThreshold,
2789667b91bSPeter Collingbourne                                        Summary.modulePath());
27901e32130SMehdi Amini     if (!CalleeSummary) {
28001e32130SMehdi Amini       DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n");
2817e88d0daSMehdi Amini       continue;
2827e88d0daSMehdi Amini     }
2832f0cc477SDavid Blaikie 
2842f0cc477SDavid Blaikie     // "Resolve" the summary
28581bbf742STeresa Johnson     const auto *ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary->getBaseObject());
2862d28f7aaSMehdi Amini 
287d9830eb7SPiotr Padlewski     assert(ResolvedCalleeSummary->instCount() <= NewThreshold &&
28801e32130SMehdi Amini            "selectCallee() didn't honor the threshold");
28901e32130SMehdi Amini 
290d2869473SPiotr Padlewski     auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
291d2869473SPiotr Padlewski       // Adjust the threshold for next level of imported functions.
292d2869473SPiotr Padlewski       // The threshold is different for hot callsites because we can then
293d2869473SPiotr Padlewski       // inline chains of hot calls.
294d2869473SPiotr Padlewski       if (IsHotCallsite)
295d2869473SPiotr Padlewski         return Threshold * ImportHotInstrFactor;
296d2869473SPiotr Padlewski       return Threshold * ImportInstrFactor;
297d2869473SPiotr Padlewski     };
298d2869473SPiotr Padlewski 
299c73cec84SEaswaran Raman     bool IsHotCallsite =
300c73cec84SEaswaran Raman         Edge.second.getHotness() == CalleeInfo::HotnessType::Hot;
3011b859a23STeresa Johnson     const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
3021b859a23STeresa Johnson 
3031b859a23STeresa Johnson     auto ExportModulePath = ResolvedCalleeSummary->modulePath();
3049667b91bSPeter Collingbourne     auto &ProcessedThreshold = ImportList[ExportModulePath][VI.getGUID()];
3051b859a23STeresa Johnson     /// Since the traversal of the call graph is DFS, we can revisit a function
3061b859a23STeresa Johnson     /// a second time with a higher threshold. In this case, it is added back to
3071b859a23STeresa Johnson     /// the worklist with the new threshold.
3081b859a23STeresa Johnson     if (ProcessedThreshold && ProcessedThreshold >= AdjThreshold) {
3091b859a23STeresa Johnson       DEBUG(dbgs() << "ignored! Target was already seen with Threshold "
3101b859a23STeresa Johnson                    << ProcessedThreshold << "\n");
3111b859a23STeresa Johnson       continue;
3121b859a23STeresa Johnson     }
31319f2aa78STeresa Johnson     bool PreviouslyImported = ProcessedThreshold != 0;
3141b859a23STeresa Johnson     // Mark this function as imported in this module, with the current Threshold
3151b859a23STeresa Johnson     ProcessedThreshold = AdjThreshold;
3161b859a23STeresa Johnson 
3171b859a23STeresa Johnson     // Make exports in the source module.
3181b859a23STeresa Johnson     if (ExportLists) {
3191b859a23STeresa Johnson       auto &ExportList = (*ExportLists)[ExportModulePath];
3209667b91bSPeter Collingbourne       ExportList.insert(VI.getGUID());
32119f2aa78STeresa Johnson       if (!PreviouslyImported) {
32219f2aa78STeresa Johnson         // This is the first time this function was exported from its source
32319f2aa78STeresa Johnson         // module, so mark all functions and globals it references as exported
3241b859a23STeresa Johnson         // to the outside if they are defined in the same source module.
325edddca22STeresa Johnson         // For efficiency, we unconditionally add all the referenced GUIDs
326edddca22STeresa Johnson         // to the ExportList for this module, and will prune out any not
327edddca22STeresa Johnson         // defined in the module later in a single pass.
3281b859a23STeresa Johnson         for (auto &Edge : ResolvedCalleeSummary->calls()) {
3291b859a23STeresa Johnson           auto CalleeGUID = Edge.first.getGUID();
330edddca22STeresa Johnson           ExportList.insert(CalleeGUID);
3311b859a23STeresa Johnson         }
3321b859a23STeresa Johnson         for (auto &Ref : ResolvedCalleeSummary->refs()) {
3331b859a23STeresa Johnson           auto GUID = Ref.getGUID();
334edddca22STeresa Johnson           ExportList.insert(GUID);
3351b859a23STeresa Johnson         }
3361b859a23STeresa Johnson       }
33719f2aa78STeresa Johnson     }
338d2869473SPiotr Padlewski 
33901e32130SMehdi Amini     // Insert the newly imported function to the worklist.
3409667b91bSPeter Collingbourne     Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, VI.getGUID());
341d450da32STeresa Johnson   }
342d450da32STeresa Johnson }
343d450da32STeresa Johnson 
34401e32130SMehdi Amini /// Given the list of globals defined in a module, compute the list of imports
34501e32130SMehdi Amini /// as well as the list of "exports", i.e. the list of symbols referenced from
34601e32130SMehdi Amini /// another module (that may require promotion).
34701e32130SMehdi Amini static void ComputeImportForModule(
348c851d216STeresa Johnson     const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
3499b490f10SMehdi Amini     FunctionImporter::ImportMapTy &ImportList,
35056584bbfSEvgeniy Stepanov     StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
35101e32130SMehdi Amini   // Worklist contains the list of function imported in this module, for which
35201e32130SMehdi Amini   // we will analyse the callees and may import further down the callgraph.
35301e32130SMehdi Amini   SmallVector<EdgeInfo, 128> Worklist;
35401e32130SMehdi Amini 
35501e32130SMehdi Amini   // Populate the worklist with the import for the functions in the current
35601e32130SMehdi Amini   // module
35728e457bcSTeresa Johnson   for (auto &GVSummary : DefinedGVSummaries) {
35856584bbfSEvgeniy Stepanov     if (!Index.isGlobalValueLive(GVSummary.second)) {
3596c475a75STeresa Johnson       DEBUG(dbgs() << "Ignores Dead GUID: " << GVSummary.first << "\n");
3606c475a75STeresa Johnson       continue;
3616c475a75STeresa Johnson     }
362cfbd0892SPeter Collingbourne     auto *FuncSummary =
363cfbd0892SPeter Collingbourne         dyn_cast<FunctionSummary>(GVSummary.second->getBaseObject());
3641aafabf7SMehdi Amini     if (!FuncSummary)
3651aafabf7SMehdi Amini       // Skip import for global variables
3661aafabf7SMehdi Amini       continue;
36724524f31SXinliang David Li     DEBUG(dbgs() << "Initialize import for " << GVSummary.first << "\n");
3682d28f7aaSMehdi Amini     computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
3699b490f10SMehdi Amini                              DefinedGVSummaries, Worklist, ImportList,
37001e32130SMehdi Amini                              ExportLists);
37101e32130SMehdi Amini   }
37201e32130SMehdi Amini 
373d2869473SPiotr Padlewski   // Process the newly imported functions and add callees to the worklist.
37442418abaSMehdi Amini   while (!Worklist.empty()) {
37501e32130SMehdi Amini     auto FuncInfo = Worklist.pop_back_val();
376475b51a7STeresa Johnson     auto *Summary = std::get<0>(FuncInfo);
377475b51a7STeresa Johnson     auto Threshold = std::get<1>(FuncInfo);
378475b51a7STeresa Johnson     auto GUID = std::get<2>(FuncInfo);
379475b51a7STeresa Johnson 
380475b51a7STeresa Johnson     // Check if we later added this summary with a higher threshold.
381475b51a7STeresa Johnson     // If so, skip this entry.
382475b51a7STeresa Johnson     auto ExportModulePath = Summary->modulePath();
383475b51a7STeresa Johnson     auto &LatestProcessedThreshold = ImportList[ExportModulePath][GUID];
384475b51a7STeresa Johnson     if (LatestProcessedThreshold > Threshold)
385475b51a7STeresa Johnson       continue;
38642418abaSMehdi Amini 
3871aafabf7SMehdi Amini     computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
3889b490f10SMehdi Amini                              Worklist, ImportList, ExportLists);
389c8c55170SMehdi Amini   }
39042418abaSMehdi Amini }
391ffe2e4aaSMehdi Amini 
392c86af334STeresa Johnson /// Compute all the import and export for every module using the Index.
39301e32130SMehdi Amini void llvm::ComputeCrossModuleImport(
39401e32130SMehdi Amini     const ModuleSummaryIndex &Index,
395c851d216STeresa Johnson     const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
39601e32130SMehdi Amini     StringMap<FunctionImporter::ImportMapTy> &ImportLists,
39756584bbfSEvgeniy Stepanov     StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
39801e32130SMehdi Amini   // For each module that has function defined, compute the import/export lists.
3991aafabf7SMehdi Amini   for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
4009b490f10SMehdi Amini     auto &ImportList = ImportLists[DefinedGVSummaries.first()];
4011aafabf7SMehdi Amini     DEBUG(dbgs() << "Computing import for Module '"
4021aafabf7SMehdi Amini                  << DefinedGVSummaries.first() << "'\n");
4039b490f10SMehdi Amini     ComputeImportForModule(DefinedGVSummaries.second, Index, ImportList,
40456584bbfSEvgeniy Stepanov                            &ExportLists);
40501e32130SMehdi Amini   }
40601e32130SMehdi Amini 
407edddca22STeresa Johnson   // When computing imports we added all GUIDs referenced by anything
408edddca22STeresa Johnson   // imported from the module to its ExportList. Now we prune each ExportList
409edddca22STeresa Johnson   // of any not defined in that module. This is more efficient than checking
410edddca22STeresa Johnson   // while computing imports because some of the summary lists may be long
411edddca22STeresa Johnson   // due to linkonce (comdat) copies.
412edddca22STeresa Johnson   for (auto &ELI : ExportLists) {
413edddca22STeresa Johnson     const auto &DefinedGVSummaries =
414edddca22STeresa Johnson         ModuleToDefinedGVSummaries.lookup(ELI.first());
415edddca22STeresa Johnson     for (auto EI = ELI.second.begin(); EI != ELI.second.end();) {
416edddca22STeresa Johnson       if (!DefinedGVSummaries.count(*EI))
417edddca22STeresa Johnson         EI = ELI.second.erase(EI);
418edddca22STeresa Johnson       else
419edddca22STeresa Johnson         ++EI;
420edddca22STeresa Johnson     }
421edddca22STeresa Johnson   }
422edddca22STeresa Johnson 
42301e32130SMehdi Amini #ifndef NDEBUG
42401e32130SMehdi Amini   DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
42501e32130SMehdi Amini                << " modules:\n");
42601e32130SMehdi Amini   for (auto &ModuleImports : ImportLists) {
42701e32130SMehdi Amini     auto ModName = ModuleImports.first();
42801e32130SMehdi Amini     auto &Exports = ExportLists[ModName];
42901e32130SMehdi Amini     DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size()
43001e32130SMehdi Amini                  << " functions. Imports from " << ModuleImports.second.size()
43101e32130SMehdi Amini                  << " modules.\n");
43201e32130SMehdi Amini     for (auto &Src : ModuleImports.second) {
43301e32130SMehdi Amini       auto SrcModName = Src.first();
43401e32130SMehdi Amini       DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
43501e32130SMehdi Amini                    << SrcModName << "\n");
43601e32130SMehdi Amini     }
43701e32130SMehdi Amini   }
43801e32130SMehdi Amini #endif
43901e32130SMehdi Amini }
44001e32130SMehdi Amini 
44181bbf742STeresa Johnson #ifndef NDEBUG
44281bbf742STeresa Johnson static void dumpImportListForModule(StringRef ModulePath,
44381bbf742STeresa Johnson                                     FunctionImporter::ImportMapTy &ImportList) {
44481bbf742STeresa Johnson   DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
44581bbf742STeresa Johnson                << ImportList.size() << " modules.\n");
44681bbf742STeresa Johnson   for (auto &Src : ImportList) {
44781bbf742STeresa Johnson     auto SrcModName = Src.first();
44881bbf742STeresa Johnson     DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
44981bbf742STeresa Johnson                  << SrcModName << "\n");
45081bbf742STeresa Johnson   }
45181bbf742STeresa Johnson }
45269b2de84STeresa Johnson #endif
45381bbf742STeresa Johnson 
454c86af334STeresa Johnson /// Compute all the imports for the given module in the Index.
455c86af334STeresa Johnson void llvm::ComputeCrossModuleImportForModule(
456c86af334STeresa Johnson     StringRef ModulePath, const ModuleSummaryIndex &Index,
457c86af334STeresa Johnson     FunctionImporter::ImportMapTy &ImportList) {
458c86af334STeresa Johnson   // Collect the list of functions this module defines.
459c86af334STeresa Johnson   // GUID -> Summary
460c851d216STeresa Johnson   GVSummaryMapTy FunctionSummaryMap;
46128e457bcSTeresa Johnson   Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
462c86af334STeresa Johnson 
463c86af334STeresa Johnson   // Compute the import list for this module.
464c86af334STeresa Johnson   DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
46528e457bcSTeresa Johnson   ComputeImportForModule(FunctionSummaryMap, Index, ImportList);
466c86af334STeresa Johnson 
467c86af334STeresa Johnson #ifndef NDEBUG
46881bbf742STeresa Johnson   dumpImportListForModule(ModulePath, ImportList);
46981bbf742STeresa Johnson #endif
470c86af334STeresa Johnson }
47181bbf742STeresa Johnson 
47281bbf742STeresa Johnson // Mark all external summaries in Index for import into the given module.
47381bbf742STeresa Johnson // Used for distributed builds using a distributed index.
47481bbf742STeresa Johnson void llvm::ComputeCrossModuleImportForModuleFromIndex(
47581bbf742STeresa Johnson     StringRef ModulePath, const ModuleSummaryIndex &Index,
47681bbf742STeresa Johnson     FunctionImporter::ImportMapTy &ImportList) {
47781bbf742STeresa Johnson   for (auto &GlobalList : Index) {
47881bbf742STeresa Johnson     // Ignore entries for undefined references.
47981bbf742STeresa Johnson     if (GlobalList.second.SummaryList.empty())
48081bbf742STeresa Johnson       continue;
48181bbf742STeresa Johnson 
48281bbf742STeresa Johnson     auto GUID = GlobalList.first;
48381bbf742STeresa Johnson     assert(GlobalList.second.SummaryList.size() == 1 &&
48481bbf742STeresa Johnson            "Expected individual combined index to have one summary per GUID");
48581bbf742STeresa Johnson     auto &Summary = GlobalList.second.SummaryList[0];
48681bbf742STeresa Johnson     // Skip the summaries for the importing module. These are included to
48781bbf742STeresa Johnson     // e.g. record required linkage changes.
48881bbf742STeresa Johnson     if (Summary->modulePath() == ModulePath)
48981bbf742STeresa Johnson       continue;
49081bbf742STeresa Johnson     // Doesn't matter what value we plug in to the map, just needs an entry
49181bbf742STeresa Johnson     // to provoke importing by thinBackend.
49281bbf742STeresa Johnson     ImportList[Summary->modulePath()][GUID] = 1;
49381bbf742STeresa Johnson   }
49481bbf742STeresa Johnson #ifndef NDEBUG
49581bbf742STeresa Johnson   dumpImportListForModule(ModulePath, ImportList);
496c86af334STeresa Johnson #endif
497c86af334STeresa Johnson }
498c86af334STeresa Johnson 
49956584bbfSEvgeniy Stepanov void llvm::computeDeadSymbols(
50056584bbfSEvgeniy Stepanov     ModuleSummaryIndex &Index,
501eaf5172cSGeorge Rimar     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
502eaf5172cSGeorge Rimar     function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing) {
50356584bbfSEvgeniy Stepanov   assert(!Index.withGlobalValueDeadStripping());
5046c475a75STeresa Johnson   if (!ComputeDead)
50556584bbfSEvgeniy Stepanov     return;
5066c475a75STeresa Johnson   if (GUIDPreservedSymbols.empty())
5076c475a75STeresa Johnson     // Don't do anything when nothing is live, this is friendly with tests.
50856584bbfSEvgeniy Stepanov     return;
50956584bbfSEvgeniy Stepanov   unsigned LiveSymbols = 0;
5109667b91bSPeter Collingbourne   SmallVector<ValueInfo, 128> Worklist;
5119667b91bSPeter Collingbourne   Worklist.reserve(GUIDPreservedSymbols.size() * 2);
5129667b91bSPeter Collingbourne   for (auto GUID : GUIDPreservedSymbols) {
5139667b91bSPeter Collingbourne     ValueInfo VI = Index.getValueInfo(GUID);
5149667b91bSPeter Collingbourne     if (!VI)
5159667b91bSPeter Collingbourne       continue;
51656584bbfSEvgeniy Stepanov     for (auto &S : VI.getSummaryList())
51756584bbfSEvgeniy Stepanov       S->setLive(true);
5186c475a75STeresa Johnson   }
51956584bbfSEvgeniy Stepanov 
5206c475a75STeresa Johnson   // Add values flagged in the index as live roots to the worklist.
52156584bbfSEvgeniy Stepanov   for (const auto &Entry : Index)
52256584bbfSEvgeniy Stepanov     for (auto &S : Entry.second.SummaryList)
52356584bbfSEvgeniy Stepanov       if (S->isLive()) {
52456584bbfSEvgeniy Stepanov         DEBUG(dbgs() << "Live root: " << Entry.first << "\n");
52528d8a49fSEugene Leviant         Worklist.push_back(ValueInfo(/*IsAnalysis=*/false, &Entry));
52656584bbfSEvgeniy Stepanov         ++LiveSymbols;
52756584bbfSEvgeniy Stepanov         break;
5286c475a75STeresa Johnson       }
5296c475a75STeresa Johnson 
53056584bbfSEvgeniy Stepanov   // Make value live and add it to the worklist if it was not live before.
53156584bbfSEvgeniy Stepanov   auto visit = [&](ValueInfo VI) {
5321958083dSTeresa Johnson     // FIXME: If we knew which edges were created for indirect call profiles,
5331958083dSTeresa Johnson     // we could skip them here. Any that are live should be reached via
5341958083dSTeresa Johnson     // other edges, e.g. reference edges. Otherwise, using a profile collected
5351958083dSTeresa Johnson     // on a slightly different binary might provoke preserving, importing
5361958083dSTeresa Johnson     // and ultimately promoting calls to functions not linked into this
5371958083dSTeresa Johnson     // binary, which increases the binary size unnecessarily. Note that
5381958083dSTeresa Johnson     // if this code changes, the importer needs to change so that edges
5391958083dSTeresa Johnson     // to functions marked dead are skipped.
5401958083dSTeresa Johnson     VI = updateValueInfoForIndirectCalls(Index, VI);
5411958083dSTeresa Johnson     if (!VI)
5421958083dSTeresa Johnson       return;
54356584bbfSEvgeniy Stepanov     for (auto &S : VI.getSummaryList())
544f625118eSTeresa Johnson       if (S->isLive())
545f625118eSTeresa Johnson         return;
546eaf5172cSGeorge Rimar 
547eaf5172cSGeorge Rimar     // We do not keep live symbols that are known to be non-prevailing.
548eaf5172cSGeorge Rimar     if (isPrevailing(VI.getGUID()) == PrevailingType::No)
549eaf5172cSGeorge Rimar       return;
550eaf5172cSGeorge Rimar 
551f625118eSTeresa Johnson     for (auto &S : VI.getSummaryList())
55256584bbfSEvgeniy Stepanov       S->setLive(true);
55356584bbfSEvgeniy Stepanov     ++LiveSymbols;
55456584bbfSEvgeniy Stepanov     Worklist.push_back(VI);
55556584bbfSEvgeniy Stepanov   };
55656584bbfSEvgeniy Stepanov 
5576c475a75STeresa Johnson   while (!Worklist.empty()) {
5589667b91bSPeter Collingbourne     auto VI = Worklist.pop_back_val();
5599667b91bSPeter Collingbourne     for (auto &Summary : VI.getSummaryList()) {
560cfbd0892SPeter Collingbourne       GlobalValueSummary *Base = Summary->getBaseObject();
561eaf5172cSGeorge Rimar       // Set base value live in case it is an alias.
562eaf5172cSGeorge Rimar       Base->setLive(true);
563cfbd0892SPeter Collingbourne       for (auto Ref : Base->refs())
56456584bbfSEvgeniy Stepanov         visit(Ref);
565cfbd0892SPeter Collingbourne       if (auto *FS = dyn_cast<FunctionSummary>(Base))
56656584bbfSEvgeniy Stepanov         for (auto Call : FS->calls())
56756584bbfSEvgeniy Stepanov           visit(Call.first);
5686c475a75STeresa Johnson     }
5696c475a75STeresa Johnson   }
57056584bbfSEvgeniy Stepanov   Index.setWithGlobalValueDeadStripping();
57156584bbfSEvgeniy Stepanov 
57256584bbfSEvgeniy Stepanov   unsigned DeadSymbols = Index.size() - LiveSymbols;
57356584bbfSEvgeniy Stepanov   DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols
57456584bbfSEvgeniy Stepanov                << " symbols Dead \n");
57556584bbfSEvgeniy Stepanov   NumDeadSymbols += DeadSymbols;
57656584bbfSEvgeniy Stepanov   NumLiveSymbols += LiveSymbols;
5776c475a75STeresa Johnson }
5786c475a75STeresa Johnson 
57984174c37STeresa Johnson /// Compute the set of summaries needed for a ThinLTO backend compilation of
58084174c37STeresa Johnson /// \p ModulePath.
58184174c37STeresa Johnson void llvm::gatherImportedSummariesForModule(
58284174c37STeresa Johnson     StringRef ModulePath,
58384174c37STeresa Johnson     const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
584cdbcbf74SMehdi Amini     const FunctionImporter::ImportMapTy &ImportList,
58584174c37STeresa Johnson     std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
58684174c37STeresa Johnson   // Include all summaries from the importing module.
58784174c37STeresa Johnson   ModuleToSummariesForIndex[ModulePath] =
58884174c37STeresa Johnson       ModuleToDefinedGVSummaries.lookup(ModulePath);
58984174c37STeresa Johnson   // Include summaries for imports.
59088c491ddSMehdi Amini   for (auto &ILI : ImportList) {
59184174c37STeresa Johnson     auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
59284174c37STeresa Johnson     const auto &DefinedGVSummaries =
59384174c37STeresa Johnson         ModuleToDefinedGVSummaries.lookup(ILI.first());
59484174c37STeresa Johnson     for (auto &GI : ILI.second) {
59584174c37STeresa Johnson       const auto &DS = DefinedGVSummaries.find(GI.first);
59684174c37STeresa Johnson       assert(DS != DefinedGVSummaries.end() &&
59784174c37STeresa Johnson              "Expected a defined summary for imported global value");
59884174c37STeresa Johnson       SummariesForIndex[GI.first] = DS->second;
59984174c37STeresa Johnson     }
60084174c37STeresa Johnson   }
60184174c37STeresa Johnson }
60284174c37STeresa Johnson 
6038570fe47STeresa Johnson /// Emit the files \p ModulePath will import from into \p OutputFilename.
604cdbcbf74SMehdi Amini std::error_code
605cdbcbf74SMehdi Amini llvm::EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename,
606cdbcbf74SMehdi Amini                        const FunctionImporter::ImportMapTy &ModuleImports) {
6078570fe47STeresa Johnson   std::error_code EC;
6088570fe47STeresa Johnson   raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
6098570fe47STeresa Johnson   if (EC)
6108570fe47STeresa Johnson     return EC;
611cdbcbf74SMehdi Amini   for (auto &ILI : ModuleImports)
6128570fe47STeresa Johnson     ImportsOS << ILI.first() << "\n";
6138570fe47STeresa Johnson   return std::error_code();
6148570fe47STeresa Johnson }
6158570fe47STeresa Johnson 
6165a95c477STeresa Johnson bool llvm::convertToDeclaration(GlobalValue &GV) {
6174566c6dbSTeresa Johnson   DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName() << "\n");
6184566c6dbSTeresa Johnson   if (Function *F = dyn_cast<Function>(&GV)) {
6194566c6dbSTeresa Johnson     F->deleteBody();
6204566c6dbSTeresa Johnson     F->clearMetadata();
6217873669bSPeter Collingbourne     F->setComdat(nullptr);
6224566c6dbSTeresa Johnson   } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
6234566c6dbSTeresa Johnson     V->setInitializer(nullptr);
6244566c6dbSTeresa Johnson     V->setLinkage(GlobalValue::ExternalLinkage);
6254566c6dbSTeresa Johnson     V->clearMetadata();
6267873669bSPeter Collingbourne     V->setComdat(nullptr);
6275a95c477STeresa Johnson   } else {
6285a95c477STeresa Johnson     GlobalValue *NewGV;
6295a95c477STeresa Johnson     if (GV.getValueType()->isFunctionTy())
6305a95c477STeresa Johnson       NewGV =
6315a95c477STeresa Johnson           Function::Create(cast<FunctionType>(GV.getValueType()),
6325a95c477STeresa Johnson                            GlobalValue::ExternalLinkage, "", GV.getParent());
6335a95c477STeresa Johnson     else
6345a95c477STeresa Johnson       NewGV =
6355a95c477STeresa Johnson           new GlobalVariable(*GV.getParent(), GV.getValueType(),
6365a95c477STeresa Johnson                              /*isConstant*/ false, GlobalValue::ExternalLinkage,
6375a95c477STeresa Johnson                              /*init*/ nullptr, "",
6385a95c477STeresa Johnson                              /*insertbefore*/ nullptr, GV.getThreadLocalMode(),
6395a95c477STeresa Johnson                              GV.getType()->getAddressSpace());
6405a95c477STeresa Johnson     NewGV->takeName(&GV);
6415a95c477STeresa Johnson     GV.replaceAllUsesWith(NewGV);
6425a95c477STeresa Johnson     return false;
6435a95c477STeresa Johnson   }
6445a95c477STeresa Johnson   return true;
645eaf5172cSGeorge Rimar }
6464566c6dbSTeresa Johnson 
647eaf5172cSGeorge Rimar /// Fixup WeakForLinker linkages in \p TheModule based on summary analysis.
648eaf5172cSGeorge Rimar void llvm::thinLTOResolveWeakForLinkerModule(
649eaf5172cSGeorge Rimar     Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
65004c9a2d6STeresa Johnson   auto updateLinkage = [&](GlobalValue &GV) {
65104c9a2d6STeresa Johnson     // See if the global summary analysis computed a new resolved linkage.
65204c9a2d6STeresa Johnson     const auto &GS = DefinedGlobals.find(GV.getGUID());
65304c9a2d6STeresa Johnson     if (GS == DefinedGlobals.end())
65404c9a2d6STeresa Johnson       return;
65504c9a2d6STeresa Johnson     auto NewLinkage = GS->second->linkage();
65604c9a2d6STeresa Johnson     if (NewLinkage == GV.getLinkage())
65704c9a2d6STeresa Johnson       return;
6586a5fbe52SDavide Italiano 
6596a5fbe52SDavide Italiano     // Switch the linkage to weakany if asked for, e.g. we do this for
6606a5fbe52SDavide Italiano     // linker redefined symbols (via --wrap or --defsym).
661f4891d29SDavide Italiano     // We record that the visibility should be changed here in `addThinLTO`
662f4891d29SDavide Italiano     // as we need access to the resolution vectors for each input file in
663f4891d29SDavide Italiano     // order to find which symbols have been redefined.
664f4891d29SDavide Italiano     // We may consider reorganizing this code and moving the linkage recording
665f4891d29SDavide Italiano     // somewhere else, e.g. in thinLTOResolveWeakForLinkerInIndex.
6666a5fbe52SDavide Italiano     if (NewLinkage == GlobalValue::WeakAnyLinkage) {
6676a5fbe52SDavide Italiano       GV.setLinkage(NewLinkage);
6686a5fbe52SDavide Italiano       return;
6696a5fbe52SDavide Italiano     }
6706a5fbe52SDavide Italiano 
6716a5fbe52SDavide Italiano     if (!GlobalValue::isWeakForLinker(GV.getLinkage()))
6726a5fbe52SDavide Italiano       return;
6734566c6dbSTeresa Johnson     // Check for a non-prevailing def that has interposable linkage
6744566c6dbSTeresa Johnson     // (e.g. non-odr weak or linkonce). In that case we can't simply
6754566c6dbSTeresa Johnson     // convert to available_externally, since it would lose the
6764566c6dbSTeresa Johnson     // interposable property and possibly get inlined. Simply drop
6774566c6dbSTeresa Johnson     // the definition in that case.
6784566c6dbSTeresa Johnson     if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) &&
6795a95c477STeresa Johnson         GlobalValue::isInterposableLinkage(GV.getLinkage())) {
6805a95c477STeresa Johnson       if (!convertToDeclaration(GV))
6815a95c477STeresa Johnson         // FIXME: Change this to collect replaced GVs and later erase
6825a95c477STeresa Johnson         // them from the parent module once thinLTOResolveWeakForLinkerGUID is
6835a95c477STeresa Johnson         // changed to enable this for aliases.
6845a95c477STeresa Johnson         llvm_unreachable("Expected GV to be converted");
6855a95c477STeresa Johnson     } else {
68633ba93c2SSteven Wu       // If the original symbols has global unnamed addr and linkonce_odr linkage,
68733ba93c2SSteven Wu       // it should be an auto hide symbol. Add hidden visibility to the symbol to
68833ba93c2SSteven Wu       // preserve the property.
68933ba93c2SSteven Wu       if (GV.hasLinkOnceODRLinkage() && GV.hasGlobalUnnamedAddr() &&
69033ba93c2SSteven Wu           NewLinkage == GlobalValue::WeakODRLinkage)
69133ba93c2SSteven Wu         GV.setVisibility(GlobalValue::HiddenVisibility);
69233ba93c2SSteven Wu 
69304c9a2d6STeresa Johnson       DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
69404c9a2d6STeresa Johnson                    << GV.getLinkage() << " to " << NewLinkage << "\n");
69504c9a2d6STeresa Johnson       GV.setLinkage(NewLinkage);
6964566c6dbSTeresa Johnson     }
6974566c6dbSTeresa Johnson     // Remove declarations from comdats, including available_externally
6986107a419STeresa Johnson     // as this is a declaration for the linker, and will be dropped eventually.
6996107a419STeresa Johnson     // It is illegal for comdats to contain declarations.
7006107a419STeresa Johnson     auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
7014566c6dbSTeresa Johnson     if (GO && GO->isDeclarationForLinker() && GO->hasComdat())
7026107a419STeresa Johnson       GO->setComdat(nullptr);
70304c9a2d6STeresa Johnson   };
70404c9a2d6STeresa Johnson 
70504c9a2d6STeresa Johnson   // Process functions and global now
70604c9a2d6STeresa Johnson   for (auto &GV : TheModule)
70704c9a2d6STeresa Johnson     updateLinkage(GV);
70804c9a2d6STeresa Johnson   for (auto &GV : TheModule.globals())
70904c9a2d6STeresa Johnson     updateLinkage(GV);
71004c9a2d6STeresa Johnson   for (auto &GV : TheModule.aliases())
71104c9a2d6STeresa Johnson     updateLinkage(GV);
71204c9a2d6STeresa Johnson }
71304c9a2d6STeresa Johnson 
71404c9a2d6STeresa Johnson /// Run internalization on \p TheModule based on symmary analysis.
71504c9a2d6STeresa Johnson void llvm::thinLTOInternalizeModule(Module &TheModule,
71604c9a2d6STeresa Johnson                                     const GVSummaryMapTy &DefinedGlobals) {
71704c9a2d6STeresa Johnson   // Declare a callback for the internalize pass that will ask for every
71804c9a2d6STeresa Johnson   // candidate GlobalValue if it can be internalized or not.
71904c9a2d6STeresa Johnson   auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
72004c9a2d6STeresa Johnson     // Lookup the linkage recorded in the summaries during global analysis.
721c3d677f9SPeter Collingbourne     auto GS = DefinedGlobals.find(GV.getGUID());
72204c9a2d6STeresa Johnson     if (GS == DefinedGlobals.end()) {
72304c9a2d6STeresa Johnson       // Must have been promoted (possibly conservatively). Find original
72404c9a2d6STeresa Johnson       // name so that we can access the correct summary and see if it can
72504c9a2d6STeresa Johnson       // be internalized again.
72604c9a2d6STeresa Johnson       // FIXME: Eventually we should control promotion instead of promoting
72704c9a2d6STeresa Johnson       // and internalizing again.
72804c9a2d6STeresa Johnson       StringRef OrigName =
72904c9a2d6STeresa Johnson           ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
73004c9a2d6STeresa Johnson       std::string OrigId = GlobalValue::getGlobalIdentifier(
73104c9a2d6STeresa Johnson           OrigName, GlobalValue::InternalLinkage,
73204c9a2d6STeresa Johnson           TheModule.getSourceFileName());
733c3d677f9SPeter Collingbourne       GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
7347ab1f692STeresa Johnson       if (GS == DefinedGlobals.end()) {
7357ab1f692STeresa Johnson         // Also check the original non-promoted non-globalized name. In some
7367ab1f692STeresa Johnson         // cases a preempted weak value is linked in as a local copy because
7377ab1f692STeresa Johnson         // it is referenced by an alias (IRLinker::linkGlobalValueProto).
7387ab1f692STeresa Johnson         // In that case, since it was originally not a local value, it was
7397ab1f692STeresa Johnson         // recorded in the index using the original name.
7407ab1f692STeresa Johnson         // FIXME: This may not be needed once PR27866 is fixed.
741c3d677f9SPeter Collingbourne         GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
74204c9a2d6STeresa Johnson         assert(GS != DefinedGlobals.end());
7437ab1f692STeresa Johnson       }
744c3d677f9SPeter Collingbourne     }
745c3d677f9SPeter Collingbourne     return !GlobalValue::isLocalLinkage(GS->second->linkage());
74604c9a2d6STeresa Johnson   };
74704c9a2d6STeresa Johnson 
74804c9a2d6STeresa Johnson   // FIXME: See if we can just internalize directly here via linkage changes
74904c9a2d6STeresa Johnson   // based on the index, rather than invoking internalizeModule.
750e9ea08a0SEugene Zelenko   internalizeModule(TheModule, MustPreserveGV);
75104c9a2d6STeresa Johnson }
75204c9a2d6STeresa Johnson 
75381bbf742STeresa Johnson /// Make alias a clone of its aliasee.
75481bbf742STeresa Johnson static Function *replaceAliasWithAliasee(Module *SrcModule, GlobalAlias *GA) {
75581bbf742STeresa Johnson   Function *Fn = cast<Function>(GA->getBaseObject());
75681bbf742STeresa Johnson 
75781bbf742STeresa Johnson   ValueToValueMapTy VMap;
75881bbf742STeresa Johnson   Function *NewFn = CloneFunction(Fn, VMap);
75981bbf742STeresa Johnson   // Clone should use the original alias's linkage and name, and we ensure
76081bbf742STeresa Johnson   // all uses of alias instead use the new clone (casted if necessary).
76181bbf742STeresa Johnson   NewFn->setLinkage(GA->getLinkage());
76281bbf742STeresa Johnson   GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewFn, GA->getType()));
76381bbf742STeresa Johnson   NewFn->takeName(GA);
76481bbf742STeresa Johnson   return NewFn;
76581bbf742STeresa Johnson }
76681bbf742STeresa Johnson 
767c8c55170SMehdi Amini // Automatically import functions in Module \p DestModule based on the summaries
768c8c55170SMehdi Amini // index.
7697f00d0a1SPeter Collingbourne Expected<bool> FunctionImporter::importFunctions(
77066043797SAdrian Prantl     Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
7715411d051SMehdi Amini   DEBUG(dbgs() << "Starting import for Module "
772311fef6eSMehdi Amini                << DestModule.getModuleIdentifier() << "\n");
773c8c55170SMehdi Amini   unsigned ImportedCount = 0;
774c8c55170SMehdi Amini 
7756d8f817fSPeter Collingbourne   IRMover Mover(DestModule);
7767e88d0daSMehdi Amini   // Do the actual import of functions now, one Module at a time
77701e32130SMehdi Amini   std::set<StringRef> ModuleNameOrderedList;
77801e32130SMehdi Amini   for (auto &FunctionsToImportPerModule : ImportList) {
77901e32130SMehdi Amini     ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
78001e32130SMehdi Amini   }
78101e32130SMehdi Amini   for (auto &Name : ModuleNameOrderedList) {
7827e88d0daSMehdi Amini     // Get the module for the import
78301e32130SMehdi Amini     const auto &FunctionsToImportPerModule = ImportList.find(Name);
78401e32130SMehdi Amini     assert(FunctionsToImportPerModule != ImportList.end());
785d9445c49SPeter Collingbourne     Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
786d9445c49SPeter Collingbourne     if (!SrcModuleOrErr)
787d9445c49SPeter Collingbourne       return SrcModuleOrErr.takeError();
788d9445c49SPeter Collingbourne     std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
7897e88d0daSMehdi Amini     assert(&DestModule.getContext() == &SrcModule->getContext() &&
7907e88d0daSMehdi Amini            "Context mismatch");
7917e88d0daSMehdi Amini 
7926cba37ceSTeresa Johnson     // If modules were created with lazy metadata loading, materialize it
7936cba37ceSTeresa Johnson     // now, before linking it (otherwise this will be a noop).
7947f00d0a1SPeter Collingbourne     if (Error Err = SrcModule->materializeMetadata())
7957f00d0a1SPeter Collingbourne       return std::move(Err);
796e5a61917STeresa Johnson 
79701e32130SMehdi Amini     auto &ImportGUIDs = FunctionsToImportPerModule->second;
79801e32130SMehdi Amini     // Find the globals to import
7996d8f817fSPeter Collingbourne     SetVector<GlobalValue *> GlobalsToImport;
8001f685e01SPiotr Padlewski     for (Function &F : *SrcModule) {
8011f685e01SPiotr Padlewski       if (!F.hasName())
8020beb858eSTeresa Johnson         continue;
8031f685e01SPiotr Padlewski       auto GUID = F.getGUID();
8040beb858eSTeresa Johnson       auto Import = ImportGUIDs.count(GUID);
805aeb1e59bSMehdi Amini       DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " << GUID
8061f685e01SPiotr Padlewski                    << " " << F.getName() << " from "
807aeb1e59bSMehdi Amini                    << SrcModule->getSourceFileName() << "\n");
8080beb858eSTeresa Johnson       if (Import) {
8097f00d0a1SPeter Collingbourne         if (Error Err = F.materialize())
8107f00d0a1SPeter Collingbourne           return std::move(Err);
8113b776128SPiotr Padlewski         if (EnableImportMetadata) {
8126deaa6afSPiotr Padlewski           // Add 'thinlto_src_module' metadata for statistics and debugging.
8133b776128SPiotr Padlewski           F.setMetadata(
8143b776128SPiotr Padlewski               "thinlto_src_module",
815e9ea08a0SEugene Zelenko               MDNode::get(DestModule.getContext(),
816e9ea08a0SEugene Zelenko                           {MDString::get(DestModule.getContext(),
8176deaa6afSPiotr Padlewski                                          SrcModule->getSourceFileName())}));
8183b776128SPiotr Padlewski         }
8191f685e01SPiotr Padlewski         GlobalsToImport.insert(&F);
82001e32130SMehdi Amini       }
82101e32130SMehdi Amini     }
8221f685e01SPiotr Padlewski     for (GlobalVariable &GV : SrcModule->globals()) {
8232d28f7aaSMehdi Amini       if (!GV.hasName())
8242d28f7aaSMehdi Amini         continue;
8252d28f7aaSMehdi Amini       auto GUID = GV.getGUID();
8262d28f7aaSMehdi Amini       auto Import = ImportGUIDs.count(GUID);
827aeb1e59bSMehdi Amini       DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " << GUID
828aeb1e59bSMehdi Amini                    << " " << GV.getName() << " from "
829aeb1e59bSMehdi Amini                    << SrcModule->getSourceFileName() << "\n");
8302d28f7aaSMehdi Amini       if (Import) {
8317f00d0a1SPeter Collingbourne         if (Error Err = GV.materialize())
8327f00d0a1SPeter Collingbourne           return std::move(Err);
8332d28f7aaSMehdi Amini         GlobalsToImport.insert(&GV);
8342d28f7aaSMehdi Amini       }
8352d28f7aaSMehdi Amini     }
8361f685e01SPiotr Padlewski     for (GlobalAlias &GA : SrcModule->aliases()) {
8371f685e01SPiotr Padlewski       if (!GA.hasName())
83801e32130SMehdi Amini         continue;
8391f685e01SPiotr Padlewski       auto GUID = GA.getGUID();
84081bbf742STeresa Johnson       auto Import = ImportGUIDs.count(GUID);
84181bbf742STeresa Johnson       DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias " << GUID
8421f685e01SPiotr Padlewski                    << " " << GA.getName() << " from "
843aeb1e59bSMehdi Amini                    << SrcModule->getSourceFileName() << "\n");
84481bbf742STeresa Johnson       if (Import) {
84581bbf742STeresa Johnson         if (Error Err = GA.materialize())
84681bbf742STeresa Johnson           return std::move(Err);
84781bbf742STeresa Johnson         // Import alias as a copy of its aliasee.
84881bbf742STeresa Johnson         GlobalObject *Base = GA.getBaseObject();
84981bbf742STeresa Johnson         if (Error Err = Base->materialize())
85081bbf742STeresa Johnson           return std::move(Err);
85181bbf742STeresa Johnson         auto *Fn = replaceAliasWithAliasee(SrcModule.get(), &GA);
85281bbf742STeresa Johnson         DEBUG(dbgs() << "Is importing aliasee fn " << Base->getGUID()
85381bbf742STeresa Johnson               << " " << Base->getName() << " from "
85481bbf742STeresa Johnson               << SrcModule->getSourceFileName() << "\n");
85581bbf742STeresa Johnson         if (EnableImportMetadata) {
85681bbf742STeresa Johnson           // Add 'thinlto_src_module' metadata for statistics and debugging.
85781bbf742STeresa Johnson           Fn->setMetadata(
85881bbf742STeresa Johnson               "thinlto_src_module",
85981bbf742STeresa Johnson               MDNode::get(DestModule.getContext(),
86081bbf742STeresa Johnson                           {MDString::get(DestModule.getContext(),
86181bbf742STeresa Johnson                                          SrcModule->getSourceFileName())}));
86201e32130SMehdi Amini         }
86381bbf742STeresa Johnson         GlobalsToImport.insert(Fn);
86481bbf742STeresa Johnson       }
86581bbf742STeresa Johnson     }
86601e32130SMehdi Amini 
86719ef4fadSMehdi Amini     // Upgrade debug info after we're done materializing all the globals and we
86819ef4fadSMehdi Amini     // have loaded all the required metadata!
86919ef4fadSMehdi Amini     UpgradeDebugInfo(*SrcModule);
87019ef4fadSMehdi Amini 
8717e88d0daSMehdi Amini     // Link in the specified functions.
87201e32130SMehdi Amini     if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
8738d05185aSMehdi Amini       return true;
8748d05185aSMehdi Amini 
875d29478f7STeresa Johnson     if (PrintImports) {
876d29478f7STeresa Johnson       for (const auto *GV : GlobalsToImport)
877d29478f7STeresa Johnson         dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
878d29478f7STeresa Johnson                << " from " << SrcModule->getSourceFileName() << "\n";
879d29478f7STeresa Johnson     }
880d29478f7STeresa Johnson 
8816d8f817fSPeter Collingbourne     if (Mover.move(std::move(SrcModule), GlobalsToImport.getArrayRef(),
8826d8f817fSPeter Collingbourne                    [](GlobalValue &, IRMover::ValueAdder) {},
883e6fd9ff9SPeter Collingbourne                    /*IsPerformingImport=*/true))
8847e88d0daSMehdi Amini       report_fatal_error("Function Import: link error");
8857e88d0daSMehdi Amini 
88601e32130SMehdi Amini     ImportedCount += GlobalsToImport.size();
8876c475a75STeresa Johnson     NumImportedModules++;
8887e88d0daSMehdi Amini   }
889e5a61917STeresa Johnson 
8906c475a75STeresa Johnson   NumImportedFunctions += ImportedCount;
891d29478f7STeresa Johnson 
8927e88d0daSMehdi Amini   DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
893c8c55170SMehdi Amini                << DestModule.getModuleIdentifier() << "\n");
894c8c55170SMehdi Amini   return ImportedCount;
89542418abaSMehdi Amini }
89642418abaSMehdi Amini 
897598bd2a2SPeter Collingbourne static bool doImportingForModule(Module &M) {
898598bd2a2SPeter Collingbourne   if (SummaryFile.empty())
899598bd2a2SPeter Collingbourne     report_fatal_error("error: -function-import requires -summary-file\n");
9006de481a3SPeter Collingbourne   Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
9016de481a3SPeter Collingbourne       getModuleSummaryIndexForFile(SummaryFile);
9026de481a3SPeter Collingbourne   if (!IndexPtrOrErr) {
9036de481a3SPeter Collingbourne     logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
9046de481a3SPeter Collingbourne                           "Error loading file '" + SummaryFile + "': ");
90542418abaSMehdi Amini     return false;
90642418abaSMehdi Amini   }
907598bd2a2SPeter Collingbourne   std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
90842418abaSMehdi Amini 
909c86af334STeresa Johnson   // First step is collecting the import list.
910c86af334STeresa Johnson   FunctionImporter::ImportMapTy ImportList;
91181bbf742STeresa Johnson   // If requested, simply import all functions in the index. This is used
91281bbf742STeresa Johnson   // when testing distributed backend handling via the opt tool, when
91381bbf742STeresa Johnson   // we have distributed indexes containing exactly the summaries to import.
91481bbf742STeresa Johnson   if (ImportAllIndex)
91581bbf742STeresa Johnson     ComputeCrossModuleImportForModuleFromIndex(M.getModuleIdentifier(), *Index,
91681bbf742STeresa Johnson                                                ImportList);
91781bbf742STeresa Johnson   else
918c86af334STeresa Johnson     ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
919c86af334STeresa Johnson                                       ImportList);
92001e32130SMehdi Amini 
9214fef68cbSTeresa Johnson   // Conservatively mark all internal values as promoted. This interface is
9224fef68cbSTeresa Johnson   // only used when doing importing via the function importing pass. The pass
9234fef68cbSTeresa Johnson   // is only enabled when testing importing via the 'opt' tool, which does
9244fef68cbSTeresa Johnson   // not do the ThinLink that would normally determine what values to promote.
9254fef68cbSTeresa Johnson   for (auto &I : *Index) {
9269667b91bSPeter Collingbourne     for (auto &S : I.second.SummaryList) {
9274fef68cbSTeresa Johnson       if (GlobalValue::isLocalLinkage(S->linkage()))
9284fef68cbSTeresa Johnson         S->setLinkage(GlobalValue::ExternalLinkage);
9294fef68cbSTeresa Johnson     }
9304fef68cbSTeresa Johnson   }
9314fef68cbSTeresa Johnson 
93201e32130SMehdi Amini   // Next we need to promote to global scope and rename any local values that
9331b00f2d9STeresa Johnson   // are potentially exported to other modules.
93401e32130SMehdi Amini   if (renameModuleForThinLTO(M, *Index, nullptr)) {
9351b00f2d9STeresa Johnson     errs() << "Error renaming module\n";
9361b00f2d9STeresa Johnson     return false;
9371b00f2d9STeresa Johnson   }
9381b00f2d9STeresa Johnson 
93942418abaSMehdi Amini   // Perform the import now.
940d16c8065SMehdi Amini   auto ModuleLoader = [&M](StringRef Identifier) {
941d16c8065SMehdi Amini     return loadFile(Identifier, M.getContext());
942d16c8065SMehdi Amini   };
9439d2bfc48SRafael Espindola   FunctionImporter Importer(*Index, ModuleLoader);
94437e24591SPeter Collingbourne   Expected<bool> Result = Importer.importFunctions(M, ImportList);
9457f00d0a1SPeter Collingbourne 
9467f00d0a1SPeter Collingbourne   // FIXME: Probably need to propagate Errors through the pass manager.
9477f00d0a1SPeter Collingbourne   if (!Result) {
9487f00d0a1SPeter Collingbourne     logAllUnhandledErrors(Result.takeError(), errs(),
9497f00d0a1SPeter Collingbourne                           "Error importing module: ");
9507f00d0a1SPeter Collingbourne     return false;
9517f00d0a1SPeter Collingbourne   }
9527f00d0a1SPeter Collingbourne 
9537f00d0a1SPeter Collingbourne   return *Result;
95421241571STeresa Johnson }
95521241571STeresa Johnson 
95621241571STeresa Johnson namespace {
957e9ea08a0SEugene Zelenko 
95821241571STeresa Johnson /// Pass that performs cross-module function import provided a summary file.
95921241571STeresa Johnson class FunctionImportLegacyPass : public ModulePass {
96021241571STeresa Johnson public:
96121241571STeresa Johnson   /// Pass identification, replacement for typeid
96221241571STeresa Johnson   static char ID;
96321241571STeresa Johnson 
964e9ea08a0SEugene Zelenko   explicit FunctionImportLegacyPass() : ModulePass(ID) {}
965e9ea08a0SEugene Zelenko 
96621241571STeresa Johnson   /// Specify pass name for debug output
967117296c0SMehdi Amini   StringRef getPassName() const override { return "Function Importing"; }
96821241571STeresa Johnson 
96921241571STeresa Johnson   bool runOnModule(Module &M) override {
97021241571STeresa Johnson     if (skipModule(M))
97121241571STeresa Johnson       return false;
97221241571STeresa Johnson 
973598bd2a2SPeter Collingbourne     return doImportingForModule(M);
97442418abaSMehdi Amini   }
97542418abaSMehdi Amini };
976e9ea08a0SEugene Zelenko 
977e9ea08a0SEugene Zelenko } // end anonymous namespace
97842418abaSMehdi Amini 
97921241571STeresa Johnson PreservedAnalyses FunctionImportPass::run(Module &M,
980fd03ac6aSSean Silva                                           ModuleAnalysisManager &AM) {
981598bd2a2SPeter Collingbourne   if (!doImportingForModule(M))
98221241571STeresa Johnson     return PreservedAnalyses::all();
98321241571STeresa Johnson 
98421241571STeresa Johnson   return PreservedAnalyses::none();
98521241571STeresa Johnson }
98621241571STeresa Johnson 
98721241571STeresa Johnson char FunctionImportLegacyPass::ID = 0;
98821241571STeresa Johnson INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
98942418abaSMehdi Amini                 "Summary Based Function Import", false, false)
99042418abaSMehdi Amini 
99142418abaSMehdi Amini namespace llvm {
992e9ea08a0SEugene Zelenko 
993598bd2a2SPeter Collingbourne Pass *createFunctionImportPass() {
994598bd2a2SPeter Collingbourne   return new FunctionImportLegacyPass();
9955fcbdb71STeresa Johnson }
996e9ea08a0SEugene Zelenko 
997e9ea08a0SEugene Zelenko } // end namespace llvm
998