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"
1542418abaSMehdi Amini 
1601e32130SMehdi Amini #include "llvm/ADT/SmallVector.h"
17d29478f7STeresa Johnson #include "llvm/ADT/Statistic.h"
1842418abaSMehdi Amini #include "llvm/ADT/StringSet.h"
1904c9a2d6STeresa Johnson #include "llvm/ADT/Triple.h"
2042418abaSMehdi Amini #include "llvm/IR/AutoUpgrade.h"
2142418abaSMehdi Amini #include "llvm/IR/DiagnosticPrinter.h"
2242418abaSMehdi Amini #include "llvm/IR/IntrinsicInst.h"
2342418abaSMehdi Amini #include "llvm/IR/Module.h"
2442418abaSMehdi Amini #include "llvm/IRReader/IRReader.h"
2542418abaSMehdi Amini #include "llvm/Linker/Linker.h"
2604c9a2d6STeresa Johnson #include "llvm/Object/IRObjectFile.h"
2726ab5772STeresa Johnson #include "llvm/Object/ModuleSummaryIndexObjectFile.h"
2842418abaSMehdi Amini #include "llvm/Support/CommandLine.h"
2942418abaSMehdi Amini #include "llvm/Support/Debug.h"
3042418abaSMehdi Amini #include "llvm/Support/SourceMgr.h"
3104c9a2d6STeresa Johnson #include "llvm/Transforms/IPO/Internalize.h"
32488a800aSTeresa Johnson #include "llvm/Transforms/Utils/FunctionImportUtils.h"
337e88d0daSMehdi Amini 
3401e32130SMehdi Amini #define DEBUG_TYPE "function-import"
357e88d0daSMehdi Amini 
3642418abaSMehdi Amini using namespace llvm;
3742418abaSMehdi Amini 
38d29478f7STeresa Johnson STATISTIC(NumImported, "Number of functions imported");
39d29478f7STeresa Johnson 
4039303619STeresa Johnson /// Limit on instruction count of imported functions.
4139303619STeresa Johnson static cl::opt<unsigned> ImportInstrLimit(
4239303619STeresa Johnson     "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
4339303619STeresa Johnson     cl::desc("Only import functions with less than N instructions"));
4439303619STeresa Johnson 
4540641748SMehdi Amini static cl::opt<float>
4640641748SMehdi Amini     ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7),
4740641748SMehdi Amini                       cl::Hidden, cl::value_desc("x"),
4840641748SMehdi Amini                       cl::desc("As we import functions, multiply the "
4940641748SMehdi Amini                                "`import-instr-limit` threshold by this factor "
5040641748SMehdi Amini                                "before processing newly imported functions"));
51ba72b95fSPiotr Padlewski 
52d2869473SPiotr Padlewski static cl::opt<float> ImportHotInstrFactor(
53d2869473SPiotr Padlewski     "import-hot-evolution-factor", cl::init(1.0), cl::Hidden,
54d2869473SPiotr Padlewski     cl::value_desc("x"),
55d2869473SPiotr Padlewski     cl::desc("As we import functions called from hot callsite, multiply the "
56d2869473SPiotr Padlewski              "`import-instr-limit` threshold by this factor "
57d2869473SPiotr Padlewski              "before processing newly imported functions"));
58d2869473SPiotr Padlewski 
59d9830eb7SPiotr Padlewski static cl::opt<float> ImportHotMultiplier(
60d9830eb7SPiotr Padlewski     "import-hot-multiplier", cl::init(3.0), cl::Hidden, cl::value_desc("x"),
61ba72b95fSPiotr Padlewski     cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"));
62ba72b95fSPiotr Padlewski 
63ba72b95fSPiotr Padlewski // FIXME: This multiplier was not really tuned up.
64ba72b95fSPiotr Padlewski static cl::opt<float> ImportColdMultiplier(
65ba72b95fSPiotr Padlewski     "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"),
66ba72b95fSPiotr Padlewski     cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"));
6740641748SMehdi Amini 
68d29478f7STeresa Johnson static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
69d29478f7STeresa Johnson                                   cl::desc("Print imported functions"));
70d29478f7STeresa Johnson 
71bda3c97cSMehdi Amini // Temporary allows the function import pass to disable always linking
72bda3c97cSMehdi Amini // referenced discardable symbols.
73bda3c97cSMehdi Amini static cl::opt<bool>
74bda3c97cSMehdi Amini     DontForceImportReferencedDiscardableSymbols("disable-force-link-odr",
75bda3c97cSMehdi Amini                                                 cl::init(false), cl::Hidden);
76bda3c97cSMehdi Amini 
773b776128SPiotr Padlewski static cl::opt<bool> EnableImportMetadata(
783b776128SPiotr Padlewski     "enable-import-metadata", cl::init(
793b776128SPiotr Padlewski #if !defined(NDEBUG)
803b776128SPiotr Padlewski                                   true /*Enabled with asserts.*/
813b776128SPiotr Padlewski #else
823b776128SPiotr Padlewski                                   false
833b776128SPiotr Padlewski #endif
843b776128SPiotr Padlewski                                   ),
853b776128SPiotr Padlewski     cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'"));
863b776128SPiotr Padlewski 
8742418abaSMehdi Amini // Load lazily a module from \p FileName in \p Context.
8842418abaSMehdi Amini static std::unique_ptr<Module> loadFile(const std::string &FileName,
8942418abaSMehdi Amini                                         LLVMContext &Context) {
9042418abaSMehdi Amini   SMDiagnostic Err;
9142418abaSMehdi Amini   DEBUG(dbgs() << "Loading '" << FileName << "'\n");
926cba37ceSTeresa Johnson   // Metadata isn't loaded until functions are imported, to minimize
936cba37ceSTeresa Johnson   // the memory overhead.
94a1080ee6STeresa Johnson   std::unique_ptr<Module> Result =
95a1080ee6STeresa Johnson       getLazyIRFileModule(FileName, Err, Context,
96a1080ee6STeresa Johnson                           /* ShouldLazyLoadMetadata = */ true);
9742418abaSMehdi Amini   if (!Result) {
9842418abaSMehdi Amini     Err.print("function-import", errs());
99d7ad221cSMehdi Amini     report_fatal_error("Abort");
10042418abaSMehdi Amini   }
10142418abaSMehdi Amini 
10242418abaSMehdi Amini   return Result;
10342418abaSMehdi Amini }
10442418abaSMehdi Amini 
1057e88d0daSMehdi Amini namespace {
10640641748SMehdi Amini 
107b4e1e829SMehdi Amini // Return true if the Summary describes a GlobalValue that can be externally
108b4e1e829SMehdi Amini // referenced, i.e. it does not need renaming (linkage is not local) or renaming
109b4e1e829SMehdi Amini // is possible (does not have a section for instance).
110b4e1e829SMehdi Amini static bool canBeExternallyReferenced(const GlobalValueSummary &Summary) {
111b4e1e829SMehdi Amini   if (!Summary.needsRenaming())
112b4e1e829SMehdi Amini     return true;
113b4e1e829SMehdi Amini 
11458fbc916STeresa Johnson   if (Summary.noRename())
11558fbc916STeresa Johnson     // Can't externally reference a global that needs renaming if has a section
11658fbc916STeresa Johnson     // or is referenced from inline assembly, for example.
117b4e1e829SMehdi Amini     return false;
118b4e1e829SMehdi Amini 
119b4e1e829SMehdi Amini   return true;
120b4e1e829SMehdi Amini }
121b4e1e829SMehdi Amini 
122b4e1e829SMehdi Amini // Return true if \p GUID describes a GlobalValue that can be externally
123b4e1e829SMehdi Amini // referenced, i.e. it does not need renaming (linkage is not local) or
124b4e1e829SMehdi Amini // renaming is possible (does not have a section for instance).
125b4e1e829SMehdi Amini static bool canBeExternallyReferenced(const ModuleSummaryIndex &Index,
126b4e1e829SMehdi Amini                                       GlobalValue::GUID GUID) {
127b4e1e829SMehdi Amini   auto Summaries = Index.findGlobalValueSummaryList(GUID);
128b4e1e829SMehdi Amini   if (Summaries == Index.end())
129b4e1e829SMehdi Amini     return true;
130b4e1e829SMehdi Amini   if (Summaries->second.size() != 1)
131b4e1e829SMehdi Amini     // If there are multiple globals with this GUID, then we know it is
132b4e1e829SMehdi Amini     // not a local symbol, and it is necessarily externally referenced.
133b4e1e829SMehdi Amini     return true;
134b4e1e829SMehdi Amini 
135b4e1e829SMehdi Amini   // We don't need to check for the module path, because if it can't be
136b4e1e829SMehdi Amini   // externally referenced and we call it, it is necessarilly in the same
137b4e1e829SMehdi Amini   // module
138b4e1e829SMehdi Amini   return canBeExternallyReferenced(**Summaries->second.begin());
139b4e1e829SMehdi Amini }
140b4e1e829SMehdi Amini 
141b4e1e829SMehdi Amini // Return true if the global described by \p Summary can be imported in another
142b4e1e829SMehdi Amini // module.
143b4e1e829SMehdi Amini static bool eligibleForImport(const ModuleSummaryIndex &Index,
144b4e1e829SMehdi Amini                               const GlobalValueSummary &Summary) {
145b4e1e829SMehdi Amini   if (!canBeExternallyReferenced(Summary))
146b4e1e829SMehdi Amini     // Can't import a global that needs renaming if has a section for instance.
147b4e1e829SMehdi Amini     // FIXME: we may be able to import it by copying it without promotion.
148b4e1e829SMehdi Amini     return false;
149b4e1e829SMehdi Amini 
150332b3b22SPiotr Padlewski   // Don't import functions that are not viable to inline.
151332b3b22SPiotr Padlewski   if (Summary.isNotViableToInline())
152332b3b22SPiotr Padlewski     return false;
153332b3b22SPiotr Padlewski 
154b4e1e829SMehdi Amini   // Check references (and potential calls) in the same module. If the current
155b4e1e829SMehdi Amini   // value references a global that can't be externally referenced it is not
156d5033a45STeresa Johnson   // eligible for import. First check the flag set when we have possible
157d5033a45STeresa Johnson   // opaque references (e.g. inline asm calls), then check the call and
158d5033a45STeresa Johnson   // reference sets.
159d5033a45STeresa Johnson   if (Summary.hasInlineAsmMaybeReferencingInternal())
160d5033a45STeresa Johnson     return false;
161b4e1e829SMehdi Amini   bool AllRefsCanBeExternallyReferenced =
162b4e1e829SMehdi Amini       llvm::all_of(Summary.refs(), [&](const ValueInfo &VI) {
163b4e1e829SMehdi Amini         return canBeExternallyReferenced(Index, VI.getGUID());
164b4e1e829SMehdi Amini       });
165b4e1e829SMehdi Amini   if (!AllRefsCanBeExternallyReferenced)
166b4e1e829SMehdi Amini     return false;
167b4e1e829SMehdi Amini 
168b4e1e829SMehdi Amini   if (auto *FuncSummary = dyn_cast<FunctionSummary>(&Summary)) {
169b4e1e829SMehdi Amini     bool AllCallsCanBeExternallyReferenced = llvm::all_of(
170b4e1e829SMehdi Amini         FuncSummary->calls(), [&](const FunctionSummary::EdgeTy &Edge) {
171b4e1e829SMehdi Amini           return canBeExternallyReferenced(Index, Edge.first.getGUID());
172b4e1e829SMehdi Amini         });
173b4e1e829SMehdi Amini     if (!AllCallsCanBeExternallyReferenced)
174b4e1e829SMehdi Amini       return false;
175b4e1e829SMehdi Amini   }
176b4e1e829SMehdi Amini   return true;
177b4e1e829SMehdi Amini }
178b4e1e829SMehdi Amini 
17901e32130SMehdi Amini /// Given a list of possible callee implementation for a call site, select one
18001e32130SMehdi Amini /// that fits the \p Threshold.
18101e32130SMehdi Amini ///
18201e32130SMehdi Amini /// FIXME: select "best" instead of first that fits. But what is "best"?
18301e32130SMehdi Amini /// - The smallest: more likely to be inlined.
18401e32130SMehdi Amini /// - The one with the least outgoing edges (already well optimized).
18501e32130SMehdi Amini /// - One from a module already being imported from in order to reduce the
18601e32130SMehdi Amini ///   number of source modules parsed/linked.
18701e32130SMehdi Amini /// - One that has PGO data attached.
18801e32130SMehdi Amini /// - [insert you fancy metric here]
1892d28f7aaSMehdi Amini static const GlobalValueSummary *
190b4e1e829SMehdi Amini selectCallee(const ModuleSummaryIndex &Index,
191b4e1e829SMehdi Amini              const GlobalValueSummaryList &CalleeSummaryList,
19228e457bcSTeresa Johnson              unsigned Threshold) {
19301e32130SMehdi Amini   auto It = llvm::find_if(
19428e457bcSTeresa Johnson       CalleeSummaryList,
19528e457bcSTeresa Johnson       [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
19628e457bcSTeresa Johnson         auto *GVSummary = SummaryPtr.get();
197f329be83SRafael Espindola         if (GlobalValue::isInterposableLinkage(GVSummary->linkage()))
1985b85d8d6SMehdi Amini           // There is no point in importing these, we can't inline them
19901e32130SMehdi Amini           return false;
2002c719cc1SMehdi Amini         if (auto *AS = dyn_cast<AliasSummary>(GVSummary)) {
2012c719cc1SMehdi Amini           GVSummary = &AS->getAliasee();
2022c719cc1SMehdi Amini           // Alias can't point to "available_externally". However when we import
2032c719cc1SMehdi Amini           // linkOnceODR the linkage does not change. So we import the alias
2042c719cc1SMehdi Amini           // and aliasee only in this case.
2052c719cc1SMehdi Amini           // FIXME: we should import alias as available_externally *function*,
2062c719cc1SMehdi Amini           // the destination module does need to know it is an alias.
2072c719cc1SMehdi Amini           if (!GlobalValue::isLinkOnceODRLinkage(GVSummary->linkage()))
2082c719cc1SMehdi Amini             return false;
2092c719cc1SMehdi Amini         }
2102c719cc1SMehdi Amini 
2112c719cc1SMehdi Amini         auto *Summary = cast<FunctionSummary>(GVSummary);
2127e88d0daSMehdi Amini 
21301e32130SMehdi Amini         if (Summary->instCount() > Threshold)
21401e32130SMehdi Amini           return false;
2157e88d0daSMehdi Amini 
216b4e1e829SMehdi Amini         if (!eligibleForImport(Index, *Summary))
217b4e1e829SMehdi Amini           return false;
218b4e1e829SMehdi Amini 
21901e32130SMehdi Amini         return true;
22001e32130SMehdi Amini       });
22128e457bcSTeresa Johnson   if (It == CalleeSummaryList.end())
22201e32130SMehdi Amini     return nullptr;
2237e88d0daSMehdi Amini 
22428e457bcSTeresa Johnson   return cast<GlobalValueSummary>(It->get());
225434e9561SRafael Espindola }
2267e88d0daSMehdi Amini 
22701e32130SMehdi Amini /// Return the summary for the function \p GUID that fits the \p Threshold, or
22801e32130SMehdi Amini /// null if there's no match.
2292d28f7aaSMehdi Amini static const GlobalValueSummary *selectCallee(GlobalValue::GUID GUID,
230ad5741b0SMehdi Amini                                               unsigned Threshold,
23101e32130SMehdi Amini                                               const ModuleSummaryIndex &Index) {
23228e457bcSTeresa Johnson   auto CalleeSummaryList = Index.findGlobalValueSummaryList(GUID);
233b4e1e829SMehdi Amini   if (CalleeSummaryList == Index.end())
23401e32130SMehdi Amini     return nullptr; // This function does not have a summary
235b4e1e829SMehdi Amini   return selectCallee(Index, CalleeSummaryList->second, Threshold);
23601e32130SMehdi Amini }
2377e88d0daSMehdi Amini 
238cb87494fSMehdi Amini /// Mark the global \p GUID as export by module \p ExportModulePath if found in
2390c3f57b1STeresa Johnson /// this module.
240cb87494fSMehdi Amini static void exportGlobalInModule(const ModuleSummaryIndex &Index,
241ad5741b0SMehdi Amini                                  StringRef ExportModulePath,
242cb87494fSMehdi Amini                                  GlobalValue::GUID GUID,
243cb87494fSMehdi Amini                                  FunctionImporter::ExportSetTy &ExportList) {
24428e457bcSTeresa Johnson   auto FindGlobalSummaryInModule =
24528e457bcSTeresa Johnson       [&](GlobalValue::GUID GUID) -> GlobalValueSummary *{
24628e457bcSTeresa Johnson         auto SummaryList = Index.findGlobalValueSummaryList(GUID);
24728e457bcSTeresa Johnson         if (SummaryList == Index.end())
24801e32130SMehdi Amini           // This global does not have a summary, it is not part of the ThinLTO
24901e32130SMehdi Amini           // process
250cb87494fSMehdi Amini           return nullptr;
25128e457bcSTeresa Johnson         auto SummaryIter = llvm::find_if(
25228e457bcSTeresa Johnson             SummaryList->second,
25328e457bcSTeresa Johnson             [&](const std::unique_ptr<GlobalValueSummary> &Summary) {
25401e32130SMehdi Amini               return Summary->modulePath() == ExportModulePath;
25501e32130SMehdi Amini             });
25628e457bcSTeresa Johnson         if (SummaryIter == SummaryList->second.end())
257cb87494fSMehdi Amini           return nullptr;
25828e457bcSTeresa Johnson         return SummaryIter->get();
259cb87494fSMehdi Amini       };
260cb87494fSMehdi Amini 
26128e457bcSTeresa Johnson   auto *Summary = FindGlobalSummaryInModule(GUID);
26228e457bcSTeresa Johnson   if (!Summary)
263cb87494fSMehdi Amini     return;
264cb87494fSMehdi Amini   // We found it in the current module, mark as exported
265cb87494fSMehdi Amini   ExportList.insert(GUID);
26601e32130SMehdi Amini }
2677e88d0daSMehdi Amini 
268475b51a7STeresa Johnson using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */,
269475b51a7STeresa Johnson                             GlobalValue::GUID>;
27001e32130SMehdi Amini 
27101e32130SMehdi Amini /// Compute the list of functions to import for a given caller. Mark these
27201e32130SMehdi Amini /// imported functions and the symbols they reference in their source module as
27301e32130SMehdi Amini /// exported from their source module.
27401e32130SMehdi Amini static void computeImportForFunction(
2753255eec1STeresa Johnson     const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
276d9830eb7SPiotr Padlewski     const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
27701e32130SMehdi Amini     SmallVectorImpl<EdgeInfo> &Worklist,
2789b490f10SMehdi Amini     FunctionImporter::ImportMapTy &ImportList,
279c86af334STeresa Johnson     StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
28001e32130SMehdi Amini   for (auto &Edge : Summary.calls()) {
2812d5487cfSTeresa Johnson     auto GUID = Edge.first.getGUID();
28201e32130SMehdi Amini     DEBUG(dbgs() << " edge -> " << GUID << " Threshold:" << Threshold << "\n");
28301e32130SMehdi Amini 
2841aafabf7SMehdi Amini     if (DefinedGVSummaries.count(GUID)) {
28501e32130SMehdi Amini       DEBUG(dbgs() << "ignored! Target already in destination module.\n");
2867e88d0daSMehdi Amini       continue;
287d450da32STeresa Johnson     }
28840641748SMehdi Amini 
289ba72b95fSPiotr Padlewski     auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
290ba72b95fSPiotr Padlewski       if (Hotness == CalleeInfo::HotnessType::Hot)
291ba72b95fSPiotr Padlewski         return ImportHotMultiplier;
292ba72b95fSPiotr Padlewski       if (Hotness == CalleeInfo::HotnessType::Cold)
293ba72b95fSPiotr Padlewski         return ImportColdMultiplier;
294ba72b95fSPiotr Padlewski       return 1.0;
295ba72b95fSPiotr Padlewski     };
296ba72b95fSPiotr Padlewski 
297d9830eb7SPiotr Padlewski     const auto NewThreshold =
298ba72b95fSPiotr Padlewski         Threshold * GetBonusMultiplier(Edge.second.Hotness);
299d2869473SPiotr Padlewski 
300d9830eb7SPiotr Padlewski     auto *CalleeSummary = selectCallee(GUID, NewThreshold, Index);
30101e32130SMehdi Amini     if (!CalleeSummary) {
30201e32130SMehdi Amini       DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n");
3037e88d0daSMehdi Amini       continue;
3047e88d0daSMehdi Amini     }
3052d28f7aaSMehdi Amini     // "Resolve" the summary, traversing alias,
3062d28f7aaSMehdi Amini     const FunctionSummary *ResolvedCalleeSummary;
3076968ef77SMehdi Amini     if (isa<AliasSummary>(CalleeSummary)) {
3082d28f7aaSMehdi Amini       ResolvedCalleeSummary = cast<FunctionSummary>(
3092d28f7aaSMehdi Amini           &cast<AliasSummary>(CalleeSummary)->getAliasee());
3102c719cc1SMehdi Amini       assert(
3112c719cc1SMehdi Amini           GlobalValue::isLinkOnceODRLinkage(ResolvedCalleeSummary->linkage()) &&
3122c719cc1SMehdi Amini           "Unexpected alias to a non-linkonceODR in import list");
3136968ef77SMehdi Amini     } else
3142d28f7aaSMehdi Amini       ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
3152d28f7aaSMehdi Amini 
316d9830eb7SPiotr Padlewski     assert(ResolvedCalleeSummary->instCount() <= NewThreshold &&
31701e32130SMehdi Amini            "selectCallee() didn't honor the threshold");
31801e32130SMehdi Amini 
319d2869473SPiotr Padlewski     auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
320d2869473SPiotr Padlewski       // Adjust the threshold for next level of imported functions.
321d2869473SPiotr Padlewski       // The threshold is different for hot callsites because we can then
322d2869473SPiotr Padlewski       // inline chains of hot calls.
323d2869473SPiotr Padlewski       if (IsHotCallsite)
324d2869473SPiotr Padlewski         return Threshold * ImportHotInstrFactor;
325d2869473SPiotr Padlewski       return Threshold * ImportInstrFactor;
326d2869473SPiotr Padlewski     };
327d2869473SPiotr Padlewski 
328d2869473SPiotr Padlewski     bool IsHotCallsite = Edge.second.Hotness == CalleeInfo::HotnessType::Hot;
3291b859a23STeresa Johnson     const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
3301b859a23STeresa Johnson 
3311b859a23STeresa Johnson     auto ExportModulePath = ResolvedCalleeSummary->modulePath();
3321b859a23STeresa Johnson     auto &ProcessedThreshold = ImportList[ExportModulePath][GUID];
3331b859a23STeresa Johnson     /// Since the traversal of the call graph is DFS, we can revisit a function
3341b859a23STeresa Johnson     /// a second time with a higher threshold. In this case, it is added back to
3351b859a23STeresa Johnson     /// the worklist with the new threshold.
3361b859a23STeresa Johnson     if (ProcessedThreshold && ProcessedThreshold >= AdjThreshold) {
3371b859a23STeresa Johnson       DEBUG(dbgs() << "ignored! Target was already seen with Threshold "
3381b859a23STeresa Johnson                    << ProcessedThreshold << "\n");
3391b859a23STeresa Johnson       continue;
3401b859a23STeresa Johnson     }
341*19f2aa78STeresa Johnson     bool PreviouslyImported = ProcessedThreshold != 0;
3421b859a23STeresa Johnson     // Mark this function as imported in this module, with the current Threshold
3431b859a23STeresa Johnson     ProcessedThreshold = AdjThreshold;
3441b859a23STeresa Johnson 
3451b859a23STeresa Johnson     // Make exports in the source module.
3461b859a23STeresa Johnson     if (ExportLists) {
3471b859a23STeresa Johnson       auto &ExportList = (*ExportLists)[ExportModulePath];
3481b859a23STeresa Johnson       ExportList.insert(GUID);
349*19f2aa78STeresa Johnson       if (!PreviouslyImported) {
350*19f2aa78STeresa Johnson         // This is the first time this function was exported from its source
351*19f2aa78STeresa Johnson         // module, so mark all functions and globals it references as exported
3521b859a23STeresa Johnson         // to the outside if they are defined in the same source module.
3531b859a23STeresa Johnson         for (auto &Edge : ResolvedCalleeSummary->calls()) {
3541b859a23STeresa Johnson           auto CalleeGUID = Edge.first.getGUID();
3551b859a23STeresa Johnson           exportGlobalInModule(Index, ExportModulePath, CalleeGUID, ExportList);
3561b859a23STeresa Johnson         }
3571b859a23STeresa Johnson         for (auto &Ref : ResolvedCalleeSummary->refs()) {
3581b859a23STeresa Johnson           auto GUID = Ref.getGUID();
3591b859a23STeresa Johnson           exportGlobalInModule(Index, ExportModulePath, GUID, ExportList);
3601b859a23STeresa Johnson         }
3611b859a23STeresa Johnson       }
362*19f2aa78STeresa Johnson     }
363d2869473SPiotr Padlewski 
36401e32130SMehdi Amini     // Insert the newly imported function to the worklist.
365475b51a7STeresa Johnson     Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, GUID);
366d450da32STeresa Johnson   }
367d450da32STeresa Johnson }
368d450da32STeresa Johnson 
36901e32130SMehdi Amini /// Given the list of globals defined in a module, compute the list of imports
37001e32130SMehdi Amini /// as well as the list of "exports", i.e. the list of symbols referenced from
37101e32130SMehdi Amini /// another module (that may require promotion).
37201e32130SMehdi Amini static void ComputeImportForModule(
373c851d216STeresa Johnson     const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
3749b490f10SMehdi Amini     FunctionImporter::ImportMapTy &ImportList,
375c86af334STeresa Johnson     StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
37601e32130SMehdi Amini   // Worklist contains the list of function imported in this module, for which
37701e32130SMehdi Amini   // we will analyse the callees and may import further down the callgraph.
37801e32130SMehdi Amini   SmallVector<EdgeInfo, 128> Worklist;
37901e32130SMehdi Amini 
38001e32130SMehdi Amini   // Populate the worklist with the import for the functions in the current
38101e32130SMehdi Amini   // module
38228e457bcSTeresa Johnson   for (auto &GVSummary : DefinedGVSummaries) {
38328e457bcSTeresa Johnson     auto *Summary = GVSummary.second;
3842d28f7aaSMehdi Amini     if (auto *AS = dyn_cast<AliasSummary>(Summary))
3852d28f7aaSMehdi Amini       Summary = &AS->getAliasee();
3861aafabf7SMehdi Amini     auto *FuncSummary = dyn_cast<FunctionSummary>(Summary);
3871aafabf7SMehdi Amini     if (!FuncSummary)
3881aafabf7SMehdi Amini       // Skip import for global variables
3891aafabf7SMehdi Amini       continue;
39028e457bcSTeresa Johnson     DEBUG(dbgs() << "Initalize import for " << GVSummary.first << "\n");
3912d28f7aaSMehdi Amini     computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
3929b490f10SMehdi Amini                              DefinedGVSummaries, Worklist, ImportList,
39301e32130SMehdi Amini                              ExportLists);
39401e32130SMehdi Amini   }
39501e32130SMehdi Amini 
396d2869473SPiotr Padlewski   // Process the newly imported functions and add callees to the worklist.
39742418abaSMehdi Amini   while (!Worklist.empty()) {
39801e32130SMehdi Amini     auto FuncInfo = Worklist.pop_back_val();
399475b51a7STeresa Johnson     auto *Summary = std::get<0>(FuncInfo);
400475b51a7STeresa Johnson     auto Threshold = std::get<1>(FuncInfo);
401475b51a7STeresa Johnson     auto GUID = std::get<2>(FuncInfo);
402475b51a7STeresa Johnson 
403475b51a7STeresa Johnson     // Check if we later added this summary with a higher threshold.
404475b51a7STeresa Johnson     // If so, skip this entry.
405475b51a7STeresa Johnson     auto ExportModulePath = Summary->modulePath();
406475b51a7STeresa Johnson     auto &LatestProcessedThreshold = ImportList[ExportModulePath][GUID];
407475b51a7STeresa Johnson     if (LatestProcessedThreshold > Threshold)
408475b51a7STeresa Johnson       continue;
40942418abaSMehdi Amini 
4101aafabf7SMehdi Amini     computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
4119b490f10SMehdi Amini                              Worklist, ImportList, ExportLists);
412c8c55170SMehdi Amini   }
41342418abaSMehdi Amini }
414ffe2e4aaSMehdi Amini 
41501e32130SMehdi Amini } // anonymous namespace
41601e32130SMehdi Amini 
417c86af334STeresa Johnson /// Compute all the import and export for every module using the Index.
41801e32130SMehdi Amini void llvm::ComputeCrossModuleImport(
41901e32130SMehdi Amini     const ModuleSummaryIndex &Index,
420c851d216STeresa Johnson     const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
42101e32130SMehdi Amini     StringMap<FunctionImporter::ImportMapTy> &ImportLists,
42201e32130SMehdi Amini     StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
42301e32130SMehdi Amini   // For each module that has function defined, compute the import/export lists.
4241aafabf7SMehdi Amini   for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
4259b490f10SMehdi Amini     auto &ImportList = ImportLists[DefinedGVSummaries.first()];
4261aafabf7SMehdi Amini     DEBUG(dbgs() << "Computing import for Module '"
4271aafabf7SMehdi Amini                  << DefinedGVSummaries.first() << "'\n");
4289b490f10SMehdi Amini     ComputeImportForModule(DefinedGVSummaries.second, Index, ImportList,
429c86af334STeresa Johnson                            &ExportLists);
43001e32130SMehdi Amini   }
43101e32130SMehdi Amini 
43201e32130SMehdi Amini #ifndef NDEBUG
43301e32130SMehdi Amini   DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
43401e32130SMehdi Amini                << " modules:\n");
43501e32130SMehdi Amini   for (auto &ModuleImports : ImportLists) {
43601e32130SMehdi Amini     auto ModName = ModuleImports.first();
43701e32130SMehdi Amini     auto &Exports = ExportLists[ModName];
43801e32130SMehdi Amini     DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size()
43901e32130SMehdi Amini                  << " functions. Imports from " << ModuleImports.second.size()
44001e32130SMehdi Amini                  << " modules.\n");
44101e32130SMehdi Amini     for (auto &Src : ModuleImports.second) {
44201e32130SMehdi Amini       auto SrcModName = Src.first();
44301e32130SMehdi Amini       DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
44401e32130SMehdi Amini                    << SrcModName << "\n");
44501e32130SMehdi Amini     }
44601e32130SMehdi Amini   }
44701e32130SMehdi Amini #endif
44801e32130SMehdi Amini }
44901e32130SMehdi Amini 
450c86af334STeresa Johnson /// Compute all the imports for the given module in the Index.
451c86af334STeresa Johnson void llvm::ComputeCrossModuleImportForModule(
452c86af334STeresa Johnson     StringRef ModulePath, const ModuleSummaryIndex &Index,
453c86af334STeresa Johnson     FunctionImporter::ImportMapTy &ImportList) {
454c86af334STeresa Johnson 
455c86af334STeresa Johnson   // Collect the list of functions this module defines.
456c86af334STeresa Johnson   // GUID -> Summary
457c851d216STeresa Johnson   GVSummaryMapTy FunctionSummaryMap;
45828e457bcSTeresa Johnson   Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
459c86af334STeresa Johnson 
460c86af334STeresa Johnson   // Compute the import list for this module.
461c86af334STeresa Johnson   DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
46228e457bcSTeresa Johnson   ComputeImportForModule(FunctionSummaryMap, Index, ImportList);
463c86af334STeresa Johnson 
464c86af334STeresa Johnson #ifndef NDEBUG
465c86af334STeresa Johnson   DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
466c86af334STeresa Johnson                << ImportList.size() << " modules.\n");
467c86af334STeresa Johnson   for (auto &Src : ImportList) {
468c86af334STeresa Johnson     auto SrcModName = Src.first();
469c86af334STeresa Johnson     DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
470c86af334STeresa Johnson                  << SrcModName << "\n");
471c86af334STeresa Johnson   }
472c86af334STeresa Johnson #endif
473c86af334STeresa Johnson }
474c86af334STeresa Johnson 
47584174c37STeresa Johnson /// Compute the set of summaries needed for a ThinLTO backend compilation of
47684174c37STeresa Johnson /// \p ModulePath.
47784174c37STeresa Johnson void llvm::gatherImportedSummariesForModule(
47884174c37STeresa Johnson     StringRef ModulePath,
47984174c37STeresa Johnson     const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
480cdbcbf74SMehdi Amini     const FunctionImporter::ImportMapTy &ImportList,
48184174c37STeresa Johnson     std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
48284174c37STeresa Johnson   // Include all summaries from the importing module.
48384174c37STeresa Johnson   ModuleToSummariesForIndex[ModulePath] =
48484174c37STeresa Johnson       ModuleToDefinedGVSummaries.lookup(ModulePath);
48584174c37STeresa Johnson   // Include summaries for imports.
48688c491ddSMehdi Amini   for (auto &ILI : ImportList) {
48784174c37STeresa Johnson     auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
48884174c37STeresa Johnson     const auto &DefinedGVSummaries =
48984174c37STeresa Johnson         ModuleToDefinedGVSummaries.lookup(ILI.first());
49084174c37STeresa Johnson     for (auto &GI : ILI.second) {
49184174c37STeresa Johnson       const auto &DS = DefinedGVSummaries.find(GI.first);
49284174c37STeresa Johnson       assert(DS != DefinedGVSummaries.end() &&
49384174c37STeresa Johnson              "Expected a defined summary for imported global value");
49484174c37STeresa Johnson       SummariesForIndex[GI.first] = DS->second;
49584174c37STeresa Johnson     }
49684174c37STeresa Johnson   }
49784174c37STeresa Johnson }
49884174c37STeresa Johnson 
4998570fe47STeresa Johnson /// Emit the files \p ModulePath will import from into \p OutputFilename.
500cdbcbf74SMehdi Amini std::error_code
501cdbcbf74SMehdi Amini llvm::EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename,
502cdbcbf74SMehdi Amini                        const FunctionImporter::ImportMapTy &ModuleImports) {
5038570fe47STeresa Johnson   std::error_code EC;
5048570fe47STeresa Johnson   raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
5058570fe47STeresa Johnson   if (EC)
5068570fe47STeresa Johnson     return EC;
507cdbcbf74SMehdi Amini   for (auto &ILI : ModuleImports)
5088570fe47STeresa Johnson     ImportsOS << ILI.first() << "\n";
5098570fe47STeresa Johnson   return std::error_code();
5108570fe47STeresa Johnson }
5118570fe47STeresa Johnson 
51204c9a2d6STeresa Johnson /// Fixup WeakForLinker linkages in \p TheModule based on summary analysis.
51304c9a2d6STeresa Johnson void llvm::thinLTOResolveWeakForLinkerModule(
51404c9a2d6STeresa Johnson     Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
51504c9a2d6STeresa Johnson   auto updateLinkage = [&](GlobalValue &GV) {
51604c9a2d6STeresa Johnson     if (!GlobalValue::isWeakForLinker(GV.getLinkage()))
51704c9a2d6STeresa Johnson       return;
51804c9a2d6STeresa Johnson     // See if the global summary analysis computed a new resolved linkage.
51904c9a2d6STeresa Johnson     const auto &GS = DefinedGlobals.find(GV.getGUID());
52004c9a2d6STeresa Johnson     if (GS == DefinedGlobals.end())
52104c9a2d6STeresa Johnson       return;
52204c9a2d6STeresa Johnson     auto NewLinkage = GS->second->linkage();
52304c9a2d6STeresa Johnson     if (NewLinkage == GV.getLinkage())
52404c9a2d6STeresa Johnson       return;
52504c9a2d6STeresa Johnson     DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
52604c9a2d6STeresa Johnson                  << GV.getLinkage() << " to " << NewLinkage << "\n");
52704c9a2d6STeresa Johnson     GV.setLinkage(NewLinkage);
5286107a419STeresa Johnson     // Remove functions converted to available_externally from comdats,
5296107a419STeresa Johnson     // as this is a declaration for the linker, and will be dropped eventually.
5306107a419STeresa Johnson     // It is illegal for comdats to contain declarations.
5316107a419STeresa Johnson     auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
5326107a419STeresa Johnson     if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) {
5336107a419STeresa Johnson       assert(GO->hasAvailableExternallyLinkage() &&
5346107a419STeresa Johnson              "Expected comdat on definition (possibly available external)");
5356107a419STeresa Johnson       GO->setComdat(nullptr);
5366107a419STeresa Johnson     }
53704c9a2d6STeresa Johnson   };
53804c9a2d6STeresa Johnson 
53904c9a2d6STeresa Johnson   // Process functions and global now
54004c9a2d6STeresa Johnson   for (auto &GV : TheModule)
54104c9a2d6STeresa Johnson     updateLinkage(GV);
54204c9a2d6STeresa Johnson   for (auto &GV : TheModule.globals())
54304c9a2d6STeresa Johnson     updateLinkage(GV);
54404c9a2d6STeresa Johnson   for (auto &GV : TheModule.aliases())
54504c9a2d6STeresa Johnson     updateLinkage(GV);
54604c9a2d6STeresa Johnson }
54704c9a2d6STeresa Johnson 
54804c9a2d6STeresa Johnson /// Run internalization on \p TheModule based on symmary analysis.
54904c9a2d6STeresa Johnson void llvm::thinLTOInternalizeModule(Module &TheModule,
55004c9a2d6STeresa Johnson                                     const GVSummaryMapTy &DefinedGlobals) {
55104c9a2d6STeresa Johnson   // Parse inline ASM and collect the list of symbols that are not defined in
55204c9a2d6STeresa Johnson   // the current module.
55304c9a2d6STeresa Johnson   StringSet<> AsmUndefinedRefs;
554863cbfbeSPeter Collingbourne   ModuleSymbolTable::CollectAsmSymbols(
55504c9a2d6STeresa Johnson       Triple(TheModule.getTargetTriple()), TheModule.getModuleInlineAsm(),
55604c9a2d6STeresa Johnson       [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) {
55704c9a2d6STeresa Johnson         if (Flags & object::BasicSymbolRef::SF_Undefined)
55804c9a2d6STeresa Johnson           AsmUndefinedRefs.insert(Name);
55904c9a2d6STeresa Johnson       });
56004c9a2d6STeresa Johnson 
56104c9a2d6STeresa Johnson   // Declare a callback for the internalize pass that will ask for every
56204c9a2d6STeresa Johnson   // candidate GlobalValue if it can be internalized or not.
56304c9a2d6STeresa Johnson   auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
56404c9a2d6STeresa Johnson     // Can't be internalized if referenced in inline asm.
56504c9a2d6STeresa Johnson     if (AsmUndefinedRefs.count(GV.getName()))
56604c9a2d6STeresa Johnson       return true;
56704c9a2d6STeresa Johnson 
56804c9a2d6STeresa Johnson     // Lookup the linkage recorded in the summaries during global analysis.
56904c9a2d6STeresa Johnson     const auto &GS = DefinedGlobals.find(GV.getGUID());
57004c9a2d6STeresa Johnson     GlobalValue::LinkageTypes Linkage;
57104c9a2d6STeresa Johnson     if (GS == DefinedGlobals.end()) {
57204c9a2d6STeresa Johnson       // Must have been promoted (possibly conservatively). Find original
57304c9a2d6STeresa Johnson       // name so that we can access the correct summary and see if it can
57404c9a2d6STeresa Johnson       // be internalized again.
57504c9a2d6STeresa Johnson       // FIXME: Eventually we should control promotion instead of promoting
57604c9a2d6STeresa Johnson       // and internalizing again.
57704c9a2d6STeresa Johnson       StringRef OrigName =
57804c9a2d6STeresa Johnson           ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
57904c9a2d6STeresa Johnson       std::string OrigId = GlobalValue::getGlobalIdentifier(
58004c9a2d6STeresa Johnson           OrigName, GlobalValue::InternalLinkage,
58104c9a2d6STeresa Johnson           TheModule.getSourceFileName());
58204c9a2d6STeresa Johnson       const auto &GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
5837ab1f692STeresa Johnson       if (GS == DefinedGlobals.end()) {
5847ab1f692STeresa Johnson         // Also check the original non-promoted non-globalized name. In some
5857ab1f692STeresa Johnson         // cases a preempted weak value is linked in as a local copy because
5867ab1f692STeresa Johnson         // it is referenced by an alias (IRLinker::linkGlobalValueProto).
5877ab1f692STeresa Johnson         // In that case, since it was originally not a local value, it was
5887ab1f692STeresa Johnson         // recorded in the index using the original name.
5897ab1f692STeresa Johnson         // FIXME: This may not be needed once PR27866 is fixed.
5907ab1f692STeresa Johnson         const auto &GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
59104c9a2d6STeresa Johnson         assert(GS != DefinedGlobals.end());
59204c9a2d6STeresa Johnson         Linkage = GS->second->linkage();
5937ab1f692STeresa Johnson       } else {
5947ab1f692STeresa Johnson         Linkage = GS->second->linkage();
5957ab1f692STeresa Johnson       }
59604c9a2d6STeresa Johnson     } else
59704c9a2d6STeresa Johnson       Linkage = GS->second->linkage();
59804c9a2d6STeresa Johnson     return !GlobalValue::isLocalLinkage(Linkage);
59904c9a2d6STeresa Johnson   };
60004c9a2d6STeresa Johnson 
60104c9a2d6STeresa Johnson   // FIXME: See if we can just internalize directly here via linkage changes
60204c9a2d6STeresa Johnson   // based on the index, rather than invoking internalizeModule.
60304c9a2d6STeresa Johnson   llvm::internalizeModule(TheModule, MustPreserveGV);
60404c9a2d6STeresa Johnson }
60504c9a2d6STeresa Johnson 
606c8c55170SMehdi Amini // Automatically import functions in Module \p DestModule based on the summaries
607c8c55170SMehdi Amini // index.
608c8c55170SMehdi Amini //
6097f00d0a1SPeter Collingbourne Expected<bool> FunctionImporter::importFunctions(
610bda3c97cSMehdi Amini     Module &DestModule, const FunctionImporter::ImportMapTy &ImportList,
611bda3c97cSMehdi Amini     bool ForceImportReferencedDiscardableSymbols) {
6125411d051SMehdi Amini   DEBUG(dbgs() << "Starting import for Module "
613311fef6eSMehdi Amini                << DestModule.getModuleIdentifier() << "\n");
614c8c55170SMehdi Amini   unsigned ImportedCount = 0;
615c8c55170SMehdi Amini 
616c8c55170SMehdi Amini   // Linker that will be used for importing function
6179d2bfc48SRafael Espindola   Linker TheLinker(DestModule);
6187e88d0daSMehdi Amini   // Do the actual import of functions now, one Module at a time
61901e32130SMehdi Amini   std::set<StringRef> ModuleNameOrderedList;
62001e32130SMehdi Amini   for (auto &FunctionsToImportPerModule : ImportList) {
62101e32130SMehdi Amini     ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
62201e32130SMehdi Amini   }
62301e32130SMehdi Amini   for (auto &Name : ModuleNameOrderedList) {
6247e88d0daSMehdi Amini     // Get the module for the import
62501e32130SMehdi Amini     const auto &FunctionsToImportPerModule = ImportList.find(Name);
62601e32130SMehdi Amini     assert(FunctionsToImportPerModule != ImportList.end());
627d9445c49SPeter Collingbourne     Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
628d9445c49SPeter Collingbourne     if (!SrcModuleOrErr)
629d9445c49SPeter Collingbourne       return SrcModuleOrErr.takeError();
630d9445c49SPeter Collingbourne     std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
6317e88d0daSMehdi Amini     assert(&DestModule.getContext() == &SrcModule->getContext() &&
6327e88d0daSMehdi Amini            "Context mismatch");
6337e88d0daSMehdi Amini 
6346cba37ceSTeresa Johnson     // If modules were created with lazy metadata loading, materialize it
6356cba37ceSTeresa Johnson     // now, before linking it (otherwise this will be a noop).
6367f00d0a1SPeter Collingbourne     if (Error Err = SrcModule->materializeMetadata())
6377f00d0a1SPeter Collingbourne       return std::move(Err);
6386cba37ceSTeresa Johnson     UpgradeDebugInfo(*SrcModule);
639e5a61917STeresa Johnson 
64001e32130SMehdi Amini     auto &ImportGUIDs = FunctionsToImportPerModule->second;
64101e32130SMehdi Amini     // Find the globals to import
64201e32130SMehdi Amini     DenseSet<const GlobalValue *> GlobalsToImport;
6431f685e01SPiotr Padlewski     for (Function &F : *SrcModule) {
6441f685e01SPiotr Padlewski       if (!F.hasName())
6450beb858eSTeresa Johnson         continue;
6461f685e01SPiotr Padlewski       auto GUID = F.getGUID();
6470beb858eSTeresa Johnson       auto Import = ImportGUIDs.count(GUID);
648aeb1e59bSMehdi Amini       DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " << GUID
6491f685e01SPiotr Padlewski                    << " " << F.getName() << " from "
650aeb1e59bSMehdi Amini                    << SrcModule->getSourceFileName() << "\n");
6510beb858eSTeresa Johnson       if (Import) {
6527f00d0a1SPeter Collingbourne         if (Error Err = F.materialize())
6537f00d0a1SPeter Collingbourne           return std::move(Err);
6543b776128SPiotr Padlewski         if (EnableImportMetadata) {
6556deaa6afSPiotr Padlewski           // Add 'thinlto_src_module' metadata for statistics and debugging.
6563b776128SPiotr Padlewski           F.setMetadata(
6573b776128SPiotr Padlewski               "thinlto_src_module",
6583b776128SPiotr Padlewski               llvm::MDNode::get(
6596deaa6afSPiotr Padlewski                   DestModule.getContext(),
6603b776128SPiotr Padlewski                   {llvm::MDString::get(DestModule.getContext(),
6616deaa6afSPiotr Padlewski                                        SrcModule->getSourceFileName())}));
6623b776128SPiotr Padlewski         }
6631f685e01SPiotr Padlewski         GlobalsToImport.insert(&F);
66401e32130SMehdi Amini       }
66501e32130SMehdi Amini     }
6661f685e01SPiotr Padlewski     for (GlobalVariable &GV : SrcModule->globals()) {
6672d28f7aaSMehdi Amini       if (!GV.hasName())
6682d28f7aaSMehdi Amini         continue;
6692d28f7aaSMehdi Amini       auto GUID = GV.getGUID();
6702d28f7aaSMehdi Amini       auto Import = ImportGUIDs.count(GUID);
671aeb1e59bSMehdi Amini       DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " << GUID
672aeb1e59bSMehdi Amini                    << " " << GV.getName() << " from "
673aeb1e59bSMehdi Amini                    << SrcModule->getSourceFileName() << "\n");
6742d28f7aaSMehdi Amini       if (Import) {
6757f00d0a1SPeter Collingbourne         if (Error Err = GV.materialize())
6767f00d0a1SPeter Collingbourne           return std::move(Err);
6772d28f7aaSMehdi Amini         GlobalsToImport.insert(&GV);
6782d28f7aaSMehdi Amini       }
6792d28f7aaSMehdi Amini     }
6801f685e01SPiotr Padlewski     for (GlobalAlias &GA : SrcModule->aliases()) {
6811f685e01SPiotr Padlewski       if (!GA.hasName())
68201e32130SMehdi Amini         continue;
6831f685e01SPiotr Padlewski       auto GUID = GA.getGUID();
6840beb858eSTeresa Johnson       auto Import = ImportGUIDs.count(GUID);
685aeb1e59bSMehdi Amini       DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias " << GUID
6861f685e01SPiotr Padlewski                    << " " << GA.getName() << " from "
687aeb1e59bSMehdi Amini                    << SrcModule->getSourceFileName() << "\n");
6880beb858eSTeresa Johnson       if (Import) {
68901e32130SMehdi Amini         // Alias can't point to "available_externally". However when we import
6909aae395fSTeresa Johnson         // linkOnceODR the linkage does not change. So we import the alias
6916968ef77SMehdi Amini         // and aliasee only in this case. This has been handled by
6926968ef77SMehdi Amini         // computeImportForFunction()
6931f685e01SPiotr Padlewski         GlobalObject *GO = GA.getBaseObject();
6946968ef77SMehdi Amini         assert(GO->hasLinkOnceODRLinkage() &&
6956968ef77SMehdi Amini                "Unexpected alias to a non-linkonceODR in import list");
6962d28f7aaSMehdi Amini #ifndef NDEBUG
6972d28f7aaSMehdi Amini         if (!GlobalsToImport.count(GO))
6982d28f7aaSMehdi Amini           DEBUG(dbgs() << " alias triggers importing aliasee " << GO->getGUID()
6992d28f7aaSMehdi Amini                        << " " << GO->getName() << " from "
7002d28f7aaSMehdi Amini                        << SrcModule->getSourceFileName() << "\n");
7012d28f7aaSMehdi Amini #endif
7027f00d0a1SPeter Collingbourne         if (Error Err = GO->materialize())
7037f00d0a1SPeter Collingbourne           return std::move(Err);
70401e32130SMehdi Amini         GlobalsToImport.insert(GO);
7057f00d0a1SPeter Collingbourne         if (Error Err = GA.materialize())
7067f00d0a1SPeter Collingbourne           return std::move(Err);
7071f685e01SPiotr Padlewski         GlobalsToImport.insert(&GA);
70801e32130SMehdi Amini       }
70901e32130SMehdi Amini     }
71001e32130SMehdi Amini 
7117e88d0daSMehdi Amini     // Link in the specified functions.
71201e32130SMehdi Amini     if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
7138d05185aSMehdi Amini       return true;
7148d05185aSMehdi Amini 
715d29478f7STeresa Johnson     if (PrintImports) {
716d29478f7STeresa Johnson       for (const auto *GV : GlobalsToImport)
717d29478f7STeresa Johnson         dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
718d29478f7STeresa Johnson                << " from " << SrcModule->getSourceFileName() << "\n";
719d29478f7STeresa Johnson     }
720d29478f7STeresa Johnson 
721bda3c97cSMehdi Amini     // Instruct the linker that the client will take care of linkonce resolution
722bda3c97cSMehdi Amini     unsigned Flags = Linker::Flags::None;
723bda3c97cSMehdi Amini     if (!ForceImportReferencedDiscardableSymbols)
724bda3c97cSMehdi Amini       Flags |= Linker::Flags::DontForceLinkLinkonceODR;
725bda3c97cSMehdi Amini 
726bda3c97cSMehdi Amini     if (TheLinker.linkInModule(std::move(SrcModule), Flags, &GlobalsToImport))
7277e88d0daSMehdi Amini       report_fatal_error("Function Import: link error");
7287e88d0daSMehdi Amini 
72901e32130SMehdi Amini     ImportedCount += GlobalsToImport.size();
7307e88d0daSMehdi Amini   }
731e5a61917STeresa Johnson 
732d29478f7STeresa Johnson   NumImported += ImportedCount;
733d29478f7STeresa Johnson 
7347e88d0daSMehdi Amini   DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
735c8c55170SMehdi Amini                << DestModule.getModuleIdentifier() << "\n");
736c8c55170SMehdi Amini   return ImportedCount;
73742418abaSMehdi Amini }
73842418abaSMehdi Amini 
73942418abaSMehdi Amini /// Summary file to use for function importing when using -function-import from
74042418abaSMehdi Amini /// the command line.
74142418abaSMehdi Amini static cl::opt<std::string>
74242418abaSMehdi Amini     SummaryFile("summary-file",
74342418abaSMehdi Amini                 cl::desc("The summary file to use for function importing."));
74442418abaSMehdi Amini 
74521241571STeresa Johnson static bool doImportingForModule(Module &M, const ModuleSummaryIndex *Index) {
7465fcbdb71STeresa Johnson   if (SummaryFile.empty() && !Index)
7475fcbdb71STeresa Johnson     report_fatal_error("error: -function-import requires -summary-file or "
7485fcbdb71STeresa Johnson                        "file from frontend\n");
74926ab5772STeresa Johnson   std::unique_ptr<ModuleSummaryIndex> IndexPtr;
7505fcbdb71STeresa Johnson   if (!SummaryFile.empty()) {
7515fcbdb71STeresa Johnson     if (Index)
7525fcbdb71STeresa Johnson       report_fatal_error("error: -summary-file and index from frontend\n");
7536de481a3SPeter Collingbourne     Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
7546de481a3SPeter Collingbourne         getModuleSummaryIndexForFile(SummaryFile);
7556de481a3SPeter Collingbourne     if (!IndexPtrOrErr) {
7566de481a3SPeter Collingbourne       logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
7576de481a3SPeter Collingbourne                             "Error loading file '" + SummaryFile + "': ");
75842418abaSMehdi Amini       return false;
75942418abaSMehdi Amini     }
7606de481a3SPeter Collingbourne     IndexPtr = std::move(*IndexPtrOrErr);
7615fcbdb71STeresa Johnson     Index = IndexPtr.get();
7625fcbdb71STeresa Johnson   }
76342418abaSMehdi Amini 
764c86af334STeresa Johnson   // First step is collecting the import list.
765c86af334STeresa Johnson   FunctionImporter::ImportMapTy ImportList;
766c86af334STeresa Johnson   ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
767c86af334STeresa Johnson                                     ImportList);
76801e32130SMehdi Amini 
7694fef68cbSTeresa Johnson   // Conservatively mark all internal values as promoted. This interface is
7704fef68cbSTeresa Johnson   // only used when doing importing via the function importing pass. The pass
7714fef68cbSTeresa Johnson   // is only enabled when testing importing via the 'opt' tool, which does
7724fef68cbSTeresa Johnson   // not do the ThinLink that would normally determine what values to promote.
7734fef68cbSTeresa Johnson   for (auto &I : *Index) {
7744fef68cbSTeresa Johnson     for (auto &S : I.second) {
7754fef68cbSTeresa Johnson       if (GlobalValue::isLocalLinkage(S->linkage()))
7764fef68cbSTeresa Johnson         S->setLinkage(GlobalValue::ExternalLinkage);
7774fef68cbSTeresa Johnson     }
7784fef68cbSTeresa Johnson   }
7794fef68cbSTeresa Johnson 
78001e32130SMehdi Amini   // Next we need to promote to global scope and rename any local values that
7811b00f2d9STeresa Johnson   // are potentially exported to other modules.
78201e32130SMehdi Amini   if (renameModuleForThinLTO(M, *Index, nullptr)) {
7831b00f2d9STeresa Johnson     errs() << "Error renaming module\n";
7841b00f2d9STeresa Johnson     return false;
7851b00f2d9STeresa Johnson   }
7861b00f2d9STeresa Johnson 
78742418abaSMehdi Amini   // Perform the import now.
788d16c8065SMehdi Amini   auto ModuleLoader = [&M](StringRef Identifier) {
789d16c8065SMehdi Amini     return loadFile(Identifier, M.getContext());
790d16c8065SMehdi Amini   };
7919d2bfc48SRafael Espindola   FunctionImporter Importer(*Index, ModuleLoader);
7927f00d0a1SPeter Collingbourne   Expected<bool> Result = Importer.importFunctions(
7937f00d0a1SPeter Collingbourne       M, ImportList, !DontForceImportReferencedDiscardableSymbols);
7947f00d0a1SPeter Collingbourne 
7957f00d0a1SPeter Collingbourne   // FIXME: Probably need to propagate Errors through the pass manager.
7967f00d0a1SPeter Collingbourne   if (!Result) {
7977f00d0a1SPeter Collingbourne     logAllUnhandledErrors(Result.takeError(), errs(),
7987f00d0a1SPeter Collingbourne                           "Error importing module: ");
7997f00d0a1SPeter Collingbourne     return false;
8007f00d0a1SPeter Collingbourne   }
8017f00d0a1SPeter Collingbourne 
8027f00d0a1SPeter Collingbourne   return *Result;
80321241571STeresa Johnson }
80421241571STeresa Johnson 
80521241571STeresa Johnson namespace {
80621241571STeresa Johnson /// Pass that performs cross-module function import provided a summary file.
80721241571STeresa Johnson class FunctionImportLegacyPass : public ModulePass {
80821241571STeresa Johnson   /// Optional module summary index to use for importing, otherwise
80921241571STeresa Johnson   /// the summary-file option must be specified.
81021241571STeresa Johnson   const ModuleSummaryIndex *Index;
81121241571STeresa Johnson 
81221241571STeresa Johnson public:
81321241571STeresa Johnson   /// Pass identification, replacement for typeid
81421241571STeresa Johnson   static char ID;
81521241571STeresa Johnson 
81621241571STeresa Johnson   /// Specify pass name for debug output
817117296c0SMehdi Amini   StringRef getPassName() const override { return "Function Importing"; }
81821241571STeresa Johnson 
81921241571STeresa Johnson   explicit FunctionImportLegacyPass(const ModuleSummaryIndex *Index = nullptr)
82021241571STeresa Johnson       : ModulePass(ID), Index(Index) {}
82121241571STeresa Johnson 
82221241571STeresa Johnson   bool runOnModule(Module &M) override {
82321241571STeresa Johnson     if (skipModule(M))
82421241571STeresa Johnson       return false;
82521241571STeresa Johnson 
82621241571STeresa Johnson     return doImportingForModule(M, Index);
82742418abaSMehdi Amini   }
82842418abaSMehdi Amini };
829fe2b5415SBenjamin Kramer } // anonymous namespace
83042418abaSMehdi Amini 
83121241571STeresa Johnson PreservedAnalyses FunctionImportPass::run(Module &M,
832fd03ac6aSSean Silva                                           ModuleAnalysisManager &AM) {
83321241571STeresa Johnson   if (!doImportingForModule(M, Index))
83421241571STeresa Johnson     return PreservedAnalyses::all();
83521241571STeresa Johnson 
83621241571STeresa Johnson   return PreservedAnalyses::none();
83721241571STeresa Johnson }
83821241571STeresa Johnson 
83921241571STeresa Johnson char FunctionImportLegacyPass::ID = 0;
84021241571STeresa Johnson INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
84142418abaSMehdi Amini                 "Summary Based Function Import", false, false)
84242418abaSMehdi Amini 
84342418abaSMehdi Amini namespace llvm {
84426ab5772STeresa Johnson Pass *createFunctionImportPass(const ModuleSummaryIndex *Index = nullptr) {
84521241571STeresa Johnson   return new FunctionImportLegacyPass(Index);
8465fcbdb71STeresa Johnson }
84742418abaSMehdi Amini }
848