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/StringMap.h"
200b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
210b57cec5SDimitry Andric #include "llvm/ADT/StringSet.h"
220b57cec5SDimitry Andric #include "llvm/Bitcode/BitcodeReader.h"
230b57cec5SDimitry Andric #include "llvm/IR/AutoUpgrade.h"
240b57cec5SDimitry Andric #include "llvm/IR/Constants.h"
250b57cec5SDimitry Andric #include "llvm/IR/Function.h"
260b57cec5SDimitry Andric #include "llvm/IR/GlobalAlias.h"
270b57cec5SDimitry Andric #include "llvm/IR/GlobalObject.h"
280b57cec5SDimitry Andric #include "llvm/IR/GlobalValue.h"
290b57cec5SDimitry Andric #include "llvm/IR/GlobalVariable.h"
300b57cec5SDimitry Andric #include "llvm/IR/Metadata.h"
310b57cec5SDimitry Andric #include "llvm/IR/Module.h"
320b57cec5SDimitry Andric #include "llvm/IR/ModuleSummaryIndex.h"
330b57cec5SDimitry Andric #include "llvm/IRReader/IRReader.h"
34480093f4SDimitry Andric #include "llvm/InitializePasses.h"
350b57cec5SDimitry Andric #include "llvm/Linker/IRMover.h"
360b57cec5SDimitry Andric #include "llvm/Object/ModuleSymbolTable.h"
370b57cec5SDimitry Andric #include "llvm/Object/SymbolicFile.h"
380b57cec5SDimitry Andric #include "llvm/Pass.h"
390b57cec5SDimitry Andric #include "llvm/Support/Casting.h"
400b57cec5SDimitry Andric #include "llvm/Support/CommandLine.h"
410b57cec5SDimitry Andric #include "llvm/Support/Debug.h"
420b57cec5SDimitry Andric #include "llvm/Support/Error.h"
430b57cec5SDimitry Andric #include "llvm/Support/ErrorHandling.h"
440b57cec5SDimitry Andric #include "llvm/Support/FileSystem.h"
450b57cec5SDimitry Andric #include "llvm/Support/SourceMgr.h"
460b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h"
470b57cec5SDimitry Andric #include "llvm/Transforms/IPO/Internalize.h"
480b57cec5SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
490b57cec5SDimitry Andric #include "llvm/Transforms/Utils/FunctionImportUtils.h"
500b57cec5SDimitry Andric #include "llvm/Transforms/Utils/ValueMapper.h"
510b57cec5SDimitry Andric #include <cassert>
520b57cec5SDimitry Andric #include <memory>
530b57cec5SDimitry Andric #include <set>
540b57cec5SDimitry Andric #include <string>
550b57cec5SDimitry Andric #include <system_error>
560b57cec5SDimitry Andric #include <tuple>
570b57cec5SDimitry Andric #include <utility>
580b57cec5SDimitry Andric 
590b57cec5SDimitry Andric using namespace llvm;
600b57cec5SDimitry Andric 
610b57cec5SDimitry Andric #define DEBUG_TYPE "function-import"
620b57cec5SDimitry Andric 
630b57cec5SDimitry Andric STATISTIC(NumImportedFunctionsThinLink,
640b57cec5SDimitry Andric           "Number of functions thin link decided to import");
650b57cec5SDimitry Andric STATISTIC(NumImportedHotFunctionsThinLink,
660b57cec5SDimitry Andric           "Number of hot functions thin link decided to import");
670b57cec5SDimitry Andric STATISTIC(NumImportedCriticalFunctionsThinLink,
680b57cec5SDimitry Andric           "Number of critical functions thin link decided to import");
690b57cec5SDimitry Andric STATISTIC(NumImportedGlobalVarsThinLink,
700b57cec5SDimitry Andric           "Number of global variables thin link decided to import");
710b57cec5SDimitry Andric STATISTIC(NumImportedFunctions, "Number of functions imported in backend");
720b57cec5SDimitry Andric STATISTIC(NumImportedGlobalVars,
730b57cec5SDimitry Andric           "Number of global variables imported in backend");
740b57cec5SDimitry Andric STATISTIC(NumImportedModules, "Number of modules imported from");
750b57cec5SDimitry Andric STATISTIC(NumDeadSymbols, "Number of dead stripped symbols in index");
760b57cec5SDimitry Andric STATISTIC(NumLiveSymbols, "Number of live symbols in index");
770b57cec5SDimitry Andric 
780b57cec5SDimitry Andric /// Limit on instruction count of imported functions.
790b57cec5SDimitry Andric static cl::opt<unsigned> ImportInstrLimit(
800b57cec5SDimitry Andric     "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
810b57cec5SDimitry Andric     cl::desc("Only import functions with less than N instructions"));
820b57cec5SDimitry Andric 
830b57cec5SDimitry Andric static cl::opt<int> ImportCutoff(
840b57cec5SDimitry Andric     "import-cutoff", cl::init(-1), cl::Hidden, cl::value_desc("N"),
850b57cec5SDimitry Andric     cl::desc("Only import first N functions if N>=0 (default -1)"));
860b57cec5SDimitry Andric 
87*5f7ddb14SDimitry Andric static cl::opt<bool>
88*5f7ddb14SDimitry Andric     ForceImportAll("force-import-all", cl::init(false), cl::Hidden,
89*5f7ddb14SDimitry Andric                    cl::desc("Import functions with noinline attribute"));
90*5f7ddb14SDimitry Andric 
910b57cec5SDimitry Andric static cl::opt<float>
920b57cec5SDimitry Andric     ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7),
930b57cec5SDimitry Andric                       cl::Hidden, cl::value_desc("x"),
940b57cec5SDimitry Andric                       cl::desc("As we import functions, multiply the "
950b57cec5SDimitry Andric                                "`import-instr-limit` threshold by this factor "
960b57cec5SDimitry Andric                                "before processing newly imported functions"));
970b57cec5SDimitry Andric 
980b57cec5SDimitry Andric static cl::opt<float> ImportHotInstrFactor(
990b57cec5SDimitry Andric     "import-hot-evolution-factor", cl::init(1.0), cl::Hidden,
1000b57cec5SDimitry Andric     cl::value_desc("x"),
1010b57cec5SDimitry Andric     cl::desc("As we import functions called from hot callsite, multiply the "
1020b57cec5SDimitry Andric              "`import-instr-limit` threshold by this factor "
1030b57cec5SDimitry Andric              "before processing newly imported functions"));
1040b57cec5SDimitry Andric 
1050b57cec5SDimitry Andric static cl::opt<float> ImportHotMultiplier(
1060b57cec5SDimitry Andric     "import-hot-multiplier", cl::init(10.0), cl::Hidden, cl::value_desc("x"),
1070b57cec5SDimitry Andric     cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"));
1080b57cec5SDimitry Andric 
1090b57cec5SDimitry Andric static cl::opt<float> ImportCriticalMultiplier(
1100b57cec5SDimitry Andric     "import-critical-multiplier", cl::init(100.0), cl::Hidden,
1110b57cec5SDimitry Andric     cl::value_desc("x"),
1120b57cec5SDimitry Andric     cl::desc(
1130b57cec5SDimitry Andric         "Multiply the `import-instr-limit` threshold for critical callsites"));
1140b57cec5SDimitry Andric 
1150b57cec5SDimitry Andric // FIXME: This multiplier was not really tuned up.
1160b57cec5SDimitry Andric static cl::opt<float> ImportColdMultiplier(
1170b57cec5SDimitry Andric     "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"),
1180b57cec5SDimitry Andric     cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"));
1190b57cec5SDimitry Andric 
1200b57cec5SDimitry Andric static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
1210b57cec5SDimitry Andric                                   cl::desc("Print imported functions"));
1220b57cec5SDimitry Andric 
1230b57cec5SDimitry Andric static cl::opt<bool> PrintImportFailures(
1240b57cec5SDimitry Andric     "print-import-failures", cl::init(false), cl::Hidden,
1250b57cec5SDimitry Andric     cl::desc("Print information for functions rejected for importing"));
1260b57cec5SDimitry Andric 
1270b57cec5SDimitry Andric static cl::opt<bool> ComputeDead("compute-dead", cl::init(true), cl::Hidden,
1280b57cec5SDimitry Andric                                  cl::desc("Compute dead symbols"));
1290b57cec5SDimitry Andric 
1300b57cec5SDimitry Andric static cl::opt<bool> EnableImportMetadata(
131af732203SDimitry Andric     "enable-import-metadata", cl::init(false), cl::Hidden,
132af732203SDimitry Andric     cl::desc("Enable import metadata like 'thinlto_src_module'"));
1330b57cec5SDimitry Andric 
1340b57cec5SDimitry Andric /// Summary file to use for function importing when using -function-import from
1350b57cec5SDimitry Andric /// the command line.
1360b57cec5SDimitry Andric static cl::opt<std::string>
1370b57cec5SDimitry Andric     SummaryFile("summary-file",
1380b57cec5SDimitry Andric                 cl::desc("The summary file to use for function importing."));
1390b57cec5SDimitry Andric 
1400b57cec5SDimitry Andric /// Used when testing importing from distributed indexes via opt
1410b57cec5SDimitry Andric // -function-import.
1420b57cec5SDimitry Andric static cl::opt<bool>
1430b57cec5SDimitry Andric     ImportAllIndex("import-all-index",
1440b57cec5SDimitry Andric                    cl::desc("Import all external functions in index."));
1450b57cec5SDimitry Andric 
1460b57cec5SDimitry Andric // Load lazily a module from \p FileName in \p Context.
loadFile(const std::string & FileName,LLVMContext & Context)1470b57cec5SDimitry Andric static std::unique_ptr<Module> loadFile(const std::string &FileName,
1480b57cec5SDimitry Andric                                         LLVMContext &Context) {
1490b57cec5SDimitry Andric   SMDiagnostic Err;
1500b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Loading '" << FileName << "'\n");
1510b57cec5SDimitry Andric   // Metadata isn't loaded until functions are imported, to minimize
1520b57cec5SDimitry Andric   // the memory overhead.
1530b57cec5SDimitry Andric   std::unique_ptr<Module> Result =
1540b57cec5SDimitry Andric       getLazyIRFileModule(FileName, Err, Context,
1550b57cec5SDimitry Andric                           /* ShouldLazyLoadMetadata = */ true);
1560b57cec5SDimitry Andric   if (!Result) {
1570b57cec5SDimitry Andric     Err.print("function-import", errs());
1580b57cec5SDimitry Andric     report_fatal_error("Abort");
1590b57cec5SDimitry Andric   }
1600b57cec5SDimitry Andric 
1610b57cec5SDimitry Andric   return Result;
1620b57cec5SDimitry Andric }
1630b57cec5SDimitry Andric 
1640b57cec5SDimitry Andric /// Given a list of possible callee implementation for a call site, select one
1650b57cec5SDimitry Andric /// that fits the \p Threshold.
1660b57cec5SDimitry Andric ///
1670b57cec5SDimitry Andric /// FIXME: select "best" instead of first that fits. But what is "best"?
1680b57cec5SDimitry Andric /// - The smallest: more likely to be inlined.
1690b57cec5SDimitry Andric /// - The one with the least outgoing edges (already well optimized).
1700b57cec5SDimitry Andric /// - One from a module already being imported from in order to reduce the
1710b57cec5SDimitry Andric ///   number of source modules parsed/linked.
1720b57cec5SDimitry Andric /// - One that has PGO data attached.
1730b57cec5SDimitry Andric /// - [insert you fancy metric here]
1740b57cec5SDimitry Andric static const GlobalValueSummary *
selectCallee(const ModuleSummaryIndex & Index,ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,unsigned Threshold,StringRef CallerModulePath,FunctionImporter::ImportFailureReason & Reason,GlobalValue::GUID GUID)1750b57cec5SDimitry Andric selectCallee(const ModuleSummaryIndex &Index,
1760b57cec5SDimitry Andric              ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
1770b57cec5SDimitry Andric              unsigned Threshold, StringRef CallerModulePath,
1780b57cec5SDimitry Andric              FunctionImporter::ImportFailureReason &Reason,
1790b57cec5SDimitry Andric              GlobalValue::GUID GUID) {
1800b57cec5SDimitry Andric   Reason = FunctionImporter::ImportFailureReason::None;
1810b57cec5SDimitry Andric   auto It = llvm::find_if(
1820b57cec5SDimitry Andric       CalleeSummaryList,
1830b57cec5SDimitry Andric       [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
1840b57cec5SDimitry Andric         auto *GVSummary = SummaryPtr.get();
1850b57cec5SDimitry Andric         if (!Index.isGlobalValueLive(GVSummary)) {
1860b57cec5SDimitry Andric           Reason = FunctionImporter::ImportFailureReason::NotLive;
1870b57cec5SDimitry Andric           return false;
1880b57cec5SDimitry Andric         }
1890b57cec5SDimitry Andric 
1900b57cec5SDimitry Andric         // For SamplePGO, in computeImportForFunction the OriginalId
1910b57cec5SDimitry Andric         // may have been used to locate the callee summary list (See
1920b57cec5SDimitry Andric         // comment there).
1930b57cec5SDimitry Andric         // The mapping from OriginalId to GUID may return a GUID
1940b57cec5SDimitry Andric         // that corresponds to a static variable. Filter it out here.
1950b57cec5SDimitry Andric         // This can happen when
1960b57cec5SDimitry Andric         // 1) There is a call to a library function which is not defined
1970b57cec5SDimitry Andric         // in the index.
1980b57cec5SDimitry Andric         // 2) There is a static variable with the  OriginalGUID identical
1990b57cec5SDimitry Andric         // to the GUID of the library function in 1);
2000b57cec5SDimitry Andric         // When this happens, the logic for SamplePGO kicks in and
2010b57cec5SDimitry Andric         // the static variable in 2) will be found, which needs to be
2020b57cec5SDimitry Andric         // filtered out.
2030b57cec5SDimitry Andric         if (GVSummary->getSummaryKind() == GlobalValueSummary::GlobalVarKind) {
2040b57cec5SDimitry Andric           Reason = FunctionImporter::ImportFailureReason::GlobalVar;
2050b57cec5SDimitry Andric           return false;
2060b57cec5SDimitry Andric         }
2070b57cec5SDimitry Andric         if (GlobalValue::isInterposableLinkage(GVSummary->linkage())) {
2080b57cec5SDimitry Andric           Reason = FunctionImporter::ImportFailureReason::InterposableLinkage;
2090b57cec5SDimitry Andric           // There is no point in importing these, we can't inline them
2100b57cec5SDimitry Andric           return false;
2110b57cec5SDimitry Andric         }
2120b57cec5SDimitry Andric 
2130b57cec5SDimitry Andric         auto *Summary = cast<FunctionSummary>(GVSummary->getBaseObject());
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 &&
2270b57cec5SDimitry Andric             Summary->modulePath() != CallerModulePath) {
2280b57cec5SDimitry Andric           Reason =
2290b57cec5SDimitry Andric               FunctionImporter::ImportFailureReason::LocalLinkageNotInModule;
2300b57cec5SDimitry Andric           return false;
2310b57cec5SDimitry Andric         }
2320b57cec5SDimitry Andric 
233480093f4SDimitry Andric         if ((Summary->instCount() > Threshold) &&
234*5f7ddb14SDimitry Andric             !Summary->fflags().AlwaysInline && !ForceImportAll) {
2350b57cec5SDimitry Andric           Reason = FunctionImporter::ImportFailureReason::TooLarge;
2360b57cec5SDimitry Andric           return false;
2370b57cec5SDimitry Andric         }
2380b57cec5SDimitry Andric 
2390b57cec5SDimitry Andric         // Skip if it isn't legal to import (e.g. may reference unpromotable
2400b57cec5SDimitry Andric         // locals).
2410b57cec5SDimitry Andric         if (Summary->notEligibleToImport()) {
2420b57cec5SDimitry Andric           Reason = FunctionImporter::ImportFailureReason::NotEligible;
2430b57cec5SDimitry Andric           return false;
2440b57cec5SDimitry Andric         }
2450b57cec5SDimitry Andric 
2460b57cec5SDimitry Andric         // Don't bother importing if we can't inline it anyway.
247*5f7ddb14SDimitry Andric         if (Summary->fflags().NoInline && !ForceImportAll) {
2480b57cec5SDimitry Andric           Reason = FunctionImporter::ImportFailureReason::NoInline;
2490b57cec5SDimitry Andric           return false;
2500b57cec5SDimitry Andric         }
2510b57cec5SDimitry Andric 
2520b57cec5SDimitry Andric         return true;
2530b57cec5SDimitry Andric       });
2540b57cec5SDimitry Andric   if (It == CalleeSummaryList.end())
2550b57cec5SDimitry Andric     return nullptr;
2560b57cec5SDimitry Andric 
2570b57cec5SDimitry Andric   return cast<GlobalValueSummary>(It->get());
2580b57cec5SDimitry Andric }
2590b57cec5SDimitry Andric 
2600b57cec5SDimitry Andric namespace {
2610b57cec5SDimitry Andric 
262af732203SDimitry Andric using EdgeInfo =
263af732203SDimitry Andric     std::tuple<const GlobalValueSummary *, unsigned /* Threshold */>;
2640b57cec5SDimitry Andric 
2650b57cec5SDimitry Andric } // anonymous namespace
2660b57cec5SDimitry Andric 
2670b57cec5SDimitry Andric static ValueInfo
updateValueInfoForIndirectCalls(const ModuleSummaryIndex & Index,ValueInfo VI)2680b57cec5SDimitry Andric updateValueInfoForIndirectCalls(const ModuleSummaryIndex &Index, ValueInfo VI) {
2690b57cec5SDimitry Andric   if (!VI.getSummaryList().empty())
2700b57cec5SDimitry Andric     return VI;
2710b57cec5SDimitry Andric   // For SamplePGO, the indirect call targets for local functions will
2720b57cec5SDimitry Andric   // have its original name annotated in profile. We try to find the
2730b57cec5SDimitry Andric   // corresponding PGOFuncName as the GUID.
2740b57cec5SDimitry Andric   // FIXME: Consider updating the edges in the graph after building
2750b57cec5SDimitry Andric   // it, rather than needing to perform this mapping on each walk.
2760b57cec5SDimitry Andric   auto GUID = Index.getGUIDFromOriginalID(VI.getGUID());
2770b57cec5SDimitry Andric   if (GUID == 0)
2780b57cec5SDimitry Andric     return ValueInfo();
2790b57cec5SDimitry Andric   return Index.getValueInfo(GUID);
2800b57cec5SDimitry Andric }
2810b57cec5SDimitry Andric 
shouldImportGlobal(const ValueInfo & VI,const GVSummaryMapTy & DefinedGVSummaries)282*5f7ddb14SDimitry Andric static bool shouldImportGlobal(const ValueInfo &VI,
283*5f7ddb14SDimitry Andric                                const GVSummaryMapTy &DefinedGVSummaries) {
284*5f7ddb14SDimitry Andric   const auto &GVS = DefinedGVSummaries.find(VI.getGUID());
285*5f7ddb14SDimitry Andric   if (GVS == DefinedGVSummaries.end())
286*5f7ddb14SDimitry Andric     return true;
287*5f7ddb14SDimitry Andric   // We should not skip import if the module contains a definition with
288*5f7ddb14SDimitry Andric   // interposable linkage type. This is required for correctness in
289*5f7ddb14SDimitry Andric   // the situation with two following conditions:
290*5f7ddb14SDimitry Andric   // * the def with interposable linkage is non-prevailing,
291*5f7ddb14SDimitry Andric   // * there is a prevailing def available for import and marked read-only.
292*5f7ddb14SDimitry Andric   // In this case, the non-prevailing def will be converted to a declaration,
293*5f7ddb14SDimitry Andric   // while the prevailing one becomes internal, thus no definitions will be
294*5f7ddb14SDimitry Andric   // available for linking. In order to prevent undefined symbol link error,
295*5f7ddb14SDimitry Andric   // the prevailing definition must be imported.
296*5f7ddb14SDimitry Andric   // FIXME: Consider adding a check that the suitable prevailing definition
297*5f7ddb14SDimitry Andric   // exists and marked read-only.
298*5f7ddb14SDimitry Andric   if (VI.getSummaryList().size() > 1 &&
299*5f7ddb14SDimitry Andric       GlobalValue::isInterposableLinkage(GVS->second->linkage()))
300*5f7ddb14SDimitry Andric     return true;
301*5f7ddb14SDimitry Andric 
302*5f7ddb14SDimitry Andric   return false;
303*5f7ddb14SDimitry Andric }
304*5f7ddb14SDimitry Andric 
computeImportForReferencedGlobals(const GlobalValueSummary & Summary,const ModuleSummaryIndex & Index,const GVSummaryMapTy & DefinedGVSummaries,SmallVectorImpl<EdgeInfo> & Worklist,FunctionImporter::ImportMapTy & ImportList,StringMap<FunctionImporter::ExportSetTy> * ExportLists)3050b57cec5SDimitry Andric static void computeImportForReferencedGlobals(
306af732203SDimitry Andric     const GlobalValueSummary &Summary, const ModuleSummaryIndex &Index,
307480093f4SDimitry Andric     const GVSummaryMapTy &DefinedGVSummaries,
308af732203SDimitry Andric     SmallVectorImpl<EdgeInfo> &Worklist,
3090b57cec5SDimitry Andric     FunctionImporter::ImportMapTy &ImportList,
3100b57cec5SDimitry Andric     StringMap<FunctionImporter::ExportSetTy> *ExportLists) {
3110b57cec5SDimitry Andric   for (auto &VI : Summary.refs()) {
312*5f7ddb14SDimitry Andric     if (!shouldImportGlobal(VI, DefinedGVSummaries)) {
3130b57cec5SDimitry Andric       LLVM_DEBUG(
3140b57cec5SDimitry Andric           dbgs() << "Ref ignored! Target already in destination module.\n");
3150b57cec5SDimitry Andric       continue;
3160b57cec5SDimitry Andric     }
3170b57cec5SDimitry Andric 
3180b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << " ref -> " << VI << "\n");
3190b57cec5SDimitry Andric 
3200b57cec5SDimitry Andric     // If this is a local variable, make sure we import the copy
3210b57cec5SDimitry Andric     // in the caller's module. The only time a local variable can
3220b57cec5SDimitry Andric     // share an entry in the index is if there is a local with the same name
3230b57cec5SDimitry Andric     // in another module that had the same source file name (in a different
3240b57cec5SDimitry Andric     // directory), where each was compiled in their own directory so there
3250b57cec5SDimitry Andric     // was not distinguishing path.
3260b57cec5SDimitry Andric     auto LocalNotInModule = [&](const GlobalValueSummary *RefSummary) -> bool {
3270b57cec5SDimitry Andric       return GlobalValue::isLocalLinkage(RefSummary->linkage()) &&
3280b57cec5SDimitry Andric              RefSummary->modulePath() != Summary.modulePath();
3290b57cec5SDimitry Andric     };
3300b57cec5SDimitry Andric 
3310b57cec5SDimitry Andric     for (auto &RefSummary : VI.getSummaryList())
3320b57cec5SDimitry Andric       if (isa<GlobalVarSummary>(RefSummary.get()) &&
333480093f4SDimitry Andric           Index.canImportGlobalVar(RefSummary.get(), /* AnalyzeRefs */ true) &&
3340b57cec5SDimitry Andric           !LocalNotInModule(RefSummary.get())) {
3350b57cec5SDimitry Andric         auto ILI = ImportList[RefSummary->modulePath()].insert(VI.getGUID());
3365ffd83dbSDimitry Andric         // Only update stat and exports if we haven't already imported this
3375ffd83dbSDimitry Andric         // variable.
3385ffd83dbSDimitry Andric         if (!ILI.second)
3395ffd83dbSDimitry Andric           break;
3400b57cec5SDimitry Andric         NumImportedGlobalVarsThinLink++;
3415ffd83dbSDimitry Andric         // Any references made by this variable will be marked exported later,
3425ffd83dbSDimitry Andric         // in ComputeCrossModuleImport, after import decisions are complete,
3435ffd83dbSDimitry Andric         // which is more efficient than adding them here.
3445ffd83dbSDimitry Andric         if (ExportLists)
3455ffd83dbSDimitry Andric           (*ExportLists)[RefSummary->modulePath()].insert(VI);
346af732203SDimitry Andric 
347af732203SDimitry Andric         // If variable is not writeonly we attempt to recursively analyze
348af732203SDimitry Andric         // its references in order to import referenced constants.
349af732203SDimitry Andric         if (!Index.isWriteOnly(cast<GlobalVarSummary>(RefSummary.get())))
350af732203SDimitry Andric           Worklist.emplace_back(RefSummary.get(), 0);
3510b57cec5SDimitry Andric         break;
3520b57cec5SDimitry Andric       }
3530b57cec5SDimitry Andric   }
3540b57cec5SDimitry Andric }
3550b57cec5SDimitry Andric 
3560b57cec5SDimitry Andric static const char *
getFailureName(FunctionImporter::ImportFailureReason Reason)3570b57cec5SDimitry Andric getFailureName(FunctionImporter::ImportFailureReason Reason) {
3580b57cec5SDimitry Andric   switch (Reason) {
3590b57cec5SDimitry Andric   case FunctionImporter::ImportFailureReason::None:
3600b57cec5SDimitry Andric     return "None";
3610b57cec5SDimitry Andric   case FunctionImporter::ImportFailureReason::GlobalVar:
3620b57cec5SDimitry Andric     return "GlobalVar";
3630b57cec5SDimitry Andric   case FunctionImporter::ImportFailureReason::NotLive:
3640b57cec5SDimitry Andric     return "NotLive";
3650b57cec5SDimitry Andric   case FunctionImporter::ImportFailureReason::TooLarge:
3660b57cec5SDimitry Andric     return "TooLarge";
3670b57cec5SDimitry Andric   case FunctionImporter::ImportFailureReason::InterposableLinkage:
3680b57cec5SDimitry Andric     return "InterposableLinkage";
3690b57cec5SDimitry Andric   case FunctionImporter::ImportFailureReason::LocalLinkageNotInModule:
3700b57cec5SDimitry Andric     return "LocalLinkageNotInModule";
3710b57cec5SDimitry Andric   case FunctionImporter::ImportFailureReason::NotEligible:
3720b57cec5SDimitry Andric     return "NotEligible";
3730b57cec5SDimitry Andric   case FunctionImporter::ImportFailureReason::NoInline:
3740b57cec5SDimitry Andric     return "NoInline";
3750b57cec5SDimitry Andric   }
3760b57cec5SDimitry Andric   llvm_unreachable("invalid reason");
3770b57cec5SDimitry Andric }
3780b57cec5SDimitry Andric 
3790b57cec5SDimitry Andric /// Compute the list of functions to import for a given caller. Mark these
3800b57cec5SDimitry Andric /// imported functions and the symbols they reference in their source module as
3810b57cec5SDimitry Andric /// exported from their source module.
computeImportForFunction(const FunctionSummary & Summary,const ModuleSummaryIndex & Index,const unsigned Threshold,const GVSummaryMapTy & DefinedGVSummaries,SmallVectorImpl<EdgeInfo> & Worklist,FunctionImporter::ImportMapTy & ImportList,StringMap<FunctionImporter::ExportSetTy> * ExportLists,FunctionImporter::ImportThresholdsTy & ImportThresholds)3820b57cec5SDimitry Andric static void computeImportForFunction(
3830b57cec5SDimitry Andric     const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
3840b57cec5SDimitry Andric     const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
3850b57cec5SDimitry Andric     SmallVectorImpl<EdgeInfo> &Worklist,
3860b57cec5SDimitry Andric     FunctionImporter::ImportMapTy &ImportList,
3870b57cec5SDimitry Andric     StringMap<FunctionImporter::ExportSetTy> *ExportLists,
3880b57cec5SDimitry Andric     FunctionImporter::ImportThresholdsTy &ImportThresholds) {
389480093f4SDimitry Andric   computeImportForReferencedGlobals(Summary, Index, DefinedGVSummaries,
390af732203SDimitry Andric                                     Worklist, ImportList, ExportLists);
3910b57cec5SDimitry Andric   static int ImportCount = 0;
3920b57cec5SDimitry Andric   for (auto &Edge : Summary.calls()) {
3930b57cec5SDimitry Andric     ValueInfo VI = Edge.first;
3940b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << " edge -> " << VI << " Threshold:" << Threshold
3950b57cec5SDimitry Andric                       << "\n");
3960b57cec5SDimitry Andric 
3970b57cec5SDimitry Andric     if (ImportCutoff >= 0 && ImportCount >= ImportCutoff) {
3980b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "ignored! import-cutoff value of " << ImportCutoff
3990b57cec5SDimitry Andric                         << " reached.\n");
4000b57cec5SDimitry Andric       continue;
4010b57cec5SDimitry Andric     }
4020b57cec5SDimitry Andric 
4030b57cec5SDimitry Andric     VI = updateValueInfoForIndirectCalls(Index, VI);
4040b57cec5SDimitry Andric     if (!VI)
4050b57cec5SDimitry Andric       continue;
4060b57cec5SDimitry Andric 
4070b57cec5SDimitry Andric     if (DefinedGVSummaries.count(VI.getGUID())) {
408*5f7ddb14SDimitry Andric       // FIXME: Consider not skipping import if the module contains
409*5f7ddb14SDimitry Andric       // a non-prevailing def with interposable linkage. The prevailing copy
410*5f7ddb14SDimitry Andric       // can safely be imported (see shouldImportGlobal()).
4110b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "ignored! Target already in destination module.\n");
4120b57cec5SDimitry Andric       continue;
4130b57cec5SDimitry Andric     }
4140b57cec5SDimitry Andric 
4150b57cec5SDimitry Andric     auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
4160b57cec5SDimitry Andric       if (Hotness == CalleeInfo::HotnessType::Hot)
4170b57cec5SDimitry Andric         return ImportHotMultiplier;
4180b57cec5SDimitry Andric       if (Hotness == CalleeInfo::HotnessType::Cold)
4190b57cec5SDimitry Andric         return ImportColdMultiplier;
4200b57cec5SDimitry Andric       if (Hotness == CalleeInfo::HotnessType::Critical)
4210b57cec5SDimitry Andric         return ImportCriticalMultiplier;
4220b57cec5SDimitry Andric       return 1.0;
4230b57cec5SDimitry Andric     };
4240b57cec5SDimitry Andric 
4250b57cec5SDimitry Andric     const auto NewThreshold =
4260b57cec5SDimitry Andric         Threshold * GetBonusMultiplier(Edge.second.getHotness());
4270b57cec5SDimitry Andric 
4280b57cec5SDimitry Andric     auto IT = ImportThresholds.insert(std::make_pair(
4290b57cec5SDimitry Andric         VI.getGUID(), std::make_tuple(NewThreshold, nullptr, nullptr)));
4300b57cec5SDimitry Andric     bool PreviouslyVisited = !IT.second;
4310b57cec5SDimitry Andric     auto &ProcessedThreshold = std::get<0>(IT.first->second);
4320b57cec5SDimitry Andric     auto &CalleeSummary = std::get<1>(IT.first->second);
4330b57cec5SDimitry Andric     auto &FailureInfo = std::get<2>(IT.first->second);
4340b57cec5SDimitry Andric 
4350b57cec5SDimitry Andric     bool IsHotCallsite =
4360b57cec5SDimitry Andric         Edge.second.getHotness() == CalleeInfo::HotnessType::Hot;
4370b57cec5SDimitry Andric     bool IsCriticalCallsite =
4380b57cec5SDimitry Andric         Edge.second.getHotness() == CalleeInfo::HotnessType::Critical;
4390b57cec5SDimitry Andric 
4400b57cec5SDimitry Andric     const FunctionSummary *ResolvedCalleeSummary = nullptr;
4410b57cec5SDimitry Andric     if (CalleeSummary) {
4420b57cec5SDimitry Andric       assert(PreviouslyVisited);
4430b57cec5SDimitry Andric       // Since the traversal of the call graph is DFS, we can revisit a function
4440b57cec5SDimitry Andric       // a second time with a higher threshold. In this case, it is added back
4450b57cec5SDimitry Andric       // to the worklist with the new threshold (so that its own callee chains
4460b57cec5SDimitry Andric       // can be considered with the higher threshold).
4470b57cec5SDimitry Andric       if (NewThreshold <= ProcessedThreshold) {
4480b57cec5SDimitry Andric         LLVM_DEBUG(
4490b57cec5SDimitry Andric             dbgs() << "ignored! Target was already imported with Threshold "
4500b57cec5SDimitry Andric                    << ProcessedThreshold << "\n");
4510b57cec5SDimitry Andric         continue;
4520b57cec5SDimitry Andric       }
4530b57cec5SDimitry Andric       // Update with new larger threshold.
4540b57cec5SDimitry Andric       ProcessedThreshold = NewThreshold;
4550b57cec5SDimitry Andric       ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
4560b57cec5SDimitry Andric     } else {
4570b57cec5SDimitry Andric       // If we already rejected importing a callee at the same or higher
4580b57cec5SDimitry Andric       // threshold, don't waste time calling selectCallee.
4590b57cec5SDimitry Andric       if (PreviouslyVisited && NewThreshold <= ProcessedThreshold) {
4600b57cec5SDimitry Andric         LLVM_DEBUG(
4610b57cec5SDimitry Andric             dbgs() << "ignored! Target was already rejected with Threshold "
4620b57cec5SDimitry Andric             << ProcessedThreshold << "\n");
4630b57cec5SDimitry Andric         if (PrintImportFailures) {
4640b57cec5SDimitry Andric           assert(FailureInfo &&
4650b57cec5SDimitry Andric                  "Expected FailureInfo for previously rejected candidate");
4660b57cec5SDimitry Andric           FailureInfo->Attempts++;
4670b57cec5SDimitry Andric         }
4680b57cec5SDimitry Andric         continue;
4690b57cec5SDimitry Andric       }
4700b57cec5SDimitry Andric 
4710b57cec5SDimitry Andric       FunctionImporter::ImportFailureReason Reason;
4720b57cec5SDimitry Andric       CalleeSummary = selectCallee(Index, VI.getSummaryList(), NewThreshold,
4730b57cec5SDimitry Andric                                    Summary.modulePath(), Reason, VI.getGUID());
4740b57cec5SDimitry Andric       if (!CalleeSummary) {
4750b57cec5SDimitry Andric         // Update with new larger threshold if this was a retry (otherwise
4760b57cec5SDimitry Andric         // we would have already inserted with NewThreshold above). Also
4770b57cec5SDimitry Andric         // update failure info if requested.
4780b57cec5SDimitry Andric         if (PreviouslyVisited) {
4790b57cec5SDimitry Andric           ProcessedThreshold = NewThreshold;
4800b57cec5SDimitry Andric           if (PrintImportFailures) {
4810b57cec5SDimitry Andric             assert(FailureInfo &&
4820b57cec5SDimitry Andric                    "Expected FailureInfo for previously rejected candidate");
4830b57cec5SDimitry Andric             FailureInfo->Reason = Reason;
4840b57cec5SDimitry Andric             FailureInfo->Attempts++;
4850b57cec5SDimitry Andric             FailureInfo->MaxHotness =
4860b57cec5SDimitry Andric                 std::max(FailureInfo->MaxHotness, Edge.second.getHotness());
4870b57cec5SDimitry Andric           }
4880b57cec5SDimitry Andric         } else if (PrintImportFailures) {
4890b57cec5SDimitry Andric           assert(!FailureInfo &&
4900b57cec5SDimitry Andric                  "Expected no FailureInfo for newly rejected candidate");
4918bcb0991SDimitry Andric           FailureInfo = std::make_unique<FunctionImporter::ImportFailureInfo>(
4920b57cec5SDimitry Andric               VI, Edge.second.getHotness(), Reason, 1);
4930b57cec5SDimitry Andric         }
494*5f7ddb14SDimitry Andric         if (ForceImportAll) {
495*5f7ddb14SDimitry Andric           std::string Msg = std::string("Failed to import function ") +
496*5f7ddb14SDimitry Andric                             VI.name().str() + " due to " +
497*5f7ddb14SDimitry Andric                             getFailureName(Reason);
498*5f7ddb14SDimitry Andric           auto Error = make_error<StringError>(
499*5f7ddb14SDimitry Andric               Msg, std::make_error_code(std::errc::operation_not_supported));
500*5f7ddb14SDimitry Andric           logAllUnhandledErrors(std::move(Error), errs(),
501*5f7ddb14SDimitry Andric                                 "Error importing module: ");
502*5f7ddb14SDimitry Andric           break;
503*5f7ddb14SDimitry Andric         } else {
504*5f7ddb14SDimitry Andric           LLVM_DEBUG(dbgs()
505*5f7ddb14SDimitry Andric                      << "ignored! No qualifying callee with summary found.\n");
5060b57cec5SDimitry Andric           continue;
5070b57cec5SDimitry Andric         }
508*5f7ddb14SDimitry Andric       }
5090b57cec5SDimitry Andric 
5100b57cec5SDimitry Andric       // "Resolve" the summary
5110b57cec5SDimitry Andric       CalleeSummary = CalleeSummary->getBaseObject();
5120b57cec5SDimitry Andric       ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
5130b57cec5SDimitry Andric 
514*5f7ddb14SDimitry Andric       assert((ResolvedCalleeSummary->fflags().AlwaysInline || ForceImportAll ||
515480093f4SDimitry Andric               (ResolvedCalleeSummary->instCount() <= NewThreshold)) &&
5160b57cec5SDimitry Andric              "selectCallee() didn't honor the threshold");
5170b57cec5SDimitry Andric 
5180b57cec5SDimitry Andric       auto ExportModulePath = ResolvedCalleeSummary->modulePath();
5190b57cec5SDimitry Andric       auto ILI = ImportList[ExportModulePath].insert(VI.getGUID());
5200b57cec5SDimitry Andric       // We previously decided to import this GUID definition if it was already
5210b57cec5SDimitry Andric       // inserted in the set of imports from the exporting module.
5220b57cec5SDimitry Andric       bool PreviouslyImported = !ILI.second;
5230b57cec5SDimitry Andric       if (!PreviouslyImported) {
5240b57cec5SDimitry Andric         NumImportedFunctionsThinLink++;
5250b57cec5SDimitry Andric         if (IsHotCallsite)
5260b57cec5SDimitry Andric           NumImportedHotFunctionsThinLink++;
5270b57cec5SDimitry Andric         if (IsCriticalCallsite)
5280b57cec5SDimitry Andric           NumImportedCriticalFunctionsThinLink++;
5290b57cec5SDimitry Andric       }
5300b57cec5SDimitry Andric 
5315ffd83dbSDimitry Andric       // Any calls/references made by this function will be marked exported
5325ffd83dbSDimitry Andric       // later, in ComputeCrossModuleImport, after import decisions are
5335ffd83dbSDimitry Andric       // complete, which is more efficient than adding them here.
5345ffd83dbSDimitry Andric       if (ExportLists)
5355ffd83dbSDimitry Andric         (*ExportLists)[ExportModulePath].insert(VI);
5360b57cec5SDimitry Andric     }
5370b57cec5SDimitry Andric 
5380b57cec5SDimitry Andric     auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
5390b57cec5SDimitry Andric       // Adjust the threshold for next level of imported functions.
5400b57cec5SDimitry Andric       // The threshold is different for hot callsites because we can then
5410b57cec5SDimitry Andric       // inline chains of hot calls.
5420b57cec5SDimitry Andric       if (IsHotCallsite)
5430b57cec5SDimitry Andric         return Threshold * ImportHotInstrFactor;
5440b57cec5SDimitry Andric       return Threshold * ImportInstrFactor;
5450b57cec5SDimitry Andric     };
5460b57cec5SDimitry Andric 
5470b57cec5SDimitry Andric     const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
5480b57cec5SDimitry Andric 
5490b57cec5SDimitry Andric     ImportCount++;
5500b57cec5SDimitry Andric 
5510b57cec5SDimitry Andric     // Insert the newly imported function to the worklist.
552af732203SDimitry Andric     Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold);
5530b57cec5SDimitry Andric   }
5540b57cec5SDimitry Andric }
5550b57cec5SDimitry Andric 
5560b57cec5SDimitry Andric /// Given the list of globals defined in a module, compute the list of imports
5570b57cec5SDimitry Andric /// as well as the list of "exports", i.e. the list of symbols referenced from
5580b57cec5SDimitry Andric /// another module (that may require promotion).
ComputeImportForModule(const GVSummaryMapTy & DefinedGVSummaries,const ModuleSummaryIndex & Index,StringRef ModName,FunctionImporter::ImportMapTy & ImportList,StringMap<FunctionImporter::ExportSetTy> * ExportLists=nullptr)5590b57cec5SDimitry Andric static void ComputeImportForModule(
5600b57cec5SDimitry Andric     const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
5610b57cec5SDimitry Andric     StringRef ModName, FunctionImporter::ImportMapTy &ImportList,
5620b57cec5SDimitry Andric     StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
5630b57cec5SDimitry Andric   // Worklist contains the list of function imported in this module, for which
5640b57cec5SDimitry Andric   // we will analyse the callees and may import further down the callgraph.
5650b57cec5SDimitry Andric   SmallVector<EdgeInfo, 128> Worklist;
5660b57cec5SDimitry Andric   FunctionImporter::ImportThresholdsTy ImportThresholds;
5670b57cec5SDimitry Andric 
5680b57cec5SDimitry Andric   // Populate the worklist with the import for the functions in the current
5690b57cec5SDimitry Andric   // module
5700b57cec5SDimitry Andric   for (auto &GVSummary : DefinedGVSummaries) {
5710b57cec5SDimitry Andric #ifndef NDEBUG
5720b57cec5SDimitry Andric     // FIXME: Change the GVSummaryMapTy to hold ValueInfo instead of GUID
5730b57cec5SDimitry Andric     // so this map look up (and possibly others) can be avoided.
5740b57cec5SDimitry Andric     auto VI = Index.getValueInfo(GVSummary.first);
5750b57cec5SDimitry Andric #endif
5760b57cec5SDimitry Andric     if (!Index.isGlobalValueLive(GVSummary.second)) {
5770b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "Ignores Dead GUID: " << VI << "\n");
5780b57cec5SDimitry Andric       continue;
5790b57cec5SDimitry Andric     }
5800b57cec5SDimitry Andric     auto *FuncSummary =
5810b57cec5SDimitry Andric         dyn_cast<FunctionSummary>(GVSummary.second->getBaseObject());
5820b57cec5SDimitry Andric     if (!FuncSummary)
5830b57cec5SDimitry Andric       // Skip import for global variables
5840b57cec5SDimitry Andric       continue;
5850b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Initialize import for " << VI << "\n");
5860b57cec5SDimitry Andric     computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
5870b57cec5SDimitry Andric                              DefinedGVSummaries, Worklist, ImportList,
5880b57cec5SDimitry Andric                              ExportLists, ImportThresholds);
5890b57cec5SDimitry Andric   }
5900b57cec5SDimitry Andric 
5910b57cec5SDimitry Andric   // Process the newly imported functions and add callees to the worklist.
5920b57cec5SDimitry Andric   while (!Worklist.empty()) {
593af732203SDimitry Andric     auto GVInfo = Worklist.pop_back_val();
594af732203SDimitry Andric     auto *Summary = std::get<0>(GVInfo);
595af732203SDimitry Andric     auto Threshold = std::get<1>(GVInfo);
5960b57cec5SDimitry Andric 
597af732203SDimitry Andric     if (auto *FS = dyn_cast<FunctionSummary>(Summary))
598af732203SDimitry Andric       computeImportForFunction(*FS, Index, Threshold, DefinedGVSummaries,
5990b57cec5SDimitry Andric                                Worklist, ImportList, ExportLists,
6000b57cec5SDimitry Andric                                ImportThresholds);
601af732203SDimitry Andric     else
602af732203SDimitry Andric       computeImportForReferencedGlobals(*Summary, Index, DefinedGVSummaries,
603af732203SDimitry Andric                                         Worklist, ImportList, ExportLists);
6040b57cec5SDimitry Andric   }
6050b57cec5SDimitry Andric 
6060b57cec5SDimitry Andric   // Print stats about functions considered but rejected for importing
6070b57cec5SDimitry Andric   // when requested.
6080b57cec5SDimitry Andric   if (PrintImportFailures) {
6090b57cec5SDimitry Andric     dbgs() << "Missed imports into module " << ModName << "\n";
6100b57cec5SDimitry Andric     for (auto &I : ImportThresholds) {
6110b57cec5SDimitry Andric       auto &ProcessedThreshold = std::get<0>(I.second);
6120b57cec5SDimitry Andric       auto &CalleeSummary = std::get<1>(I.second);
6130b57cec5SDimitry Andric       auto &FailureInfo = std::get<2>(I.second);
6140b57cec5SDimitry Andric       if (CalleeSummary)
6150b57cec5SDimitry Andric         continue; // We are going to import.
6160b57cec5SDimitry Andric       assert(FailureInfo);
6170b57cec5SDimitry Andric       FunctionSummary *FS = nullptr;
6180b57cec5SDimitry Andric       if (!FailureInfo->VI.getSummaryList().empty())
6190b57cec5SDimitry Andric         FS = dyn_cast<FunctionSummary>(
6200b57cec5SDimitry Andric             FailureInfo->VI.getSummaryList()[0]->getBaseObject());
6210b57cec5SDimitry Andric       dbgs() << FailureInfo->VI
6220b57cec5SDimitry Andric              << ": Reason = " << getFailureName(FailureInfo->Reason)
6230b57cec5SDimitry Andric              << ", Threshold = " << ProcessedThreshold
6240b57cec5SDimitry Andric              << ", Size = " << (FS ? (int)FS->instCount() : -1)
6250b57cec5SDimitry Andric              << ", MaxHotness = " << getHotnessName(FailureInfo->MaxHotness)
6260b57cec5SDimitry Andric              << ", Attempts = " << FailureInfo->Attempts << "\n";
6270b57cec5SDimitry Andric     }
6280b57cec5SDimitry Andric   }
6290b57cec5SDimitry Andric }
6300b57cec5SDimitry Andric 
6310b57cec5SDimitry Andric #ifndef NDEBUG
isGlobalVarSummary(const ModuleSummaryIndex & Index,ValueInfo VI)632480093f4SDimitry Andric static bool isGlobalVarSummary(const ModuleSummaryIndex &Index, ValueInfo VI) {
6330b57cec5SDimitry Andric   auto SL = VI.getSummaryList();
634480093f4SDimitry Andric   return SL.empty()
635480093f4SDimitry Andric              ? false
636480093f4SDimitry Andric              : SL[0]->getSummaryKind() == GlobalValueSummary::GlobalVarKind;
6370b57cec5SDimitry Andric }
6380b57cec5SDimitry Andric 
isGlobalVarSummary(const ModuleSummaryIndex & Index,GlobalValue::GUID G)639480093f4SDimitry Andric static bool isGlobalVarSummary(const ModuleSummaryIndex &Index,
640480093f4SDimitry Andric                                GlobalValue::GUID G) {
641480093f4SDimitry Andric   if (const auto &VI = Index.getValueInfo(G))
642480093f4SDimitry Andric     return isGlobalVarSummary(Index, VI);
643480093f4SDimitry Andric   return false;
644480093f4SDimitry Andric }
6450b57cec5SDimitry Andric 
6460b57cec5SDimitry Andric template <class T>
numGlobalVarSummaries(const ModuleSummaryIndex & Index,T & Cont)6470b57cec5SDimitry Andric static unsigned numGlobalVarSummaries(const ModuleSummaryIndex &Index,
6480b57cec5SDimitry Andric                                       T &Cont) {
6490b57cec5SDimitry Andric   unsigned NumGVS = 0;
6500b57cec5SDimitry Andric   for (auto &V : Cont)
651480093f4SDimitry Andric     if (isGlobalVarSummary(Index, V))
6520b57cec5SDimitry Andric       ++NumGVS;
6530b57cec5SDimitry Andric   return NumGVS;
6540b57cec5SDimitry Andric }
6550b57cec5SDimitry Andric #endif
6560b57cec5SDimitry Andric 
657480093f4SDimitry Andric #ifndef NDEBUG
658480093f4SDimitry Andric static bool
checkVariableImport(const ModuleSummaryIndex & Index,StringMap<FunctionImporter::ImportMapTy> & ImportLists,StringMap<FunctionImporter::ExportSetTy> & ExportLists)659480093f4SDimitry Andric checkVariableImport(const ModuleSummaryIndex &Index,
660480093f4SDimitry Andric                     StringMap<FunctionImporter::ImportMapTy> &ImportLists,
661480093f4SDimitry Andric                     StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
662480093f4SDimitry Andric 
663480093f4SDimitry Andric   DenseSet<GlobalValue::GUID> FlattenedImports;
664480093f4SDimitry Andric 
665480093f4SDimitry Andric   for (auto &ImportPerModule : ImportLists)
666480093f4SDimitry Andric     for (auto &ExportPerModule : ImportPerModule.second)
667480093f4SDimitry Andric       FlattenedImports.insert(ExportPerModule.second.begin(),
668480093f4SDimitry Andric                               ExportPerModule.second.end());
669480093f4SDimitry Andric 
670480093f4SDimitry Andric   // Checks that all GUIDs of read/writeonly vars we see in export lists
671480093f4SDimitry Andric   // are also in the import lists. Otherwise we my face linker undefs,
672480093f4SDimitry Andric   // because readonly and writeonly vars are internalized in their
673480093f4SDimitry Andric   // source modules.
674480093f4SDimitry Andric   auto IsReadOrWriteOnlyVar = [&](StringRef ModulePath, const ValueInfo &VI) {
675480093f4SDimitry Andric     auto *GVS = dyn_cast_or_null<GlobalVarSummary>(
676480093f4SDimitry Andric         Index.findSummaryInModule(VI, ModulePath));
677480093f4SDimitry Andric     return GVS && (Index.isReadOnly(GVS) || Index.isWriteOnly(GVS));
678480093f4SDimitry Andric   };
679480093f4SDimitry Andric 
680480093f4SDimitry Andric   for (auto &ExportPerModule : ExportLists)
681480093f4SDimitry Andric     for (auto &VI : ExportPerModule.second)
682480093f4SDimitry Andric       if (!FlattenedImports.count(VI.getGUID()) &&
683480093f4SDimitry Andric           IsReadOrWriteOnlyVar(ExportPerModule.first(), VI))
684480093f4SDimitry Andric         return false;
685480093f4SDimitry Andric 
686480093f4SDimitry Andric   return true;
687480093f4SDimitry Andric }
688480093f4SDimitry Andric #endif
689480093f4SDimitry Andric 
6900b57cec5SDimitry Andric /// Compute all the import and export for every module using the Index.
ComputeCrossModuleImport(const ModuleSummaryIndex & Index,const StringMap<GVSummaryMapTy> & ModuleToDefinedGVSummaries,StringMap<FunctionImporter::ImportMapTy> & ImportLists,StringMap<FunctionImporter::ExportSetTy> & ExportLists)6910b57cec5SDimitry Andric void llvm::ComputeCrossModuleImport(
6920b57cec5SDimitry Andric     const ModuleSummaryIndex &Index,
6930b57cec5SDimitry Andric     const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
6940b57cec5SDimitry Andric     StringMap<FunctionImporter::ImportMapTy> &ImportLists,
6950b57cec5SDimitry Andric     StringMap<FunctionImporter::ExportSetTy> &ExportLists) {
6960b57cec5SDimitry Andric   // For each module that has function defined, compute the import/export lists.
6970b57cec5SDimitry Andric   for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
6980b57cec5SDimitry Andric     auto &ImportList = ImportLists[DefinedGVSummaries.first()];
6990b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "Computing import for Module '"
7000b57cec5SDimitry Andric                       << DefinedGVSummaries.first() << "'\n");
7010b57cec5SDimitry Andric     ComputeImportForModule(DefinedGVSummaries.second, Index,
7020b57cec5SDimitry Andric                            DefinedGVSummaries.first(), ImportList,
7030b57cec5SDimitry Andric                            &ExportLists);
7040b57cec5SDimitry Andric   }
7050b57cec5SDimitry Andric 
7065ffd83dbSDimitry Andric   // When computing imports we only added the variables and functions being
7075ffd83dbSDimitry Andric   // imported to the export list. We also need to mark any references and calls
7085ffd83dbSDimitry Andric   // they make as exported as well. We do this here, as it is more efficient
7095ffd83dbSDimitry Andric   // since we may import the same values multiple times into different modules
7105ffd83dbSDimitry Andric   // during the import computation.
7110b57cec5SDimitry Andric   for (auto &ELI : ExportLists) {
7125ffd83dbSDimitry Andric     FunctionImporter::ExportSetTy NewExports;
7130b57cec5SDimitry Andric     const auto &DefinedGVSummaries =
7140b57cec5SDimitry Andric         ModuleToDefinedGVSummaries.lookup(ELI.first());
7155ffd83dbSDimitry Andric     for (auto &EI : ELI.second) {
7165ffd83dbSDimitry Andric       // Find the copy defined in the exporting module so that we can mark the
7175ffd83dbSDimitry Andric       // values it references in that specific definition as exported.
7185ffd83dbSDimitry Andric       // Below we will add all references and called values, without regard to
7195ffd83dbSDimitry Andric       // whether they are also defined in this module. We subsequently prune the
7205ffd83dbSDimitry Andric       // list to only include those defined in the exporting module, see comment
7215ffd83dbSDimitry Andric       // there as to why.
7225ffd83dbSDimitry Andric       auto DS = DefinedGVSummaries.find(EI.getGUID());
7235ffd83dbSDimitry Andric       // Anything marked exported during the import computation must have been
7245ffd83dbSDimitry Andric       // defined in the exporting module.
7255ffd83dbSDimitry Andric       assert(DS != DefinedGVSummaries.end());
7265ffd83dbSDimitry Andric       auto *S = DS->getSecond();
7275ffd83dbSDimitry Andric       S = S->getBaseObject();
7285ffd83dbSDimitry Andric       if (auto *GVS = dyn_cast<GlobalVarSummary>(S)) {
7295ffd83dbSDimitry Andric         // Export referenced functions and variables. We don't export/promote
7305ffd83dbSDimitry Andric         // objects referenced by writeonly variable initializer, because
7315ffd83dbSDimitry Andric         // we convert such variables initializers to "zeroinitializer".
7325ffd83dbSDimitry Andric         // See processGlobalForThinLTO.
7335ffd83dbSDimitry Andric         if (!Index.isWriteOnly(GVS))
7345ffd83dbSDimitry Andric           for (const auto &VI : GVS->refs())
7355ffd83dbSDimitry Andric             NewExports.insert(VI);
7365ffd83dbSDimitry Andric       } else {
7375ffd83dbSDimitry Andric         auto *FS = cast<FunctionSummary>(S);
7385ffd83dbSDimitry Andric         for (auto &Edge : FS->calls())
7395ffd83dbSDimitry Andric           NewExports.insert(Edge.first);
7405ffd83dbSDimitry Andric         for (auto &Ref : FS->refs())
7415ffd83dbSDimitry Andric           NewExports.insert(Ref);
7425ffd83dbSDimitry Andric       }
7435ffd83dbSDimitry Andric     }
7445ffd83dbSDimitry Andric     // Prune list computed above to only include values defined in the exporting
7455ffd83dbSDimitry Andric     // module. We do this after the above insertion since we may hit the same
7465ffd83dbSDimitry Andric     // ref/call target multiple times in above loop, and it is more efficient to
7475ffd83dbSDimitry Andric     // avoid a set lookup each time.
7485ffd83dbSDimitry Andric     for (auto EI = NewExports.begin(); EI != NewExports.end();) {
749480093f4SDimitry Andric       if (!DefinedGVSummaries.count(EI->getGUID()))
7505ffd83dbSDimitry Andric         NewExports.erase(EI++);
7510b57cec5SDimitry Andric       else
7520b57cec5SDimitry Andric         ++EI;
7530b57cec5SDimitry Andric     }
7545ffd83dbSDimitry Andric     ELI.second.insert(NewExports.begin(), NewExports.end());
7550b57cec5SDimitry Andric   }
7560b57cec5SDimitry Andric 
757480093f4SDimitry Andric   assert(checkVariableImport(Index, ImportLists, ExportLists));
7580b57cec5SDimitry Andric #ifndef NDEBUG
7590b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
7600b57cec5SDimitry Andric                     << " modules:\n");
7610b57cec5SDimitry Andric   for (auto &ModuleImports : ImportLists) {
7620b57cec5SDimitry Andric     auto ModName = ModuleImports.first();
7630b57cec5SDimitry Andric     auto &Exports = ExportLists[ModName];
7640b57cec5SDimitry Andric     unsigned NumGVS = numGlobalVarSummaries(Index, Exports);
7650b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << "* Module " << ModName << " exports "
7660b57cec5SDimitry Andric                       << Exports.size() - NumGVS << " functions and " << NumGVS
7670b57cec5SDimitry Andric                       << " vars. Imports from " << ModuleImports.second.size()
7680b57cec5SDimitry Andric                       << " modules.\n");
7690b57cec5SDimitry Andric     for (auto &Src : ModuleImports.second) {
7700b57cec5SDimitry Andric       auto SrcModName = Src.first();
7710b57cec5SDimitry Andric       unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second);
7720b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod
7730b57cec5SDimitry Andric                         << " functions imported from " << SrcModName << "\n");
7740b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod
7750b57cec5SDimitry Andric                         << " global vars imported from " << SrcModName << "\n");
7760b57cec5SDimitry Andric     }
7770b57cec5SDimitry Andric   }
7780b57cec5SDimitry Andric #endif
7790b57cec5SDimitry Andric }
7800b57cec5SDimitry Andric 
7810b57cec5SDimitry Andric #ifndef NDEBUG
dumpImportListForModule(const ModuleSummaryIndex & Index,StringRef ModulePath,FunctionImporter::ImportMapTy & ImportList)7820b57cec5SDimitry Andric static void dumpImportListForModule(const ModuleSummaryIndex &Index,
7830b57cec5SDimitry Andric                                     StringRef ModulePath,
7840b57cec5SDimitry Andric                                     FunctionImporter::ImportMapTy &ImportList) {
7850b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
7860b57cec5SDimitry Andric                     << ImportList.size() << " modules.\n");
7870b57cec5SDimitry Andric   for (auto &Src : ImportList) {
7880b57cec5SDimitry Andric     auto SrcModName = Src.first();
7890b57cec5SDimitry Andric     unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second);
7900b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod
7910b57cec5SDimitry Andric                       << " functions imported from " << SrcModName << "\n");
7920b57cec5SDimitry Andric     LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod << " vars imported from "
7930b57cec5SDimitry Andric                       << SrcModName << "\n");
7940b57cec5SDimitry Andric   }
7950b57cec5SDimitry Andric }
7960b57cec5SDimitry Andric #endif
7970b57cec5SDimitry Andric 
7980b57cec5SDimitry Andric /// Compute all the imports for the given module in the Index.
ComputeCrossModuleImportForModule(StringRef ModulePath,const ModuleSummaryIndex & Index,FunctionImporter::ImportMapTy & ImportList)7990b57cec5SDimitry Andric void llvm::ComputeCrossModuleImportForModule(
8000b57cec5SDimitry Andric     StringRef ModulePath, const ModuleSummaryIndex &Index,
8010b57cec5SDimitry Andric     FunctionImporter::ImportMapTy &ImportList) {
8020b57cec5SDimitry Andric   // Collect the list of functions this module defines.
8030b57cec5SDimitry Andric   // GUID -> Summary
8040b57cec5SDimitry Andric   GVSummaryMapTy FunctionSummaryMap;
8050b57cec5SDimitry Andric   Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
8060b57cec5SDimitry Andric 
8070b57cec5SDimitry Andric   // Compute the import list for this module.
8080b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
8090b57cec5SDimitry Andric   ComputeImportForModule(FunctionSummaryMap, Index, ModulePath, ImportList);
8100b57cec5SDimitry Andric 
8110b57cec5SDimitry Andric #ifndef NDEBUG
8120b57cec5SDimitry Andric   dumpImportListForModule(Index, ModulePath, ImportList);
8130b57cec5SDimitry Andric #endif
8140b57cec5SDimitry Andric }
8150b57cec5SDimitry Andric 
8160b57cec5SDimitry Andric // Mark all external summaries in Index for import into the given module.
8170b57cec5SDimitry Andric // Used for distributed builds using a distributed index.
ComputeCrossModuleImportForModuleFromIndex(StringRef ModulePath,const ModuleSummaryIndex & Index,FunctionImporter::ImportMapTy & ImportList)8180b57cec5SDimitry Andric void llvm::ComputeCrossModuleImportForModuleFromIndex(
8190b57cec5SDimitry Andric     StringRef ModulePath, const ModuleSummaryIndex &Index,
8200b57cec5SDimitry Andric     FunctionImporter::ImportMapTy &ImportList) {
8210b57cec5SDimitry Andric   for (auto &GlobalList : Index) {
8220b57cec5SDimitry Andric     // Ignore entries for undefined references.
8230b57cec5SDimitry Andric     if (GlobalList.second.SummaryList.empty())
8240b57cec5SDimitry Andric       continue;
8250b57cec5SDimitry Andric 
8260b57cec5SDimitry Andric     auto GUID = GlobalList.first;
8270b57cec5SDimitry Andric     assert(GlobalList.second.SummaryList.size() == 1 &&
8280b57cec5SDimitry Andric            "Expected individual combined index to have one summary per GUID");
8290b57cec5SDimitry Andric     auto &Summary = GlobalList.second.SummaryList[0];
8300b57cec5SDimitry Andric     // Skip the summaries for the importing module. These are included to
8310b57cec5SDimitry Andric     // e.g. record required linkage changes.
8320b57cec5SDimitry Andric     if (Summary->modulePath() == ModulePath)
8330b57cec5SDimitry Andric       continue;
8340b57cec5SDimitry Andric     // Add an entry to provoke importing by thinBackend.
8350b57cec5SDimitry Andric     ImportList[Summary->modulePath()].insert(GUID);
8360b57cec5SDimitry Andric   }
8370b57cec5SDimitry Andric #ifndef NDEBUG
8380b57cec5SDimitry Andric   dumpImportListForModule(Index, ModulePath, ImportList);
8390b57cec5SDimitry Andric #endif
8400b57cec5SDimitry Andric }
8410b57cec5SDimitry Andric 
computeDeadSymbols(ModuleSummaryIndex & Index,const DenseSet<GlobalValue::GUID> & GUIDPreservedSymbols,function_ref<PrevailingType (GlobalValue::GUID)> isPrevailing)8420b57cec5SDimitry Andric void llvm::computeDeadSymbols(
8430b57cec5SDimitry Andric     ModuleSummaryIndex &Index,
8440b57cec5SDimitry Andric     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
8450b57cec5SDimitry Andric     function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing) {
8460b57cec5SDimitry Andric   assert(!Index.withGlobalValueDeadStripping());
8470b57cec5SDimitry Andric   if (!ComputeDead)
8480b57cec5SDimitry Andric     return;
8490b57cec5SDimitry Andric   if (GUIDPreservedSymbols.empty())
8500b57cec5SDimitry Andric     // Don't do anything when nothing is live, this is friendly with tests.
8510b57cec5SDimitry Andric     return;
8520b57cec5SDimitry Andric   unsigned LiveSymbols = 0;
8530b57cec5SDimitry Andric   SmallVector<ValueInfo, 128> Worklist;
8540b57cec5SDimitry Andric   Worklist.reserve(GUIDPreservedSymbols.size() * 2);
8550b57cec5SDimitry Andric   for (auto GUID : GUIDPreservedSymbols) {
8560b57cec5SDimitry Andric     ValueInfo VI = Index.getValueInfo(GUID);
8570b57cec5SDimitry Andric     if (!VI)
8580b57cec5SDimitry Andric       continue;
8590b57cec5SDimitry Andric     for (auto &S : VI.getSummaryList())
8600b57cec5SDimitry Andric       S->setLive(true);
8610b57cec5SDimitry Andric   }
8620b57cec5SDimitry Andric 
8630b57cec5SDimitry Andric   // Add values flagged in the index as live roots to the worklist.
8640b57cec5SDimitry Andric   for (const auto &Entry : Index) {
8650b57cec5SDimitry Andric     auto VI = Index.getValueInfo(Entry);
8660b57cec5SDimitry Andric     for (auto &S : Entry.second.SummaryList)
8670b57cec5SDimitry Andric       if (S->isLive()) {
8680b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "Live root: " << VI << "\n");
8690b57cec5SDimitry Andric         Worklist.push_back(VI);
8700b57cec5SDimitry Andric         ++LiveSymbols;
8710b57cec5SDimitry Andric         break;
8720b57cec5SDimitry Andric       }
8730b57cec5SDimitry Andric   }
8740b57cec5SDimitry Andric 
8750b57cec5SDimitry Andric   // Make value live and add it to the worklist if it was not live before.
8768bcb0991SDimitry Andric   auto visit = [&](ValueInfo VI, bool IsAliasee) {
8770b57cec5SDimitry Andric     // FIXME: If we knew which edges were created for indirect call profiles,
8780b57cec5SDimitry Andric     // we could skip them here. Any that are live should be reached via
8790b57cec5SDimitry Andric     // other edges, e.g. reference edges. Otherwise, using a profile collected
8800b57cec5SDimitry Andric     // on a slightly different binary might provoke preserving, importing
8810b57cec5SDimitry Andric     // and ultimately promoting calls to functions not linked into this
8820b57cec5SDimitry Andric     // binary, which increases the binary size unnecessarily. Note that
8830b57cec5SDimitry Andric     // if this code changes, the importer needs to change so that edges
8840b57cec5SDimitry Andric     // to functions marked dead are skipped.
8850b57cec5SDimitry Andric     VI = updateValueInfoForIndirectCalls(Index, VI);
8860b57cec5SDimitry Andric     if (!VI)
8870b57cec5SDimitry Andric       return;
8880b57cec5SDimitry Andric 
8890b57cec5SDimitry Andric     if (llvm::any_of(VI.getSummaryList(),
8900b57cec5SDimitry Andric                      [](const std::unique_ptr<llvm::GlobalValueSummary> &S) {
8910b57cec5SDimitry Andric                        return S->isLive();
8920b57cec5SDimitry Andric                      }))
8930b57cec5SDimitry Andric       return;
8940b57cec5SDimitry Andric 
8950b57cec5SDimitry Andric     // We only keep live symbols that are known to be non-prevailing if any are
8960b57cec5SDimitry Andric     // available_externally, linkonceodr, weakodr. Those symbols are discarded
8970b57cec5SDimitry Andric     // later in the EliminateAvailableExternally pass and setting them to
8980b57cec5SDimitry Andric     // not-live could break downstreams users of liveness information (PR36483)
8990b57cec5SDimitry Andric     // or limit optimization opportunities.
9000b57cec5SDimitry Andric     if (isPrevailing(VI.getGUID()) == PrevailingType::No) {
9010b57cec5SDimitry Andric       bool KeepAliveLinkage = false;
9020b57cec5SDimitry Andric       bool Interposable = false;
9030b57cec5SDimitry Andric       for (auto &S : VI.getSummaryList()) {
9040b57cec5SDimitry Andric         if (S->linkage() == GlobalValue::AvailableExternallyLinkage ||
9050b57cec5SDimitry Andric             S->linkage() == GlobalValue::WeakODRLinkage ||
9060b57cec5SDimitry Andric             S->linkage() == GlobalValue::LinkOnceODRLinkage)
9070b57cec5SDimitry Andric           KeepAliveLinkage = true;
9080b57cec5SDimitry Andric         else if (GlobalValue::isInterposableLinkage(S->linkage()))
9090b57cec5SDimitry Andric           Interposable = true;
9100b57cec5SDimitry Andric       }
9110b57cec5SDimitry Andric 
9128bcb0991SDimitry Andric       if (!IsAliasee) {
9130b57cec5SDimitry Andric         if (!KeepAliveLinkage)
9140b57cec5SDimitry Andric           return;
9150b57cec5SDimitry Andric 
9160b57cec5SDimitry Andric         if (Interposable)
9170b57cec5SDimitry Andric           report_fatal_error(
9188bcb0991SDimitry Andric               "Interposable and available_externally/linkonce_odr/weak_odr "
9198bcb0991SDimitry Andric               "symbol");
9208bcb0991SDimitry Andric       }
9210b57cec5SDimitry Andric     }
9220b57cec5SDimitry Andric 
9230b57cec5SDimitry Andric     for (auto &S : VI.getSummaryList())
9240b57cec5SDimitry Andric       S->setLive(true);
9250b57cec5SDimitry Andric     ++LiveSymbols;
9260b57cec5SDimitry Andric     Worklist.push_back(VI);
9270b57cec5SDimitry Andric   };
9280b57cec5SDimitry Andric 
9290b57cec5SDimitry Andric   while (!Worklist.empty()) {
9300b57cec5SDimitry Andric     auto VI = Worklist.pop_back_val();
9310b57cec5SDimitry Andric     for (auto &Summary : VI.getSummaryList()) {
9320b57cec5SDimitry Andric       if (auto *AS = dyn_cast<AliasSummary>(Summary.get())) {
9330b57cec5SDimitry Andric         // If this is an alias, visit the aliasee VI to ensure that all copies
9340b57cec5SDimitry Andric         // are marked live and it is added to the worklist for further
9350b57cec5SDimitry Andric         // processing of its references.
9368bcb0991SDimitry Andric         visit(AS->getAliaseeVI(), true);
9370b57cec5SDimitry Andric         continue;
9380b57cec5SDimitry Andric       }
9390b57cec5SDimitry Andric       for (auto Ref : Summary->refs())
9408bcb0991SDimitry Andric         visit(Ref, false);
9410b57cec5SDimitry Andric       if (auto *FS = dyn_cast<FunctionSummary>(Summary.get()))
9420b57cec5SDimitry Andric         for (auto Call : FS->calls())
9438bcb0991SDimitry Andric           visit(Call.first, false);
9440b57cec5SDimitry Andric     }
9450b57cec5SDimitry Andric   }
9460b57cec5SDimitry Andric   Index.setWithGlobalValueDeadStripping();
9470b57cec5SDimitry Andric 
9480b57cec5SDimitry Andric   unsigned DeadSymbols = Index.size() - LiveSymbols;
9490b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols
9500b57cec5SDimitry Andric                     << " symbols Dead \n");
9510b57cec5SDimitry Andric   NumDeadSymbols += DeadSymbols;
9520b57cec5SDimitry Andric   NumLiveSymbols += LiveSymbols;
9530b57cec5SDimitry Andric }
9540b57cec5SDimitry Andric 
9550b57cec5SDimitry 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)9560b57cec5SDimitry Andric void llvm::computeDeadSymbolsWithConstProp(
9570b57cec5SDimitry Andric     ModuleSummaryIndex &Index,
9580b57cec5SDimitry Andric     const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
9590b57cec5SDimitry Andric     function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing,
9600b57cec5SDimitry Andric     bool ImportEnabled) {
9610b57cec5SDimitry Andric   computeDeadSymbols(Index, GUIDPreservedSymbols, isPrevailing);
962480093f4SDimitry Andric   if (ImportEnabled)
9630b57cec5SDimitry Andric     Index.propagateAttributes(GUIDPreservedSymbols);
9640b57cec5SDimitry Andric }
9650b57cec5SDimitry Andric 
9660b57cec5SDimitry Andric /// Compute the set of summaries needed for a ThinLTO backend compilation of
9670b57cec5SDimitry Andric /// \p ModulePath.
gatherImportedSummariesForModule(StringRef ModulePath,const StringMap<GVSummaryMapTy> & ModuleToDefinedGVSummaries,const FunctionImporter::ImportMapTy & ImportList,std::map<std::string,GVSummaryMapTy> & ModuleToSummariesForIndex)9680b57cec5SDimitry Andric void llvm::gatherImportedSummariesForModule(
9690b57cec5SDimitry Andric     StringRef ModulePath,
9700b57cec5SDimitry Andric     const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
9710b57cec5SDimitry Andric     const FunctionImporter::ImportMapTy &ImportList,
9720b57cec5SDimitry Andric     std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
9730b57cec5SDimitry Andric   // Include all summaries from the importing module.
9745ffd83dbSDimitry Andric   ModuleToSummariesForIndex[std::string(ModulePath)] =
9750b57cec5SDimitry Andric       ModuleToDefinedGVSummaries.lookup(ModulePath);
9760b57cec5SDimitry Andric   // Include summaries for imports.
9770b57cec5SDimitry Andric   for (auto &ILI : ImportList) {
9785ffd83dbSDimitry Andric     auto &SummariesForIndex =
9795ffd83dbSDimitry Andric         ModuleToSummariesForIndex[std::string(ILI.first())];
9800b57cec5SDimitry Andric     const auto &DefinedGVSummaries =
9810b57cec5SDimitry Andric         ModuleToDefinedGVSummaries.lookup(ILI.first());
9820b57cec5SDimitry Andric     for (auto &GI : ILI.second) {
9830b57cec5SDimitry Andric       const auto &DS = DefinedGVSummaries.find(GI);
9840b57cec5SDimitry Andric       assert(DS != DefinedGVSummaries.end() &&
9850b57cec5SDimitry Andric              "Expected a defined summary for imported global value");
9860b57cec5SDimitry Andric       SummariesForIndex[GI] = DS->second;
9870b57cec5SDimitry Andric     }
9880b57cec5SDimitry Andric   }
9890b57cec5SDimitry Andric }
9900b57cec5SDimitry Andric 
9910b57cec5SDimitry Andric /// Emit the files \p ModulePath will import from into \p OutputFilename.
EmitImportsFiles(StringRef ModulePath,StringRef OutputFilename,const std::map<std::string,GVSummaryMapTy> & ModuleToSummariesForIndex)9920b57cec5SDimitry Andric std::error_code llvm::EmitImportsFiles(
9930b57cec5SDimitry Andric     StringRef ModulePath, StringRef OutputFilename,
9940b57cec5SDimitry Andric     const std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
9950b57cec5SDimitry Andric   std::error_code EC;
9968bcb0991SDimitry Andric   raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::OF_None);
9970b57cec5SDimitry Andric   if (EC)
9980b57cec5SDimitry Andric     return EC;
9990b57cec5SDimitry Andric   for (auto &ILI : ModuleToSummariesForIndex)
10000b57cec5SDimitry Andric     // The ModuleToSummariesForIndex map includes an entry for the current
10010b57cec5SDimitry Andric     // Module (needed for writing out the index files). We don't want to
10020b57cec5SDimitry Andric     // include it in the imports file, however, so filter it out.
10030b57cec5SDimitry Andric     if (ILI.first != ModulePath)
10040b57cec5SDimitry Andric       ImportsOS << ILI.first << "\n";
10050b57cec5SDimitry Andric   return std::error_code();
10060b57cec5SDimitry Andric }
10070b57cec5SDimitry Andric 
convertToDeclaration(GlobalValue & GV)10080b57cec5SDimitry Andric bool llvm::convertToDeclaration(GlobalValue &GV) {
10090b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName()
10100b57cec5SDimitry Andric                     << "\n");
10110b57cec5SDimitry Andric   if (Function *F = dyn_cast<Function>(&GV)) {
10120b57cec5SDimitry Andric     F->deleteBody();
10130b57cec5SDimitry Andric     F->clearMetadata();
10140b57cec5SDimitry Andric     F->setComdat(nullptr);
10150b57cec5SDimitry Andric   } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
10160b57cec5SDimitry Andric     V->setInitializer(nullptr);
10170b57cec5SDimitry Andric     V->setLinkage(GlobalValue::ExternalLinkage);
10180b57cec5SDimitry Andric     V->clearMetadata();
10190b57cec5SDimitry Andric     V->setComdat(nullptr);
10200b57cec5SDimitry Andric   } else {
10210b57cec5SDimitry Andric     GlobalValue *NewGV;
10220b57cec5SDimitry Andric     if (GV.getValueType()->isFunctionTy())
10230b57cec5SDimitry Andric       NewGV =
10240b57cec5SDimitry Andric           Function::Create(cast<FunctionType>(GV.getValueType()),
10250b57cec5SDimitry Andric                            GlobalValue::ExternalLinkage, GV.getAddressSpace(),
10260b57cec5SDimitry Andric                            "", GV.getParent());
10270b57cec5SDimitry Andric     else
10280b57cec5SDimitry Andric       NewGV =
10290b57cec5SDimitry Andric           new GlobalVariable(*GV.getParent(), GV.getValueType(),
10300b57cec5SDimitry Andric                              /*isConstant*/ false, GlobalValue::ExternalLinkage,
10310b57cec5SDimitry Andric                              /*init*/ nullptr, "",
10320b57cec5SDimitry Andric                              /*insertbefore*/ nullptr, GV.getThreadLocalMode(),
10330b57cec5SDimitry Andric                              GV.getType()->getAddressSpace());
10340b57cec5SDimitry Andric     NewGV->takeName(&GV);
10350b57cec5SDimitry Andric     GV.replaceAllUsesWith(NewGV);
10360b57cec5SDimitry Andric     return false;
10370b57cec5SDimitry Andric   }
10385ffd83dbSDimitry Andric   if (!GV.isImplicitDSOLocal())
10395ffd83dbSDimitry Andric     GV.setDSOLocal(false);
10400b57cec5SDimitry Andric   return true;
10410b57cec5SDimitry Andric }
10420b57cec5SDimitry Andric 
thinLTOResolvePrevailingInModule(Module & TheModule,const GVSummaryMapTy & DefinedGlobals)10430b57cec5SDimitry Andric void llvm::thinLTOResolvePrevailingInModule(
10440b57cec5SDimitry Andric     Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
10450b57cec5SDimitry Andric   auto updateLinkage = [&](GlobalValue &GV) {
10460b57cec5SDimitry Andric     // See if the global summary analysis computed a new resolved linkage.
10470b57cec5SDimitry Andric     const auto &GS = DefinedGlobals.find(GV.getGUID());
10480b57cec5SDimitry Andric     if (GS == DefinedGlobals.end())
10490b57cec5SDimitry Andric       return;
10500b57cec5SDimitry Andric     auto NewLinkage = GS->second->linkage();
10510b57cec5SDimitry Andric     if (GlobalValue::isLocalLinkage(GV.getLinkage()) ||
10528bcb0991SDimitry Andric         // Don't internalize anything here, because the code below
10538bcb0991SDimitry Andric         // lacks necessary correctness checks. Leave this job to
10548bcb0991SDimitry Andric         // LLVM 'internalize' pass.
10558bcb0991SDimitry Andric         GlobalValue::isLocalLinkage(NewLinkage) ||
10560b57cec5SDimitry Andric         // In case it was dead and already converted to declaration.
10570b57cec5SDimitry Andric         GV.isDeclaration())
10580b57cec5SDimitry Andric       return;
10598bcb0991SDimitry Andric 
1060*5f7ddb14SDimitry Andric     // Set the potentially more constraining visibility computed from summaries.
1061*5f7ddb14SDimitry Andric     // The DefaultVisibility condition is because older GlobalValueSummary does
1062*5f7ddb14SDimitry Andric     // not record DefaultVisibility and we don't want to change protected/hidden
1063*5f7ddb14SDimitry Andric     // to default.
1064*5f7ddb14SDimitry Andric     if (GS->second->getVisibility() != GlobalValue::DefaultVisibility)
1065*5f7ddb14SDimitry Andric       GV.setVisibility(GS->second->getVisibility());
1066*5f7ddb14SDimitry Andric 
1067*5f7ddb14SDimitry Andric     if (NewLinkage == GV.getLinkage())
1068*5f7ddb14SDimitry Andric       return;
1069*5f7ddb14SDimitry Andric 
10700b57cec5SDimitry Andric     // Check for a non-prevailing def that has interposable linkage
10710b57cec5SDimitry Andric     // (e.g. non-odr weak or linkonce). In that case we can't simply
10720b57cec5SDimitry Andric     // convert to available_externally, since it would lose the
10730b57cec5SDimitry Andric     // interposable property and possibly get inlined. Simply drop
10740b57cec5SDimitry Andric     // the definition in that case.
10750b57cec5SDimitry Andric     if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) &&
10760b57cec5SDimitry Andric         GlobalValue::isInterposableLinkage(GV.getLinkage())) {
10770b57cec5SDimitry Andric       if (!convertToDeclaration(GV))
10780b57cec5SDimitry Andric         // FIXME: Change this to collect replaced GVs and later erase
10790b57cec5SDimitry Andric         // them from the parent module once thinLTOResolvePrevailingGUID is
10800b57cec5SDimitry Andric         // changed to enable this for aliases.
10810b57cec5SDimitry Andric         llvm_unreachable("Expected GV to be converted");
10820b57cec5SDimitry Andric     } else {
10830b57cec5SDimitry Andric       // If all copies of the original symbol had global unnamed addr and
10840b57cec5SDimitry Andric       // linkonce_odr linkage, it should be an auto hide symbol. In that case
10850b57cec5SDimitry Andric       // the thin link would have marked it as CanAutoHide. Add hidden visibility
10860b57cec5SDimitry Andric       // to the symbol to preserve the property.
10870b57cec5SDimitry Andric       if (NewLinkage == GlobalValue::WeakODRLinkage &&
10880b57cec5SDimitry Andric           GS->second->canAutoHide()) {
10890b57cec5SDimitry Andric         assert(GV.hasLinkOnceODRLinkage() && GV.hasGlobalUnnamedAddr());
10900b57cec5SDimitry Andric         GV.setVisibility(GlobalValue::HiddenVisibility);
10910b57cec5SDimitry Andric       }
10920b57cec5SDimitry Andric 
10930b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName()
10940b57cec5SDimitry Andric                         << "` from " << GV.getLinkage() << " to " << NewLinkage
10950b57cec5SDimitry Andric                         << "\n");
10960b57cec5SDimitry Andric       GV.setLinkage(NewLinkage);
10970b57cec5SDimitry Andric     }
10980b57cec5SDimitry Andric     // Remove declarations from comdats, including available_externally
10990b57cec5SDimitry Andric     // as this is a declaration for the linker, and will be dropped eventually.
11000b57cec5SDimitry Andric     // It is illegal for comdats to contain declarations.
11010b57cec5SDimitry Andric     auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
11020b57cec5SDimitry Andric     if (GO && GO->isDeclarationForLinker() && GO->hasComdat())
11030b57cec5SDimitry Andric       GO->setComdat(nullptr);
11040b57cec5SDimitry Andric   };
11050b57cec5SDimitry Andric 
11060b57cec5SDimitry Andric   // Process functions and global now
11070b57cec5SDimitry Andric   for (auto &GV : TheModule)
11080b57cec5SDimitry Andric     updateLinkage(GV);
11090b57cec5SDimitry Andric   for (auto &GV : TheModule.globals())
11100b57cec5SDimitry Andric     updateLinkage(GV);
11110b57cec5SDimitry Andric   for (auto &GV : TheModule.aliases())
11120b57cec5SDimitry Andric     updateLinkage(GV);
11130b57cec5SDimitry Andric }
11140b57cec5SDimitry Andric 
11150b57cec5SDimitry Andric /// Run internalization on \p TheModule based on symmary analysis.
thinLTOInternalizeModule(Module & TheModule,const GVSummaryMapTy & DefinedGlobals)11160b57cec5SDimitry Andric void llvm::thinLTOInternalizeModule(Module &TheModule,
11170b57cec5SDimitry Andric                                     const GVSummaryMapTy &DefinedGlobals) {
11180b57cec5SDimitry Andric   // Declare a callback for the internalize pass that will ask for every
11190b57cec5SDimitry Andric   // candidate GlobalValue if it can be internalized or not.
11200b57cec5SDimitry Andric   auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
11210b57cec5SDimitry Andric     // Lookup the linkage recorded in the summaries during global analysis.
11220b57cec5SDimitry Andric     auto GS = DefinedGlobals.find(GV.getGUID());
11230b57cec5SDimitry Andric     if (GS == DefinedGlobals.end()) {
11240b57cec5SDimitry Andric       // Must have been promoted (possibly conservatively). Find original
11250b57cec5SDimitry Andric       // name so that we can access the correct summary and see if it can
11260b57cec5SDimitry Andric       // be internalized again.
11270b57cec5SDimitry Andric       // FIXME: Eventually we should control promotion instead of promoting
11280b57cec5SDimitry Andric       // and internalizing again.
11290b57cec5SDimitry Andric       StringRef OrigName =
11300b57cec5SDimitry Andric           ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName());
11310b57cec5SDimitry Andric       std::string OrigId = GlobalValue::getGlobalIdentifier(
11320b57cec5SDimitry Andric           OrigName, GlobalValue::InternalLinkage,
11330b57cec5SDimitry Andric           TheModule.getSourceFileName());
11340b57cec5SDimitry Andric       GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
11350b57cec5SDimitry Andric       if (GS == DefinedGlobals.end()) {
11360b57cec5SDimitry Andric         // Also check the original non-promoted non-globalized name. In some
11370b57cec5SDimitry Andric         // cases a preempted weak value is linked in as a local copy because
11380b57cec5SDimitry Andric         // it is referenced by an alias (IRLinker::linkGlobalValueProto).
11390b57cec5SDimitry Andric         // In that case, since it was originally not a local value, it was
11400b57cec5SDimitry Andric         // recorded in the index using the original name.
11410b57cec5SDimitry Andric         // FIXME: This may not be needed once PR27866 is fixed.
11420b57cec5SDimitry Andric         GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
11430b57cec5SDimitry Andric         assert(GS != DefinedGlobals.end());
11440b57cec5SDimitry Andric       }
11450b57cec5SDimitry Andric     }
11460b57cec5SDimitry Andric     return !GlobalValue::isLocalLinkage(GS->second->linkage());
11470b57cec5SDimitry Andric   };
11480b57cec5SDimitry Andric 
11490b57cec5SDimitry Andric   // FIXME: See if we can just internalize directly here via linkage changes
11500b57cec5SDimitry Andric   // based on the index, rather than invoking internalizeModule.
11510b57cec5SDimitry Andric   internalizeModule(TheModule, MustPreserveGV);
11520b57cec5SDimitry Andric }
11530b57cec5SDimitry Andric 
11540b57cec5SDimitry Andric /// Make alias a clone of its aliasee.
replaceAliasWithAliasee(Module * SrcModule,GlobalAlias * GA)11550b57cec5SDimitry Andric static Function *replaceAliasWithAliasee(Module *SrcModule, GlobalAlias *GA) {
11560b57cec5SDimitry Andric   Function *Fn = cast<Function>(GA->getBaseObject());
11570b57cec5SDimitry Andric 
11580b57cec5SDimitry Andric   ValueToValueMapTy VMap;
11590b57cec5SDimitry Andric   Function *NewFn = CloneFunction(Fn, VMap);
11600b57cec5SDimitry Andric   // Clone should use the original alias's linkage, visibility and name, and we
11610b57cec5SDimitry Andric   // ensure all uses of alias instead use the new clone (casted if necessary).
11620b57cec5SDimitry Andric   NewFn->setLinkage(GA->getLinkage());
11630b57cec5SDimitry Andric   NewFn->setVisibility(GA->getVisibility());
11640b57cec5SDimitry Andric   GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewFn, GA->getType()));
11650b57cec5SDimitry Andric   NewFn->takeName(GA);
11660b57cec5SDimitry Andric   return NewFn;
11670b57cec5SDimitry Andric }
11680b57cec5SDimitry Andric 
11690b57cec5SDimitry Andric // Internalize values that we marked with specific attribute
11700b57cec5SDimitry Andric // in processGlobalForThinLTO.
internalizeGVsAfterImport(Module & M)11710b57cec5SDimitry Andric static void internalizeGVsAfterImport(Module &M) {
11720b57cec5SDimitry Andric   for (auto &GV : M.globals())
11730b57cec5SDimitry Andric     // Skip GVs which have been converted to declarations
11740b57cec5SDimitry Andric     // by dropDeadSymbols.
11750b57cec5SDimitry Andric     if (!GV.isDeclaration() && GV.hasAttribute("thinlto-internalize")) {
11760b57cec5SDimitry Andric       GV.setLinkage(GlobalValue::InternalLinkage);
11770b57cec5SDimitry Andric       GV.setVisibility(GlobalValue::DefaultVisibility);
11780b57cec5SDimitry Andric     }
11790b57cec5SDimitry Andric }
11800b57cec5SDimitry Andric 
11810b57cec5SDimitry Andric // Automatically import functions in Module \p DestModule based on the summaries
11820b57cec5SDimitry Andric // index.
importFunctions(Module & DestModule,const FunctionImporter::ImportMapTy & ImportList)11830b57cec5SDimitry Andric Expected<bool> FunctionImporter::importFunctions(
11840b57cec5SDimitry Andric     Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
11850b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Starting import for Module "
11860b57cec5SDimitry Andric                     << DestModule.getModuleIdentifier() << "\n");
11870b57cec5SDimitry Andric   unsigned ImportedCount = 0, ImportedGVCount = 0;
11880b57cec5SDimitry Andric 
11890b57cec5SDimitry Andric   IRMover Mover(DestModule);
11900b57cec5SDimitry Andric   // Do the actual import of functions now, one Module at a time
11910b57cec5SDimitry Andric   std::set<StringRef> ModuleNameOrderedList;
11920b57cec5SDimitry Andric   for (auto &FunctionsToImportPerModule : ImportList) {
11930b57cec5SDimitry Andric     ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
11940b57cec5SDimitry Andric   }
11950b57cec5SDimitry Andric   for (auto &Name : ModuleNameOrderedList) {
11960b57cec5SDimitry Andric     // Get the module for the import
11970b57cec5SDimitry Andric     const auto &FunctionsToImportPerModule = ImportList.find(Name);
11980b57cec5SDimitry Andric     assert(FunctionsToImportPerModule != ImportList.end());
11990b57cec5SDimitry Andric     Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
12000b57cec5SDimitry Andric     if (!SrcModuleOrErr)
12010b57cec5SDimitry Andric       return SrcModuleOrErr.takeError();
12020b57cec5SDimitry Andric     std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
12030b57cec5SDimitry Andric     assert(&DestModule.getContext() == &SrcModule->getContext() &&
12040b57cec5SDimitry Andric            "Context mismatch");
12050b57cec5SDimitry Andric 
12060b57cec5SDimitry Andric     // If modules were created with lazy metadata loading, materialize it
12070b57cec5SDimitry Andric     // now, before linking it (otherwise this will be a noop).
12080b57cec5SDimitry Andric     if (Error Err = SrcModule->materializeMetadata())
12090b57cec5SDimitry Andric       return std::move(Err);
12100b57cec5SDimitry Andric 
12110b57cec5SDimitry Andric     auto &ImportGUIDs = FunctionsToImportPerModule->second;
12120b57cec5SDimitry Andric     // Find the globals to import
12130b57cec5SDimitry Andric     SetVector<GlobalValue *> GlobalsToImport;
12140b57cec5SDimitry Andric     for (Function &F : *SrcModule) {
12150b57cec5SDimitry Andric       if (!F.hasName())
12160b57cec5SDimitry Andric         continue;
12170b57cec5SDimitry Andric       auto GUID = F.getGUID();
12180b57cec5SDimitry Andric       auto Import = ImportGUIDs.count(GUID);
12190b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function "
12200b57cec5SDimitry Andric                         << GUID << " " << F.getName() << " from "
12210b57cec5SDimitry Andric                         << SrcModule->getSourceFileName() << "\n");
12220b57cec5SDimitry Andric       if (Import) {
12230b57cec5SDimitry Andric         if (Error Err = F.materialize())
12240b57cec5SDimitry Andric           return std::move(Err);
12250b57cec5SDimitry Andric         if (EnableImportMetadata) {
12260b57cec5SDimitry Andric           // Add 'thinlto_src_module' metadata for statistics and debugging.
12270b57cec5SDimitry Andric           F.setMetadata(
12280b57cec5SDimitry Andric               "thinlto_src_module",
12290b57cec5SDimitry Andric               MDNode::get(DestModule.getContext(),
12300b57cec5SDimitry Andric                           {MDString::get(DestModule.getContext(),
12310b57cec5SDimitry Andric                                          SrcModule->getSourceFileName())}));
12320b57cec5SDimitry Andric         }
12330b57cec5SDimitry Andric         GlobalsToImport.insert(&F);
12340b57cec5SDimitry Andric       }
12350b57cec5SDimitry Andric     }
12360b57cec5SDimitry Andric     for (GlobalVariable &GV : SrcModule->globals()) {
12370b57cec5SDimitry Andric       if (!GV.hasName())
12380b57cec5SDimitry Andric         continue;
12390b57cec5SDimitry Andric       auto GUID = GV.getGUID();
12400b57cec5SDimitry Andric       auto Import = ImportGUIDs.count(GUID);
12410b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global "
12420b57cec5SDimitry Andric                         << GUID << " " << GV.getName() << " from "
12430b57cec5SDimitry Andric                         << SrcModule->getSourceFileName() << "\n");
12440b57cec5SDimitry Andric       if (Import) {
12450b57cec5SDimitry Andric         if (Error Err = GV.materialize())
12460b57cec5SDimitry Andric           return std::move(Err);
12470b57cec5SDimitry Andric         ImportedGVCount += GlobalsToImport.insert(&GV);
12480b57cec5SDimitry Andric       }
12490b57cec5SDimitry Andric     }
12500b57cec5SDimitry Andric     for (GlobalAlias &GA : SrcModule->aliases()) {
12510b57cec5SDimitry Andric       if (!GA.hasName())
12520b57cec5SDimitry Andric         continue;
12530b57cec5SDimitry Andric       auto GUID = GA.getGUID();
12540b57cec5SDimitry Andric       auto Import = ImportGUIDs.count(GUID);
12550b57cec5SDimitry Andric       LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias "
12560b57cec5SDimitry Andric                         << GUID << " " << GA.getName() << " from "
12570b57cec5SDimitry Andric                         << SrcModule->getSourceFileName() << "\n");
12580b57cec5SDimitry Andric       if (Import) {
12590b57cec5SDimitry Andric         if (Error Err = GA.materialize())
12600b57cec5SDimitry Andric           return std::move(Err);
12610b57cec5SDimitry Andric         // Import alias as a copy of its aliasee.
12620b57cec5SDimitry Andric         GlobalObject *Base = GA.getBaseObject();
12630b57cec5SDimitry Andric         if (Error Err = Base->materialize())
12640b57cec5SDimitry Andric           return std::move(Err);
12650b57cec5SDimitry Andric         auto *Fn = replaceAliasWithAliasee(SrcModule.get(), &GA);
12660b57cec5SDimitry Andric         LLVM_DEBUG(dbgs() << "Is importing aliasee fn " << Base->getGUID()
12670b57cec5SDimitry Andric                           << " " << Base->getName() << " from "
12680b57cec5SDimitry Andric                           << SrcModule->getSourceFileName() << "\n");
12690b57cec5SDimitry Andric         if (EnableImportMetadata) {
12700b57cec5SDimitry Andric           // Add 'thinlto_src_module' metadata for statistics and debugging.
12710b57cec5SDimitry Andric           Fn->setMetadata(
12720b57cec5SDimitry Andric               "thinlto_src_module",
12730b57cec5SDimitry Andric               MDNode::get(DestModule.getContext(),
12740b57cec5SDimitry Andric                           {MDString::get(DestModule.getContext(),
12750b57cec5SDimitry Andric                                          SrcModule->getSourceFileName())}));
12760b57cec5SDimitry Andric         }
12770b57cec5SDimitry Andric         GlobalsToImport.insert(Fn);
12780b57cec5SDimitry Andric       }
12790b57cec5SDimitry Andric     }
12800b57cec5SDimitry Andric 
12810b57cec5SDimitry Andric     // Upgrade debug info after we're done materializing all the globals and we
12820b57cec5SDimitry Andric     // have loaded all the required metadata!
12830b57cec5SDimitry Andric     UpgradeDebugInfo(*SrcModule);
12840b57cec5SDimitry Andric 
12855ffd83dbSDimitry Andric     // Set the partial sample profile ratio in the profile summary module flag
12865ffd83dbSDimitry Andric     // of the imported source module, if applicable, so that the profile summary
12875ffd83dbSDimitry Andric     // module flag will match with that of the destination module when it's
12885ffd83dbSDimitry Andric     // imported.
12895ffd83dbSDimitry Andric     SrcModule->setPartialSampleProfileRatio(Index);
12905ffd83dbSDimitry Andric 
12910b57cec5SDimitry Andric     // Link in the specified functions.
12925ffd83dbSDimitry Andric     if (renameModuleForThinLTO(*SrcModule, Index, ClearDSOLocalOnDeclarations,
12935ffd83dbSDimitry Andric                                &GlobalsToImport))
12940b57cec5SDimitry Andric       return true;
12950b57cec5SDimitry Andric 
12960b57cec5SDimitry Andric     if (PrintImports) {
12970b57cec5SDimitry Andric       for (const auto *GV : GlobalsToImport)
12980b57cec5SDimitry Andric         dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
12990b57cec5SDimitry Andric                << " from " << SrcModule->getSourceFileName() << "\n";
13000b57cec5SDimitry Andric     }
13010b57cec5SDimitry Andric 
13025ffd83dbSDimitry Andric     if (Error Err = Mover.move(
13035ffd83dbSDimitry Andric             std::move(SrcModule), GlobalsToImport.getArrayRef(),
13040b57cec5SDimitry Andric             [](GlobalValue &, IRMover::ValueAdder) {},
13050b57cec5SDimitry Andric             /*IsPerformingImport=*/true))
13065ffd83dbSDimitry Andric       report_fatal_error("Function Import: link error: " +
13075ffd83dbSDimitry Andric                          toString(std::move(Err)));
13080b57cec5SDimitry Andric 
13090b57cec5SDimitry Andric     ImportedCount += GlobalsToImport.size();
13100b57cec5SDimitry Andric     NumImportedModules++;
13110b57cec5SDimitry Andric   }
13120b57cec5SDimitry Andric 
13130b57cec5SDimitry Andric   internalizeGVsAfterImport(DestModule);
13140b57cec5SDimitry Andric 
13150b57cec5SDimitry Andric   NumImportedFunctions += (ImportedCount - ImportedGVCount);
13160b57cec5SDimitry Andric   NumImportedGlobalVars += ImportedGVCount;
13170b57cec5SDimitry Andric 
13180b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Imported " << ImportedCount - ImportedGVCount
13190b57cec5SDimitry Andric                     << " functions for Module "
13200b57cec5SDimitry Andric                     << DestModule.getModuleIdentifier() << "\n");
13210b57cec5SDimitry Andric   LLVM_DEBUG(dbgs() << "Imported " << ImportedGVCount
13220b57cec5SDimitry Andric                     << " global variables for Module "
13230b57cec5SDimitry Andric                     << DestModule.getModuleIdentifier() << "\n");
13240b57cec5SDimitry Andric   return ImportedCount;
13250b57cec5SDimitry Andric }
13260b57cec5SDimitry Andric 
doImportingForModule(Module & M)13270b57cec5SDimitry Andric static bool doImportingForModule(Module &M) {
13280b57cec5SDimitry Andric   if (SummaryFile.empty())
13290b57cec5SDimitry Andric     report_fatal_error("error: -function-import requires -summary-file\n");
13300b57cec5SDimitry Andric   Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr =
13310b57cec5SDimitry Andric       getModuleSummaryIndexForFile(SummaryFile);
13320b57cec5SDimitry Andric   if (!IndexPtrOrErr) {
13330b57cec5SDimitry Andric     logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
13340b57cec5SDimitry Andric                           "Error loading file '" + SummaryFile + "': ");
13350b57cec5SDimitry Andric     return false;
13360b57cec5SDimitry Andric   }
13370b57cec5SDimitry Andric   std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
13380b57cec5SDimitry Andric 
13390b57cec5SDimitry Andric   // First step is collecting the import list.
13400b57cec5SDimitry Andric   FunctionImporter::ImportMapTy ImportList;
13410b57cec5SDimitry Andric   // If requested, simply import all functions in the index. This is used
13420b57cec5SDimitry Andric   // when testing distributed backend handling via the opt tool, when
13430b57cec5SDimitry Andric   // we have distributed indexes containing exactly the summaries to import.
13440b57cec5SDimitry Andric   if (ImportAllIndex)
13450b57cec5SDimitry Andric     ComputeCrossModuleImportForModuleFromIndex(M.getModuleIdentifier(), *Index,
13460b57cec5SDimitry Andric                                                ImportList);
13470b57cec5SDimitry Andric   else
13480b57cec5SDimitry Andric     ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index,
13490b57cec5SDimitry Andric                                       ImportList);
13500b57cec5SDimitry Andric 
13510b57cec5SDimitry Andric   // Conservatively mark all internal values as promoted. This interface is
13520b57cec5SDimitry Andric   // only used when doing importing via the function importing pass. The pass
13530b57cec5SDimitry Andric   // is only enabled when testing importing via the 'opt' tool, which does
13540b57cec5SDimitry Andric   // not do the ThinLink that would normally determine what values to promote.
13550b57cec5SDimitry Andric   for (auto &I : *Index) {
13560b57cec5SDimitry Andric     for (auto &S : I.second.SummaryList) {
13570b57cec5SDimitry Andric       if (GlobalValue::isLocalLinkage(S->linkage()))
13580b57cec5SDimitry Andric         S->setLinkage(GlobalValue::ExternalLinkage);
13590b57cec5SDimitry Andric     }
13600b57cec5SDimitry Andric   }
13610b57cec5SDimitry Andric 
13620b57cec5SDimitry Andric   // Next we need to promote to global scope and rename any local values that
13630b57cec5SDimitry Andric   // are potentially exported to other modules.
1364af732203SDimitry Andric   if (renameModuleForThinLTO(M, *Index, /*ClearDSOLocalOnDeclarations=*/false,
13655ffd83dbSDimitry Andric                              /*GlobalsToImport=*/nullptr)) {
13660b57cec5SDimitry Andric     errs() << "Error renaming module\n";
13670b57cec5SDimitry Andric     return false;
13680b57cec5SDimitry Andric   }
13690b57cec5SDimitry Andric 
13700b57cec5SDimitry Andric   // Perform the import now.
13710b57cec5SDimitry Andric   auto ModuleLoader = [&M](StringRef Identifier) {
13725ffd83dbSDimitry Andric     return loadFile(std::string(Identifier), M.getContext());
13730b57cec5SDimitry Andric   };
13745ffd83dbSDimitry Andric   FunctionImporter Importer(*Index, ModuleLoader,
13755ffd83dbSDimitry Andric                             /*ClearDSOLocalOnDeclarations=*/false);
13760b57cec5SDimitry Andric   Expected<bool> Result = Importer.importFunctions(M, ImportList);
13770b57cec5SDimitry Andric 
13780b57cec5SDimitry Andric   // FIXME: Probably need to propagate Errors through the pass manager.
13790b57cec5SDimitry Andric   if (!Result) {
13800b57cec5SDimitry Andric     logAllUnhandledErrors(Result.takeError(), errs(),
13810b57cec5SDimitry Andric                           "Error importing module: ");
13820b57cec5SDimitry Andric     return false;
13830b57cec5SDimitry Andric   }
13840b57cec5SDimitry Andric 
13850b57cec5SDimitry Andric   return *Result;
13860b57cec5SDimitry Andric }
13870b57cec5SDimitry Andric 
13880b57cec5SDimitry Andric namespace {
13890b57cec5SDimitry Andric 
13900b57cec5SDimitry Andric /// Pass that performs cross-module function import provided a summary file.
13910b57cec5SDimitry Andric class FunctionImportLegacyPass : public ModulePass {
13920b57cec5SDimitry Andric public:
13930b57cec5SDimitry Andric   /// Pass identification, replacement for typeid
13940b57cec5SDimitry Andric   static char ID;
13950b57cec5SDimitry Andric 
FunctionImportLegacyPass()13960b57cec5SDimitry Andric   explicit FunctionImportLegacyPass() : ModulePass(ID) {}
13970b57cec5SDimitry Andric 
13980b57cec5SDimitry Andric   /// Specify pass name for debug output
getPassName() const13990b57cec5SDimitry Andric   StringRef getPassName() const override { return "Function Importing"; }
14000b57cec5SDimitry Andric 
runOnModule(Module & M)14010b57cec5SDimitry Andric   bool runOnModule(Module &M) override {
14020b57cec5SDimitry Andric     if (skipModule(M))
14030b57cec5SDimitry Andric       return false;
14040b57cec5SDimitry Andric 
14050b57cec5SDimitry Andric     return doImportingForModule(M);
14060b57cec5SDimitry Andric   }
14070b57cec5SDimitry Andric };
14080b57cec5SDimitry Andric 
14090b57cec5SDimitry Andric } // end anonymous namespace
14100b57cec5SDimitry Andric 
run(Module & M,ModuleAnalysisManager & AM)14110b57cec5SDimitry Andric PreservedAnalyses FunctionImportPass::run(Module &M,
14120b57cec5SDimitry Andric                                           ModuleAnalysisManager &AM) {
14130b57cec5SDimitry Andric   if (!doImportingForModule(M))
14140b57cec5SDimitry Andric     return PreservedAnalyses::all();
14150b57cec5SDimitry Andric 
14160b57cec5SDimitry Andric   return PreservedAnalyses::none();
14170b57cec5SDimitry Andric }
14180b57cec5SDimitry Andric 
14190b57cec5SDimitry Andric char FunctionImportLegacyPass::ID = 0;
14200b57cec5SDimitry Andric INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
14210b57cec5SDimitry Andric                 "Summary Based Function Import", false, false)
14220b57cec5SDimitry Andric 
14230b57cec5SDimitry Andric namespace llvm {
14240b57cec5SDimitry Andric 
createFunctionImportPass()14250b57cec5SDimitry Andric Pass *createFunctionImportPass() {
14260b57cec5SDimitry Andric   return new FunctionImportLegacyPass();
14270b57cec5SDimitry Andric }
14280b57cec5SDimitry Andric 
14290b57cec5SDimitry Andric } // end namespace llvm
1430