10b57cec5SDimitry Andric //===- FunctionImport.cpp - ThinLTO Summary-based Function Import ---------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric //
90b57cec5SDimitry Andric // This file implements Function import based on summaries.
100b57cec5SDimitry Andric //
110b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
120b57cec5SDimitry Andric 
130b57cec5SDimitry Andric #include "llvm/Transforms/IPO/FunctionImport.h"
140b57cec5SDimitry Andric #include "llvm/ADT/ArrayRef.h"
150b57cec5SDimitry Andric #include "llvm/ADT/STLExtras.h"
160b57cec5SDimitry Andric #include "llvm/ADT/SetVector.h"
170b57cec5SDimitry Andric #include "llvm/ADT/SmallVector.h"
180b57cec5SDimitry Andric #include "llvm/ADT/Statistic.h"
190b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
200b57cec5SDimitry Andric #include "llvm/Bitcode/BitcodeReader.h"
210b57cec5SDimitry Andric #include "llvm/IR/AutoUpgrade.h"
220b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
230b57cec5SDimitry Andric #include "llvm/IR/Function.h"
240b57cec5SDimitry Andric #include "llvm/IR/GlobalAlias.h"
250b57cec5SDimitry Andric #include "llvm/IR/GlobalObject.h"
260b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
270b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
280b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
290b57cec5SDimitry Andric #include "llvm/IR/Module.h"
300b57cec5SDimitry Andric #include "llvm/IR/ModuleSummaryIndex.h"
310b57cec5SDimitry Andric #include "llvm/IRReader/IRReader.h"
320b57cec5SDimitry Andric #include "llvm/Linker/IRMover.h"
330b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
340b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
350b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
36349cc55cSDimitry Andric #include "llvm/Support/Errc.h"
370b57cec5SDimitry Andric #include "llvm/Support/Error.h"
380b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
390b57cec5SDimitry Andric #include "llvm/Support/FileSystem.h"
40*c9157d92SDimitry Andric #include "llvm/Support/JSON.h"
410b57cec5SDimitry Andric #include "llvm/Support/SourceMgr.h"
420b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
430b57cec5SDimitry Andric #include "llvm/Transforms/IPO/Internalize.h"
440b57cec5SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
450b57cec5SDimitry Andric #include "llvm/Transforms/Utils/FunctionImportUtils.h"
460b57cec5SDimitry Andric #include "llvm/Transforms/Utils/ValueMapper.h"
470b57cec5SDimitry Andric #include <cassert>
480b57cec5SDimitry Andric #include <memory>
490b57cec5SDimitry Andric #include <set>
500b57cec5SDimitry Andric #include <string>
510b57cec5SDimitry Andric #include <system_error>
520b57cec5SDimitry Andric #include <tuple>
530b57cec5SDimitry Andric #include <utility>
540b57cec5SDimitry Andric 
550b57cec5SDimitry Andric using namespace llvm;
560b57cec5SDimitry Andric 
570b57cec5SDimitry Andric #define DEBUG_TYPE "function-import"
580b57cec5SDimitry Andric 
590b57cec5SDimitry Andric STATISTIC(NumImportedFunctionsThinLink,
600b57cec5SDimitry Andric           "Number of functions thin link decided to import");
610b57cec5SDimitry Andric STATISTIC(NumImportedHotFunctionsThinLink,
620b57cec5SDimitry Andric           "Number of hot functions thin link decided to import");
630b57cec5SDimitry Andric STATISTIC(NumImportedCriticalFunctionsThinLink,
640b57cec5SDimitry Andric           "Number of critical functions thin link decided to import");
650b57cec5SDimitry Andric STATISTIC(NumImportedGlobalVarsThinLink,
660b57cec5SDimitry Andric           "Number of global variables thin link decided to import");
670b57cec5SDimitry Andric STATISTIC(NumImportedFunctions, "Number of functions imported in backend");
680b57cec5SDimitry Andric STATISTIC(NumImportedGlobalVars,
690b57cec5SDimitry Andric           "Number of global variables imported in backend");
700b57cec5SDimitry Andric STATISTIC(NumImportedModules, "Number of modules imported from");
710b57cec5SDimitry Andric STATISTIC(NumDeadSymbols, "Number of dead stripped symbols in index");
720b57cec5SDimitry Andric STATISTIC(NumLiveSymbols, "Number of live symbols in index");
730b57cec5SDimitry Andric 
740b57cec5SDimitry Andric /// Limit on instruction count of imported functions.
750b57cec5SDimitry Andric static cl::opt<unsigned> ImportInstrLimit(
760b57cec5SDimitry Andric     "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
770b57cec5SDimitry Andric     cl::desc("Only import functions with less than N instructions"));
780b57cec5SDimitry Andric 
790b57cec5SDimitry Andric static cl::opt<int> ImportCutoff(
800b57cec5SDimitry Andric     "import-cutoff", cl::init(-1), cl::Hidden, cl::value_desc("N"),
810b57cec5SDimitry Andric     cl::desc("Only import first N functions if N>=0 (default -1)"));
820b57cec5SDimitry Andric 
83fe6060f1SDimitry Andric static cl::opt<bool>
84fe6060f1SDimitry Andric     ForceImportAll("force-import-all", cl::init(false), cl::Hidden,
85fe6060f1SDimitry Andric                    cl::desc("Import functions with noinline attribute"));
86fe6060f1SDimitry Andric 
870b57cec5SDimitry Andric static cl::opt<float>
880b57cec5SDimitry Andric     ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7),
890b57cec5SDimitry Andric                       cl::Hidden, cl::value_desc("x"),
900b57cec5SDimitry Andric                       cl::desc("As we import functions, multiply the "
910b57cec5SDimitry Andric                                "`import-instr-limit` threshold by this factor "
920b57cec5SDimitry Andric                                "before processing newly imported functions"));
930b57cec5SDimitry Andric 
940b57cec5SDimitry Andric static cl::opt<float> ImportHotInstrFactor(
950b57cec5SDimitry Andric     "import-hot-evolution-factor", cl::init(1.0), cl::Hidden,
960b57cec5SDimitry Andric     cl::value_desc("x"),
970b57cec5SDimitry Andric     cl::desc("As we import functions called from hot callsite, multiply the "
980b57cec5SDimitry Andric              "`import-instr-limit` threshold by this factor "
990b57cec5SDimitry Andric              "before processing newly imported functions"));
1000b57cec5SDimitry Andric 
1010b57cec5SDimitry Andric static cl::opt<float> ImportHotMultiplier(
1020b57cec5SDimitry Andric     "import-hot-multiplier", cl::init(10.0), cl::Hidden, cl::value_desc("x"),
1030b57cec5SDimitry Andric     cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"));
1040b57cec5SDimitry Andric 
1050b57cec5SDimitry Andric static cl::opt<float> ImportCriticalMultiplier(
1060b57cec5SDimitry Andric     "import-critical-multiplier", cl::init(100.0), cl::Hidden,
1070b57cec5SDimitry Andric     cl::value_desc("x"),
1080b57cec5SDimitry Andric     cl::desc(
1090b57cec5SDimitry Andric         "Multiply the `import-instr-limit` threshold for critical callsites"));
1100b57cec5SDimitry Andric 
1110b57cec5SDimitry Andric // FIXME: This multiplier was not really tuned up.
1120b57cec5SDimitry Andric static cl::opt<float> ImportColdMultiplier(
1130b57cec5SDimitry Andric     "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"),
1140b57cec5SDimitry Andric     cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"));
1150b57cec5SDimitry Andric 
1160b57cec5SDimitry Andric static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
1170b57cec5SDimitry Andric                                   cl::desc("Print imported functions"));
1180b57cec5SDimitry Andric 
1190b57cec5SDimitry Andric static cl::opt<bool> PrintImportFailures(
1200b57cec5SDimitry Andric     "print-import-failures", cl::init(false), cl::Hidden,
1210b57cec5SDimitry Andric     cl::desc("Print information for functions rejected for importing"));
1220b57cec5SDimitry Andric 
1230b57cec5SDimitry Andric static cl::opt<bool> ComputeDead("compute-dead", cl::init(true), cl::Hidden,
1240b57cec5SDimitry Andric                                  cl::desc("Compute dead symbols"));
1250b57cec5SDimitry Andric 
1260b57cec5SDimitry Andric static cl::opt<bool> EnableImportMetadata(
127e8d8bef9SDimitry Andric     "enable-import-metadata", cl::init(false), cl::Hidden,
128e8d8bef9SDimitry Andric     cl::desc("Enable import metadata like 'thinlto_src_module'"));
1290b57cec5SDimitry Andric 
1300b57cec5SDimitry Andric /// Summary file to use for function importing when using -function-import from
1310b57cec5SDimitry Andric /// the command line.
1320b57cec5SDimitry Andric static cl::opt<std::string>
1330b57cec5SDimitry Andric     SummaryFile("summary-file",
1340b57cec5SDimitry Andric                 cl::desc("The summary file to use for function importing."));
1350b57cec5SDimitry Andric 
1360b57cec5SDimitry Andric /// Used when testing importing from distributed indexes via opt
1370b57cec5SDimitry Andric // -function-import.
1380b57cec5SDimitry Andric static cl::opt<bool>
1390b57cec5SDimitry Andric     ImportAllIndex("import-all-index",
1400b57cec5SDimitry Andric                    cl::desc("Import all external functions in index."));
1410b57cec5SDimitry Andric 
142*c9157d92SDimitry Andric /// Pass a workload description file - an example of workload would be the
143*c9157d92SDimitry Andric /// functions executed to satisfy a RPC request. A workload is defined by a root
144*c9157d92SDimitry Andric /// function and the list of functions that are (frequently) needed to satisfy
145*c9157d92SDimitry Andric /// it. The module that defines the root will have all those functions imported.
146*c9157d92SDimitry Andric /// The file contains a JSON dictionary. The keys are root functions, the values
147*c9157d92SDimitry Andric /// are lists of functions to import in the module defining the root. It is
148*c9157d92SDimitry Andric /// assumed -funique-internal-linkage-names was used, thus ensuring function
149*c9157d92SDimitry Andric /// names are unique even for local linkage ones.
150*c9157d92SDimitry Andric static cl::opt<std::string> WorkloadDefinitions(
151*c9157d92SDimitry Andric     "thinlto-workload-def",
152*c9157d92SDimitry Andric     cl::desc("Pass a workload definition. This is a file containing a JSON "
153*c9157d92SDimitry Andric              "dictionary. The keys are root functions, the values are lists of "
154*c9157d92SDimitry Andric              "functions to import in the module defining the root. It is "
155*c9157d92SDimitry Andric              "assumed -funique-internal-linkage-names was used, to ensure "
156*c9157d92SDimitry Andric              "local linkage functions have unique names. For example: \n"
157*c9157d92SDimitry Andric              "{\n"
158*c9157d92SDimitry Andric              "  \"rootFunction_1\": [\"function_to_import_1\", "
159*c9157d92SDimitry Andric              "\"function_to_import_2\"], \n"
160*c9157d92SDimitry Andric              "  \"rootFunction_2\": [\"function_to_import_3\", "
161*c9157d92SDimitry Andric              "\"function_to_import_4\"] \n"
162*c9157d92SDimitry Andric              "}"),
163*c9157d92SDimitry Andric     cl::Hidden);
164*c9157d92SDimitry Andric 
1650b57cec5SDimitry Andric // Load lazily a module from \p FileName in \p Context.
loadFile(const std::string & FileName,LLVMContext & Context)1660b57cec5SDimitry Andric static std::unique_ptr<Module> loadFile(const std::string &FileName,
1670b57cec5SDimitry Andric                                         LLVMContext &Context) {
1680b57cec5SDimitry Andric   SMDiagnostic Err;
1690b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Loading '" << FileName << "'\n");
1700b57cec5SDimitry Andric   // Metadata isn't loaded until functions are imported, to minimize
1710b57cec5SDimitry Andric   // the memory overhead.
1720b57cec5SDimitry Andric   std::unique_ptr<Module> Result =
1730b57cec5SDimitry Andric       getLazyIRFileModule(FileName, Err, Context,
1740b57cec5SDimitry Andric                           /* ShouldLazyLoadMetadata = */ true);
1750b57cec5SDimitry Andric   if (!Result) {
1760b57cec5SDimitry Andric     Err.print("function-import", errs());
1770b57cec5SDimitry Andric     report_fatal_error("Abort");
1780b57cec5SDimitry Andric   }
1790b57cec5SDimitry Andric 
1800b57cec5SDimitry Andric   return Result;
1810b57cec5SDimitry Andric }
1820b57cec5SDimitry Andric 
183fe013be4SDimitry Andric /// Given a list of possible callee implementation for a call site, qualify the
184fe013be4SDimitry Andric /// legality of importing each. The return is a range of pairs. Each pair
185fe013be4SDimitry Andric /// corresponds to a candidate. The first value is the ImportFailureReason for
186fe013be4SDimitry Andric /// that candidate, the second is the candidate.
qualifyCalleeCandidates(const ModuleSummaryIndex & Index,ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,StringRef CallerModulePath)187fe013be4SDimitry Andric static auto qualifyCalleeCandidates(
188fe013be4SDimitry Andric     const ModuleSummaryIndex &Index,
1890b57cec5SDimitry Andric     ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
190fe013be4SDimitry Andric     StringRef CallerModulePath) {
191fe013be4SDimitry Andric   return llvm::map_range(
1920b57cec5SDimitry Andric       CalleeSummaryList,
193fe013be4SDimitry Andric       [&Index, CalleeSummaryList,
194fe013be4SDimitry Andric        CallerModulePath](const std::unique_ptr<GlobalValueSummary> &SummaryPtr)
195fe013be4SDimitry Andric           -> std::pair<FunctionImporter::ImportFailureReason,
196fe013be4SDimitry Andric                        const GlobalValueSummary *> {
1970b57cec5SDimitry Andric         auto *GVSummary = SummaryPtr.get();
198fe013be4SDimitry Andric         if (!Index.isGlobalValueLive(GVSummary))
199fe013be4SDimitry Andric           return {FunctionImporter::ImportFailureReason::NotLive, GVSummary};
2000b57cec5SDimitry Andric 
201fe013be4SDimitry Andric         if (GlobalValue::isInterposableLinkage(GVSummary->linkage()))
202fe013be4SDimitry Andric           return {FunctionImporter::ImportFailureReason::InterposableLinkage,
203fe013be4SDimitry Andric                   GVSummary};
2040b57cec5SDimitry Andric 
205fe013be4SDimitry Andric         auto *Summary = dyn_cast<FunctionSummary>(GVSummary->getBaseObject());
206fe013be4SDimitry Andric 
207fe013be4SDimitry Andric         // Ignore any callees that aren't actually functions. This could happen
208fe013be4SDimitry Andric         // in the case of GUID hash collisions. It could also happen in theory
209fe013be4SDimitry Andric         // for SamplePGO profiles collected on old versions of the code after
210fe013be4SDimitry Andric         // renaming, since we synthesize edges to any inlined callees appearing
211fe013be4SDimitry Andric         // in the profile.
212fe013be4SDimitry Andric         if (!Summary)
213fe013be4SDimitry Andric           return {FunctionImporter::ImportFailureReason::GlobalVar, GVSummary};
2140b57cec5SDimitry Andric 
2150b57cec5SDimitry Andric         // If this is a local function, make sure we import the copy
2160b57cec5SDimitry Andric         // in the caller's module. The only time a local function can
2170b57cec5SDimitry Andric         // share an entry in the index is if there is a local with the same name
2180b57cec5SDimitry Andric         // in another module that had the same source file name (in a different
2190b57cec5SDimitry Andric         // directory), where each was compiled in their own directory so there
2200b57cec5SDimitry Andric         // was not distinguishing path.
2210b57cec5SDimitry Andric         // However, do the import from another module if there is only one
2220b57cec5SDimitry Andric         // entry in the list - in that case this must be a reference due
2230b57cec5SDimitry Andric         // to indirect call profile data, since a function pointer can point to
2240b57cec5SDimitry Andric         // a local in another module.
2250b57cec5SDimitry Andric         if (GlobalValue::isLocalLinkage(Summary->linkage()) &&
2260b57cec5SDimitry Andric             CalleeSummaryList.size() > 1 &&
227fe013be4SDimitry Andric             Summary->modulePath() != CallerModulePath)
228fe013be4SDimitry Andric           return {
229fe013be4SDimitry Andric               FunctionImporter::ImportFailureReason::LocalLinkageNotInModule,
230fe013be4SDimitry Andric               GVSummary};
2310b57cec5SDimitry Andric 
2320b57cec5SDimitry Andric         // Skip if it isn't legal to import (e.g. may reference unpromotable
2330b57cec5SDimitry Andric         // locals).
234fe013be4SDimitry Andric         if (Summary->notEligibleToImport())
235fe013be4SDimitry Andric           return {FunctionImporter::ImportFailureReason::NotEligible,
236fe013be4SDimitry Andric                   GVSummary};
237fe013be4SDimitry Andric 
238fe013be4SDimitry Andric         return {FunctionImporter::ImportFailureReason::None, GVSummary};
239fe013be4SDimitry Andric       });
240fe013be4SDimitry Andric }
241fe013be4SDimitry Andric 
242fe013be4SDimitry Andric /// Given a list of possible callee implementation for a call site, select one
243fe013be4SDimitry Andric /// that fits the \p Threshold. If none are found, the Reason will give the last
244fe013be4SDimitry Andric /// reason for the failure (last, in the order of CalleeSummaryList entries).
245fe013be4SDimitry Andric ///
246fe013be4SDimitry Andric /// FIXME: select "best" instead of first that fits. But what is "best"?
247fe013be4SDimitry Andric /// - The smallest: more likely to be inlined.
248fe013be4SDimitry Andric /// - The one with the least outgoing edges (already well optimized).
249fe013be4SDimitry Andric /// - One from a module already being imported from in order to reduce the
250fe013be4SDimitry Andric ///   number of source modules parsed/linked.
251fe013be4SDimitry Andric /// - One that has PGO data attached.
252fe013be4SDimitry Andric /// - [insert you fancy metric here]
253fe013be4SDimitry Andric static const GlobalValueSummary *
selectCallee(const ModuleSummaryIndex & Index,ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,unsigned Threshold,StringRef CallerModulePath,FunctionImporter::ImportFailureReason & Reason)254fe013be4SDimitry Andric selectCallee(const ModuleSummaryIndex &Index,
255fe013be4SDimitry Andric              ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
256fe013be4SDimitry Andric              unsigned Threshold, StringRef CallerModulePath,
257fe013be4SDimitry Andric              FunctionImporter::ImportFailureReason &Reason) {
258fe013be4SDimitry Andric   auto QualifiedCandidates =
259fe013be4SDimitry Andric       qualifyCalleeCandidates(Index, CalleeSummaryList, CallerModulePath);
260fe013be4SDimitry Andric   for (auto QualifiedValue : QualifiedCandidates) {
261fe013be4SDimitry Andric     Reason = QualifiedValue.first;
262fe013be4SDimitry Andric     if (Reason != FunctionImporter::ImportFailureReason::None)
263fe013be4SDimitry Andric       continue;
264fe013be4SDimitry Andric     auto *Summary =
265fe013be4SDimitry Andric         cast<FunctionSummary>(QualifiedValue.second->getBaseObject());
266fe013be4SDimitry Andric 
267fe013be4SDimitry Andric     if ((Summary->instCount() > Threshold) && !Summary->fflags().AlwaysInline &&
268fe013be4SDimitry Andric         !ForceImportAll) {
269fe013be4SDimitry Andric       Reason = FunctionImporter::ImportFailureReason::TooLarge;
270fe013be4SDimitry Andric       continue;
2710b57cec5SDimitry Andric     }
2720b57cec5SDimitry Andric 
2730b57cec5SDimitry Andric     // Don't bother importing if we can't inline it anyway.
274fe6060f1SDimitry Andric     if (Summary->fflags().NoInline && !ForceImportAll) {
2750b57cec5SDimitry Andric       Reason = FunctionImporter::ImportFailureReason::NoInline;
276fe013be4SDimitry Andric       continue;
2770b57cec5SDimitry Andric     }
2780b57cec5SDimitry Andric 
279fe013be4SDimitry Andric     return Summary;
280fe013be4SDimitry Andric   }
2810b57cec5SDimitry Andric   return nullptr;
2820b57cec5SDimitry Andric }
2830b57cec5SDimitry Andric 
2840b57cec5SDimitry Andric namespace {
2850b57cec5SDimitry Andric 
286fe013be4SDimitry Andric using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */>;
2870b57cec5SDimitry Andric 
2880b57cec5SDimitry Andric } // anonymous namespace
2890b57cec5SDimitry Andric 
290fe013be4SDimitry Andric /// Import globals referenced by a function or other globals that are being
291fe013be4SDimitry Andric /// imported, if importing such global is possible.
292fe013be4SDimitry Andric class GlobalsImporter final {
293fe013be4SDimitry Andric   const ModuleSummaryIndex &Index;
294fe013be4SDimitry Andric   const GVSummaryMapTy &DefinedGVSummaries;
295fe013be4SDimitry Andric   function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
296fe013be4SDimitry Andric       IsPrevailing;
297fe013be4SDimitry Andric   FunctionImporter::ImportMapTy &ImportList;
298*c9157d92SDimitry Andric   DenseMap<StringRef, FunctionImporter::ExportSetTy> *const ExportLists;
299fe013be4SDimitry Andric 
shouldImportGlobal(const ValueInfo & VI)300fe013be4SDimitry Andric   bool shouldImportGlobal(const ValueInfo &VI) {
301fe6060f1SDimitry Andric     const auto &GVS = DefinedGVSummaries.find(VI.getGUID());
302fe6060f1SDimitry Andric     if (GVS == DefinedGVSummaries.end())
303fe6060f1SDimitry Andric       return true;
304fe013be4SDimitry Andric     // We should not skip import if the module contains a non-prevailing
305fe013be4SDimitry Andric     // definition with interposable linkage type. This is required for
306fe013be4SDimitry Andric     // correctness in the situation where there is a prevailing def available
307fe013be4SDimitry Andric     // for import and marked read-only. In this case, the non-prevailing def
308fe013be4SDimitry Andric     // will be converted to a declaration, while the prevailing one becomes
309fe013be4SDimitry Andric     // internal, thus no definitions will be available for linking. In order to
310fe013be4SDimitry Andric     // prevent undefined symbol link error, the prevailing definition must be
311fe013be4SDimitry Andric     // imported.
312fe6060f1SDimitry Andric     // FIXME: Consider adding a check that the suitable prevailing definition
313fe6060f1SDimitry Andric     // exists and marked read-only.
314fe6060f1SDimitry Andric     if (VI.getSummaryList().size() > 1 &&
315fe013be4SDimitry Andric         GlobalValue::isInterposableLinkage(GVS->second->linkage()) &&
316fe013be4SDimitry Andric         !IsPrevailing(VI.getGUID(), GVS->second))
317fe6060f1SDimitry Andric       return true;
318fe6060f1SDimitry Andric 
319fe6060f1SDimitry Andric     return false;
320fe6060f1SDimitry Andric   }
321fe6060f1SDimitry Andric 
322fe013be4SDimitry Andric   void
onImportingSummaryImpl(const GlobalValueSummary & Summary,SmallVectorImpl<const GlobalVarSummary * > & Worklist)323fe013be4SDimitry Andric   onImportingSummaryImpl(const GlobalValueSummary &Summary,
324fe013be4SDimitry Andric                          SmallVectorImpl<const GlobalVarSummary *> &Worklist) {
325bdd1243dSDimitry Andric     for (const auto &VI : Summary.refs()) {
326fe013be4SDimitry Andric       if (!shouldImportGlobal(VI)) {
3270b57cec5SDimitry Andric         LLVM_DEBUG(
3280b57cec5SDimitry Andric             dbgs() << "Ref ignored! Target already in destination module.\n");
3290b57cec5SDimitry Andric         continue;
3300b57cec5SDimitry Andric       }
3310b57cec5SDimitry Andric 
3320b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << " ref -> " << VI << "\n");
3330b57cec5SDimitry Andric 
3340b57cec5SDimitry Andric       // If this is a local variable, make sure we import the copy
3350b57cec5SDimitry Andric       // in the caller's module. The only time a local variable can
3360b57cec5SDimitry Andric       // share an entry in the index is if there is a local with the same name
3370b57cec5SDimitry Andric       // in another module that had the same source file name (in a different
3380b57cec5SDimitry Andric       // directory), where each was compiled in their own directory so there
3390b57cec5SDimitry Andric       // was not distinguishing path.
340fe013be4SDimitry Andric       auto LocalNotInModule =
341fe013be4SDimitry Andric           [&](const GlobalValueSummary *RefSummary) -> bool {
3420b57cec5SDimitry Andric         return GlobalValue::isLocalLinkage(RefSummary->linkage()) &&
3430b57cec5SDimitry Andric                RefSummary->modulePath() != Summary.modulePath();
3440b57cec5SDimitry Andric       };
3450b57cec5SDimitry Andric 
346fe013be4SDimitry Andric       for (const auto &RefSummary : VI.getSummaryList()) {
347fe013be4SDimitry Andric         const auto *GVS = dyn_cast<GlobalVarSummary>(RefSummary.get());
348fe013be4SDimitry Andric         // Functions could be referenced by global vars - e.g. a vtable; but we
349fe013be4SDimitry Andric         // don't currently imagine a reason those would be imported here, rather
350fe013be4SDimitry Andric         // than as part of the logic deciding which functions to import (i.e.
351fe013be4SDimitry Andric         // based on profile information). Should we decide to handle them here,
352fe013be4SDimitry Andric         // we can refactor accordingly at that time.
353fe013be4SDimitry Andric         if (!GVS || !Index.canImportGlobalVar(GVS, /* AnalyzeRefs */ true) ||
354fe013be4SDimitry Andric             LocalNotInModule(GVS))
355fe013be4SDimitry Andric           continue;
3560b57cec5SDimitry Andric         auto ILI = ImportList[RefSummary->modulePath()].insert(VI.getGUID());
3575ffd83dbSDimitry Andric         // Only update stat and exports if we haven't already imported this
3585ffd83dbSDimitry Andric         // variable.
3595ffd83dbSDimitry Andric         if (!ILI.second)
3605ffd83dbSDimitry Andric           break;
3610b57cec5SDimitry Andric         NumImportedGlobalVarsThinLink++;
362fe013be4SDimitry Andric         // Any references made by this variable will be marked exported
363fe013be4SDimitry Andric         // later, in ComputeCrossModuleImport, after import decisions are
364fe013be4SDimitry Andric         // complete, which is more efficient than adding them here.
3655ffd83dbSDimitry Andric         if (ExportLists)
3665ffd83dbSDimitry Andric           (*ExportLists)[RefSummary->modulePath()].insert(VI);
367e8d8bef9SDimitry Andric 
368e8d8bef9SDimitry Andric         // If variable is not writeonly we attempt to recursively analyze
369e8d8bef9SDimitry Andric         // its references in order to import referenced constants.
370fe013be4SDimitry Andric         if (!Index.isWriteOnly(GVS))
371fe013be4SDimitry Andric           Worklist.emplace_back(GVS);
3720b57cec5SDimitry Andric         break;
3730b57cec5SDimitry Andric       }
3740b57cec5SDimitry Andric     }
3750b57cec5SDimitry Andric   }
3760b57cec5SDimitry Andric 
377fe013be4SDimitry Andric public:
GlobalsImporter(const ModuleSummaryIndex & Index,const GVSummaryMapTy & DefinedGVSummaries,function_ref<bool (GlobalValue::GUID,const GlobalValueSummary *)> IsPrevailing,FunctionImporter::ImportMapTy & ImportList,DenseMap<StringRef,FunctionImporter::ExportSetTy> * ExportLists)378fe013be4SDimitry Andric   GlobalsImporter(
379fe013be4SDimitry Andric       const ModuleSummaryIndex &Index, const GVSummaryMapTy &DefinedGVSummaries,
380fe013be4SDimitry Andric       function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
381fe013be4SDimitry Andric           IsPrevailing,
382fe013be4SDimitry Andric       FunctionImporter::ImportMapTy &ImportList,
383*c9157d92SDimitry Andric       DenseMap<StringRef, FunctionImporter::ExportSetTy> *ExportLists)
384fe013be4SDimitry Andric       : Index(Index), DefinedGVSummaries(DefinedGVSummaries),
385fe013be4SDimitry Andric         IsPrevailing(IsPrevailing), ImportList(ImportList),
386fe013be4SDimitry Andric         ExportLists(ExportLists) {}
387fe013be4SDimitry Andric 
onImportingSummary(const GlobalValueSummary & Summary)388fe013be4SDimitry Andric   void onImportingSummary(const GlobalValueSummary &Summary) {
389fe013be4SDimitry Andric     SmallVector<const GlobalVarSummary *, 128> Worklist;
390fe013be4SDimitry Andric     onImportingSummaryImpl(Summary, Worklist);
391fe013be4SDimitry Andric     while (!Worklist.empty())
392fe013be4SDimitry Andric       onImportingSummaryImpl(*Worklist.pop_back_val(), Worklist);
393fe013be4SDimitry Andric   }
394fe013be4SDimitry Andric };
395fe013be4SDimitry Andric 
396*c9157d92SDimitry Andric static const char *getFailureName(FunctionImporter::ImportFailureReason Reason);
397*c9157d92SDimitry Andric 
398*c9157d92SDimitry Andric /// Determine the list of imports and exports for each module.
399*c9157d92SDimitry Andric class ModuleImportsManager {
400*c9157d92SDimitry Andric protected:
401*c9157d92SDimitry Andric   function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
402*c9157d92SDimitry Andric       IsPrevailing;
403*c9157d92SDimitry Andric   const ModuleSummaryIndex &Index;
404*c9157d92SDimitry Andric   DenseMap<StringRef, FunctionImporter::ExportSetTy> *const ExportLists;
405*c9157d92SDimitry Andric 
ModuleImportsManager(function_ref<bool (GlobalValue::GUID,const GlobalValueSummary *)> IsPrevailing,const ModuleSummaryIndex & Index,DenseMap<StringRef,FunctionImporter::ExportSetTy> * ExportLists=nullptr)406*c9157d92SDimitry Andric   ModuleImportsManager(
407*c9157d92SDimitry Andric       function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
408*c9157d92SDimitry Andric           IsPrevailing,
409*c9157d92SDimitry Andric       const ModuleSummaryIndex &Index,
410*c9157d92SDimitry Andric       DenseMap<StringRef, FunctionImporter::ExportSetTy> *ExportLists = nullptr)
411*c9157d92SDimitry Andric       : IsPrevailing(IsPrevailing), Index(Index), ExportLists(ExportLists) {}
412*c9157d92SDimitry Andric 
413*c9157d92SDimitry Andric public:
414*c9157d92SDimitry Andric   virtual ~ModuleImportsManager() = default;
415*c9157d92SDimitry Andric 
416*c9157d92SDimitry Andric   /// Given the list of globals defined in a module, compute the list of imports
417*c9157d92SDimitry Andric   /// as well as the list of "exports", i.e. the list of symbols referenced from
418*c9157d92SDimitry Andric   /// another module (that may require promotion).
419*c9157d92SDimitry Andric   virtual void
420*c9157d92SDimitry Andric   computeImportForModule(const GVSummaryMapTy &DefinedGVSummaries,
421*c9157d92SDimitry Andric                          StringRef ModName,
422*c9157d92SDimitry Andric                          FunctionImporter::ImportMapTy &ImportList);
423*c9157d92SDimitry Andric 
424*c9157d92SDimitry Andric   static std::unique_ptr<ModuleImportsManager>
425*c9157d92SDimitry Andric   create(function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
426*c9157d92SDimitry Andric              IsPrevailing,
427*c9157d92SDimitry Andric          const ModuleSummaryIndex &Index,
428*c9157d92SDimitry Andric          DenseMap<StringRef, FunctionImporter::ExportSetTy> *ExportLists =
429*c9157d92SDimitry Andric              nullptr);
430*c9157d92SDimitry Andric };
431*c9157d92SDimitry Andric 
432*c9157d92SDimitry Andric /// A ModuleImportsManager that operates based on a workload definition (see
433*c9157d92SDimitry Andric /// -thinlto-workload-def). For modules that do not define workload roots, it
434*c9157d92SDimitry Andric /// applies the base ModuleImportsManager import policy.
435*c9157d92SDimitry Andric class WorkloadImportsManager : public ModuleImportsManager {
436*c9157d92SDimitry Andric   // Keep a module name -> value infos to import association. We use it to
437*c9157d92SDimitry Andric   // determine if a module's import list should be done by the base
438*c9157d92SDimitry Andric   // ModuleImportsManager or by us.
439*c9157d92SDimitry Andric   StringMap<DenseSet<ValueInfo>> Workloads;
440*c9157d92SDimitry Andric 
441*c9157d92SDimitry Andric   void
computeImportForModule(const GVSummaryMapTy & DefinedGVSummaries,StringRef ModName,FunctionImporter::ImportMapTy & ImportList)442*c9157d92SDimitry Andric   computeImportForModule(const GVSummaryMapTy &DefinedGVSummaries,
443*c9157d92SDimitry Andric                          StringRef ModName,
444*c9157d92SDimitry Andric                          FunctionImporter::ImportMapTy &ImportList) override {
445*c9157d92SDimitry Andric     auto SetIter = Workloads.find(ModName);
446*c9157d92SDimitry Andric     if (SetIter == Workloads.end()) {
447*c9157d92SDimitry Andric       LLVM_DEBUG(dbgs() << "[Workload] " << ModName
448*c9157d92SDimitry Andric                         << " does not contain the root of any context.\n");
449*c9157d92SDimitry Andric       return ModuleImportsManager::computeImportForModule(DefinedGVSummaries,
450*c9157d92SDimitry Andric                                                           ModName, ImportList);
451*c9157d92SDimitry Andric     }
452*c9157d92SDimitry Andric     LLVM_DEBUG(dbgs() << "[Workload] " << ModName
453*c9157d92SDimitry Andric                       << " contains the root(s) of context(s).\n");
454*c9157d92SDimitry Andric 
455*c9157d92SDimitry Andric     GlobalsImporter GVI(Index, DefinedGVSummaries, IsPrevailing, ImportList,
456*c9157d92SDimitry Andric                         ExportLists);
457*c9157d92SDimitry Andric     auto &ValueInfos = SetIter->second;
458*c9157d92SDimitry Andric     SmallVector<EdgeInfo, 128> GlobWorklist;
459*c9157d92SDimitry Andric     for (auto &VI : llvm::make_early_inc_range(ValueInfos)) {
460*c9157d92SDimitry Andric       auto It = DefinedGVSummaries.find(VI.getGUID());
461*c9157d92SDimitry Andric       if (It != DefinedGVSummaries.end() &&
462*c9157d92SDimitry Andric           IsPrevailing(VI.getGUID(), It->second)) {
463*c9157d92SDimitry Andric         LLVM_DEBUG(
464*c9157d92SDimitry Andric             dbgs() << "[Workload] " << VI.name()
465*c9157d92SDimitry Andric                    << " has the prevailing variant already in the module "
466*c9157d92SDimitry Andric                    << ModName << ". No need to import\n");
467*c9157d92SDimitry Andric         continue;
468*c9157d92SDimitry Andric       }
469*c9157d92SDimitry Andric       auto Candidates =
470*c9157d92SDimitry Andric           qualifyCalleeCandidates(Index, VI.getSummaryList(), ModName);
471*c9157d92SDimitry Andric 
472*c9157d92SDimitry Andric       const GlobalValueSummary *GVS = nullptr;
473*c9157d92SDimitry Andric       auto PotentialCandidates = llvm::map_range(
474*c9157d92SDimitry Andric           llvm::make_filter_range(
475*c9157d92SDimitry Andric               Candidates,
476*c9157d92SDimitry Andric               [&](const auto &Candidate) {
477*c9157d92SDimitry Andric                 LLVM_DEBUG(dbgs() << "[Workflow] Candidate for " << VI.name()
478*c9157d92SDimitry Andric                                   << " from " << Candidate.second->modulePath()
479*c9157d92SDimitry Andric                                   << " ImportFailureReason: "
480*c9157d92SDimitry Andric                                   << getFailureName(Candidate.first) << "\n");
481*c9157d92SDimitry Andric                 return Candidate.first ==
482*c9157d92SDimitry Andric                         FunctionImporter::ImportFailureReason::None;
483*c9157d92SDimitry Andric               }),
484*c9157d92SDimitry Andric           [](const auto &Candidate) { return Candidate.second; });
485*c9157d92SDimitry Andric       if (PotentialCandidates.empty()) {
486*c9157d92SDimitry Andric         LLVM_DEBUG(dbgs() << "[Workload] Not importing " << VI.name()
487*c9157d92SDimitry Andric                           << " because can't find eligible Callee. Guid is: "
488*c9157d92SDimitry Andric                           << Function::getGUID(VI.name()) << "\n");
489*c9157d92SDimitry Andric         continue;
490*c9157d92SDimitry Andric       }
491*c9157d92SDimitry Andric       /// We will prefer importing the prevailing candidate, if not, we'll
492*c9157d92SDimitry Andric       /// still pick the first available candidate. The reason we want to make
493*c9157d92SDimitry Andric       /// sure we do import the prevailing candidate is because the goal of
494*c9157d92SDimitry Andric       /// workload-awareness is to enable optimizations specializing the call
495*c9157d92SDimitry Andric       /// graph of that workload. Suppose a function is already defined in the
496*c9157d92SDimitry Andric       /// module, but it's not the prevailing variant. Suppose also we do not
497*c9157d92SDimitry Andric       /// inline it (in fact, if it were interposable, we can't inline it),
498*c9157d92SDimitry Andric       /// but we could specialize it to the workload in other ways. However,
499*c9157d92SDimitry Andric       /// the linker would drop it in the favor of the prevailing copy.
500*c9157d92SDimitry Andric       /// Instead, by importing the prevailing variant (assuming also the use
501*c9157d92SDimitry Andric       /// of `-avail-extern-to-local`), we keep the specialization. We could
502*c9157d92SDimitry Andric       /// alteranatively make the non-prevailing variant local, but the
503*c9157d92SDimitry Andric       /// prevailing one is also the one for which we would have previously
504*c9157d92SDimitry Andric       /// collected profiles, making it preferrable.
505*c9157d92SDimitry Andric       auto PrevailingCandidates = llvm::make_filter_range(
506*c9157d92SDimitry Andric           PotentialCandidates, [&](const auto *Candidate) {
507*c9157d92SDimitry Andric             return IsPrevailing(VI.getGUID(), Candidate);
508*c9157d92SDimitry Andric           });
509*c9157d92SDimitry Andric       if (PrevailingCandidates.empty()) {
510*c9157d92SDimitry Andric         GVS = *PotentialCandidates.begin();
511*c9157d92SDimitry Andric         if (!llvm::hasSingleElement(PotentialCandidates) &&
512*c9157d92SDimitry Andric             GlobalValue::isLocalLinkage(GVS->linkage()))
513*c9157d92SDimitry Andric           LLVM_DEBUG(
514*c9157d92SDimitry Andric               dbgs()
515*c9157d92SDimitry Andric               << "[Workload] Found multiple non-prevailing candidates for "
516*c9157d92SDimitry Andric               << VI.name()
517*c9157d92SDimitry Andric               << ". This is unexpected. Are module paths passed to the "
518*c9157d92SDimitry Andric                  "compiler unique for the modules passed to the linker?");
519*c9157d92SDimitry Andric         // We could in theory have multiple (interposable) copies of a symbol
520*c9157d92SDimitry Andric         // when there is no prevailing candidate, if say the prevailing copy was
521*c9157d92SDimitry Andric         // in a native object being linked in. However, we should in theory be
522*c9157d92SDimitry Andric         // marking all of these non-prevailing IR copies dead in that case, in
523*c9157d92SDimitry Andric         // which case they won't be candidates.
524*c9157d92SDimitry Andric         assert(GVS->isLive());
525*c9157d92SDimitry Andric       } else {
526*c9157d92SDimitry Andric         assert(llvm::hasSingleElement(PrevailingCandidates));
527*c9157d92SDimitry Andric         GVS = *PrevailingCandidates.begin();
528*c9157d92SDimitry Andric       }
529*c9157d92SDimitry Andric 
530*c9157d92SDimitry Andric       auto ExportingModule = GVS->modulePath();
531*c9157d92SDimitry Andric       // We checked that for the prevailing case, but if we happen to have for
532*c9157d92SDimitry Andric       // example an internal that's defined in this module, it'd have no
533*c9157d92SDimitry Andric       // PrevailingCandidates.
534*c9157d92SDimitry Andric       if (ExportingModule == ModName) {
535*c9157d92SDimitry Andric         LLVM_DEBUG(dbgs() << "[Workload] Not importing " << VI.name()
536*c9157d92SDimitry Andric                           << " because its defining module is the same as the "
537*c9157d92SDimitry Andric                              "current module\n");
538*c9157d92SDimitry Andric         continue;
539*c9157d92SDimitry Andric       }
540*c9157d92SDimitry Andric       LLVM_DEBUG(dbgs() << "[Workload][Including]" << VI.name() << " from "
541*c9157d92SDimitry Andric                         << ExportingModule << " : "
542*c9157d92SDimitry Andric                         << Function::getGUID(VI.name()) << "\n");
543*c9157d92SDimitry Andric       ImportList[ExportingModule].insert(VI.getGUID());
544*c9157d92SDimitry Andric       GVI.onImportingSummary(*GVS);
545*c9157d92SDimitry Andric       if (ExportLists)
546*c9157d92SDimitry Andric         (*ExportLists)[ExportingModule].insert(VI);
547*c9157d92SDimitry Andric     }
548*c9157d92SDimitry Andric     LLVM_DEBUG(dbgs() << "[Workload] Done\n");
549*c9157d92SDimitry Andric   }
550*c9157d92SDimitry Andric 
551*c9157d92SDimitry Andric public:
WorkloadImportsManager(function_ref<bool (GlobalValue::GUID,const GlobalValueSummary *)> IsPrevailing,const ModuleSummaryIndex & Index,DenseMap<StringRef,FunctionImporter::ExportSetTy> * ExportLists)552*c9157d92SDimitry Andric   WorkloadImportsManager(
553*c9157d92SDimitry Andric       function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
554*c9157d92SDimitry Andric           IsPrevailing,
555*c9157d92SDimitry Andric       const ModuleSummaryIndex &Index,
556*c9157d92SDimitry Andric       DenseMap<StringRef, FunctionImporter::ExportSetTy> *ExportLists)
557*c9157d92SDimitry Andric       : ModuleImportsManager(IsPrevailing, Index, ExportLists) {
558*c9157d92SDimitry Andric     // Since the workload def uses names, we need a quick lookup
559*c9157d92SDimitry Andric     // name->ValueInfo.
560*c9157d92SDimitry Andric     StringMap<ValueInfo> NameToValueInfo;
561*c9157d92SDimitry Andric     StringSet<> AmbiguousNames;
562*c9157d92SDimitry Andric     for (auto &I : Index) {
563*c9157d92SDimitry Andric       ValueInfo VI = Index.getValueInfo(I);
564*c9157d92SDimitry Andric       if (!NameToValueInfo.insert(std::make_pair(VI.name(), VI)).second)
565*c9157d92SDimitry Andric         LLVM_DEBUG(AmbiguousNames.insert(VI.name()));
566*c9157d92SDimitry Andric     }
567*c9157d92SDimitry Andric     auto DbgReportIfAmbiguous = [&](StringRef Name) {
568*c9157d92SDimitry Andric       LLVM_DEBUG(if (AmbiguousNames.count(Name) > 0) {
569*c9157d92SDimitry Andric         dbgs() << "[Workload] Function name " << Name
570*c9157d92SDimitry Andric                << " present in the workload definition is ambiguous. Consider "
571*c9157d92SDimitry Andric                   "compiling with -funique-internal-linkage-names.";
572*c9157d92SDimitry Andric       });
573*c9157d92SDimitry Andric     };
574*c9157d92SDimitry Andric     std::error_code EC;
575*c9157d92SDimitry Andric     auto BufferOrErr = MemoryBuffer::getFileOrSTDIN(WorkloadDefinitions);
576*c9157d92SDimitry Andric     if (std::error_code EC = BufferOrErr.getError()) {
577*c9157d92SDimitry Andric       report_fatal_error("Failed to open context file");
578*c9157d92SDimitry Andric       return;
579*c9157d92SDimitry Andric     }
580*c9157d92SDimitry Andric     auto Buffer = std::move(BufferOrErr.get());
581*c9157d92SDimitry Andric     std::map<std::string, std::vector<std::string>> WorkloadDefs;
582*c9157d92SDimitry Andric     json::Path::Root NullRoot;
583*c9157d92SDimitry Andric     // The JSON is supposed to contain a dictionary matching the type of
584*c9157d92SDimitry Andric     // WorkloadDefs. For example:
585*c9157d92SDimitry Andric     // {
586*c9157d92SDimitry Andric     //   "rootFunction_1": ["function_to_import_1", "function_to_import_2"],
587*c9157d92SDimitry Andric     //   "rootFunction_2": ["function_to_import_3", "function_to_import_4"]
588*c9157d92SDimitry Andric     // }
589*c9157d92SDimitry Andric     auto Parsed = json::parse(Buffer->getBuffer());
590*c9157d92SDimitry Andric     if (!Parsed)
591*c9157d92SDimitry Andric       report_fatal_error(Parsed.takeError());
592*c9157d92SDimitry Andric     if (!json::fromJSON(*Parsed, WorkloadDefs, NullRoot))
593*c9157d92SDimitry Andric       report_fatal_error("Invalid thinlto contextual profile format.");
594*c9157d92SDimitry Andric     for (const auto &Workload : WorkloadDefs) {
595*c9157d92SDimitry Andric       const auto &Root = Workload.first;
596*c9157d92SDimitry Andric       DbgReportIfAmbiguous(Root);
597*c9157d92SDimitry Andric       LLVM_DEBUG(dbgs() << "[Workload] Root: " << Root << "\n");
598*c9157d92SDimitry Andric       const auto &AllCallees = Workload.second;
599*c9157d92SDimitry Andric       auto RootIt = NameToValueInfo.find(Root);
600*c9157d92SDimitry Andric       if (RootIt == NameToValueInfo.end()) {
601*c9157d92SDimitry Andric         LLVM_DEBUG(dbgs() << "[Workload] Root " << Root
602*c9157d92SDimitry Andric                           << " not found in this linkage unit.\n");
603*c9157d92SDimitry Andric         continue;
604*c9157d92SDimitry Andric       }
605*c9157d92SDimitry Andric       auto RootVI = RootIt->second;
606*c9157d92SDimitry Andric       if (RootVI.getSummaryList().size() != 1) {
607*c9157d92SDimitry Andric         LLVM_DEBUG(dbgs() << "[Workload] Root " << Root
608*c9157d92SDimitry Andric                           << " should have exactly one summary, but has "
609*c9157d92SDimitry Andric                           << RootVI.getSummaryList().size() << ". Skipping.\n");
610*c9157d92SDimitry Andric         continue;
611*c9157d92SDimitry Andric       }
612*c9157d92SDimitry Andric       StringRef RootDefiningModule =
613*c9157d92SDimitry Andric           RootVI.getSummaryList().front()->modulePath();
614*c9157d92SDimitry Andric       LLVM_DEBUG(dbgs() << "[Workload] Root defining module for " << Root
615*c9157d92SDimitry Andric                         << " is : " << RootDefiningModule << "\n");
616*c9157d92SDimitry Andric       auto &Set = Workloads[RootDefiningModule];
617*c9157d92SDimitry Andric       for (const auto &Callee : AllCallees) {
618*c9157d92SDimitry Andric         LLVM_DEBUG(dbgs() << "[Workload] " << Callee << "\n");
619*c9157d92SDimitry Andric         DbgReportIfAmbiguous(Callee);
620*c9157d92SDimitry Andric         auto ElemIt = NameToValueInfo.find(Callee);
621*c9157d92SDimitry Andric         if (ElemIt == NameToValueInfo.end()) {
622*c9157d92SDimitry Andric           LLVM_DEBUG(dbgs() << "[Workload] " << Callee << " not found\n");
623*c9157d92SDimitry Andric           continue;
624*c9157d92SDimitry Andric         }
625*c9157d92SDimitry Andric         Set.insert(ElemIt->second);
626*c9157d92SDimitry Andric       }
627*c9157d92SDimitry Andric       LLVM_DEBUG({
628*c9157d92SDimitry Andric         dbgs() << "[Workload] Root: " << Root << " we have " << Set.size()
629*c9157d92SDimitry Andric                << " distinct callees.\n";
630*c9157d92SDimitry Andric         for (const auto &VI : Set) {
631*c9157d92SDimitry Andric           dbgs() << "[Workload] Root: " << Root
632*c9157d92SDimitry Andric                  << " Would include: " << VI.getGUID() << "\n";
633*c9157d92SDimitry Andric         }
634*c9157d92SDimitry Andric       });
635*c9157d92SDimitry Andric     }
636*c9157d92SDimitry Andric   }
637*c9157d92SDimitry Andric };
638*c9157d92SDimitry Andric 
create(function_ref<bool (GlobalValue::GUID,const GlobalValueSummary *)> IsPrevailing,const ModuleSummaryIndex & Index,DenseMap<StringRef,FunctionImporter::ExportSetTy> * ExportLists)639*c9157d92SDimitry Andric std::unique_ptr<ModuleImportsManager> ModuleImportsManager::create(
640*c9157d92SDimitry Andric     function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
641*c9157d92SDimitry Andric         IsPrevailing,
642*c9157d92SDimitry Andric     const ModuleSummaryIndex &Index,
643*c9157d92SDimitry Andric     DenseMap<StringRef, FunctionImporter::ExportSetTy> *ExportLists) {
644*c9157d92SDimitry Andric   if (WorkloadDefinitions.empty()) {
645*c9157d92SDimitry Andric     LLVM_DEBUG(dbgs() << "[Workload] Using the regular imports manager.\n");
646*c9157d92SDimitry Andric     return std::unique_ptr<ModuleImportsManager>(
647*c9157d92SDimitry Andric         new ModuleImportsManager(IsPrevailing, Index, ExportLists));
648*c9157d92SDimitry Andric   }
649*c9157d92SDimitry Andric   LLVM_DEBUG(dbgs() << "[Workload] Using the contextual imports manager.\n");
650*c9157d92SDimitry Andric   return std::make_unique<WorkloadImportsManager>(IsPrevailing, Index,
651*c9157d92SDimitry Andric                                                   ExportLists);
652*c9157d92SDimitry Andric }
653*c9157d92SDimitry Andric 
6540b57cec5SDimitry Andric static const char *
getFailureName(FunctionImporter::ImportFailureReason Reason)6550b57cec5SDimitry Andric getFailureName(FunctionImporter::ImportFailureReason Reason) {
6560b57cec5SDimitry Andric   switch (Reason) {
6570b57cec5SDimitry Andric   case FunctionImporter::ImportFailureReason::None:
6580b57cec5SDimitry Andric     return "None";
6590b57cec5SDimitry Andric   case FunctionImporter::ImportFailureReason::GlobalVar:
6600b57cec5SDimitry Andric     return "GlobalVar";
6610b57cec5SDimitry Andric   case FunctionImporter::ImportFailureReason::NotLive:
6620b57cec5SDimitry Andric     return "NotLive";
6630b57cec5SDimitry Andric   case FunctionImporter::ImportFailureReason::TooLarge:
6640b57cec5SDimitry Andric     return "TooLarge";
6650b57cec5SDimitry Andric   case FunctionImporter::ImportFailureReason::InterposableLinkage:
6660b57cec5SDimitry Andric     return "InterposableLinkage";
6670b57cec5SDimitry Andric   case FunctionImporter::ImportFailureReason::LocalLinkageNotInModule:
6680b57cec5SDimitry Andric     return "LocalLinkageNotInModule";
6690b57cec5SDimitry Andric   case FunctionImporter::ImportFailureReason::NotEligible:
6700b57cec5SDimitry Andric     return "NotEligible";
6710b57cec5SDimitry Andric   case FunctionImporter::ImportFailureReason::NoInline:
6720b57cec5SDimitry Andric     return "NoInline";
6730b57cec5SDimitry Andric   }
6740b57cec5SDimitry Andric   llvm_unreachable("invalid reason");
6750b57cec5SDimitry Andric }
6760b57cec5SDimitry Andric 
6770b57cec5SDimitry Andric /// Compute the list of functions to import for a given caller. Mark these
6780b57cec5SDimitry Andric /// imported functions and the symbols they reference in their source module as
6790b57cec5SDimitry Andric /// exported from their source module.
computeImportForFunction(const FunctionSummary & Summary,const ModuleSummaryIndex & Index,const unsigned Threshold,const GVSummaryMapTy & DefinedGVSummaries,function_ref<bool (GlobalValue::GUID,const GlobalValueSummary *)> isPrevailing,SmallVectorImpl<EdgeInfo> & Worklist,GlobalsImporter & GVImporter,FunctionImporter::ImportMapTy & ImportList,DenseMap<StringRef,FunctionImporter::ExportSetTy> * ExportLists,FunctionImporter::ImportThresholdsTy & ImportThresholds)6800b57cec5SDimitry Andric static void computeImportForFunction(
6810b57cec5SDimitry Andric     const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
6820b57cec5SDimitry Andric     const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
683fe013be4SDimitry Andric     function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
684fe013be4SDimitry Andric         isPrevailing,
685fe013be4SDimitry Andric     SmallVectorImpl<EdgeInfo> &Worklist, GlobalsImporter &GVImporter,
6860b57cec5SDimitry Andric     FunctionImporter::ImportMapTy &ImportList,
687*c9157d92SDimitry Andric     DenseMap<StringRef, FunctionImporter::ExportSetTy> *ExportLists,
6880b57cec5SDimitry Andric     FunctionImporter::ImportThresholdsTy &ImportThresholds) {
689fe013be4SDimitry Andric   GVImporter.onImportingSummary(Summary);
6900b57cec5SDimitry Andric   static int ImportCount = 0;
691bdd1243dSDimitry Andric   for (const auto &Edge : Summary.calls()) {
6920b57cec5SDimitry Andric     ValueInfo VI = Edge.first;
6930b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << " edge -> " << VI << " Threshold:" << Threshold
6940b57cec5SDimitry Andric                       << "\n");
6950b57cec5SDimitry Andric 
6960b57cec5SDimitry Andric     if (ImportCutoff >= 0 && ImportCount >= ImportCutoff) {
6970b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "ignored! import-cutoff value of " << ImportCutoff
6980b57cec5SDimitry Andric                         << " reached.\n");
6990b57cec5SDimitry Andric       continue;
7000b57cec5SDimitry Andric     }
7010b57cec5SDimitry Andric 
7020b57cec5SDimitry Andric     if (DefinedGVSummaries.count(VI.getGUID())) {
703fe6060f1SDimitry Andric       // FIXME: Consider not skipping import if the module contains
704fe6060f1SDimitry Andric       // a non-prevailing def with interposable linkage. The prevailing copy
705fe6060f1SDimitry Andric       // can safely be imported (see shouldImportGlobal()).
7060b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "ignored! Target already in destination module.\n");
7070b57cec5SDimitry Andric       continue;
7080b57cec5SDimitry Andric     }
7090b57cec5SDimitry Andric 
7100b57cec5SDimitry Andric     auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
7110b57cec5SDimitry Andric       if (Hotness == CalleeInfo::HotnessType::Hot)
7120b57cec5SDimitry Andric         return ImportHotMultiplier;
7130b57cec5SDimitry Andric       if (Hotness == CalleeInfo::HotnessType::Cold)
7140b57cec5SDimitry Andric         return ImportColdMultiplier;
7150b57cec5SDimitry Andric       if (Hotness == CalleeInfo::HotnessType::Critical)
7160b57cec5SDimitry Andric         return ImportCriticalMultiplier;
7170b57cec5SDimitry Andric       return 1.0;
7180b57cec5SDimitry Andric     };
7190b57cec5SDimitry Andric 
7200b57cec5SDimitry Andric     const auto NewThreshold =
7210b57cec5SDimitry Andric         Threshold * GetBonusMultiplier(Edge.second.getHotness());
7220b57cec5SDimitry Andric 
7230b57cec5SDimitry Andric     auto IT = ImportThresholds.insert(std::make_pair(
7240b57cec5SDimitry Andric         VI.getGUID(), std::make_tuple(NewThreshold, nullptr, nullptr)));
7250b57cec5SDimitry Andric     bool PreviouslyVisited = !IT.second;
7260b57cec5SDimitry Andric     auto &ProcessedThreshold = std::get<0>(IT.first->second);
7270b57cec5SDimitry Andric     auto &CalleeSummary = std::get<1>(IT.first->second);
7280b57cec5SDimitry Andric     auto &FailureInfo = std::get<2>(IT.first->second);
7290b57cec5SDimitry Andric 
7300b57cec5SDimitry Andric     bool IsHotCallsite =
7310b57cec5SDimitry Andric         Edge.second.getHotness() == CalleeInfo::HotnessType::Hot;
7320b57cec5SDimitry Andric     bool IsCriticalCallsite =
7330b57cec5SDimitry Andric         Edge.second.getHotness() == CalleeInfo::HotnessType::Critical;
7340b57cec5SDimitry Andric 
7350b57cec5SDimitry Andric     const FunctionSummary *ResolvedCalleeSummary = nullptr;
7360b57cec5SDimitry Andric     if (CalleeSummary) {
7370b57cec5SDimitry Andric       assert(PreviouslyVisited);
7380b57cec5SDimitry Andric       // Since the traversal of the call graph is DFS, we can revisit a function
7390b57cec5SDimitry Andric       // a second time with a higher threshold. In this case, it is added back
7400b57cec5SDimitry Andric       // to the worklist with the new threshold (so that its own callee chains
7410b57cec5SDimitry Andric       // can be considered with the higher threshold).
7420b57cec5SDimitry Andric       if (NewThreshold <= ProcessedThreshold) {
7430b57cec5SDimitry Andric         LLVM_DEBUG(
7440b57cec5SDimitry Andric             dbgs() << "ignored! Target was already imported with Threshold "
7450b57cec5SDimitry Andric                    << ProcessedThreshold << "\n");
7460b57cec5SDimitry Andric         continue;
7470b57cec5SDimitry Andric       }
7480b57cec5SDimitry Andric       // Update with new larger threshold.
7490b57cec5SDimitry Andric       ProcessedThreshold = NewThreshold;
7500b57cec5SDimitry Andric       ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
7510b57cec5SDimitry Andric     } else {
7520b57cec5SDimitry Andric       // If we already rejected importing a callee at the same or higher
7530b57cec5SDimitry Andric       // threshold, don't waste time calling selectCallee.
7540b57cec5SDimitry Andric       if (PreviouslyVisited && NewThreshold <= ProcessedThreshold) {
7550b57cec5SDimitry Andric         LLVM_DEBUG(
7560b57cec5SDimitry Andric             dbgs() << "ignored! Target was already rejected with Threshold "
7570b57cec5SDimitry Andric             << ProcessedThreshold << "\n");
7580b57cec5SDimitry Andric         if (PrintImportFailures) {
7590b57cec5SDimitry Andric           assert(FailureInfo &&
7600b57cec5SDimitry Andric                  "Expected FailureInfo for previously rejected candidate");
7610b57cec5SDimitry Andric           FailureInfo->Attempts++;
7620b57cec5SDimitry Andric         }
7630b57cec5SDimitry Andric         continue;
7640b57cec5SDimitry Andric       }
7650b57cec5SDimitry Andric 
766*c9157d92SDimitry Andric       FunctionImporter::ImportFailureReason Reason{};
7670b57cec5SDimitry Andric       CalleeSummary = selectCallee(Index, VI.getSummaryList(), NewThreshold,
768fe013be4SDimitry Andric                                    Summary.modulePath(), Reason);
7690b57cec5SDimitry Andric       if (!CalleeSummary) {
7700b57cec5SDimitry Andric         // Update with new larger threshold if this was a retry (otherwise
7710b57cec5SDimitry Andric         // we would have already inserted with NewThreshold above). Also
7720b57cec5SDimitry Andric         // update failure info if requested.
7730b57cec5SDimitry Andric         if (PreviouslyVisited) {
7740b57cec5SDimitry Andric           ProcessedThreshold = NewThreshold;
7750b57cec5SDimitry Andric           if (PrintImportFailures) {
7760b57cec5SDimitry Andric             assert(FailureInfo &&
7770b57cec5SDimitry Andric                    "Expected FailureInfo for previously rejected candidate");
7780b57cec5SDimitry Andric             FailureInfo->Reason = Reason;
7790b57cec5SDimitry Andric             FailureInfo->Attempts++;
7800b57cec5SDimitry Andric             FailureInfo->MaxHotness =
7810b57cec5SDimitry Andric                 std::max(FailureInfo->MaxHotness, Edge.second.getHotness());
7820b57cec5SDimitry Andric           }
7830b57cec5SDimitry Andric         } else if (PrintImportFailures) {
7840b57cec5SDimitry Andric           assert(!FailureInfo &&
7850b57cec5SDimitry Andric                  "Expected no FailureInfo for newly rejected candidate");
7868bcb0991SDimitry Andric           FailureInfo = std::make_unique<FunctionImporter::ImportFailureInfo>(
7870b57cec5SDimitry Andric               VI, Edge.second.getHotness(), Reason, 1);
7880b57cec5SDimitry Andric         }
789fe6060f1SDimitry Andric         if (ForceImportAll) {
790fe6060f1SDimitry Andric           std::string Msg = std::string("Failed to import function ") +
791fe6060f1SDimitry Andric                             VI.name().str() + " due to " +
792fe6060f1SDimitry Andric                             getFailureName(Reason);
793fe6060f1SDimitry Andric           auto Error = make_error<StringError>(
794349cc55cSDimitry Andric               Msg, make_error_code(errc::not_supported));
795fe6060f1SDimitry Andric           logAllUnhandledErrors(std::move(Error), errs(),
796fe6060f1SDimitry Andric                                 "Error importing module: ");
797fe6060f1SDimitry Andric           break;
798fe6060f1SDimitry Andric         } else {
799fe6060f1SDimitry Andric           LLVM_DEBUG(dbgs()
800fe6060f1SDimitry Andric                      << "ignored! No qualifying callee with summary found.\n");
8010b57cec5SDimitry Andric           continue;
8020b57cec5SDimitry Andric         }
803fe6060f1SDimitry Andric       }
8040b57cec5SDimitry Andric 
8050b57cec5SDimitry Andric       // "Resolve" the summary
8060b57cec5SDimitry Andric       CalleeSummary = CalleeSummary->getBaseObject();
8070b57cec5SDimitry Andric       ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
8080b57cec5SDimitry Andric 
809fe6060f1SDimitry Andric       assert((ResolvedCalleeSummary->fflags().AlwaysInline || ForceImportAll ||
810480093f4SDimitry Andric               (ResolvedCalleeSummary->instCount() <= NewThreshold)) &&
8110b57cec5SDimitry Andric              "selectCallee() didn't honor the threshold");
8120b57cec5SDimitry Andric 
8130b57cec5SDimitry Andric       auto ExportModulePath = ResolvedCalleeSummary->modulePath();
8140b57cec5SDimitry Andric       auto ILI = ImportList[ExportModulePath].insert(VI.getGUID());
8150b57cec5SDimitry Andric       // We previously decided to import this GUID definition if it was already
8160b57cec5SDimitry Andric       // inserted in the set of imports from the exporting module.
8170b57cec5SDimitry Andric       bool PreviouslyImported = !ILI.second;
8180b57cec5SDimitry Andric       if (!PreviouslyImported) {
8190b57cec5SDimitry Andric         NumImportedFunctionsThinLink++;
8200b57cec5SDimitry Andric         if (IsHotCallsite)
8210b57cec5SDimitry Andric           NumImportedHotFunctionsThinLink++;
8220b57cec5SDimitry Andric         if (IsCriticalCallsite)
8230b57cec5SDimitry Andric           NumImportedCriticalFunctionsThinLink++;
8240b57cec5SDimitry Andric       }
8250b57cec5SDimitry Andric 
8265ffd83dbSDimitry Andric       // Any calls/references made by this function will be marked exported
8275ffd83dbSDimitry Andric       // later, in ComputeCrossModuleImport, after import decisions are
8285ffd83dbSDimitry Andric       // complete, which is more efficient than adding them here.
8295ffd83dbSDimitry Andric       if (ExportLists)
8305ffd83dbSDimitry Andric         (*ExportLists)[ExportModulePath].insert(VI);
8310b57cec5SDimitry Andric     }
8320b57cec5SDimitry Andric 
8330b57cec5SDimitry Andric     auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
8340b57cec5SDimitry Andric       // Adjust the threshold for next level of imported functions.
8350b57cec5SDimitry Andric       // The threshold is different for hot callsites because we can then
8360b57cec5SDimitry Andric       // inline chains of hot calls.
8370b57cec5SDimitry Andric       if (IsHotCallsite)
8380b57cec5SDimitry Andric         return Threshold * ImportHotInstrFactor;
8390b57cec5SDimitry Andric       return Threshold * ImportInstrFactor;
8400b57cec5SDimitry Andric     };
8410b57cec5SDimitry Andric 
8420b57cec5SDimitry Andric     const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
8430b57cec5SDimitry Andric 
8440b57cec5SDimitry Andric     ImportCount++;
8450b57cec5SDimitry Andric 
8460b57cec5SDimitry Andric     // Insert the newly imported function to the worklist.
847e8d8bef9SDimitry Andric     Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold);
8480b57cec5SDimitry Andric   }
8490b57cec5SDimitry Andric }
8500b57cec5SDimitry Andric 
computeImportForModule(const GVSummaryMapTy & DefinedGVSummaries,StringRef ModName,FunctionImporter::ImportMapTy & ImportList)851*c9157d92SDimitry Andric void ModuleImportsManager::computeImportForModule(
852*c9157d92SDimitry Andric     const GVSummaryMapTy &DefinedGVSummaries, StringRef ModName,
853*c9157d92SDimitry Andric     FunctionImporter::ImportMapTy &ImportList) {
8540b57cec5SDimitry Andric   // Worklist contains the list of function imported in this module, for which
8550b57cec5SDimitry Andric   // we will analyse the callees and may import further down the callgraph.
8560b57cec5SDimitry Andric   SmallVector<EdgeInfo, 128> Worklist;
857*c9157d92SDimitry Andric   GlobalsImporter GVI(Index, DefinedGVSummaries, IsPrevailing, ImportList,
858fe013be4SDimitry Andric                       ExportLists);
8590b57cec5SDimitry Andric   FunctionImporter::ImportThresholdsTy ImportThresholds;
8600b57cec5SDimitry Andric 
8610b57cec5SDimitry Andric   // Populate the worklist with the import for the functions in the current
8620b57cec5SDimitry Andric   // module
863bdd1243dSDimitry Andric   for (const auto &GVSummary : DefinedGVSummaries) {
8640b57cec5SDimitry Andric #ifndef NDEBUG
8650b57cec5SDimitry Andric     // FIXME: Change the GVSummaryMapTy to hold ValueInfo instead of GUID
8660b57cec5SDimitry Andric     // so this map look up (and possibly others) can be avoided.
8670b57cec5SDimitry Andric     auto VI = Index.getValueInfo(GVSummary.first);
8680b57cec5SDimitry Andric #endif
8690b57cec5SDimitry Andric     if (!Index.isGlobalValueLive(GVSummary.second)) {
8700b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "Ignores Dead GUID: " << VI << "\n");
8710b57cec5SDimitry Andric       continue;
8720b57cec5SDimitry Andric     }
8730b57cec5SDimitry Andric     auto *FuncSummary =
8740b57cec5SDimitry Andric         dyn_cast<FunctionSummary>(GVSummary.second->getBaseObject());
8750b57cec5SDimitry Andric     if (!FuncSummary)
8760b57cec5SDimitry Andric       // Skip import for global variables
8770b57cec5SDimitry Andric       continue;
8780b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Initialize import for " << VI << "\n");
8790b57cec5SDimitry Andric     computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
880*c9157d92SDimitry Andric                              DefinedGVSummaries, IsPrevailing, Worklist, GVI,
881fe013be4SDimitry Andric                              ImportList, ExportLists, ImportThresholds);
8820b57cec5SDimitry Andric   }
8830b57cec5SDimitry Andric 
8840b57cec5SDimitry Andric   // Process the newly imported functions and add callees to the worklist.
8850b57cec5SDimitry Andric   while (!Worklist.empty()) {
886e8d8bef9SDimitry Andric     auto GVInfo = Worklist.pop_back_val();
887e8d8bef9SDimitry Andric     auto *Summary = std::get<0>(GVInfo);
888e8d8bef9SDimitry Andric     auto Threshold = std::get<1>(GVInfo);
8890b57cec5SDimitry Andric 
890e8d8bef9SDimitry Andric     if (auto *FS = dyn_cast<FunctionSummary>(Summary))
891e8d8bef9SDimitry Andric       computeImportForFunction(*FS, Index, Threshold, DefinedGVSummaries,
892*c9157d92SDimitry Andric                                IsPrevailing, Worklist, GVI, ImportList,
893fe013be4SDimitry Andric                                ExportLists, ImportThresholds);
8940b57cec5SDimitry Andric   }
8950b57cec5SDimitry Andric 
8960b57cec5SDimitry Andric   // Print stats about functions considered but rejected for importing
8970b57cec5SDimitry Andric   // when requested.
8980b57cec5SDimitry Andric   if (PrintImportFailures) {
8990b57cec5SDimitry Andric     dbgs() << "Missed imports into module " << ModName << "\n";
9000b57cec5SDimitry Andric     for (auto &I : ImportThresholds) {
9010b57cec5SDimitry Andric       auto &ProcessedThreshold = std::get<0>(I.second);
9020b57cec5SDimitry Andric       auto &CalleeSummary = std::get<1>(I.second);
9030b57cec5SDimitry Andric       auto &FailureInfo = std::get<2>(I.second);
9040b57cec5SDimitry Andric       if (CalleeSummary)
9050b57cec5SDimitry Andric         continue; // We are going to import.
9060b57cec5SDimitry Andric       assert(FailureInfo);
9070b57cec5SDimitry Andric       FunctionSummary *FS = nullptr;
9080b57cec5SDimitry Andric       if (!FailureInfo->VI.getSummaryList().empty())
9090b57cec5SDimitry Andric         FS = dyn_cast<FunctionSummary>(
9100b57cec5SDimitry Andric             FailureInfo->VI.getSummaryList()[0]->getBaseObject());
9110b57cec5SDimitry Andric       dbgs() << FailureInfo->VI
9120b57cec5SDimitry Andric              << ": Reason = " << getFailureName(FailureInfo->Reason)
9130b57cec5SDimitry Andric              << ", Threshold = " << ProcessedThreshold
9140b57cec5SDimitry Andric              << ", Size = " << (FS ? (int)FS->instCount() : -1)
9150b57cec5SDimitry Andric              << ", MaxHotness = " << getHotnessName(FailureInfo->MaxHotness)
9160b57cec5SDimitry Andric              << ", Attempts = " << FailureInfo->Attempts << "\n";
9170b57cec5SDimitry Andric     }
9180b57cec5SDimitry Andric   }
9190b57cec5SDimitry Andric }
9200b57cec5SDimitry Andric 
9210b57cec5SDimitry Andric #ifndef NDEBUG
isGlobalVarSummary(const ModuleSummaryIndex & Index,ValueInfo VI)922480093f4SDimitry Andric static bool isGlobalVarSummary(const ModuleSummaryIndex &Index, ValueInfo VI) {
9230b57cec5SDimitry Andric   auto SL = VI.getSummaryList();
924480093f4SDimitry Andric   return SL.empty()
925480093f4SDimitry Andric              ? false
926480093f4SDimitry Andric              : SL[0]->getSummaryKind() == GlobalValueSummary::GlobalVarKind;
9270b57cec5SDimitry Andric }
9280b57cec5SDimitry Andric 
isGlobalVarSummary(const ModuleSummaryIndex & Index,GlobalValue::GUID G)929480093f4SDimitry Andric static bool isGlobalVarSummary(const ModuleSummaryIndex &Index,
930480093f4SDimitry Andric                                GlobalValue::GUID G) {
931480093f4SDimitry Andric   if (const auto &VI = Index.getValueInfo(G))
932480093f4SDimitry Andric     return isGlobalVarSummary(Index, VI);
933480093f4SDimitry Andric   return false;
934480093f4SDimitry Andric }
9350b57cec5SDimitry Andric 
9360b57cec5SDimitry Andric template <class T>
numGlobalVarSummaries(const ModuleSummaryIndex & Index,T & Cont)9370b57cec5SDimitry Andric static unsigned numGlobalVarSummaries(const ModuleSummaryIndex &Index,
9380b57cec5SDimitry Andric                                       T &Cont) {
9390b57cec5SDimitry Andric   unsigned NumGVS = 0;
9400b57cec5SDimitry Andric   for (auto &V : Cont)
941480093f4SDimitry Andric     if (isGlobalVarSummary(Index, V))
9420b57cec5SDimitry Andric       ++NumGVS;
9430b57cec5SDimitry Andric   return NumGVS;
9440b57cec5SDimitry Andric }
9450b57cec5SDimitry Andric #endif
9460b57cec5SDimitry Andric 
947480093f4SDimitry Andric #ifndef NDEBUG
checkVariableImport(const ModuleSummaryIndex & Index,DenseMap<StringRef,FunctionImporter::ImportMapTy> & ImportLists,DenseMap<StringRef,FunctionImporter::ExportSetTy> & ExportLists)948*c9157d92SDimitry Andric static bool checkVariableImport(
949*c9157d92SDimitry Andric     const ModuleSummaryIndex &Index,
950*c9157d92SDimitry Andric     DenseMap<StringRef, FunctionImporter::ImportMapTy> &ImportLists,
951*c9157d92SDimitry Andric     DenseMap<StringRef, FunctionImporter::ExportSetTy> &ExportLists) {
952480093f4SDimitry Andric 
953480093f4SDimitry Andric   DenseSet<GlobalValue::GUID> FlattenedImports;
954480093f4SDimitry Andric 
955480093f4SDimitry Andric   for (auto &ImportPerModule : ImportLists)
956480093f4SDimitry Andric     for (auto &ExportPerModule : ImportPerModule.second)
957480093f4SDimitry Andric       FlattenedImports.insert(ExportPerModule.second.begin(),
958480093f4SDimitry Andric                               ExportPerModule.second.end());
959480093f4SDimitry Andric 
960480093f4SDimitry Andric   // Checks that all GUIDs of read/writeonly vars we see in export lists
961480093f4SDimitry Andric   // are also in the import lists. Otherwise we my face linker undefs,
962480093f4SDimitry Andric   // because readonly and writeonly vars are internalized in their
963fe013be4SDimitry Andric   // source modules. The exception would be if it has a linkage type indicating
964fe013be4SDimitry Andric   // that there may have been a copy existing in the importing module (e.g.
965fe013be4SDimitry Andric   // linkonce_odr). In that case we cannot accurately do this checking.
966fe013be4SDimitry Andric   auto IsReadOrWriteOnlyVarNeedingImporting = [&](StringRef ModulePath,
967fe013be4SDimitry Andric                                                   const ValueInfo &VI) {
968480093f4SDimitry Andric     auto *GVS = dyn_cast_or_null<GlobalVarSummary>(
969480093f4SDimitry Andric         Index.findSummaryInModule(VI, ModulePath));
970fe013be4SDimitry Andric     return GVS && (Index.isReadOnly(GVS) || Index.isWriteOnly(GVS)) &&
971fe013be4SDimitry Andric            !(GVS->linkage() == GlobalValue::AvailableExternallyLinkage ||
972fe013be4SDimitry Andric              GVS->linkage() == GlobalValue::WeakODRLinkage ||
973fe013be4SDimitry Andric              GVS->linkage() == GlobalValue::LinkOnceODRLinkage);
974480093f4SDimitry Andric   };
975480093f4SDimitry Andric 
976480093f4SDimitry Andric   for (auto &ExportPerModule : ExportLists)
977480093f4SDimitry Andric     for (auto &VI : ExportPerModule.second)
978480093f4SDimitry Andric       if (!FlattenedImports.count(VI.getGUID()) &&
979*c9157d92SDimitry Andric           IsReadOrWriteOnlyVarNeedingImporting(ExportPerModule.first, VI))
980480093f4SDimitry Andric         return false;
981480093f4SDimitry Andric 
982480093f4SDimitry Andric   return true;
983480093f4SDimitry Andric }
984480093f4SDimitry Andric #endif
985480093f4SDimitry Andric 
9860b57cec5SDimitry Andric /// Compute all the import and export for every module using the Index.
ComputeCrossModuleImport(const ModuleSummaryIndex & Index,const DenseMap<StringRef,GVSummaryMapTy> & ModuleToDefinedGVSummaries,function_ref<bool (GlobalValue::GUID,const GlobalValueSummary *)> isPrevailing,DenseMap<StringRef,FunctionImporter::ImportMapTy> & ImportLists,DenseMap<StringRef,FunctionImporter::ExportSetTy> & ExportLists)9870b57cec5SDimitry Andric void llvm::ComputeCrossModuleImport(
9880b57cec5SDimitry Andric     const ModuleSummaryIndex &Index,
989*c9157d92SDimitry Andric     const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
990fe013be4SDimitry Andric     function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
991fe013be4SDimitry Andric         isPrevailing,
992*c9157d92SDimitry Andric     DenseMap<StringRef, FunctionImporter::ImportMapTy> &ImportLists,
993*c9157d92SDimitry Andric     DenseMap<StringRef, FunctionImporter::ExportSetTy> &ExportLists) {
994*c9157d92SDimitry Andric   auto MIS = ModuleImportsManager::create(isPrevailing, Index, &ExportLists);
9950b57cec5SDimitry Andric   // For each module that has function defined, compute the import/export lists.
996bdd1243dSDimitry Andric   for (const auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
997*c9157d92SDimitry Andric     auto &ImportList = ImportLists[DefinedGVSummaries.first];
9980b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Computing import for Module '"
999*c9157d92SDimitry Andric                       << DefinedGVSummaries.first << "'\n");
1000*c9157d92SDimitry Andric     MIS->computeImportForModule(DefinedGVSummaries.second,
1001*c9157d92SDimitry Andric                                 DefinedGVSummaries.first, ImportList);
10020b57cec5SDimitry Andric   }
10030b57cec5SDimitry Andric 
10045ffd83dbSDimitry Andric   // When computing imports we only added the variables and functions being
10055ffd83dbSDimitry Andric   // imported to the export list. We also need to mark any references and calls
10065ffd83dbSDimitry Andric   // they make as exported as well. We do this here, as it is more efficient
10075ffd83dbSDimitry Andric   // since we may import the same values multiple times into different modules
10085ffd83dbSDimitry Andric   // during the import computation.
10090b57cec5SDimitry Andric   for (auto &ELI : ExportLists) {
10105ffd83dbSDimitry Andric     FunctionImporter::ExportSetTy NewExports;
10110b57cec5SDimitry Andric     const auto &DefinedGVSummaries =
1012*c9157d92SDimitry Andric         ModuleToDefinedGVSummaries.lookup(ELI.first);
10135ffd83dbSDimitry Andric     for (auto &EI : ELI.second) {
10145ffd83dbSDimitry Andric       // Find the copy defined in the exporting module so that we can mark the
10155ffd83dbSDimitry Andric       // values it references in that specific definition as exported.
10165ffd83dbSDimitry Andric       // Below we will add all references and called values, without regard to
10175ffd83dbSDimitry Andric       // whether they are also defined in this module. We subsequently prune the
10185ffd83dbSDimitry Andric       // list to only include those defined in the exporting module, see comment
10195ffd83dbSDimitry Andric       // there as to why.
10205ffd83dbSDimitry Andric       auto DS = DefinedGVSummaries.find(EI.getGUID());
10215ffd83dbSDimitry Andric       // Anything marked exported during the import computation must have been
10225ffd83dbSDimitry Andric       // defined in the exporting module.
10235ffd83dbSDimitry Andric       assert(DS != DefinedGVSummaries.end());
10245ffd83dbSDimitry Andric       auto *S = DS->getSecond();
10255ffd83dbSDimitry Andric       S = S->getBaseObject();
10265ffd83dbSDimitry Andric       if (auto *GVS = dyn_cast<GlobalVarSummary>(S)) {
10275ffd83dbSDimitry Andric         // Export referenced functions and variables. We don't export/promote
10285ffd83dbSDimitry Andric         // objects referenced by writeonly variable initializer, because
10295ffd83dbSDimitry Andric         // we convert such variables initializers to "zeroinitializer".
10305ffd83dbSDimitry Andric         // See processGlobalForThinLTO.
10315ffd83dbSDimitry Andric         if (!Index.isWriteOnly(GVS))
10325ffd83dbSDimitry Andric           for (const auto &VI : GVS->refs())
10335ffd83dbSDimitry Andric             NewExports.insert(VI);
10345ffd83dbSDimitry Andric       } else {
10355ffd83dbSDimitry Andric         auto *FS = cast<FunctionSummary>(S);
1036bdd1243dSDimitry Andric         for (const auto &Edge : FS->calls())
10375ffd83dbSDimitry Andric           NewExports.insert(Edge.first);
1038bdd1243dSDimitry Andric         for (const auto &Ref : FS->refs())
10395ffd83dbSDimitry Andric           NewExports.insert(Ref);
10405ffd83dbSDimitry Andric       }
10415ffd83dbSDimitry Andric     }
10425ffd83dbSDimitry Andric     // Prune list computed above to only include values defined in the exporting
10435ffd83dbSDimitry Andric     // module. We do this after the above insertion since we may hit the same
10445ffd83dbSDimitry Andric     // ref/call target multiple times in above loop, and it is more efficient to
10455ffd83dbSDimitry Andric     // avoid a set lookup each time.
10465ffd83dbSDimitry Andric     for (auto EI = NewExports.begin(); EI != NewExports.end();) {
1047480093f4SDimitry Andric       if (!DefinedGVSummaries.count(EI->getGUID()))
10485ffd83dbSDimitry Andric         NewExports.erase(EI++);
10490b57cec5SDimitry Andric       else
10500b57cec5SDimitry Andric         ++EI;
10510b57cec5SDimitry Andric     }
10525ffd83dbSDimitry Andric     ELI.second.insert(NewExports.begin(), NewExports.end());
10530b57cec5SDimitry Andric   }
10540b57cec5SDimitry Andric 
1055480093f4SDimitry Andric   assert(checkVariableImport(Index, ImportLists, ExportLists));
10560b57cec5SDimitry Andric #ifndef NDEBUG
10570b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
10580b57cec5SDimitry Andric                     << " modules:\n");
10590b57cec5SDimitry Andric   for (auto &ModuleImports : ImportLists) {
1060*c9157d92SDimitry Andric     auto ModName = ModuleImports.first;
10610b57cec5SDimitry Andric     auto &Exports = ExportLists[ModName];
10620b57cec5SDimitry Andric     unsigned NumGVS = numGlobalVarSummaries(Index, Exports);
10630b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "* Module " << ModName << " exports "
10640b57cec5SDimitry Andric                       << Exports.size() - NumGVS << " functions and " << NumGVS
10650b57cec5SDimitry Andric                       << " vars. Imports from " << ModuleImports.second.size()
10660b57cec5SDimitry Andric                       << " modules.\n");
10670b57cec5SDimitry Andric     for (auto &Src : ModuleImports.second) {
1068*c9157d92SDimitry Andric       auto SrcModName = Src.first;
10690b57cec5SDimitry Andric       unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second);
10700b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod
10710b57cec5SDimitry Andric                         << " functions imported from " << SrcModName << "\n");
10720b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod
10730b57cec5SDimitry Andric                         << " global vars imported from " << SrcModName << "\n");
10740b57cec5SDimitry Andric     }
10750b57cec5SDimitry Andric   }
10760b57cec5SDimitry Andric #endif
10770b57cec5SDimitry Andric }
10780b57cec5SDimitry Andric 
10790b57cec5SDimitry Andric #ifndef NDEBUG
dumpImportListForModule(const ModuleSummaryIndex & Index,StringRef ModulePath,FunctionImporter::ImportMapTy & ImportList)10800b57cec5SDimitry Andric static void dumpImportListForModule(const ModuleSummaryIndex &Index,
10810b57cec5SDimitry Andric                                     StringRef ModulePath,
10820b57cec5SDimitry Andric                                     FunctionImporter::ImportMapTy &ImportList) {
10830b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
10840b57cec5SDimitry Andric                     << ImportList.size() << " modules.\n");
10850b57cec5SDimitry Andric   for (auto &Src : ImportList) {
1086*c9157d92SDimitry Andric     auto SrcModName = Src.first;
10870b57cec5SDimitry Andric     unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second);
10880b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod
10890b57cec5SDimitry Andric                       << " functions imported from " << SrcModName << "\n");
10900b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod << " vars imported from "
10910b57cec5SDimitry Andric                       << SrcModName << "\n");
10920b57cec5SDimitry Andric   }
10930b57cec5SDimitry Andric }
10940b57cec5SDimitry Andric #endif
10950b57cec5SDimitry Andric 
1096*c9157d92SDimitry Andric /// Compute all the imports for the given module using the Index.
1097*c9157d92SDimitry Andric ///
1098*c9157d92SDimitry Andric /// \p isPrevailing is a callback that will be called with a global value's GUID
1099*c9157d92SDimitry Andric /// and summary and should return whether the module corresponding to the
1100*c9157d92SDimitry Andric /// summary contains the linker-prevailing copy of that value.
1101*c9157d92SDimitry Andric ///
1102*c9157d92SDimitry Andric /// \p ImportList will be populated with a map that can be passed to
1103*c9157d92SDimitry Andric /// FunctionImporter::importFunctions() above (see description there).
ComputeCrossModuleImportForModuleForTest(StringRef ModulePath,function_ref<bool (GlobalValue::GUID,const GlobalValueSummary *)> isPrevailing,const ModuleSummaryIndex & Index,FunctionImporter::ImportMapTy & ImportList)1104*c9157d92SDimitry Andric static void ComputeCrossModuleImportForModuleForTest(
1105fe013be4SDimitry Andric     StringRef ModulePath,
1106fe013be4SDimitry Andric     function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
1107fe013be4SDimitry Andric         isPrevailing,
1108fe013be4SDimitry Andric     const ModuleSummaryIndex &Index,
11090b57cec5SDimitry Andric     FunctionImporter::ImportMapTy &ImportList) {
11100b57cec5SDimitry Andric   // Collect the list of functions this module defines.
11110b57cec5SDimitry Andric   // GUID -> Summary
11120b57cec5SDimitry Andric   GVSummaryMapTy FunctionSummaryMap;
11130b57cec5SDimitry Andric   Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
11140b57cec5SDimitry Andric 
11150b57cec5SDimitry Andric   // Compute the import list for this module.
11160b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
1117*c9157d92SDimitry Andric   auto MIS = ModuleImportsManager::create(isPrevailing, Index);
1118*c9157d92SDimitry Andric   MIS->computeImportForModule(FunctionSummaryMap, ModulePath, ImportList);
11190b57cec5SDimitry Andric 
11200b57cec5SDimitry Andric #ifndef NDEBUG
11210b57cec5SDimitry Andric   dumpImportListForModule(Index, ModulePath, ImportList);
11220b57cec5SDimitry Andric #endif
11230b57cec5SDimitry Andric }
11240b57cec5SDimitry Andric 
1125*c9157d92SDimitry Andric /// Mark all external summaries in \p Index for import into the given module.
1126*c9157d92SDimitry Andric /// Used for testing the case of distributed builds using a distributed index.
1127*c9157d92SDimitry Andric ///
1128*c9157d92SDimitry Andric /// \p ImportList will be populated with a map that can be passed to
1129*c9157d92SDimitry Andric /// FunctionImporter::importFunctions() above (see description there).
ComputeCrossModuleImportForModuleFromIndexForTest(StringRef ModulePath,const ModuleSummaryIndex & Index,FunctionImporter::ImportMapTy & ImportList)1130*c9157d92SDimitry Andric static void ComputeCrossModuleImportForModuleFromIndexForTest(
11310b57cec5SDimitry Andric     StringRef ModulePath, const ModuleSummaryIndex &Index,
11320b57cec5SDimitry Andric     FunctionImporter::ImportMapTy &ImportList) {
1133bdd1243dSDimitry Andric   for (const auto &GlobalList : Index) {
11340b57cec5SDimitry Andric     // Ignore entries for undefined references.
11350b57cec5SDimitry Andric     if (GlobalList.second.SummaryList.empty())
11360b57cec5SDimitry Andric       continue;
11370b57cec5SDimitry Andric 
11380b57cec5SDimitry Andric     auto GUID = GlobalList.first;
11390b57cec5SDimitry Andric     assert(GlobalList.second.SummaryList.size() == 1 &&
11400b57cec5SDimitry Andric            "Expected individual combined index to have one summary per GUID");
11410b57cec5SDimitry Andric     auto &Summary = GlobalList.second.SummaryList[0];
11420b57cec5SDimitry Andric     // Skip the summaries for the importing module. These are included to
11430b57cec5SDimitry Andric     // e.g. record required linkage changes.
11440b57cec5SDimitry Andric     if (Summary->modulePath() == ModulePath)
11450b57cec5SDimitry Andric       continue;
11460b57cec5SDimitry Andric     // Add an entry to provoke importing by thinBackend.
11470b57cec5SDimitry Andric     ImportList[Summary->modulePath()].insert(GUID);
11480b57cec5SDimitry Andric   }
11490b57cec5SDimitry Andric #ifndef NDEBUG
11500b57cec5SDimitry Andric   dumpImportListForModule(Index, ModulePath, ImportList);
11510b57cec5SDimitry Andric #endif
11520b57cec5SDimitry Andric }
11530b57cec5SDimitry Andric 
1154349cc55cSDimitry Andric // For SamplePGO, the indirect call targets for local functions will
1155349cc55cSDimitry Andric // have its original name annotated in profile. We try to find the
1156349cc55cSDimitry Andric // corresponding PGOFuncName as the GUID, and fix up the edges
1157349cc55cSDimitry Andric // accordingly.
updateValueInfoForIndirectCalls(ModuleSummaryIndex & Index,FunctionSummary * FS)1158349cc55cSDimitry Andric void updateValueInfoForIndirectCalls(ModuleSummaryIndex &Index,
1159349cc55cSDimitry Andric                                      FunctionSummary *FS) {
1160349cc55cSDimitry Andric   for (auto &EI : FS->mutableCalls()) {
1161349cc55cSDimitry Andric     if (!EI.first.getSummaryList().empty())
1162349cc55cSDimitry Andric       continue;
1163349cc55cSDimitry Andric     auto GUID = Index.getGUIDFromOriginalID(EI.first.getGUID());
1164349cc55cSDimitry Andric     if (GUID == 0)
1165349cc55cSDimitry Andric       continue;
1166349cc55cSDimitry Andric     // Update the edge to point directly to the correct GUID.
1167349cc55cSDimitry Andric     auto VI = Index.getValueInfo(GUID);
1168349cc55cSDimitry Andric     if (llvm::any_of(
1169349cc55cSDimitry Andric             VI.getSummaryList(),
1170349cc55cSDimitry Andric             [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
1171349cc55cSDimitry Andric               // The mapping from OriginalId to GUID may return a GUID
1172349cc55cSDimitry Andric               // that corresponds to a static variable. Filter it out here.
1173349cc55cSDimitry Andric               // This can happen when
1174349cc55cSDimitry Andric               // 1) There is a call to a library function which is not defined
1175349cc55cSDimitry Andric               // in the index.
1176349cc55cSDimitry Andric               // 2) There is a static variable with the  OriginalGUID identical
1177349cc55cSDimitry Andric               // to the GUID of the library function in 1);
1178349cc55cSDimitry Andric               // When this happens the static variable in 2) will be found,
1179349cc55cSDimitry Andric               // which needs to be filtered out.
1180349cc55cSDimitry Andric               return SummaryPtr->getSummaryKind() ==
1181349cc55cSDimitry Andric                      GlobalValueSummary::GlobalVarKind;
1182349cc55cSDimitry Andric             }))
1183349cc55cSDimitry Andric       continue;
1184349cc55cSDimitry Andric     EI.first = VI;
1185349cc55cSDimitry Andric   }
1186349cc55cSDimitry Andric }
1187349cc55cSDimitry Andric 
updateIndirectCalls(ModuleSummaryIndex & Index)1188349cc55cSDimitry Andric void llvm::updateIndirectCalls(ModuleSummaryIndex &Index) {
1189349cc55cSDimitry Andric   for (const auto &Entry : Index) {
1190bdd1243dSDimitry Andric     for (const auto &S : Entry.second.SummaryList) {
1191349cc55cSDimitry Andric       if (auto *FS = dyn_cast<FunctionSummary>(S.get()))
1192349cc55cSDimitry Andric         updateValueInfoForIndirectCalls(Index, FS);
1193349cc55cSDimitry Andric     }
1194349cc55cSDimitry Andric   }
1195349cc55cSDimitry Andric }
1196349cc55cSDimitry Andric 
computeDeadSymbolsAndUpdateIndirectCalls(ModuleSummaryIndex & Index,const DenseSet<GlobalValue::GUID> & GUIDPreservedSymbols,function_ref<PrevailingType (GlobalValue::GUID)> isPrevailing)1197349cc55cSDimitry Andric void llvm::computeDeadSymbolsAndUpdateIndirectCalls(
11980b57cec5SDimitry Andric     ModuleSummaryIndex &Index,
11990b57cec5SDimitry Andric     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
12000b57cec5SDimitry Andric     function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing) {
12010b57cec5SDimitry Andric   assert(!Index.withGlobalValueDeadStripping());
1202349cc55cSDimitry Andric   if (!ComputeDead ||
12030b57cec5SDimitry Andric       // Don't do anything when nothing is live, this is friendly with tests.
1204349cc55cSDimitry Andric       GUIDPreservedSymbols.empty()) {
1205349cc55cSDimitry Andric     // Still need to update indirect calls.
1206349cc55cSDimitry Andric     updateIndirectCalls(Index);
12070b57cec5SDimitry Andric     return;
1208349cc55cSDimitry Andric   }
12090b57cec5SDimitry Andric   unsigned LiveSymbols = 0;
12100b57cec5SDimitry Andric   SmallVector<ValueInfo, 128> Worklist;
12110b57cec5SDimitry Andric   Worklist.reserve(GUIDPreservedSymbols.size() * 2);
12120b57cec5SDimitry Andric   for (auto GUID : GUIDPreservedSymbols) {
12130b57cec5SDimitry Andric     ValueInfo VI = Index.getValueInfo(GUID);
12140b57cec5SDimitry Andric     if (!VI)
12150b57cec5SDimitry Andric       continue;
1216bdd1243dSDimitry Andric     for (const auto &S : VI.getSummaryList())
12170b57cec5SDimitry Andric       S->setLive(true);
12180b57cec5SDimitry Andric   }
12190b57cec5SDimitry Andric 
12200b57cec5SDimitry Andric   // Add values flagged in the index as live roots to the worklist.
12210b57cec5SDimitry Andric   for (const auto &Entry : Index) {
12220b57cec5SDimitry Andric     auto VI = Index.getValueInfo(Entry);
1223bdd1243dSDimitry Andric     for (const auto &S : Entry.second.SummaryList) {
1224349cc55cSDimitry Andric       if (auto *FS = dyn_cast<FunctionSummary>(S.get()))
1225349cc55cSDimitry Andric         updateValueInfoForIndirectCalls(Index, FS);
12260b57cec5SDimitry Andric       if (S->isLive()) {
12270b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "Live root: " << VI << "\n");
12280b57cec5SDimitry Andric         Worklist.push_back(VI);
12290b57cec5SDimitry Andric         ++LiveSymbols;
12300b57cec5SDimitry Andric         break;
12310b57cec5SDimitry Andric       }
12320b57cec5SDimitry Andric     }
1233349cc55cSDimitry Andric   }
12340b57cec5SDimitry Andric 
12350b57cec5SDimitry Andric   // Make value live and add it to the worklist if it was not live before.
12368bcb0991SDimitry Andric   auto visit = [&](ValueInfo VI, bool IsAliasee) {
12370b57cec5SDimitry Andric     // FIXME: If we knew which edges were created for indirect call profiles,
12380b57cec5SDimitry Andric     // we could skip them here. Any that are live should be reached via
12390b57cec5SDimitry Andric     // other edges, e.g. reference edges. Otherwise, using a profile collected
12400b57cec5SDimitry Andric     // on a slightly different binary might provoke preserving, importing
12410b57cec5SDimitry Andric     // and ultimately promoting calls to functions not linked into this
12420b57cec5SDimitry Andric     // binary, which increases the binary size unnecessarily. Note that
12430b57cec5SDimitry Andric     // if this code changes, the importer needs to change so that edges
12440b57cec5SDimitry Andric     // to functions marked dead are skipped.
12450b57cec5SDimitry Andric 
12460b57cec5SDimitry Andric     if (llvm::any_of(VI.getSummaryList(),
12470b57cec5SDimitry Andric                      [](const std::unique_ptr<llvm::GlobalValueSummary> &S) {
12480b57cec5SDimitry Andric                        return S->isLive();
12490b57cec5SDimitry Andric                      }))
12500b57cec5SDimitry Andric       return;
12510b57cec5SDimitry Andric 
12520b57cec5SDimitry Andric     // We only keep live symbols that are known to be non-prevailing if any are
12530b57cec5SDimitry Andric     // available_externally, linkonceodr, weakodr. Those symbols are discarded
12540b57cec5SDimitry Andric     // later in the EliminateAvailableExternally pass and setting them to
12550b57cec5SDimitry Andric     // not-live could break downstreams users of liveness information (PR36483)
12560b57cec5SDimitry Andric     // or limit optimization opportunities.
12570b57cec5SDimitry Andric     if (isPrevailing(VI.getGUID()) == PrevailingType::No) {
12580b57cec5SDimitry Andric       bool KeepAliveLinkage = false;
12590b57cec5SDimitry Andric       bool Interposable = false;
1260bdd1243dSDimitry Andric       for (const auto &S : VI.getSummaryList()) {
12610b57cec5SDimitry Andric         if (S->linkage() == GlobalValue::AvailableExternallyLinkage ||
12620b57cec5SDimitry Andric             S->linkage() == GlobalValue::WeakODRLinkage ||
12630b57cec5SDimitry Andric             S->linkage() == GlobalValue::LinkOnceODRLinkage)
12640b57cec5SDimitry Andric           KeepAliveLinkage = true;
12650b57cec5SDimitry Andric         else if (GlobalValue::isInterposableLinkage(S->linkage()))
12660b57cec5SDimitry Andric           Interposable = true;
12670b57cec5SDimitry Andric       }
12680b57cec5SDimitry Andric 
12698bcb0991SDimitry Andric       if (!IsAliasee) {
12700b57cec5SDimitry Andric         if (!KeepAliveLinkage)
12710b57cec5SDimitry Andric           return;
12720b57cec5SDimitry Andric 
12730b57cec5SDimitry Andric         if (Interposable)
12740b57cec5SDimitry Andric           report_fatal_error(
12758bcb0991SDimitry Andric               "Interposable and available_externally/linkonce_odr/weak_odr "
12768bcb0991SDimitry Andric               "symbol");
12778bcb0991SDimitry Andric       }
12780b57cec5SDimitry Andric     }
12790b57cec5SDimitry Andric 
1280bdd1243dSDimitry Andric     for (const auto &S : VI.getSummaryList())
12810b57cec5SDimitry Andric       S->setLive(true);
12820b57cec5SDimitry Andric     ++LiveSymbols;
12830b57cec5SDimitry Andric     Worklist.push_back(VI);
12840b57cec5SDimitry Andric   };
12850b57cec5SDimitry Andric 
12860b57cec5SDimitry Andric   while (!Worklist.empty()) {
12870b57cec5SDimitry Andric     auto VI = Worklist.pop_back_val();
1288bdd1243dSDimitry Andric     for (const auto &Summary : VI.getSummaryList()) {
12890b57cec5SDimitry Andric       if (auto *AS = dyn_cast<AliasSummary>(Summary.get())) {
12900b57cec5SDimitry Andric         // If this is an alias, visit the aliasee VI to ensure that all copies
12910b57cec5SDimitry Andric         // are marked live and it is added to the worklist for further
12920b57cec5SDimitry Andric         // processing of its references.
12938bcb0991SDimitry Andric         visit(AS->getAliaseeVI(), true);
12940b57cec5SDimitry Andric         continue;
12950b57cec5SDimitry Andric       }
12960b57cec5SDimitry Andric       for (auto Ref : Summary->refs())
12978bcb0991SDimitry Andric         visit(Ref, false);
12980b57cec5SDimitry Andric       if (auto *FS = dyn_cast<FunctionSummary>(Summary.get()))
12990b57cec5SDimitry Andric         for (auto Call : FS->calls())
13008bcb0991SDimitry Andric           visit(Call.first, false);
13010b57cec5SDimitry Andric     }
13020b57cec5SDimitry Andric   }
13030b57cec5SDimitry Andric   Index.setWithGlobalValueDeadStripping();
13040b57cec5SDimitry Andric 
13050b57cec5SDimitry Andric   unsigned DeadSymbols = Index.size() - LiveSymbols;
13060b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols
13070b57cec5SDimitry Andric                     << " symbols Dead \n");
13080b57cec5SDimitry Andric   NumDeadSymbols += DeadSymbols;
13090b57cec5SDimitry Andric   NumLiveSymbols += LiveSymbols;
13100b57cec5SDimitry Andric }
13110b57cec5SDimitry Andric 
13120b57cec5SDimitry Andric // Compute dead symbols and propagate constants in combined index.
computeDeadSymbolsWithConstProp(ModuleSummaryIndex & Index,const DenseSet<GlobalValue::GUID> & GUIDPreservedSymbols,function_ref<PrevailingType (GlobalValue::GUID)> isPrevailing,bool ImportEnabled)13130b57cec5SDimitry Andric void llvm::computeDeadSymbolsWithConstProp(
13140b57cec5SDimitry Andric     ModuleSummaryIndex &Index,
13150b57cec5SDimitry Andric     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
13160b57cec5SDimitry Andric     function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing,
13170b57cec5SDimitry Andric     bool ImportEnabled) {
1318349cc55cSDimitry Andric   computeDeadSymbolsAndUpdateIndirectCalls(Index, GUIDPreservedSymbols,
1319349cc55cSDimitry Andric                                            isPrevailing);
1320480093f4SDimitry Andric   if (ImportEnabled)
13210b57cec5SDimitry Andric     Index.propagateAttributes(GUIDPreservedSymbols);
13220b57cec5SDimitry Andric }
13230b57cec5SDimitry Andric 
13240b57cec5SDimitry Andric /// Compute the set of summaries needed for a ThinLTO backend compilation of
13250b57cec5SDimitry Andric /// \p ModulePath.
gatherImportedSummariesForModule(StringRef ModulePath,const DenseMap<StringRef,GVSummaryMapTy> & ModuleToDefinedGVSummaries,const FunctionImporter::ImportMapTy & ImportList,std::map<std::string,GVSummaryMapTy> & ModuleToSummariesForIndex)13260b57cec5SDimitry Andric void llvm::gatherImportedSummariesForModule(
13270b57cec5SDimitry Andric     StringRef ModulePath,
1328*c9157d92SDimitry Andric     const DenseMap<StringRef, GVSummaryMapTy> &ModuleToDefinedGVSummaries,
13290b57cec5SDimitry Andric     const FunctionImporter::ImportMapTy &ImportList,
13300b57cec5SDimitry Andric     std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
13310b57cec5SDimitry Andric   // Include all summaries from the importing module.
13325ffd83dbSDimitry Andric   ModuleToSummariesForIndex[std::string(ModulePath)] =
13330b57cec5SDimitry Andric       ModuleToDefinedGVSummaries.lookup(ModulePath);
13340b57cec5SDimitry Andric   // Include summaries for imports.
1335bdd1243dSDimitry Andric   for (const auto &ILI : ImportList) {
1336*c9157d92SDimitry Andric     auto &SummariesForIndex = ModuleToSummariesForIndex[std::string(ILI.first)];
13370b57cec5SDimitry Andric     const auto &DefinedGVSummaries =
1338*c9157d92SDimitry Andric         ModuleToDefinedGVSummaries.lookup(ILI.first);
1339bdd1243dSDimitry Andric     for (const auto &GI : ILI.second) {
13400b57cec5SDimitry Andric       const auto &DS = DefinedGVSummaries.find(GI);
13410b57cec5SDimitry Andric       assert(DS != DefinedGVSummaries.end() &&
13420b57cec5SDimitry Andric              "Expected a defined summary for imported global value");
13430b57cec5SDimitry Andric       SummariesForIndex[GI] = DS->second;
13440b57cec5SDimitry Andric     }
13450b57cec5SDimitry Andric   }
13460b57cec5SDimitry Andric }
13470b57cec5SDimitry Andric 
13480b57cec5SDimitry Andric /// Emit the files \p ModulePath will import from into \p OutputFilename.
EmitImportsFiles(StringRef ModulePath,StringRef OutputFilename,const std::map<std::string,GVSummaryMapTy> & ModuleToSummariesForIndex)13490b57cec5SDimitry Andric std::error_code llvm::EmitImportsFiles(
13500b57cec5SDimitry Andric     StringRef ModulePath, StringRef OutputFilename,
13510b57cec5SDimitry Andric     const std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
13520b57cec5SDimitry Andric   std::error_code EC;
13538bcb0991SDimitry Andric   raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::OF_None);
13540b57cec5SDimitry Andric   if (EC)
13550b57cec5SDimitry Andric     return EC;
1356bdd1243dSDimitry Andric   for (const auto &ILI : ModuleToSummariesForIndex)
13570b57cec5SDimitry Andric     // The ModuleToSummariesForIndex map includes an entry for the current
13580b57cec5SDimitry Andric     // Module (needed for writing out the index files). We don't want to
13590b57cec5SDimitry Andric     // include it in the imports file, however, so filter it out.
13600b57cec5SDimitry Andric     if (ILI.first != ModulePath)
13610b57cec5SDimitry Andric       ImportsOS << ILI.first << "\n";
13620b57cec5SDimitry Andric   return std::error_code();
13630b57cec5SDimitry Andric }
13640b57cec5SDimitry Andric 
convertToDeclaration(GlobalValue & GV)13650b57cec5SDimitry Andric bool llvm::convertToDeclaration(GlobalValue &GV) {
13660b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName()
13670b57cec5SDimitry Andric                     << "\n");
13680b57cec5SDimitry Andric   if (Function *F = dyn_cast<Function>(&GV)) {
13690b57cec5SDimitry Andric     F->deleteBody();
13700b57cec5SDimitry Andric     F->clearMetadata();
13710b57cec5SDimitry Andric     F->setComdat(nullptr);
13720b57cec5SDimitry Andric   } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
13730b57cec5SDimitry Andric     V->setInitializer(nullptr);
13740b57cec5SDimitry Andric     V->setLinkage(GlobalValue::ExternalLinkage);
13750b57cec5SDimitry Andric     V->clearMetadata();
13760b57cec5SDimitry Andric     V->setComdat(nullptr);
13770b57cec5SDimitry Andric   } else {
13780b57cec5SDimitry Andric     GlobalValue *NewGV;
13790b57cec5SDimitry Andric     if (GV.getValueType()->isFunctionTy())
13800b57cec5SDimitry Andric       NewGV =
13810b57cec5SDimitry Andric           Function::Create(cast<FunctionType>(GV.getValueType()),
13820b57cec5SDimitry Andric                            GlobalValue::ExternalLinkage, GV.getAddressSpace(),
13830b57cec5SDimitry Andric                            "", GV.getParent());
13840b57cec5SDimitry Andric     else
13850b57cec5SDimitry Andric       NewGV =
13860b57cec5SDimitry Andric           new GlobalVariable(*GV.getParent(), GV.getValueType(),
13870b57cec5SDimitry Andric                              /*isConstant*/ false, GlobalValue::ExternalLinkage,
13880b57cec5SDimitry Andric                              /*init*/ nullptr, "",
13890b57cec5SDimitry Andric                              /*insertbefore*/ nullptr, GV.getThreadLocalMode(),
13900b57cec5SDimitry Andric                              GV.getType()->getAddressSpace());
13910b57cec5SDimitry Andric     NewGV->takeName(&GV);
13920b57cec5SDimitry Andric     GV.replaceAllUsesWith(NewGV);
13930b57cec5SDimitry Andric     return false;
13940b57cec5SDimitry Andric   }
13955ffd83dbSDimitry Andric   if (!GV.isImplicitDSOLocal())
13965ffd83dbSDimitry Andric     GV.setDSOLocal(false);
13970b57cec5SDimitry Andric   return true;
13980b57cec5SDimitry Andric }
13990b57cec5SDimitry Andric 
thinLTOFinalizeInModule(Module & TheModule,const GVSummaryMapTy & DefinedGlobals,bool PropagateAttrs)1400349cc55cSDimitry Andric void llvm::thinLTOFinalizeInModule(Module &TheModule,
1401349cc55cSDimitry Andric                                    const GVSummaryMapTy &DefinedGlobals,
1402349cc55cSDimitry Andric                                    bool PropagateAttrs) {
1403bdd1243dSDimitry Andric   DenseSet<Comdat *> NonPrevailingComdats;
1404349cc55cSDimitry Andric   auto FinalizeInModule = [&](GlobalValue &GV, bool Propagate = false) {
14050b57cec5SDimitry Andric     // See if the global summary analysis computed a new resolved linkage.
14060b57cec5SDimitry Andric     const auto &GS = DefinedGlobals.find(GV.getGUID());
14070b57cec5SDimitry Andric     if (GS == DefinedGlobals.end())
14080b57cec5SDimitry Andric       return;
1409349cc55cSDimitry Andric 
1410349cc55cSDimitry Andric     if (Propagate)
1411349cc55cSDimitry Andric       if (FunctionSummary *FS = dyn_cast<FunctionSummary>(GS->second)) {
1412349cc55cSDimitry Andric         if (Function *F = dyn_cast<Function>(&GV)) {
1413349cc55cSDimitry Andric           // TODO: propagate ReadNone and ReadOnly.
1414349cc55cSDimitry Andric           if (FS->fflags().ReadNone && !F->doesNotAccessMemory())
1415349cc55cSDimitry Andric             F->setDoesNotAccessMemory();
1416349cc55cSDimitry Andric 
1417349cc55cSDimitry Andric           if (FS->fflags().ReadOnly && !F->onlyReadsMemory())
1418349cc55cSDimitry Andric             F->setOnlyReadsMemory();
1419349cc55cSDimitry Andric 
1420349cc55cSDimitry Andric           if (FS->fflags().NoRecurse && !F->doesNotRecurse())
1421349cc55cSDimitry Andric             F->setDoesNotRecurse();
1422349cc55cSDimitry Andric 
1423349cc55cSDimitry Andric           if (FS->fflags().NoUnwind && !F->doesNotThrow())
1424349cc55cSDimitry Andric             F->setDoesNotThrow();
1425349cc55cSDimitry Andric         }
1426349cc55cSDimitry Andric       }
1427349cc55cSDimitry Andric 
14280b57cec5SDimitry Andric     auto NewLinkage = GS->second->linkage();
14290b57cec5SDimitry Andric     if (GlobalValue::isLocalLinkage(GV.getLinkage()) ||
14308bcb0991SDimitry Andric         // Don't internalize anything here, because the code below
14318bcb0991SDimitry Andric         // lacks necessary correctness checks. Leave this job to
14328bcb0991SDimitry Andric         // LLVM 'internalize' pass.
14338bcb0991SDimitry Andric         GlobalValue::isLocalLinkage(NewLinkage) ||
14340b57cec5SDimitry Andric         // In case it was dead and already converted to declaration.
14350b57cec5SDimitry Andric         GV.isDeclaration())
14360b57cec5SDimitry Andric       return;
14378bcb0991SDimitry Andric 
1438fe6060f1SDimitry Andric     // Set the potentially more constraining visibility computed from summaries.
1439fe6060f1SDimitry Andric     // The DefaultVisibility condition is because older GlobalValueSummary does
1440fe6060f1SDimitry Andric     // not record DefaultVisibility and we don't want to change protected/hidden
1441fe6060f1SDimitry Andric     // to default.
1442fe6060f1SDimitry Andric     if (GS->second->getVisibility() != GlobalValue::DefaultVisibility)
1443fe6060f1SDimitry Andric       GV.setVisibility(GS->second->getVisibility());
1444fe6060f1SDimitry Andric 
1445fe6060f1SDimitry Andric     if (NewLinkage == GV.getLinkage())
1446fe6060f1SDimitry Andric       return;
1447fe6060f1SDimitry Andric 
14480b57cec5SDimitry Andric     // Check for a non-prevailing def that has interposable linkage
14490b57cec5SDimitry Andric     // (e.g. non-odr weak or linkonce). In that case we can't simply
14500b57cec5SDimitry Andric     // convert to available_externally, since it would lose the
14510b57cec5SDimitry Andric     // interposable property and possibly get inlined. Simply drop
14520b57cec5SDimitry Andric     // the definition in that case.
14530b57cec5SDimitry Andric     if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) &&
14540b57cec5SDimitry Andric         GlobalValue::isInterposableLinkage(GV.getLinkage())) {
14550b57cec5SDimitry Andric       if (!convertToDeclaration(GV))
14560b57cec5SDimitry Andric         // FIXME: Change this to collect replaced GVs and later erase
14570b57cec5SDimitry Andric         // them from the parent module once thinLTOResolvePrevailingGUID is
14580b57cec5SDimitry Andric         // changed to enable this for aliases.
14590b57cec5SDimitry Andric         llvm_unreachable("Expected GV to be converted");
14600b57cec5SDimitry Andric     } else {
14610b57cec5SDimitry Andric       // If all copies of the original symbol had global unnamed addr and
146281ad6265SDimitry Andric       // linkonce_odr linkage, or if all of them had local unnamed addr linkage
146381ad6265SDimitry Andric       // and are constants, then it should be an auto hide symbol. In that case
146481ad6265SDimitry Andric       // the thin link would have marked it as CanAutoHide. Add hidden
146581ad6265SDimitry Andric       // visibility to the symbol to preserve the property.
14660b57cec5SDimitry Andric       if (NewLinkage == GlobalValue::WeakODRLinkage &&
14670b57cec5SDimitry Andric           GS->second->canAutoHide()) {
146881ad6265SDimitry Andric         assert(GV.canBeOmittedFromSymbolTable());
14690b57cec5SDimitry Andric         GV.setVisibility(GlobalValue::HiddenVisibility);
14700b57cec5SDimitry Andric       }
14710b57cec5SDimitry Andric 
14720b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName()
14730b57cec5SDimitry Andric                         << "` from " << GV.getLinkage() << " to " << NewLinkage
14740b57cec5SDimitry Andric                         << "\n");
14750b57cec5SDimitry Andric       GV.setLinkage(NewLinkage);
14760b57cec5SDimitry Andric     }
14770b57cec5SDimitry Andric     // Remove declarations from comdats, including available_externally
14780b57cec5SDimitry Andric     // as this is a declaration for the linker, and will be dropped eventually.
14790b57cec5SDimitry Andric     // It is illegal for comdats to contain declarations.
14800b57cec5SDimitry Andric     auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
1481bdd1243dSDimitry Andric     if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) {
1482bdd1243dSDimitry Andric       if (GO->getComdat()->getName() == GO->getName())
1483bdd1243dSDimitry Andric         NonPrevailingComdats.insert(GO->getComdat());
14840b57cec5SDimitry Andric       GO->setComdat(nullptr);
1485bdd1243dSDimitry Andric     }
14860b57cec5SDimitry Andric   };
14870b57cec5SDimitry Andric 
14880b57cec5SDimitry Andric   // Process functions and global now
14890b57cec5SDimitry Andric   for (auto &GV : TheModule)
1490349cc55cSDimitry Andric     FinalizeInModule(GV, PropagateAttrs);
14910b57cec5SDimitry Andric   for (auto &GV : TheModule.globals())
1492349cc55cSDimitry Andric     FinalizeInModule(GV);
14930b57cec5SDimitry Andric   for (auto &GV : TheModule.aliases())
1494349cc55cSDimitry Andric     FinalizeInModule(GV);
1495bdd1243dSDimitry Andric 
1496bdd1243dSDimitry Andric   // For a non-prevailing comdat, all its members must be available_externally.
1497bdd1243dSDimitry Andric   // FinalizeInModule has handled non-local-linkage GlobalValues. Here we handle
1498bdd1243dSDimitry Andric   // local linkage GlobalValues.
1499bdd1243dSDimitry Andric   if (NonPrevailingComdats.empty())
1500bdd1243dSDimitry Andric     return;
1501bdd1243dSDimitry Andric   for (auto &GO : TheModule.global_objects()) {
1502bdd1243dSDimitry Andric     if (auto *C = GO.getComdat(); C && NonPrevailingComdats.count(C)) {
1503bdd1243dSDimitry Andric       GO.setComdat(nullptr);
1504bdd1243dSDimitry Andric       GO.setLinkage(GlobalValue::AvailableExternallyLinkage);
1505bdd1243dSDimitry Andric     }
1506bdd1243dSDimitry Andric   }
1507bdd1243dSDimitry Andric   bool Changed;
1508bdd1243dSDimitry Andric   do {
1509bdd1243dSDimitry Andric     Changed = false;
1510bdd1243dSDimitry Andric     // If an alias references a GlobalValue in a non-prevailing comdat, change
1511bdd1243dSDimitry Andric     // it to available_externally. For simplicity we only handle GlobalValue and
1512bdd1243dSDimitry Andric     // ConstantExpr with a base object. ConstantExpr without a base object is
1513bdd1243dSDimitry Andric     // unlikely used in a COMDAT.
1514bdd1243dSDimitry Andric     for (auto &GA : TheModule.aliases()) {
1515bdd1243dSDimitry Andric       if (GA.hasAvailableExternallyLinkage())
1516bdd1243dSDimitry Andric         continue;
1517bdd1243dSDimitry Andric       GlobalObject *Obj = GA.getAliaseeObject();
1518bdd1243dSDimitry Andric       assert(Obj && "aliasee without an base object is unimplemented");
1519bdd1243dSDimitry Andric       if (Obj->hasAvailableExternallyLinkage()) {
1520bdd1243dSDimitry Andric         GA.setLinkage(GlobalValue::AvailableExternallyLinkage);
1521bdd1243dSDimitry Andric         Changed = true;
1522bdd1243dSDimitry Andric       }
1523bdd1243dSDimitry Andric     }
1524bdd1243dSDimitry Andric   } while (Changed);
15250b57cec5SDimitry Andric }
15260b57cec5SDimitry Andric 
15270b57cec5SDimitry Andric /// Run internalization on \p TheModule based on symmary analysis.
thinLTOInternalizeModule(Module & TheModule,const GVSummaryMapTy & DefinedGlobals)15280b57cec5SDimitry Andric void llvm::thinLTOInternalizeModule(Module &TheModule,
15290b57cec5SDimitry Andric                                     const GVSummaryMapTy &DefinedGlobals) {
15300b57cec5SDimitry Andric   // Declare a callback for the internalize pass that will ask for every
15310b57cec5SDimitry Andric   // candidate GlobalValue if it can be internalized or not.
15320b57cec5SDimitry Andric   auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
1533fcaf7f86SDimitry Andric     // It may be the case that GV is on a chain of an ifunc, its alias and
1534fcaf7f86SDimitry Andric     // subsequent aliases. In this case, the summary for the value is not
1535fcaf7f86SDimitry Andric     // available.
1536fcaf7f86SDimitry Andric     if (isa<GlobalIFunc>(&GV) ||
1537fcaf7f86SDimitry Andric         (isa<GlobalAlias>(&GV) &&
1538fcaf7f86SDimitry Andric          isa<GlobalIFunc>(cast<GlobalAlias>(&GV)->getAliaseeObject())))
1539fcaf7f86SDimitry Andric       return true;
1540fcaf7f86SDimitry Andric 
15410b57cec5SDimitry Andric     // Lookup the linkage recorded in the summaries during global analysis.
15420b57cec5SDimitry Andric     auto GS = DefinedGlobals.find(GV.getGUID());
15430b57cec5SDimitry Andric     if (GS == DefinedGlobals.end()) {
15440b57cec5SDimitry Andric       // Must have been promoted (possibly conservatively). Find original
15450b57cec5SDimitry Andric       // name so that we can access the correct summary and see if it can
15460b57cec5SDimitry Andric       // be internalized again.
15470b57cec5SDimitry Andric       // FIXME: Eventually we should control promotion instead of promoting
15480b57cec5SDimitry Andric       // and internalizing again.
15490b57cec5SDimitry Andric       StringRef OrigName =
15500b57cec5SDimitry Andric           ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
15510b57cec5SDimitry Andric       std::string OrigId = GlobalValue::getGlobalIdentifier(
15520b57cec5SDimitry Andric           OrigName, GlobalValue::InternalLinkage,
15530b57cec5SDimitry Andric           TheModule.getSourceFileName());
15540b57cec5SDimitry Andric       GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
15550b57cec5SDimitry Andric       if (GS == DefinedGlobals.end()) {
15560b57cec5SDimitry Andric         // Also check the original non-promoted non-globalized name. In some
15570b57cec5SDimitry Andric         // cases a preempted weak value is linked in as a local copy because
15580b57cec5SDimitry Andric         // it is referenced by an alias (IRLinker::linkGlobalValueProto).
15590b57cec5SDimitry Andric         // In that case, since it was originally not a local value, it was
15600b57cec5SDimitry Andric         // recorded in the index using the original name.
15610b57cec5SDimitry Andric         // FIXME: This may not be needed once PR27866 is fixed.
15620b57cec5SDimitry Andric         GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
15630b57cec5SDimitry Andric         assert(GS != DefinedGlobals.end());
15640b57cec5SDimitry Andric       }
15650b57cec5SDimitry Andric     }
15660b57cec5SDimitry Andric     return !GlobalValue::isLocalLinkage(GS->second->linkage());
15670b57cec5SDimitry Andric   };
15680b57cec5SDimitry Andric 
15690b57cec5SDimitry Andric   // FIXME: See if we can just internalize directly here via linkage changes
15700b57cec5SDimitry Andric   // based on the index, rather than invoking internalizeModule.
15710b57cec5SDimitry Andric   internalizeModule(TheModule, MustPreserveGV);
15720b57cec5SDimitry Andric }
15730b57cec5SDimitry Andric 
15740b57cec5SDimitry Andric /// Make alias a clone of its aliasee.
replaceAliasWithAliasee(Module * SrcModule,GlobalAlias * GA)15750b57cec5SDimitry Andric static Function *replaceAliasWithAliasee(Module *SrcModule, GlobalAlias *GA) {
1576349cc55cSDimitry Andric   Function *Fn = cast<Function>(GA->getAliaseeObject());
15770b57cec5SDimitry Andric 
15780b57cec5SDimitry Andric   ValueToValueMapTy VMap;
15790b57cec5SDimitry Andric   Function *NewFn = CloneFunction(Fn, VMap);
15800b57cec5SDimitry Andric   // Clone should use the original alias's linkage, visibility and name, and we
15810b57cec5SDimitry Andric   // ensure all uses of alias instead use the new clone (casted if necessary).
15820b57cec5SDimitry Andric   NewFn->setLinkage(GA->getLinkage());
15830b57cec5SDimitry Andric   NewFn->setVisibility(GA->getVisibility());
1584*c9157d92SDimitry Andric   GA->replaceAllUsesWith(NewFn);
15850b57cec5SDimitry Andric   NewFn->takeName(GA);
15860b57cec5SDimitry Andric   return NewFn;
15870b57cec5SDimitry Andric }
15880b57cec5SDimitry Andric 
15890b57cec5SDimitry Andric // Internalize values that we marked with specific attribute
15900b57cec5SDimitry Andric // in processGlobalForThinLTO.
internalizeGVsAfterImport(Module & M)15910b57cec5SDimitry Andric static void internalizeGVsAfterImport(Module &M) {
15920b57cec5SDimitry Andric   for (auto &GV : M.globals())
15930b57cec5SDimitry Andric     // Skip GVs which have been converted to declarations
15940b57cec5SDimitry Andric     // by dropDeadSymbols.
15950b57cec5SDimitry Andric     if (!GV.isDeclaration() && GV.hasAttribute("thinlto-internalize")) {
15960b57cec5SDimitry Andric       GV.setLinkage(GlobalValue::InternalLinkage);
15970b57cec5SDimitry Andric       GV.setVisibility(GlobalValue::DefaultVisibility);
15980b57cec5SDimitry Andric     }
15990b57cec5SDimitry Andric }
16000b57cec5SDimitry Andric 
16010b57cec5SDimitry Andric // Automatically import functions in Module \p DestModule based on the summaries
16020b57cec5SDimitry Andric // index.
importFunctions(Module & DestModule,const FunctionImporter::ImportMapTy & ImportList)16030b57cec5SDimitry Andric Expected<bool> FunctionImporter::importFunctions(
16040b57cec5SDimitry Andric     Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
16050b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Starting import for Module "
16060b57cec5SDimitry Andric                     << DestModule.getModuleIdentifier() << "\n");
16070b57cec5SDimitry Andric   unsigned ImportedCount = 0, ImportedGVCount = 0;
16080b57cec5SDimitry Andric 
16090b57cec5SDimitry Andric   IRMover Mover(DestModule);
16100b57cec5SDimitry Andric   // Do the actual import of functions now, one Module at a time
16110b57cec5SDimitry Andric   std::set<StringRef> ModuleNameOrderedList;
1612bdd1243dSDimitry Andric   for (const auto &FunctionsToImportPerModule : ImportList) {
1613*c9157d92SDimitry Andric     ModuleNameOrderedList.insert(FunctionsToImportPerModule.first);
16140b57cec5SDimitry Andric   }
1615bdd1243dSDimitry Andric   for (const auto &Name : ModuleNameOrderedList) {
16160b57cec5SDimitry Andric     // Get the module for the import
16170b57cec5SDimitry Andric     const auto &FunctionsToImportPerModule = ImportList.find(Name);
16180b57cec5SDimitry Andric     assert(FunctionsToImportPerModule != ImportList.end());
16190b57cec5SDimitry Andric     Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
16200b57cec5SDimitry Andric     if (!SrcModuleOrErr)
16210b57cec5SDimitry Andric       return SrcModuleOrErr.takeError();
16220b57cec5SDimitry Andric     std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
16230b57cec5SDimitry Andric     assert(&DestModule.getContext() == &SrcModule->getContext() &&
16240b57cec5SDimitry Andric            "Context mismatch");
16250b57cec5SDimitry Andric 
16260b57cec5SDimitry Andric     // If modules were created with lazy metadata loading, materialize it
16270b57cec5SDimitry Andric     // now, before linking it (otherwise this will be a noop).
16280b57cec5SDimitry Andric     if (Error Err = SrcModule->materializeMetadata())
16290b57cec5SDimitry Andric       return std::move(Err);
16300b57cec5SDimitry Andric 
16310b57cec5SDimitry Andric     auto &ImportGUIDs = FunctionsToImportPerModule->second;
16320b57cec5SDimitry Andric     // Find the globals to import
16330b57cec5SDimitry Andric     SetVector<GlobalValue *> GlobalsToImport;
16340b57cec5SDimitry Andric     for (Function &F : *SrcModule) {
16350b57cec5SDimitry Andric       if (!F.hasName())
16360b57cec5SDimitry Andric         continue;
16370b57cec5SDimitry Andric       auto GUID = F.getGUID();
16380b57cec5SDimitry Andric       auto Import = ImportGUIDs.count(GUID);
16390b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function "
16400b57cec5SDimitry Andric                         << GUID << " " << F.getName() << " from "
16410b57cec5SDimitry Andric                         << SrcModule->getSourceFileName() << "\n");
16420b57cec5SDimitry Andric       if (Import) {
16430b57cec5SDimitry Andric         if (Error Err = F.materialize())
16440b57cec5SDimitry Andric           return std::move(Err);
16450b57cec5SDimitry Andric         if (EnableImportMetadata) {
16460b57cec5SDimitry Andric           // Add 'thinlto_src_module' metadata for statistics and debugging.
16470b57cec5SDimitry Andric           F.setMetadata(
16480b57cec5SDimitry Andric               "thinlto_src_module",
16490b57cec5SDimitry Andric               MDNode::get(DestModule.getContext(),
16500b57cec5SDimitry Andric                           {MDString::get(DestModule.getContext(),
16510b57cec5SDimitry Andric                                          SrcModule->getSourceFileName())}));
16520b57cec5SDimitry Andric         }
16530b57cec5SDimitry Andric         GlobalsToImport.insert(&F);
16540b57cec5SDimitry Andric       }
16550b57cec5SDimitry Andric     }
16560b57cec5SDimitry Andric     for (GlobalVariable &GV : SrcModule->globals()) {
16570b57cec5SDimitry Andric       if (!GV.hasName())
16580b57cec5SDimitry Andric         continue;
16590b57cec5SDimitry Andric       auto GUID = GV.getGUID();
16600b57cec5SDimitry Andric       auto Import = ImportGUIDs.count(GUID);
16610b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global "
16620b57cec5SDimitry Andric                         << GUID << " " << GV.getName() << " from "
16630b57cec5SDimitry Andric                         << SrcModule->getSourceFileName() << "\n");
16640b57cec5SDimitry Andric       if (Import) {
16650b57cec5SDimitry Andric         if (Error Err = GV.materialize())
16660b57cec5SDimitry Andric           return std::move(Err);
16670b57cec5SDimitry Andric         ImportedGVCount += GlobalsToImport.insert(&GV);
16680b57cec5SDimitry Andric       }
16690b57cec5SDimitry Andric     }
16700b57cec5SDimitry Andric     for (GlobalAlias &GA : SrcModule->aliases()) {
1671fcaf7f86SDimitry Andric       if (!GA.hasName() || isa<GlobalIFunc>(GA.getAliaseeObject()))
16720b57cec5SDimitry Andric         continue;
16730b57cec5SDimitry Andric       auto GUID = GA.getGUID();
16740b57cec5SDimitry Andric       auto Import = ImportGUIDs.count(GUID);
16750b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias "
16760b57cec5SDimitry Andric                         << GUID << " " << GA.getName() << " from "
16770b57cec5SDimitry Andric                         << SrcModule->getSourceFileName() << "\n");
16780b57cec5SDimitry Andric       if (Import) {
16790b57cec5SDimitry Andric         if (Error Err = GA.materialize())
16800b57cec5SDimitry Andric           return std::move(Err);
16810b57cec5SDimitry Andric         // Import alias as a copy of its aliasee.
1682349cc55cSDimitry Andric         GlobalObject *GO = GA.getAliaseeObject();
1683349cc55cSDimitry Andric         if (Error Err = GO->materialize())
16840b57cec5SDimitry Andric           return std::move(Err);
16850b57cec5SDimitry Andric         auto *Fn = replaceAliasWithAliasee(SrcModule.get(), &GA);
1686349cc55cSDimitry Andric         LLVM_DEBUG(dbgs() << "Is importing aliasee fn " << GO->getGUID() << " "
1687349cc55cSDimitry Andric                           << GO->getName() << " from "
16880b57cec5SDimitry Andric                           << SrcModule->getSourceFileName() << "\n");
16890b57cec5SDimitry Andric         if (EnableImportMetadata) {
16900b57cec5SDimitry Andric           // Add 'thinlto_src_module' metadata for statistics and debugging.
16910b57cec5SDimitry Andric           Fn->setMetadata(
16920b57cec5SDimitry Andric               "thinlto_src_module",
16930b57cec5SDimitry Andric               MDNode::get(DestModule.getContext(),
16940b57cec5SDimitry Andric                           {MDString::get(DestModule.getContext(),
16950b57cec5SDimitry Andric                                          SrcModule->getSourceFileName())}));
16960b57cec5SDimitry Andric         }
16970b57cec5SDimitry Andric         GlobalsToImport.insert(Fn);
16980b57cec5SDimitry Andric       }
16990b57cec5SDimitry Andric     }
17000b57cec5SDimitry Andric 
17010b57cec5SDimitry Andric     // Upgrade debug info after we're done materializing all the globals and we
17020b57cec5SDimitry Andric     // have loaded all the required metadata!
17030b57cec5SDimitry Andric     UpgradeDebugInfo(*SrcModule);
17040b57cec5SDimitry Andric 
17055ffd83dbSDimitry Andric     // Set the partial sample profile ratio in the profile summary module flag
17065ffd83dbSDimitry Andric     // of the imported source module, if applicable, so that the profile summary
17075ffd83dbSDimitry Andric     // module flag will match with that of the destination module when it's
17085ffd83dbSDimitry Andric     // imported.
17095ffd83dbSDimitry Andric     SrcModule->setPartialSampleProfileRatio(Index);
17105ffd83dbSDimitry Andric 
17110b57cec5SDimitry Andric     // Link in the specified functions.
17125ffd83dbSDimitry Andric     if (renameModuleForThinLTO(*SrcModule, Index, ClearDSOLocalOnDeclarations,
17135ffd83dbSDimitry Andric                                &GlobalsToImport))
17140b57cec5SDimitry Andric       return true;
17150b57cec5SDimitry Andric 
17160b57cec5SDimitry Andric     if (PrintImports) {
17170b57cec5SDimitry Andric       for (const auto *GV : GlobalsToImport)
17180b57cec5SDimitry Andric         dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
17190b57cec5SDimitry Andric                << " from " << SrcModule->getSourceFileName() << "\n";
17200b57cec5SDimitry Andric     }
17210b57cec5SDimitry Andric 
172281ad6265SDimitry Andric     if (Error Err = Mover.move(std::move(SrcModule),
172381ad6265SDimitry Andric                                GlobalsToImport.getArrayRef(), nullptr,
17240b57cec5SDimitry Andric                                /*IsPerformingImport=*/true))
1725fe013be4SDimitry Andric       return createStringError(errc::invalid_argument,
1726fe013be4SDimitry Andric                                Twine("Function Import: link error: ") +
17275ffd83dbSDimitry Andric                                    toString(std::move(Err)));
17280b57cec5SDimitry Andric 
17290b57cec5SDimitry Andric     ImportedCount += GlobalsToImport.size();
17300b57cec5SDimitry Andric     NumImportedModules++;
17310b57cec5SDimitry Andric   }
17320b57cec5SDimitry Andric 
17330b57cec5SDimitry Andric   internalizeGVsAfterImport(DestModule);
17340b57cec5SDimitry Andric 
17350b57cec5SDimitry Andric   NumImportedFunctions += (ImportedCount - ImportedGVCount);
17360b57cec5SDimitry Andric   NumImportedGlobalVars += ImportedGVCount;
17370b57cec5SDimitry Andric 
17380b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Imported " << ImportedCount - ImportedGVCount
17390b57cec5SDimitry Andric                     << " functions for Module "
17400b57cec5SDimitry Andric                     << DestModule.getModuleIdentifier() << "\n");
17410b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Imported " << ImportedGVCount
17420b57cec5SDimitry Andric                     << " global variables for Module "
17430b57cec5SDimitry Andric                     << DestModule.getModuleIdentifier() << "\n");
17440b57cec5SDimitry Andric   return ImportedCount;
17450b57cec5SDimitry Andric }
17460b57cec5SDimitry Andric 
doImportingForModuleForTest(Module & M,function_ref<bool (GlobalValue::GUID,const GlobalValueSummary *)> isPrevailing)1747*c9157d92SDimitry Andric static bool doImportingForModuleForTest(
1748fe013be4SDimitry Andric     Module &M, function_ref<bool(GlobalValue::GUID, const GlobalValueSummary *)>
1749fe013be4SDimitry Andric                    isPrevailing) {
17500b57cec5SDimitry Andric   if (SummaryFile.empty())
17510b57cec5SDimitry Andric     report_fatal_error("error: -function-import requires -summary-file\n");
17520b57cec5SDimitry Andric   Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
17530b57cec5SDimitry Andric       getModuleSummaryIndexForFile(SummaryFile);
17540b57cec5SDimitry Andric   if (!IndexPtrOrErr) {
17550b57cec5SDimitry Andric     logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
17560b57cec5SDimitry Andric                           "Error loading file '" + SummaryFile + "': ");
17570b57cec5SDimitry Andric     return false;
17580b57cec5SDimitry Andric   }
17590b57cec5SDimitry Andric   std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
17600b57cec5SDimitry Andric 
17610b57cec5SDimitry Andric   // First step is collecting the import list.
17620b57cec5SDimitry Andric   FunctionImporter::ImportMapTy ImportList;
17630b57cec5SDimitry Andric   // If requested, simply import all functions in the index. This is used
17640b57cec5SDimitry Andric   // when testing distributed backend handling via the opt tool, when
17650b57cec5SDimitry Andric   // we have distributed indexes containing exactly the summaries to import.
17660b57cec5SDimitry Andric   if (ImportAllIndex)
1767*c9157d92SDimitry Andric     ComputeCrossModuleImportForModuleFromIndexForTest(M.getModuleIdentifier(),
1768fe013be4SDimitry Andric                                                       *Index, ImportList);
1769*c9157d92SDimitry Andric   else
1770*c9157d92SDimitry Andric     ComputeCrossModuleImportForModuleForTest(M.getModuleIdentifier(),
1771*c9157d92SDimitry Andric                                              isPrevailing, *Index, ImportList);
17720b57cec5SDimitry Andric 
17730b57cec5SDimitry Andric   // Conservatively mark all internal values as promoted. This interface is
17740b57cec5SDimitry Andric   // only used when doing importing via the function importing pass. The pass
17750b57cec5SDimitry Andric   // is only enabled when testing importing via the 'opt' tool, which does
17760b57cec5SDimitry Andric   // not do the ThinLink that would normally determine what values to promote.
17770b57cec5SDimitry Andric   for (auto &I : *Index) {
17780b57cec5SDimitry Andric     for (auto &S : I.second.SummaryList) {
17790b57cec5SDimitry Andric       if (GlobalValue::isLocalLinkage(S->linkage()))
17800b57cec5SDimitry Andric         S->setLinkage(GlobalValue::ExternalLinkage);
17810b57cec5SDimitry Andric     }
17820b57cec5SDimitry Andric   }
17830b57cec5SDimitry Andric 
17840b57cec5SDimitry Andric   // Next we need to promote to global scope and rename any local values that
17850b57cec5SDimitry Andric   // are potentially exported to other modules.
1786e8d8bef9SDimitry Andric   if (renameModuleForThinLTO(M, *Index, /*ClearDSOLocalOnDeclarations=*/false,
17875ffd83dbSDimitry Andric                              /*GlobalsToImport=*/nullptr)) {
17880b57cec5SDimitry Andric     errs() << "Error renaming module\n";
1789fe013be4SDimitry Andric     return true;
17900b57cec5SDimitry Andric   }
17910b57cec5SDimitry Andric 
17920b57cec5SDimitry Andric   // Perform the import now.
17930b57cec5SDimitry Andric   auto ModuleLoader = [&M](StringRef Identifier) {
17945ffd83dbSDimitry Andric     return loadFile(std::string(Identifier), M.getContext());
17950b57cec5SDimitry Andric   };
17965ffd83dbSDimitry Andric   FunctionImporter Importer(*Index, ModuleLoader,
17975ffd83dbSDimitry Andric                             /*ClearDSOLocalOnDeclarations=*/false);
17980b57cec5SDimitry Andric   Expected<bool> Result = Importer.importFunctions(M, ImportList);
17990b57cec5SDimitry Andric 
18000b57cec5SDimitry Andric   // FIXME: Probably need to propagate Errors through the pass manager.
18010b57cec5SDimitry Andric   if (!Result) {
18020b57cec5SDimitry Andric     logAllUnhandledErrors(Result.takeError(), errs(),
18030b57cec5SDimitry Andric                           "Error importing module: ");
1804fe013be4SDimitry Andric     return true;
18050b57cec5SDimitry Andric   }
18060b57cec5SDimitry Andric 
1807fe013be4SDimitry Andric   return true;
18080b57cec5SDimitry Andric }
18090b57cec5SDimitry Andric 
run(Module & M,ModuleAnalysisManager & AM)18100b57cec5SDimitry Andric PreservedAnalyses FunctionImportPass::run(Module &M,
18110b57cec5SDimitry Andric                                           ModuleAnalysisManager &AM) {
1812fe013be4SDimitry Andric   // This is only used for testing the function import pass via opt, where we
1813fe013be4SDimitry Andric   // don't have prevailing information from the LTO context available, so just
1814fe013be4SDimitry Andric   // conservatively assume everything is prevailing (which is fine for the very
1815fe013be4SDimitry Andric   // limited use of prevailing checking in this pass).
1816fe013be4SDimitry Andric   auto isPrevailing = [](GlobalValue::GUID, const GlobalValueSummary *) {
1817fe013be4SDimitry Andric     return true;
1818fe013be4SDimitry Andric   };
1819*c9157d92SDimitry Andric   if (!doImportingForModuleForTest(M, isPrevailing))
18200b57cec5SDimitry Andric     return PreservedAnalyses::all();
18210b57cec5SDimitry Andric 
18220b57cec5SDimitry Andric   return PreservedAnalyses::none();
18230b57cec5SDimitry Andric }
1824