142418abaSMehdi Amini //===- FunctionImport.cpp - ThinLTO Summary-based Function Import ---------===// 242418abaSMehdi Amini // 32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information. 52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 642418abaSMehdi Amini // 742418abaSMehdi Amini //===----------------------------------------------------------------------===// 842418abaSMehdi Amini // 942418abaSMehdi Amini // This file implements Function import based on summaries. 1042418abaSMehdi Amini // 1142418abaSMehdi Amini //===----------------------------------------------------------------------===// 1242418abaSMehdi Amini 1342418abaSMehdi Amini #include "llvm/Transforms/IPO/FunctionImport.h" 14e9ea08a0SEugene Zelenko #include "llvm/ADT/ArrayRef.h" 15e9ea08a0SEugene Zelenko #include "llvm/ADT/STLExtras.h" 16e9ea08a0SEugene Zelenko #include "llvm/ADT/SetVector.h" 1701e32130SMehdi Amini #include "llvm/ADT/SmallVector.h" 18d29478f7STeresa Johnson #include "llvm/ADT/Statistic.h" 19e9ea08a0SEugene Zelenko #include "llvm/ADT/StringMap.h" 200efed325SSimon Pilgrim #include "llvm/ADT/StringRef.h" 21b040fcc6SCharles Saternos #include "llvm/ADT/StringSet.h" 22c15d60b7SPeter Collingbourne #include "llvm/Bitcode/BitcodeReader.h" 2342418abaSMehdi Amini #include "llvm/IR/AutoUpgrade.h" 2481bbf742STeresa Johnson #include "llvm/IR/Constants.h" 25e9ea08a0SEugene Zelenko #include "llvm/IR/Function.h" 26e9ea08a0SEugene Zelenko #include "llvm/IR/GlobalAlias.h" 27e9ea08a0SEugene Zelenko #include "llvm/IR/GlobalObject.h" 28e9ea08a0SEugene Zelenko #include "llvm/IR/GlobalValue.h" 29e9ea08a0SEugene Zelenko #include "llvm/IR/GlobalVariable.h" 30e9ea08a0SEugene Zelenko #include "llvm/IR/Metadata.h" 3142418abaSMehdi Amini #include "llvm/IR/Module.h" 32e9ea08a0SEugene Zelenko #include "llvm/IR/ModuleSummaryIndex.h" 3342418abaSMehdi Amini #include "llvm/IRReader/IRReader.h" 3405da2fe5SReid Kleckner #include "llvm/InitializePasses.h" 35e9ea08a0SEugene Zelenko #include "llvm/Linker/IRMover.h" 36e9ea08a0SEugene Zelenko #include "llvm/Object/ModuleSymbolTable.h" 37e9ea08a0SEugene Zelenko #include "llvm/Object/SymbolicFile.h" 38e9ea08a0SEugene Zelenko #include "llvm/Pass.h" 39e9ea08a0SEugene Zelenko #include "llvm/Support/Casting.h" 4042418abaSMehdi Amini #include "llvm/Support/CommandLine.h" 4142418abaSMehdi Amini #include "llvm/Support/Debug.h" 42e9ea08a0SEugene Zelenko #include "llvm/Support/Error.h" 43e9ea08a0SEugene Zelenko #include "llvm/Support/ErrorHandling.h" 44e9ea08a0SEugene Zelenko #include "llvm/Support/FileSystem.h" 4542418abaSMehdi Amini #include "llvm/Support/SourceMgr.h" 46e9ea08a0SEugene Zelenko #include "llvm/Support/raw_ostream.h" 4704c9a2d6STeresa Johnson #include "llvm/Transforms/IPO/Internalize.h" 4881bbf742STeresa Johnson #include "llvm/Transforms/Utils/Cloning.h" 49488a800aSTeresa Johnson #include "llvm/Transforms/Utils/FunctionImportUtils.h" 5081bbf742STeresa Johnson #include "llvm/Transforms/Utils/ValueMapper.h" 51e9ea08a0SEugene Zelenko #include <cassert> 52e9ea08a0SEugene Zelenko #include <memory> 53e9ea08a0SEugene Zelenko #include <set> 54e9ea08a0SEugene Zelenko #include <string> 55e9ea08a0SEugene Zelenko #include <system_error> 56e9ea08a0SEugene Zelenko #include <tuple> 57e9ea08a0SEugene Zelenko #include <utility> 587e88d0daSMehdi Amini 5942418abaSMehdi Amini using namespace llvm; 6042418abaSMehdi Amini 61e9ea08a0SEugene Zelenko #define DEBUG_TYPE "function-import" 62e9ea08a0SEugene Zelenko 63d2c234a4STeresa Johnson STATISTIC(NumImportedFunctionsThinLink, 64d2c234a4STeresa Johnson "Number of functions thin link decided to import"); 65d2c234a4STeresa Johnson STATISTIC(NumImportedHotFunctionsThinLink, 66d2c234a4STeresa Johnson "Number of hot functions thin link decided to import"); 67d2c234a4STeresa Johnson STATISTIC(NumImportedCriticalFunctionsThinLink, 68d2c234a4STeresa Johnson "Number of critical functions thin link decided to import"); 69d2c234a4STeresa Johnson STATISTIC(NumImportedGlobalVarsThinLink, 70d2c234a4STeresa Johnson "Number of global variables thin link decided to import"); 71d2c234a4STeresa Johnson STATISTIC(NumImportedFunctions, "Number of functions imported in backend"); 72d2c234a4STeresa Johnson STATISTIC(NumImportedGlobalVars, 73d2c234a4STeresa Johnson "Number of global variables imported in backend"); 746c475a75STeresa Johnson STATISTIC(NumImportedModules, "Number of modules imported from"); 756c475a75STeresa Johnson STATISTIC(NumDeadSymbols, "Number of dead stripped symbols in index"); 766c475a75STeresa Johnson STATISTIC(NumLiveSymbols, "Number of live symbols in index"); 77d29478f7STeresa Johnson 7839303619STeresa Johnson /// Limit on instruction count of imported functions. 7939303619STeresa Johnson static cl::opt<unsigned> ImportInstrLimit( 8039303619STeresa Johnson "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"), 8139303619STeresa Johnson cl::desc("Only import functions with less than N instructions")); 8239303619STeresa Johnson 83974706ebSTeresa Johnson static cl::opt<int> ImportCutoff( 84974706ebSTeresa Johnson "import-cutoff", cl::init(-1), cl::Hidden, cl::value_desc("N"), 85974706ebSTeresa Johnson cl::desc("Only import first N functions if N>=0 (default -1)")); 86974706ebSTeresa Johnson 8740641748SMehdi Amini static cl::opt<float> 8840641748SMehdi Amini ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7), 8940641748SMehdi Amini cl::Hidden, cl::value_desc("x"), 9040641748SMehdi Amini cl::desc("As we import functions, multiply the " 9140641748SMehdi Amini "`import-instr-limit` threshold by this factor " 9240641748SMehdi Amini "before processing newly imported functions")); 93ba72b95fSPiotr Padlewski 94d2869473SPiotr Padlewski static cl::opt<float> ImportHotInstrFactor( 95d2869473SPiotr Padlewski "import-hot-evolution-factor", cl::init(1.0), cl::Hidden, 96d2869473SPiotr Padlewski cl::value_desc("x"), 97d2869473SPiotr Padlewski cl::desc("As we import functions called from hot callsite, multiply the " 98d2869473SPiotr Padlewski "`import-instr-limit` threshold by this factor " 99d2869473SPiotr Padlewski "before processing newly imported functions")); 100d2869473SPiotr Padlewski 101d9830eb7SPiotr Padlewski static cl::opt<float> ImportHotMultiplier( 1028260d665SDehao Chen "import-hot-multiplier", cl::init(10.0), cl::Hidden, cl::value_desc("x"), 103ba72b95fSPiotr Padlewski cl::desc("Multiply the `import-instr-limit` threshold for hot callsites")); 104ba72b95fSPiotr Padlewski 10564c46574SDehao Chen static cl::opt<float> ImportCriticalMultiplier( 10664c46574SDehao Chen "import-critical-multiplier", cl::init(100.0), cl::Hidden, 10764c46574SDehao Chen cl::value_desc("x"), 10864c46574SDehao Chen cl::desc( 10964c46574SDehao Chen "Multiply the `import-instr-limit` threshold for critical callsites")); 11064c46574SDehao Chen 111ba72b95fSPiotr Padlewski // FIXME: This multiplier was not really tuned up. 112ba72b95fSPiotr Padlewski static cl::opt<float> ImportColdMultiplier( 113ba72b95fSPiotr Padlewski "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"), 114ba72b95fSPiotr Padlewski cl::desc("Multiply the `import-instr-limit` threshold for cold callsites")); 11540641748SMehdi Amini 116d29478f7STeresa Johnson static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden, 117d29478f7STeresa Johnson cl::desc("Print imported functions")); 118d29478f7STeresa Johnson 119cb9a82fcSTeresa Johnson static cl::opt<bool> PrintImportFailures( 120cb9a82fcSTeresa Johnson "print-import-failures", cl::init(false), cl::Hidden, 121cb9a82fcSTeresa Johnson cl::desc("Print information for functions rejected for importing")); 122cb9a82fcSTeresa Johnson 1236c475a75STeresa Johnson static cl::opt<bool> ComputeDead("compute-dead", cl::init(true), cl::Hidden, 1246c475a75STeresa Johnson cl::desc("Compute dead symbols")); 1256c475a75STeresa Johnson 1263b776128SPiotr Padlewski static cl::opt<bool> EnableImportMetadata( 1273b776128SPiotr Padlewski "enable-import-metadata", cl::init( 1283b776128SPiotr Padlewski #if !defined(NDEBUG) 1293b776128SPiotr Padlewski true /*Enabled with asserts.*/ 1303b776128SPiotr Padlewski #else 1313b776128SPiotr Padlewski false 1323b776128SPiotr Padlewski #endif 1333b776128SPiotr Padlewski ), 1343b776128SPiotr Padlewski cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'")); 1353b776128SPiotr Padlewski 136e9ea08a0SEugene Zelenko /// Summary file to use for function importing when using -function-import from 137e9ea08a0SEugene Zelenko /// the command line. 138e9ea08a0SEugene Zelenko static cl::opt<std::string> 139e9ea08a0SEugene Zelenko SummaryFile("summary-file", 140e9ea08a0SEugene Zelenko cl::desc("The summary file to use for function importing.")); 141e9ea08a0SEugene Zelenko 14281bbf742STeresa Johnson /// Used when testing importing from distributed indexes via opt 14381bbf742STeresa Johnson // -function-import. 14481bbf742STeresa Johnson static cl::opt<bool> 14581bbf742STeresa Johnson ImportAllIndex("import-all-index", 14681bbf742STeresa Johnson cl::desc("Import all external functions in index.")); 14781bbf742STeresa Johnson 14842418abaSMehdi Amini // Load lazily a module from \p FileName in \p Context. 14942418abaSMehdi Amini static std::unique_ptr<Module> loadFile(const std::string &FileName, 15042418abaSMehdi Amini LLVMContext &Context) { 15142418abaSMehdi Amini SMDiagnostic Err; 152d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Loading '" << FileName << "'\n"); 1536cba37ceSTeresa Johnson // Metadata isn't loaded until functions are imported, to minimize 1546cba37ceSTeresa Johnson // the memory overhead. 155a1080ee6STeresa Johnson std::unique_ptr<Module> Result = 156a1080ee6STeresa Johnson getLazyIRFileModule(FileName, Err, Context, 157a1080ee6STeresa Johnson /* ShouldLazyLoadMetadata = */ true); 15842418abaSMehdi Amini if (!Result) { 15942418abaSMehdi Amini Err.print("function-import", errs()); 160d7ad221cSMehdi Amini report_fatal_error("Abort"); 16142418abaSMehdi Amini } 16242418abaSMehdi Amini 16342418abaSMehdi Amini return Result; 16442418abaSMehdi Amini } 16542418abaSMehdi Amini 16601e32130SMehdi Amini /// Given a list of possible callee implementation for a call site, select one 16701e32130SMehdi Amini /// that fits the \p Threshold. 16801e32130SMehdi Amini /// 16901e32130SMehdi Amini /// FIXME: select "best" instead of first that fits. But what is "best"? 17001e32130SMehdi Amini /// - The smallest: more likely to be inlined. 17101e32130SMehdi Amini /// - The one with the least outgoing edges (already well optimized). 17201e32130SMehdi Amini /// - One from a module already being imported from in order to reduce the 17301e32130SMehdi Amini /// number of source modules parsed/linked. 17401e32130SMehdi Amini /// - One that has PGO data attached. 17501e32130SMehdi Amini /// - [insert you fancy metric here] 1762d28f7aaSMehdi Amini static const GlobalValueSummary * 177b4e1e829SMehdi Amini selectCallee(const ModuleSummaryIndex &Index, 1789667b91bSPeter Collingbourne ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList, 179cb9a82fcSTeresa Johnson unsigned Threshold, StringRef CallerModulePath, 180cb9a82fcSTeresa Johnson FunctionImporter::ImportFailureReason &Reason, 181cb9a82fcSTeresa Johnson GlobalValue::GUID GUID) { 182cb9a82fcSTeresa Johnson Reason = FunctionImporter::ImportFailureReason::None; 18301e32130SMehdi Amini auto It = llvm::find_if( 18428e457bcSTeresa Johnson CalleeSummaryList, 18528e457bcSTeresa Johnson [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) { 18628e457bcSTeresa Johnson auto *GVSummary = SummaryPtr.get(); 187cb9a82fcSTeresa Johnson if (!Index.isGlobalValueLive(GVSummary)) { 188cb9a82fcSTeresa Johnson Reason = FunctionImporter::ImportFailureReason::NotLive; 189eaf5172cSGeorge Rimar return false; 190cb9a82fcSTeresa Johnson } 191eaf5172cSGeorge Rimar 19273305f82STeresa Johnson // For SamplePGO, in computeImportForFunction the OriginalId 19373305f82STeresa Johnson // may have been used to locate the callee summary list (See 19473305f82STeresa Johnson // comment there). 19573305f82STeresa Johnson // The mapping from OriginalId to GUID may return a GUID 19673305f82STeresa Johnson // that corresponds to a static variable. Filter it out here. 19773305f82STeresa Johnson // This can happen when 19873305f82STeresa Johnson // 1) There is a call to a library function which is not defined 19973305f82STeresa Johnson // in the index. 20073305f82STeresa Johnson // 2) There is a static variable with the OriginalGUID identical 20173305f82STeresa Johnson // to the GUID of the library function in 1); 20273305f82STeresa Johnson // When this happens, the logic for SamplePGO kicks in and 20373305f82STeresa Johnson // the static variable in 2) will be found, which needs to be 20473305f82STeresa Johnson // filtered out. 205cb9a82fcSTeresa Johnson if (GVSummary->getSummaryKind() == GlobalValueSummary::GlobalVarKind) { 206cb9a82fcSTeresa Johnson Reason = FunctionImporter::ImportFailureReason::GlobalVar; 20773305f82STeresa Johnson return false; 208cb9a82fcSTeresa Johnson } 209cb9a82fcSTeresa Johnson if (GlobalValue::isInterposableLinkage(GVSummary->linkage())) { 210cb9a82fcSTeresa Johnson Reason = FunctionImporter::ImportFailureReason::InterposableLinkage; 2115b85d8d6SMehdi Amini // There is no point in importing these, we can't inline them 21201e32130SMehdi Amini return false; 213cb9a82fcSTeresa Johnson } 2142c719cc1SMehdi Amini 21581bbf742STeresa Johnson auto *Summary = cast<FunctionSummary>(GVSummary->getBaseObject()); 2167e88d0daSMehdi Amini 21783aaf358STeresa Johnson // If this is a local function, make sure we import the copy 21883aaf358STeresa Johnson // in the caller's module. The only time a local function can 21983aaf358STeresa Johnson // share an entry in the index is if there is a local with the same name 22083aaf358STeresa Johnson // in another module that had the same source file name (in a different 22183aaf358STeresa Johnson // directory), where each was compiled in their own directory so there 22283aaf358STeresa Johnson // was not distinguishing path. 22383aaf358STeresa Johnson // However, do the import from another module if there is only one 22483aaf358STeresa Johnson // entry in the list - in that case this must be a reference due 22583aaf358STeresa Johnson // to indirect call profile data, since a function pointer can point to 22683aaf358STeresa Johnson // a local in another module. 22783aaf358STeresa Johnson if (GlobalValue::isLocalLinkage(Summary->linkage()) && 22883aaf358STeresa Johnson CalleeSummaryList.size() > 1 && 229cb9a82fcSTeresa Johnson Summary->modulePath() != CallerModulePath) { 230cb9a82fcSTeresa Johnson Reason = 231cb9a82fcSTeresa Johnson FunctionImporter::ImportFailureReason::LocalLinkageNotInModule; 23283aaf358STeresa Johnson return false; 233cb9a82fcSTeresa Johnson } 23483aaf358STeresa Johnson 235b11391bbSTeresa Johnson if ((Summary->instCount() > Threshold) && 236b11391bbSTeresa Johnson !Summary->fflags().AlwaysInline) { 237cb9a82fcSTeresa Johnson Reason = FunctionImporter::ImportFailureReason::TooLarge; 238f9dc3deaSTeresa Johnson return false; 239cb9a82fcSTeresa Johnson } 240f9dc3deaSTeresa Johnson 241cb397461STeresa Johnson // Skip if it isn't legal to import (e.g. may reference unpromotable 242cb397461STeresa Johnson // locals). 243cb9a82fcSTeresa Johnson if (Summary->notEligibleToImport()) { 244cb9a82fcSTeresa Johnson Reason = FunctionImporter::ImportFailureReason::NotEligible; 245b4e1e829SMehdi Amini return false; 246cb9a82fcSTeresa Johnson } 247b4e1e829SMehdi Amini 248cb397461STeresa Johnson // Don't bother importing if we can't inline it anyway. 249cb397461STeresa Johnson if (Summary->fflags().NoInline) { 250cb397461STeresa Johnson Reason = FunctionImporter::ImportFailureReason::NoInline; 251cb397461STeresa Johnson return false; 252cb397461STeresa Johnson } 253cb397461STeresa Johnson 25401e32130SMehdi Amini return true; 25501e32130SMehdi Amini }); 25628e457bcSTeresa Johnson if (It == CalleeSummaryList.end()) 25701e32130SMehdi Amini return nullptr; 2587e88d0daSMehdi Amini 259f9dc3deaSTeresa Johnson return cast<GlobalValueSummary>(It->get()); 260434e9561SRafael Espindola } 2617e88d0daSMehdi Amini 262e9ea08a0SEugene Zelenko namespace { 263e9ea08a0SEugene Zelenko 264475b51a7STeresa Johnson using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */, 265475b51a7STeresa Johnson GlobalValue::GUID>; 26601e32130SMehdi Amini 267e9ea08a0SEugene Zelenko } // anonymous namespace 268e9ea08a0SEugene Zelenko 2691958083dSTeresa Johnson static ValueInfo 2701958083dSTeresa Johnson updateValueInfoForIndirectCalls(const ModuleSummaryIndex &Index, ValueInfo VI) { 2711958083dSTeresa Johnson if (!VI.getSummaryList().empty()) 2721958083dSTeresa Johnson return VI; 2731958083dSTeresa Johnson // For SamplePGO, the indirect call targets for local functions will 2741958083dSTeresa Johnson // have its original name annotated in profile. We try to find the 2751958083dSTeresa Johnson // corresponding PGOFuncName as the GUID. 2761958083dSTeresa Johnson // FIXME: Consider updating the edges in the graph after building 2771958083dSTeresa Johnson // it, rather than needing to perform this mapping on each walk. 2781958083dSTeresa Johnson auto GUID = Index.getGUIDFromOriginalID(VI.getGUID()); 2791958083dSTeresa Johnson if (GUID == 0) 28028d8a49fSEugene Leviant return ValueInfo(); 2811958083dSTeresa Johnson return Index.getValueInfo(GUID); 2821958083dSTeresa Johnson } 2831958083dSTeresa Johnson 28419e23874SEugene Leviant static void computeImportForReferencedGlobals( 285dde58938Sevgeny const FunctionSummary &Summary, const ModuleSummaryIndex &Index, 286dde58938Sevgeny const GVSummaryMapTy &DefinedGVSummaries, 28719e23874SEugene Leviant FunctionImporter::ImportMapTy &ImportList, 28819e23874SEugene Leviant StringMap<FunctionImporter::ExportSetTy> *ExportLists) { 28919e23874SEugene Leviant for (auto &VI : Summary.refs()) { 29019e23874SEugene Leviant if (DefinedGVSummaries.count(VI.getGUID())) { 291d34e60caSNicola Zaghen LLVM_DEBUG( 292d34e60caSNicola Zaghen dbgs() << "Ref ignored! Target already in destination module.\n"); 29319e23874SEugene Leviant continue; 29419e23874SEugene Leviant } 29519e23874SEugene Leviant 2967e7b13d0STeresa Johnson LLVM_DEBUG(dbgs() << " ref -> " << VI << "\n"); 29719e23874SEugene Leviant 29893f99962STeresa Johnson // If this is a local variable, make sure we import the copy 29993f99962STeresa Johnson // in the caller's module. The only time a local variable can 30093f99962STeresa Johnson // share an entry in the index is if there is a local with the same name 30193f99962STeresa Johnson // in another module that had the same source file name (in a different 30293f99962STeresa Johnson // directory), where each was compiled in their own directory so there 30393f99962STeresa Johnson // was not distinguishing path. 30493f99962STeresa Johnson auto LocalNotInModule = [&](const GlobalValueSummary *RefSummary) -> bool { 30593f99962STeresa Johnson return GlobalValue::isLocalLinkage(RefSummary->linkage()) && 30693f99962STeresa Johnson RefSummary->modulePath() != Summary.modulePath(); 30793f99962STeresa Johnson }; 30893f99962STeresa Johnson 309dde58938Sevgeny auto MarkExported = [&](const ValueInfo &VI, const GlobalValueSummary *S) { 310dde58938Sevgeny if (ExportLists) 3113d708bf5Sevgeny (*ExportLists)[S->modulePath()].insert(VI); 312dde58938Sevgeny }; 313dde58938Sevgeny 31419e23874SEugene Leviant for (auto &RefSummary : VI.getSummaryList()) 315bf46e741SEugene Leviant if (isa<GlobalVarSummary>(RefSummary.get()) && 316dde58938Sevgeny Index.canImportGlobalVar(RefSummary.get(), /* AnalyzeRefs */ true) && 31793f99962STeresa Johnson !LocalNotInModule(RefSummary.get())) { 318d2c234a4STeresa Johnson auto ILI = ImportList[RefSummary->modulePath()].insert(VI.getGUID()); 319d2c234a4STeresa Johnson // Only update stat if we haven't already imported this variable. 320d2c234a4STeresa Johnson if (ILI.second) 321d2c234a4STeresa Johnson NumImportedGlobalVarsThinLink++; 322dde58938Sevgeny MarkExported(VI, RefSummary.get()); 3237f92d66fSevgeny // Promote referenced functions and variables. We don't promote 3247f92d66fSevgeny // objects referenced by writeonly variable initializer, because 3257f92d66fSevgeny // we convert such variables initializers to "zeroinitializer". 3267f92d66fSevgeny // See processGlobalForThinLTO. 3277f92d66fSevgeny if (!Index.isWriteOnly(cast<GlobalVarSummary>(RefSummary.get()))) 328dde58938Sevgeny for (const auto &VI : RefSummary->refs()) 329dde58938Sevgeny for (const auto &RefFn : VI.getSummaryList()) 330dde58938Sevgeny MarkExported(VI, RefFn.get()); 33119e23874SEugene Leviant break; 33219e23874SEugene Leviant } 33319e23874SEugene Leviant } 33419e23874SEugene Leviant } 33519e23874SEugene Leviant 336cb9a82fcSTeresa Johnson static const char * 337cb9a82fcSTeresa Johnson getFailureName(FunctionImporter::ImportFailureReason Reason) { 338cb9a82fcSTeresa Johnson switch (Reason) { 339cb9a82fcSTeresa Johnson case FunctionImporter::ImportFailureReason::None: 340cb9a82fcSTeresa Johnson return "None"; 341cb9a82fcSTeresa Johnson case FunctionImporter::ImportFailureReason::GlobalVar: 342cb9a82fcSTeresa Johnson return "GlobalVar"; 343cb9a82fcSTeresa Johnson case FunctionImporter::ImportFailureReason::NotLive: 344cb9a82fcSTeresa Johnson return "NotLive"; 345cb9a82fcSTeresa Johnson case FunctionImporter::ImportFailureReason::TooLarge: 346cb9a82fcSTeresa Johnson return "TooLarge"; 347cb9a82fcSTeresa Johnson case FunctionImporter::ImportFailureReason::InterposableLinkage: 348cb9a82fcSTeresa Johnson return "InterposableLinkage"; 349cb9a82fcSTeresa Johnson case FunctionImporter::ImportFailureReason::LocalLinkageNotInModule: 350cb9a82fcSTeresa Johnson return "LocalLinkageNotInModule"; 351cb9a82fcSTeresa Johnson case FunctionImporter::ImportFailureReason::NotEligible: 352cb9a82fcSTeresa Johnson return "NotEligible"; 353cb397461STeresa Johnson case FunctionImporter::ImportFailureReason::NoInline: 354cb397461STeresa Johnson return "NoInline"; 355cb9a82fcSTeresa Johnson } 356cb9a82fcSTeresa Johnson llvm_unreachable("invalid reason"); 357cb9a82fcSTeresa Johnson } 358cb9a82fcSTeresa Johnson 35901e32130SMehdi Amini /// Compute the list of functions to import for a given caller. Mark these 36001e32130SMehdi Amini /// imported functions and the symbols they reference in their source module as 36101e32130SMehdi Amini /// exported from their source module. 36201e32130SMehdi Amini static void computeImportForFunction( 3633255eec1STeresa Johnson const FunctionSummary &Summary, const ModuleSummaryIndex &Index, 364d9830eb7SPiotr Padlewski const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries, 36501e32130SMehdi Amini SmallVectorImpl<EdgeInfo> &Worklist, 3669b490f10SMehdi Amini FunctionImporter::ImportMapTy &ImportList, 367d68935c5STeresa Johnson StringMap<FunctionImporter::ExportSetTy> *ExportLists, 368d68935c5STeresa Johnson FunctionImporter::ImportThresholdsTy &ImportThresholds) { 369dde58938Sevgeny computeImportForReferencedGlobals(Summary, Index, DefinedGVSummaries, 370dde58938Sevgeny ImportList, ExportLists); 371974706ebSTeresa Johnson static int ImportCount = 0; 37201e32130SMehdi Amini for (auto &Edge : Summary.calls()) { 3739667b91bSPeter Collingbourne ValueInfo VI = Edge.first; 3747e7b13d0STeresa Johnson LLVM_DEBUG(dbgs() << " edge -> " << VI << " Threshold:" << Threshold 3757e7b13d0STeresa Johnson << "\n"); 37601e32130SMehdi Amini 377974706ebSTeresa Johnson if (ImportCutoff >= 0 && ImportCount >= ImportCutoff) { 378d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "ignored! import-cutoff value of " << ImportCutoff 379974706ebSTeresa Johnson << " reached.\n"); 380974706ebSTeresa Johnson continue; 381974706ebSTeresa Johnson } 382974706ebSTeresa Johnson 3831958083dSTeresa Johnson VI = updateValueInfoForIndirectCalls(Index, VI); 3849667b91bSPeter Collingbourne if (!VI) 3859667b91bSPeter Collingbourne continue; 3864a435e08SDehao Chen 3879667b91bSPeter Collingbourne if (DefinedGVSummaries.count(VI.getGUID())) { 388d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "ignored! Target already in destination module.\n"); 3897e88d0daSMehdi Amini continue; 390d450da32STeresa Johnson } 39140641748SMehdi Amini 392ba72b95fSPiotr Padlewski auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float { 393ba72b95fSPiotr Padlewski if (Hotness == CalleeInfo::HotnessType::Hot) 394ba72b95fSPiotr Padlewski return ImportHotMultiplier; 395ba72b95fSPiotr Padlewski if (Hotness == CalleeInfo::HotnessType::Cold) 396ba72b95fSPiotr Padlewski return ImportColdMultiplier; 39764c46574SDehao Chen if (Hotness == CalleeInfo::HotnessType::Critical) 39864c46574SDehao Chen return ImportCriticalMultiplier; 399ba72b95fSPiotr Padlewski return 1.0; 400ba72b95fSPiotr Padlewski }; 401ba72b95fSPiotr Padlewski 402d9830eb7SPiotr Padlewski const auto NewThreshold = 403c73cec84SEaswaran Raman Threshold * GetBonusMultiplier(Edge.second.getHotness()); 404d2869473SPiotr Padlewski 405cb9a82fcSTeresa Johnson auto IT = ImportThresholds.insert(std::make_pair( 406cb9a82fcSTeresa Johnson VI.getGUID(), std::make_tuple(NewThreshold, nullptr, nullptr))); 407d68935c5STeresa Johnson bool PreviouslyVisited = !IT.second; 408cb9a82fcSTeresa Johnson auto &ProcessedThreshold = std::get<0>(IT.first->second); 409cb9a82fcSTeresa Johnson auto &CalleeSummary = std::get<1>(IT.first->second); 410cb9a82fcSTeresa Johnson auto &FailureInfo = std::get<2>(IT.first->second); 411d68935c5STeresa Johnson 412d2c234a4STeresa Johnson bool IsHotCallsite = 413d2c234a4STeresa Johnson Edge.second.getHotness() == CalleeInfo::HotnessType::Hot; 414d2c234a4STeresa Johnson bool IsCriticalCallsite = 415d2c234a4STeresa Johnson Edge.second.getHotness() == CalleeInfo::HotnessType::Critical; 416d2c234a4STeresa Johnson 417d68935c5STeresa Johnson const FunctionSummary *ResolvedCalleeSummary = nullptr; 418d68935c5STeresa Johnson if (CalleeSummary) { 419d68935c5STeresa Johnson assert(PreviouslyVisited); 420d68935c5STeresa Johnson // Since the traversal of the call graph is DFS, we can revisit a function 421d68935c5STeresa Johnson // a second time with a higher threshold. In this case, it is added back 422d68935c5STeresa Johnson // to the worklist with the new threshold (so that its own callee chains 423d68935c5STeresa Johnson // can be considered with the higher threshold). 424d68935c5STeresa Johnson if (NewThreshold <= ProcessedThreshold) { 425d68935c5STeresa Johnson LLVM_DEBUG( 426d68935c5STeresa Johnson dbgs() << "ignored! Target was already imported with Threshold " 427d68935c5STeresa Johnson << ProcessedThreshold << "\n"); 428d68935c5STeresa Johnson continue; 429d68935c5STeresa Johnson } 430d68935c5STeresa Johnson // Update with new larger threshold. 431d68935c5STeresa Johnson ProcessedThreshold = NewThreshold; 432d68935c5STeresa Johnson ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary); 433d68935c5STeresa Johnson } else { 434d68935c5STeresa Johnson // If we already rejected importing a callee at the same or higher 435d68935c5STeresa Johnson // threshold, don't waste time calling selectCallee. 436d68935c5STeresa Johnson if (PreviouslyVisited && NewThreshold <= ProcessedThreshold) { 437d68935c5STeresa Johnson LLVM_DEBUG( 438d68935c5STeresa Johnson dbgs() << "ignored! Target was already rejected with Threshold " 439d68935c5STeresa Johnson << ProcessedThreshold << "\n"); 440cb9a82fcSTeresa Johnson if (PrintImportFailures) { 441cb9a82fcSTeresa Johnson assert(FailureInfo && 442cb9a82fcSTeresa Johnson "Expected FailureInfo for previously rejected candidate"); 443cb9a82fcSTeresa Johnson FailureInfo->Attempts++; 444cb9a82fcSTeresa Johnson } 445d68935c5STeresa Johnson continue; 446d68935c5STeresa Johnson } 447d68935c5STeresa Johnson 448cb9a82fcSTeresa Johnson FunctionImporter::ImportFailureReason Reason; 449d68935c5STeresa Johnson CalleeSummary = selectCallee(Index, VI.getSummaryList(), NewThreshold, 450cb9a82fcSTeresa Johnson Summary.modulePath(), Reason, VI.getGUID()); 45101e32130SMehdi Amini if (!CalleeSummary) { 452d68935c5STeresa Johnson // Update with new larger threshold if this was a retry (otherwise 453cb9a82fcSTeresa Johnson // we would have already inserted with NewThreshold above). Also 454cb9a82fcSTeresa Johnson // update failure info if requested. 455cb9a82fcSTeresa Johnson if (PreviouslyVisited) { 456d68935c5STeresa Johnson ProcessedThreshold = NewThreshold; 457cb9a82fcSTeresa Johnson if (PrintImportFailures) { 458cb9a82fcSTeresa Johnson assert(FailureInfo && 459cb9a82fcSTeresa Johnson "Expected FailureInfo for previously rejected candidate"); 460cb9a82fcSTeresa Johnson FailureInfo->Reason = Reason; 461cb9a82fcSTeresa Johnson FailureInfo->Attempts++; 462cb9a82fcSTeresa Johnson FailureInfo->MaxHotness = 463cb9a82fcSTeresa Johnson std::max(FailureInfo->MaxHotness, Edge.second.getHotness()); 464cb9a82fcSTeresa Johnson } 465cb9a82fcSTeresa Johnson } else if (PrintImportFailures) { 466cb9a82fcSTeresa Johnson assert(!FailureInfo && 467cb9a82fcSTeresa Johnson "Expected no FailureInfo for newly rejected candidate"); 4680eaee545SJonas Devlieghere FailureInfo = std::make_unique<FunctionImporter::ImportFailureInfo>( 469cb9a82fcSTeresa Johnson VI, Edge.second.getHotness(), Reason, 1); 470cb9a82fcSTeresa Johnson } 471d34e60caSNicola Zaghen LLVM_DEBUG( 472d34e60caSNicola Zaghen dbgs() << "ignored! No qualifying callee with summary found.\n"); 4737e88d0daSMehdi Amini continue; 4747e88d0daSMehdi Amini } 4752f0cc477SDavid Blaikie 4762f0cc477SDavid Blaikie // "Resolve" the summary 477d68935c5STeresa Johnson CalleeSummary = CalleeSummary->getBaseObject(); 478d68935c5STeresa Johnson ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary); 4792d28f7aaSMehdi Amini 480b11391bbSTeresa Johnson assert((ResolvedCalleeSummary->fflags().AlwaysInline || 481b11391bbSTeresa Johnson (ResolvedCalleeSummary->instCount() <= NewThreshold)) && 48201e32130SMehdi Amini "selectCallee() didn't honor the threshold"); 48301e32130SMehdi Amini 4841b859a23STeresa Johnson auto ExportModulePath = ResolvedCalleeSummary->modulePath(); 485d68935c5STeresa Johnson auto ILI = ImportList[ExportModulePath].insert(VI.getGUID()); 486d68935c5STeresa Johnson // We previously decided to import this GUID definition if it was already 487d68935c5STeresa Johnson // inserted in the set of imports from the exporting module. 488d68935c5STeresa Johnson bool PreviouslyImported = !ILI.second; 489d2c234a4STeresa Johnson if (!PreviouslyImported) { 490d2c234a4STeresa Johnson NumImportedFunctionsThinLink++; 491d2c234a4STeresa Johnson if (IsHotCallsite) 492d2c234a4STeresa Johnson NumImportedHotFunctionsThinLink++; 493d2c234a4STeresa Johnson if (IsCriticalCallsite) 494d2c234a4STeresa Johnson NumImportedCriticalFunctionsThinLink++; 495d2c234a4STeresa Johnson } 496974706ebSTeresa Johnson 4971b859a23STeresa Johnson // Make exports in the source module. 4981b859a23STeresa Johnson if (ExportLists) { 4991b859a23STeresa Johnson auto &ExportList = (*ExportLists)[ExportModulePath]; 5003d708bf5Sevgeny ExportList.insert(VI); 50119f2aa78STeresa Johnson if (!PreviouslyImported) { 50219f2aa78STeresa Johnson // This is the first time this function was exported from its source 50319f2aa78STeresa Johnson // module, so mark all functions and globals it references as exported 5041b859a23STeresa Johnson // to the outside if they are defined in the same source module. 505edddca22STeresa Johnson // For efficiency, we unconditionally add all the referenced GUIDs 506edddca22STeresa Johnson // to the ExportList for this module, and will prune out any not 507edddca22STeresa Johnson // defined in the module later in a single pass. 5083d708bf5Sevgeny for (auto &Edge : ResolvedCalleeSummary->calls()) 5093d708bf5Sevgeny ExportList.insert(Edge.first); 5103d708bf5Sevgeny 5113d708bf5Sevgeny for (auto &Ref : ResolvedCalleeSummary->refs()) 5123d708bf5Sevgeny ExportList.insert(Ref); 5131b859a23STeresa Johnson } 51419f2aa78STeresa Johnson } 515d68935c5STeresa Johnson } 516d68935c5STeresa Johnson 517d68935c5STeresa Johnson auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) { 518d68935c5STeresa Johnson // Adjust the threshold for next level of imported functions. 519d68935c5STeresa Johnson // The threshold is different for hot callsites because we can then 520d68935c5STeresa Johnson // inline chains of hot calls. 521d68935c5STeresa Johnson if (IsHotCallsite) 522d68935c5STeresa Johnson return Threshold * ImportHotInstrFactor; 523d68935c5STeresa Johnson return Threshold * ImportInstrFactor; 524d68935c5STeresa Johnson }; 525d68935c5STeresa Johnson 526d68935c5STeresa Johnson const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite); 527d68935c5STeresa Johnson 528d68935c5STeresa Johnson ImportCount++; 529d2869473SPiotr Padlewski 53001e32130SMehdi Amini // Insert the newly imported function to the worklist. 5319667b91bSPeter Collingbourne Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, VI.getGUID()); 532d450da32STeresa Johnson } 533d450da32STeresa Johnson } 534d450da32STeresa Johnson 53501e32130SMehdi Amini /// Given the list of globals defined in a module, compute the list of imports 53601e32130SMehdi Amini /// as well as the list of "exports", i.e. the list of symbols referenced from 53701e32130SMehdi Amini /// another module (that may require promotion). 53801e32130SMehdi Amini static void ComputeImportForModule( 539c851d216STeresa Johnson const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index, 540cb9a82fcSTeresa Johnson StringRef ModName, FunctionImporter::ImportMapTy &ImportList, 54156584bbfSEvgeniy Stepanov StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) { 54201e32130SMehdi Amini // Worklist contains the list of function imported in this module, for which 54301e32130SMehdi Amini // we will analyse the callees and may import further down the callgraph. 54401e32130SMehdi Amini SmallVector<EdgeInfo, 128> Worklist; 545d68935c5STeresa Johnson FunctionImporter::ImportThresholdsTy ImportThresholds; 54601e32130SMehdi Amini 54701e32130SMehdi Amini // Populate the worklist with the import for the functions in the current 54801e32130SMehdi Amini // module 54928e457bcSTeresa Johnson for (auto &GVSummary : DefinedGVSummaries) { 5507e7b13d0STeresa Johnson #ifndef NDEBUG 5517e7b13d0STeresa Johnson // FIXME: Change the GVSummaryMapTy to hold ValueInfo instead of GUID 5527e7b13d0STeresa Johnson // so this map look up (and possibly others) can be avoided. 5537e7b13d0STeresa Johnson auto VI = Index.getValueInfo(GVSummary.first); 5547e7b13d0STeresa Johnson #endif 55556584bbfSEvgeniy Stepanov if (!Index.isGlobalValueLive(GVSummary.second)) { 5567e7b13d0STeresa Johnson LLVM_DEBUG(dbgs() << "Ignores Dead GUID: " << VI << "\n"); 5576c475a75STeresa Johnson continue; 5586c475a75STeresa Johnson } 559cfbd0892SPeter Collingbourne auto *FuncSummary = 560cfbd0892SPeter Collingbourne dyn_cast<FunctionSummary>(GVSummary.second->getBaseObject()); 5611aafabf7SMehdi Amini if (!FuncSummary) 5621aafabf7SMehdi Amini // Skip import for global variables 5631aafabf7SMehdi Amini continue; 5647e7b13d0STeresa Johnson LLVM_DEBUG(dbgs() << "Initialize import for " << VI << "\n"); 5652d28f7aaSMehdi Amini computeImportForFunction(*FuncSummary, Index, ImportInstrLimit, 5669b490f10SMehdi Amini DefinedGVSummaries, Worklist, ImportList, 567d68935c5STeresa Johnson ExportLists, ImportThresholds); 56801e32130SMehdi Amini } 56901e32130SMehdi Amini 570d2869473SPiotr Padlewski // Process the newly imported functions and add callees to the worklist. 57142418abaSMehdi Amini while (!Worklist.empty()) { 57201e32130SMehdi Amini auto FuncInfo = Worklist.pop_back_val(); 573475b51a7STeresa Johnson auto *Summary = std::get<0>(FuncInfo); 574475b51a7STeresa Johnson auto Threshold = std::get<1>(FuncInfo); 57542418abaSMehdi Amini 5761aafabf7SMehdi Amini computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries, 577d68935c5STeresa Johnson Worklist, ImportList, ExportLists, 578d68935c5STeresa Johnson ImportThresholds); 579c8c55170SMehdi Amini } 580cb9a82fcSTeresa Johnson 581cb9a82fcSTeresa Johnson // Print stats about functions considered but rejected for importing 582cb9a82fcSTeresa Johnson // when requested. 583cb9a82fcSTeresa Johnson if (PrintImportFailures) { 584cb9a82fcSTeresa Johnson dbgs() << "Missed imports into module " << ModName << "\n"; 585cb9a82fcSTeresa Johnson for (auto &I : ImportThresholds) { 586cb9a82fcSTeresa Johnson auto &ProcessedThreshold = std::get<0>(I.second); 587cb9a82fcSTeresa Johnson auto &CalleeSummary = std::get<1>(I.second); 588cb9a82fcSTeresa Johnson auto &FailureInfo = std::get<2>(I.second); 589cb9a82fcSTeresa Johnson if (CalleeSummary) 590cb9a82fcSTeresa Johnson continue; // We are going to import. 591cb9a82fcSTeresa Johnson assert(FailureInfo); 592cb9a82fcSTeresa Johnson FunctionSummary *FS = nullptr; 593cb9a82fcSTeresa Johnson if (!FailureInfo->VI.getSummaryList().empty()) 594cb9a82fcSTeresa Johnson FS = dyn_cast<FunctionSummary>( 595cb9a82fcSTeresa Johnson FailureInfo->VI.getSummaryList()[0]->getBaseObject()); 596cb9a82fcSTeresa Johnson dbgs() << FailureInfo->VI 597cb9a82fcSTeresa Johnson << ": Reason = " << getFailureName(FailureInfo->Reason) 598cb9a82fcSTeresa Johnson << ", Threshold = " << ProcessedThreshold 599cb9a82fcSTeresa Johnson << ", Size = " << (FS ? (int)FS->instCount() : -1) 600cb9a82fcSTeresa Johnson << ", MaxHotness = " << getHotnessName(FailureInfo->MaxHotness) 601cb9a82fcSTeresa Johnson << ", Attempts = " << FailureInfo->Attempts << "\n"; 602cb9a82fcSTeresa Johnson } 603cb9a82fcSTeresa Johnson } 60442418abaSMehdi Amini } 605ffe2e4aaSMehdi Amini 60619e23874SEugene Leviant #ifndef NDEBUG 60719e23874SEugene Leviant static bool isGlobalVarSummary(const ModuleSummaryIndex &Index, 60819e23874SEugene Leviant GlobalValue::GUID G) { 60919e23874SEugene Leviant if (const auto &VI = Index.getValueInfo(G)) { 61019e23874SEugene Leviant auto SL = VI.getSummaryList(); 61119e23874SEugene Leviant if (!SL.empty()) 61219e23874SEugene Leviant return SL[0]->getSummaryKind() == GlobalValueSummary::GlobalVarKind; 61319e23874SEugene Leviant } 61419e23874SEugene Leviant return false; 61519e23874SEugene Leviant } 61619e23874SEugene Leviant 61719e23874SEugene Leviant static GlobalValue::GUID getGUID(GlobalValue::GUID G) { return G; } 61819e23874SEugene Leviant 61919e23874SEugene Leviant template <class T> 6201fc0da48SBenjamin Kramer static unsigned numGlobalVarSummaries(const ModuleSummaryIndex &Index, 6211fc0da48SBenjamin Kramer T &Cont) { 62219e23874SEugene Leviant unsigned NumGVS = 0; 62319e23874SEugene Leviant for (auto &V : Cont) 62419e23874SEugene Leviant if (isGlobalVarSummary(Index, getGUID(V))) 62519e23874SEugene Leviant ++NumGVS; 62619e23874SEugene Leviant return NumGVS; 62719e23874SEugene Leviant } 62819e23874SEugene Leviant #endif 62919e23874SEugene Leviant 630*8bcd01f4SFangrui Song #ifndef NDEBUG 6313d708bf5Sevgeny static bool 6323d708bf5Sevgeny checkVariableImport(const ModuleSummaryIndex &Index, 6333d708bf5Sevgeny StringMap<FunctionImporter::ImportMapTy> &ImportLists, 6343d708bf5Sevgeny StringMap<FunctionImporter::ExportSetTy> &ExportLists) { 6353d708bf5Sevgeny 6363d708bf5Sevgeny DenseSet<GlobalValue::GUID> FlattenedImports; 6373d708bf5Sevgeny 6383d708bf5Sevgeny for (auto &ImportPerModule : ImportLists) 6393d708bf5Sevgeny for (auto &ExportPerModule : ImportPerModule.second) 6403d708bf5Sevgeny FlattenedImports.insert(ExportPerModule.second.begin(), 6413d708bf5Sevgeny ExportPerModule.second.end()); 6423d708bf5Sevgeny 6433d708bf5Sevgeny // Checks that all GUIDs of read/writeonly vars we see in export lists 6443d708bf5Sevgeny // are also in the import lists. Otherwise we my face linker undefs, 6453d708bf5Sevgeny // because readonly and writeonly vars are internalized in their 6463d708bf5Sevgeny // source modules. 6473d708bf5Sevgeny auto IsReadOrWriteOnlyVar = [&](StringRef ModulePath, const ValueInfo &VI) { 6483d708bf5Sevgeny auto *GVS = dyn_cast_or_null<GlobalVarSummary>( 6493d708bf5Sevgeny Index.findSummaryInModule(VI, ModulePath)); 6503d708bf5Sevgeny return GVS && (Index.isReadOnly(GVS) || Index.isWriteOnly(GVS)); 6513d708bf5Sevgeny }; 6523d708bf5Sevgeny 6533d708bf5Sevgeny for (auto &ExportPerModule : ExportLists) 6543d708bf5Sevgeny for (auto &VI : ExportPerModule.second) 6553d708bf5Sevgeny if (!FlattenedImports.count(VI.getGUID()) && 6563d708bf5Sevgeny IsReadOrWriteOnlyVar(ExportPerModule.first(), VI)) 6573d708bf5Sevgeny return false; 6583d708bf5Sevgeny 6593d708bf5Sevgeny return true; 6603d708bf5Sevgeny } 661*8bcd01f4SFangrui Song #endif 6623d708bf5Sevgeny 663c86af334STeresa Johnson /// Compute all the import and export for every module using the Index. 66401e32130SMehdi Amini void llvm::ComputeCrossModuleImport( 66501e32130SMehdi Amini const ModuleSummaryIndex &Index, 666c851d216STeresa Johnson const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries, 66701e32130SMehdi Amini StringMap<FunctionImporter::ImportMapTy> &ImportLists, 66856584bbfSEvgeniy Stepanov StringMap<FunctionImporter::ExportSetTy> &ExportLists) { 66901e32130SMehdi Amini // For each module that has function defined, compute the import/export lists. 6701aafabf7SMehdi Amini for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) { 6719b490f10SMehdi Amini auto &ImportList = ImportLists[DefinedGVSummaries.first()]; 672d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Computing import for Module '" 6731aafabf7SMehdi Amini << DefinedGVSummaries.first() << "'\n"); 674cb9a82fcSTeresa Johnson ComputeImportForModule(DefinedGVSummaries.second, Index, 675cb9a82fcSTeresa Johnson DefinedGVSummaries.first(), ImportList, 67656584bbfSEvgeniy Stepanov &ExportLists); 67701e32130SMehdi Amini } 67801e32130SMehdi Amini 679edddca22STeresa Johnson // When computing imports we added all GUIDs referenced by anything 680edddca22STeresa Johnson // imported from the module to its ExportList. Now we prune each ExportList 681edddca22STeresa Johnson // of any not defined in that module. This is more efficient than checking 682edddca22STeresa Johnson // while computing imports because some of the summary lists may be long 683edddca22STeresa Johnson // due to linkonce (comdat) copies. 684edddca22STeresa Johnson for (auto &ELI : ExportLists) { 685edddca22STeresa Johnson const auto &DefinedGVSummaries = 686edddca22STeresa Johnson ModuleToDefinedGVSummaries.lookup(ELI.first()); 687360f6617SBenjamin Kramer for (auto EI = ELI.second.begin(); EI != ELI.second.end();) { 6883d708bf5Sevgeny if (!DefinedGVSummaries.count(EI->getGUID())) 6893d708bf5Sevgeny ELI.second.erase(EI++); 690360f6617SBenjamin Kramer else 691360f6617SBenjamin Kramer ++EI; 692360f6617SBenjamin Kramer } 693edddca22STeresa Johnson } 694edddca22STeresa Johnson 6953d708bf5Sevgeny assert(checkVariableImport(Index, ImportLists, ExportLists)); 69601e32130SMehdi Amini #ifndef NDEBUG 697d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size() 69801e32130SMehdi Amini << " modules:\n"); 69901e32130SMehdi Amini for (auto &ModuleImports : ImportLists) { 70001e32130SMehdi Amini auto ModName = ModuleImports.first(); 70101e32130SMehdi Amini auto &Exports = ExportLists[ModName]; 70219e23874SEugene Leviant unsigned NumGVS = numGlobalVarSummaries(Index, Exports); 703d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "* Module " << ModName << " exports " 70419e23874SEugene Leviant << Exports.size() - NumGVS << " functions and " << NumGVS 705d34e60caSNicola Zaghen << " vars. Imports from " << ModuleImports.second.size() 706d34e60caSNicola Zaghen << " modules.\n"); 70701e32130SMehdi Amini for (auto &Src : ModuleImports.second) { 70801e32130SMehdi Amini auto SrcModName = Src.first(); 70919e23874SEugene Leviant unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second); 710d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod 71119e23874SEugene Leviant << " functions imported from " << SrcModName << "\n"); 712d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod 713d34e60caSNicola Zaghen << " global vars imported from " << SrcModName << "\n"); 71401e32130SMehdi Amini } 71501e32130SMehdi Amini } 71601e32130SMehdi Amini #endif 71701e32130SMehdi Amini } 71801e32130SMehdi Amini 71981bbf742STeresa Johnson #ifndef NDEBUG 72019e23874SEugene Leviant static void dumpImportListForModule(const ModuleSummaryIndex &Index, 72119e23874SEugene Leviant StringRef ModulePath, 72281bbf742STeresa Johnson FunctionImporter::ImportMapTy &ImportList) { 723d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "* Module " << ModulePath << " imports from " 72481bbf742STeresa Johnson << ImportList.size() << " modules.\n"); 72581bbf742STeresa Johnson for (auto &Src : ImportList) { 72681bbf742STeresa Johnson auto SrcModName = Src.first(); 72719e23874SEugene Leviant unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second); 728d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod 72919e23874SEugene Leviant << " functions imported from " << SrcModName << "\n"); 730d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod << " vars imported from " 73181bbf742STeresa Johnson << SrcModName << "\n"); 73281bbf742STeresa Johnson } 73381bbf742STeresa Johnson } 73469b2de84STeresa Johnson #endif 73581bbf742STeresa Johnson 736c86af334STeresa Johnson /// Compute all the imports for the given module in the Index. 737c86af334STeresa Johnson void llvm::ComputeCrossModuleImportForModule( 738c86af334STeresa Johnson StringRef ModulePath, const ModuleSummaryIndex &Index, 739c86af334STeresa Johnson FunctionImporter::ImportMapTy &ImportList) { 740c86af334STeresa Johnson // Collect the list of functions this module defines. 741c86af334STeresa Johnson // GUID -> Summary 742c851d216STeresa Johnson GVSummaryMapTy FunctionSummaryMap; 74328e457bcSTeresa Johnson Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap); 744c86af334STeresa Johnson 745c86af334STeresa Johnson // Compute the import list for this module. 746d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n"); 747cb9a82fcSTeresa Johnson ComputeImportForModule(FunctionSummaryMap, Index, ModulePath, ImportList); 748c86af334STeresa Johnson 749c86af334STeresa Johnson #ifndef NDEBUG 75019e23874SEugene Leviant dumpImportListForModule(Index, ModulePath, ImportList); 75181bbf742STeresa Johnson #endif 752c86af334STeresa Johnson } 75381bbf742STeresa Johnson 75481bbf742STeresa Johnson // Mark all external summaries in Index for import into the given module. 75581bbf742STeresa Johnson // Used for distributed builds using a distributed index. 75681bbf742STeresa Johnson void llvm::ComputeCrossModuleImportForModuleFromIndex( 75781bbf742STeresa Johnson StringRef ModulePath, const ModuleSummaryIndex &Index, 75881bbf742STeresa Johnson FunctionImporter::ImportMapTy &ImportList) { 75981bbf742STeresa Johnson for (auto &GlobalList : Index) { 76081bbf742STeresa Johnson // Ignore entries for undefined references. 76181bbf742STeresa Johnson if (GlobalList.second.SummaryList.empty()) 76281bbf742STeresa Johnson continue; 76381bbf742STeresa Johnson 76481bbf742STeresa Johnson auto GUID = GlobalList.first; 76581bbf742STeresa Johnson assert(GlobalList.second.SummaryList.size() == 1 && 76681bbf742STeresa Johnson "Expected individual combined index to have one summary per GUID"); 76781bbf742STeresa Johnson auto &Summary = GlobalList.second.SummaryList[0]; 76881bbf742STeresa Johnson // Skip the summaries for the importing module. These are included to 76981bbf742STeresa Johnson // e.g. record required linkage changes. 77081bbf742STeresa Johnson if (Summary->modulePath() == ModulePath) 77181bbf742STeresa Johnson continue; 772d68935c5STeresa Johnson // Add an entry to provoke importing by thinBackend. 773d68935c5STeresa Johnson ImportList[Summary->modulePath()].insert(GUID); 77481bbf742STeresa Johnson } 77581bbf742STeresa Johnson #ifndef NDEBUG 77619e23874SEugene Leviant dumpImportListForModule(Index, ModulePath, ImportList); 777c86af334STeresa Johnson #endif 778c86af334STeresa Johnson } 779c86af334STeresa Johnson 78056584bbfSEvgeniy Stepanov void llvm::computeDeadSymbols( 78156584bbfSEvgeniy Stepanov ModuleSummaryIndex &Index, 782eaf5172cSGeorge Rimar const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols, 783eaf5172cSGeorge Rimar function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing) { 78456584bbfSEvgeniy Stepanov assert(!Index.withGlobalValueDeadStripping()); 7856c475a75STeresa Johnson if (!ComputeDead) 78656584bbfSEvgeniy Stepanov return; 7876c475a75STeresa Johnson if (GUIDPreservedSymbols.empty()) 7886c475a75STeresa Johnson // Don't do anything when nothing is live, this is friendly with tests. 78956584bbfSEvgeniy Stepanov return; 79056584bbfSEvgeniy Stepanov unsigned LiveSymbols = 0; 7919667b91bSPeter Collingbourne SmallVector<ValueInfo, 128> Worklist; 7929667b91bSPeter Collingbourne Worklist.reserve(GUIDPreservedSymbols.size() * 2); 7939667b91bSPeter Collingbourne for (auto GUID : GUIDPreservedSymbols) { 7949667b91bSPeter Collingbourne ValueInfo VI = Index.getValueInfo(GUID); 7959667b91bSPeter Collingbourne if (!VI) 7969667b91bSPeter Collingbourne continue; 79756584bbfSEvgeniy Stepanov for (auto &S : VI.getSummaryList()) 79856584bbfSEvgeniy Stepanov S->setLive(true); 7996c475a75STeresa Johnson } 80056584bbfSEvgeniy Stepanov 8016c475a75STeresa Johnson // Add values flagged in the index as live roots to the worklist. 8027e7b13d0STeresa Johnson for (const auto &Entry : Index) { 8037e7b13d0STeresa Johnson auto VI = Index.getValueInfo(Entry); 80456584bbfSEvgeniy Stepanov for (auto &S : Entry.second.SummaryList) 80556584bbfSEvgeniy Stepanov if (S->isLive()) { 8067e7b13d0STeresa Johnson LLVM_DEBUG(dbgs() << "Live root: " << VI << "\n"); 8077e7b13d0STeresa Johnson Worklist.push_back(VI); 80856584bbfSEvgeniy Stepanov ++LiveSymbols; 80956584bbfSEvgeniy Stepanov break; 8106c475a75STeresa Johnson } 8117e7b13d0STeresa Johnson } 8126c475a75STeresa Johnson 81356584bbfSEvgeniy Stepanov // Make value live and add it to the worklist if it was not live before. 814ea314fd4STeresa Johnson auto visit = [&](ValueInfo VI, bool IsAliasee) { 8151958083dSTeresa Johnson // FIXME: If we knew which edges were created for indirect call profiles, 8161958083dSTeresa Johnson // we could skip them here. Any that are live should be reached via 8171958083dSTeresa Johnson // other edges, e.g. reference edges. Otherwise, using a profile collected 8181958083dSTeresa Johnson // on a slightly different binary might provoke preserving, importing 8191958083dSTeresa Johnson // and ultimately promoting calls to functions not linked into this 8201958083dSTeresa Johnson // binary, which increases the binary size unnecessarily. Note that 8211958083dSTeresa Johnson // if this code changes, the importer needs to change so that edges 8221958083dSTeresa Johnson // to functions marked dead are skipped. 8231958083dSTeresa Johnson VI = updateValueInfoForIndirectCalls(Index, VI); 8241958083dSTeresa Johnson if (!VI) 8251958083dSTeresa Johnson return; 82633e3b4b9SXin Tong 8275b2f6a1bSTeresa Johnson if (llvm::any_of(VI.getSummaryList(), 82833e3b4b9SXin Tong [](const std::unique_ptr<llvm::GlobalValueSummary> &S) { 82933e3b4b9SXin Tong return S->isLive(); 83033e3b4b9SXin Tong })) 831f625118eSTeresa Johnson return; 832eaf5172cSGeorge Rimar 833aab60006SVlad Tsyrklevich // We only keep live symbols that are known to be non-prevailing if any are 834bfdad33bSXin Tong // available_externally, linkonceodr, weakodr. Those symbols are discarded 835bfdad33bSXin Tong // later in the EliminateAvailableExternally pass and setting them to 836bfdad33bSXin Tong // not-live could break downstreams users of liveness information (PR36483) 837bfdad33bSXin Tong // or limit optimization opportunities. 838aab60006SVlad Tsyrklevich if (isPrevailing(VI.getGUID()) == PrevailingType::No) { 839bfdad33bSXin Tong bool KeepAliveLinkage = false; 840aab60006SVlad Tsyrklevich bool Interposable = false; 841aab60006SVlad Tsyrklevich for (auto &S : VI.getSummaryList()) { 842bfdad33bSXin Tong if (S->linkage() == GlobalValue::AvailableExternallyLinkage || 843bfdad33bSXin Tong S->linkage() == GlobalValue::WeakODRLinkage || 844bfdad33bSXin Tong S->linkage() == GlobalValue::LinkOnceODRLinkage) 845bfdad33bSXin Tong KeepAliveLinkage = true; 846aab60006SVlad Tsyrklevich else if (GlobalValue::isInterposableLinkage(S->linkage())) 847aab60006SVlad Tsyrklevich Interposable = true; 848aab60006SVlad Tsyrklevich } 849aab60006SVlad Tsyrklevich 850ea314fd4STeresa Johnson if (!IsAliasee) { 851bfdad33bSXin Tong if (!KeepAliveLinkage) 852eaf5172cSGeorge Rimar return; 853eaf5172cSGeorge Rimar 854aab60006SVlad Tsyrklevich if (Interposable) 855bfdad33bSXin Tong report_fatal_error( 856ea314fd4STeresa Johnson "Interposable and available_externally/linkonce_odr/weak_odr " 857ea314fd4STeresa Johnson "symbol"); 858ea314fd4STeresa Johnson } 859aab60006SVlad Tsyrklevich } 860aab60006SVlad Tsyrklevich 861f625118eSTeresa Johnson for (auto &S : VI.getSummaryList()) 86256584bbfSEvgeniy Stepanov S->setLive(true); 86356584bbfSEvgeniy Stepanov ++LiveSymbols; 86456584bbfSEvgeniy Stepanov Worklist.push_back(VI); 86556584bbfSEvgeniy Stepanov }; 86656584bbfSEvgeniy Stepanov 8676c475a75STeresa Johnson while (!Worklist.empty()) { 8689667b91bSPeter Collingbourne auto VI = Worklist.pop_back_val(); 8699667b91bSPeter Collingbourne for (auto &Summary : VI.getSummaryList()) { 8705b2f6a1bSTeresa Johnson if (auto *AS = dyn_cast<AliasSummary>(Summary.get())) { 8715b2f6a1bSTeresa Johnson // If this is an alias, visit the aliasee VI to ensure that all copies 8725b2f6a1bSTeresa Johnson // are marked live and it is added to the worklist for further 8735b2f6a1bSTeresa Johnson // processing of its references. 874ea314fd4STeresa Johnson visit(AS->getAliaseeVI(), true); 8755b2f6a1bSTeresa Johnson continue; 8765b2f6a1bSTeresa Johnson } 8775b2f6a1bSTeresa Johnson 8785b2f6a1bSTeresa Johnson Summary->setLive(true); 8795b2f6a1bSTeresa Johnson for (auto Ref : Summary->refs()) 880ea314fd4STeresa Johnson visit(Ref, false); 8815b2f6a1bSTeresa Johnson if (auto *FS = dyn_cast<FunctionSummary>(Summary.get())) 88256584bbfSEvgeniy Stepanov for (auto Call : FS->calls()) 883ea314fd4STeresa Johnson visit(Call.first, false); 8846c475a75STeresa Johnson } 8856c475a75STeresa Johnson } 88656584bbfSEvgeniy Stepanov Index.setWithGlobalValueDeadStripping(); 88756584bbfSEvgeniy Stepanov 88856584bbfSEvgeniy Stepanov unsigned DeadSymbols = Index.size() - LiveSymbols; 889d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols 89056584bbfSEvgeniy Stepanov << " symbols Dead \n"); 89156584bbfSEvgeniy Stepanov NumDeadSymbols += DeadSymbols; 89256584bbfSEvgeniy Stepanov NumLiveSymbols += LiveSymbols; 8936c475a75STeresa Johnson } 8946c475a75STeresa Johnson 895bf46e741SEugene Leviant // Compute dead symbols and propagate constants in combined index. 896bf46e741SEugene Leviant void llvm::computeDeadSymbolsWithConstProp( 897bf46e741SEugene Leviant ModuleSummaryIndex &Index, 898bf46e741SEugene Leviant const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols, 899bf46e741SEugene Leviant function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing, 900bf46e741SEugene Leviant bool ImportEnabled) { 901bf46e741SEugene Leviant computeDeadSymbols(Index, GUIDPreservedSymbols, isPrevailing); 902bf46e741SEugene Leviant if (ImportEnabled) { 9033aef3528SEugene Leviant Index.propagateAttributes(GUIDPreservedSymbols); 904bf46e741SEugene Leviant } else { 9053aef3528SEugene Leviant // If import is disabled we should drop read/write-only attribute 906bf46e741SEugene Leviant // from all summaries to prevent internalization. 907bf46e741SEugene Leviant for (auto &P : Index) 908bf46e741SEugene Leviant for (auto &S : P.second.SummaryList) 9093aef3528SEugene Leviant if (auto *GVS = dyn_cast<GlobalVarSummary>(S.get())) { 910bf46e741SEugene Leviant GVS->setReadOnly(false); 9113aef3528SEugene Leviant GVS->setWriteOnly(false); 9123aef3528SEugene Leviant } 913bf46e741SEugene Leviant } 914dde58938Sevgeny Index.setWithAttributePropagation(); 915bf46e741SEugene Leviant } 916bf46e741SEugene Leviant 91784174c37STeresa Johnson /// Compute the set of summaries needed for a ThinLTO backend compilation of 91884174c37STeresa Johnson /// \p ModulePath. 91984174c37STeresa Johnson void llvm::gatherImportedSummariesForModule( 92084174c37STeresa Johnson StringRef ModulePath, 92184174c37STeresa Johnson const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries, 922cdbcbf74SMehdi Amini const FunctionImporter::ImportMapTy &ImportList, 92384174c37STeresa Johnson std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) { 92484174c37STeresa Johnson // Include all summaries from the importing module. 92584174c37STeresa Johnson ModuleToSummariesForIndex[ModulePath] = 92684174c37STeresa Johnson ModuleToDefinedGVSummaries.lookup(ModulePath); 92784174c37STeresa Johnson // Include summaries for imports. 92888c491ddSMehdi Amini for (auto &ILI : ImportList) { 92984174c37STeresa Johnson auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()]; 93084174c37STeresa Johnson const auto &DefinedGVSummaries = 93184174c37STeresa Johnson ModuleToDefinedGVSummaries.lookup(ILI.first()); 93284174c37STeresa Johnson for (auto &GI : ILI.second) { 933d68935c5STeresa Johnson const auto &DS = DefinedGVSummaries.find(GI); 93484174c37STeresa Johnson assert(DS != DefinedGVSummaries.end() && 93584174c37STeresa Johnson "Expected a defined summary for imported global value"); 936d68935c5STeresa Johnson SummariesForIndex[GI] = DS->second; 93784174c37STeresa Johnson } 93884174c37STeresa Johnson } 93984174c37STeresa Johnson } 94084174c37STeresa Johnson 9418570fe47STeresa Johnson /// Emit the files \p ModulePath will import from into \p OutputFilename. 942c0320ef4STeresa Johnson std::error_code llvm::EmitImportsFiles( 943c0320ef4STeresa Johnson StringRef ModulePath, StringRef OutputFilename, 944c0320ef4STeresa Johnson const std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) { 9458570fe47STeresa Johnson std::error_code EC; 946d9b948b6SFangrui Song raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::OF_None); 9478570fe47STeresa Johnson if (EC) 9488570fe47STeresa Johnson return EC; 949c0320ef4STeresa Johnson for (auto &ILI : ModuleToSummariesForIndex) 950c0320ef4STeresa Johnson // The ModuleToSummariesForIndex map includes an entry for the current 951c0320ef4STeresa Johnson // Module (needed for writing out the index files). We don't want to 952c0320ef4STeresa Johnson // include it in the imports file, however, so filter it out. 953c0320ef4STeresa Johnson if (ILI.first != ModulePath) 954c0320ef4STeresa Johnson ImportsOS << ILI.first << "\n"; 9558570fe47STeresa Johnson return std::error_code(); 9568570fe47STeresa Johnson } 9578570fe47STeresa Johnson 9585a95c477STeresa Johnson bool llvm::convertToDeclaration(GlobalValue &GV) { 959d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName() 960d34e60caSNicola Zaghen << "\n"); 9614566c6dbSTeresa Johnson if (Function *F = dyn_cast<Function>(&GV)) { 9624566c6dbSTeresa Johnson F->deleteBody(); 9634566c6dbSTeresa Johnson F->clearMetadata(); 9647873669bSPeter Collingbourne F->setComdat(nullptr); 9654566c6dbSTeresa Johnson } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) { 9664566c6dbSTeresa Johnson V->setInitializer(nullptr); 9674566c6dbSTeresa Johnson V->setLinkage(GlobalValue::ExternalLinkage); 9684566c6dbSTeresa Johnson V->clearMetadata(); 9697873669bSPeter Collingbourne V->setComdat(nullptr); 9705a95c477STeresa Johnson } else { 9715a95c477STeresa Johnson GlobalValue *NewGV; 9725a95c477STeresa Johnson if (GV.getValueType()->isFunctionTy()) 9735a95c477STeresa Johnson NewGV = 9745a95c477STeresa Johnson Function::Create(cast<FunctionType>(GV.getValueType()), 975f920da00SDylan McKay GlobalValue::ExternalLinkage, GV.getAddressSpace(), 976f920da00SDylan McKay "", GV.getParent()); 9775a95c477STeresa Johnson else 9785a95c477STeresa Johnson NewGV = 9795a95c477STeresa Johnson new GlobalVariable(*GV.getParent(), GV.getValueType(), 9805a95c477STeresa Johnson /*isConstant*/ false, GlobalValue::ExternalLinkage, 9815a95c477STeresa Johnson /*init*/ nullptr, "", 9825a95c477STeresa Johnson /*insertbefore*/ nullptr, GV.getThreadLocalMode(), 9835a95c477STeresa Johnson GV.getType()->getAddressSpace()); 9845a95c477STeresa Johnson NewGV->takeName(&GV); 9855a95c477STeresa Johnson GV.replaceAllUsesWith(NewGV); 9865a95c477STeresa Johnson return false; 9875a95c477STeresa Johnson } 9885a95c477STeresa Johnson return true; 989eaf5172cSGeorge Rimar } 9904566c6dbSTeresa Johnson 991e61652a3SPirama Arumuga Nainar /// Fixup prevailing symbol linkages in \p TheModule based on summary analysis. 992e61652a3SPirama Arumuga Nainar void llvm::thinLTOResolvePrevailingInModule( 993eaf5172cSGeorge Rimar Module &TheModule, const GVSummaryMapTy &DefinedGlobals) { 99404c9a2d6STeresa Johnson auto updateLinkage = [&](GlobalValue &GV) { 99504c9a2d6STeresa Johnson // See if the global summary analysis computed a new resolved linkage. 99604c9a2d6STeresa Johnson const auto &GS = DefinedGlobals.find(GV.getGUID()); 99704c9a2d6STeresa Johnson if (GS == DefinedGlobals.end()) 99804c9a2d6STeresa Johnson return; 99904c9a2d6STeresa Johnson auto NewLinkage = GS->second->linkage(); 100004c9a2d6STeresa Johnson if (NewLinkage == GV.getLinkage()) 100104c9a2d6STeresa Johnson return; 1002e61652a3SPirama Arumuga Nainar if (GlobalValue::isLocalLinkage(GV.getLinkage()) || 1003e5dd30f7SEugene Leviant // Don't internalize anything here, because the code below 1004e5dd30f7SEugene Leviant // lacks necessary correctness checks. Leave this job to 1005e5dd30f7SEugene Leviant // LLVM 'internalize' pass. 10060f418677SEugene Leviant GlobalValue::isLocalLinkage(NewLinkage) || 1007e61652a3SPirama Arumuga Nainar // In case it was dead and already converted to declaration. 1008e61652a3SPirama Arumuga Nainar GV.isDeclaration()) 10096a5fbe52SDavide Italiano return; 1010ea314fd4STeresa Johnson 10114566c6dbSTeresa Johnson // Check for a non-prevailing def that has interposable linkage 10124566c6dbSTeresa Johnson // (e.g. non-odr weak or linkonce). In that case we can't simply 10134566c6dbSTeresa Johnson // convert to available_externally, since it would lose the 10144566c6dbSTeresa Johnson // interposable property and possibly get inlined. Simply drop 10154566c6dbSTeresa Johnson // the definition in that case. 10164566c6dbSTeresa Johnson if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) && 10175a95c477STeresa Johnson GlobalValue::isInterposableLinkage(GV.getLinkage())) { 10185a95c477STeresa Johnson if (!convertToDeclaration(GV)) 10195a95c477STeresa Johnson // FIXME: Change this to collect replaced GVs and later erase 1020e61652a3SPirama Arumuga Nainar // them from the parent module once thinLTOResolvePrevailingGUID is 10215a95c477STeresa Johnson // changed to enable this for aliases. 10225a95c477STeresa Johnson llvm_unreachable("Expected GV to be converted"); 10235a95c477STeresa Johnson } else { 102437b80122STeresa Johnson // If all copies of the original symbol had global unnamed addr and 102537b80122STeresa Johnson // linkonce_odr linkage, it should be an auto hide symbol. In that case 102637b80122STeresa Johnson // the thin link would have marked it as CanAutoHide. Add hidden visibility 102737b80122STeresa Johnson // to the symbol to preserve the property. 102837b80122STeresa Johnson if (NewLinkage == GlobalValue::WeakODRLinkage && 102937b80122STeresa Johnson GS->second->canAutoHide()) { 103037b80122STeresa Johnson assert(GV.hasLinkOnceODRLinkage() && GV.hasGlobalUnnamedAddr()); 103133ba93c2SSteven Wu GV.setVisibility(GlobalValue::HiddenVisibility); 103237b80122STeresa Johnson } 103333ba93c2SSteven Wu 1034d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() 1035d34e60caSNicola Zaghen << "` from " << GV.getLinkage() << " to " << NewLinkage 1036d34e60caSNicola Zaghen << "\n"); 103704c9a2d6STeresa Johnson GV.setLinkage(NewLinkage); 10384566c6dbSTeresa Johnson } 10394566c6dbSTeresa Johnson // Remove declarations from comdats, including available_externally 10406107a419STeresa Johnson // as this is a declaration for the linker, and will be dropped eventually. 10416107a419STeresa Johnson // It is illegal for comdats to contain declarations. 10426107a419STeresa Johnson auto *GO = dyn_cast_or_null<GlobalObject>(&GV); 10434566c6dbSTeresa Johnson if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) 10446107a419STeresa Johnson GO->setComdat(nullptr); 104504c9a2d6STeresa Johnson }; 104604c9a2d6STeresa Johnson 104704c9a2d6STeresa Johnson // Process functions and global now 104804c9a2d6STeresa Johnson for (auto &GV : TheModule) 104904c9a2d6STeresa Johnson updateLinkage(GV); 105004c9a2d6STeresa Johnson for (auto &GV : TheModule.globals()) 105104c9a2d6STeresa Johnson updateLinkage(GV); 105204c9a2d6STeresa Johnson for (auto &GV : TheModule.aliases()) 105304c9a2d6STeresa Johnson updateLinkage(GV); 105404c9a2d6STeresa Johnson } 105504c9a2d6STeresa Johnson 105604c9a2d6STeresa Johnson /// Run internalization on \p TheModule based on symmary analysis. 105704c9a2d6STeresa Johnson void llvm::thinLTOInternalizeModule(Module &TheModule, 105804c9a2d6STeresa Johnson const GVSummaryMapTy &DefinedGlobals) { 105904c9a2d6STeresa Johnson // Declare a callback for the internalize pass that will ask for every 106004c9a2d6STeresa Johnson // candidate GlobalValue if it can be internalized or not. 106104c9a2d6STeresa Johnson auto MustPreserveGV = [&](const GlobalValue &GV) -> bool { 106204c9a2d6STeresa Johnson // Lookup the linkage recorded in the summaries during global analysis. 1063c3d677f9SPeter Collingbourne auto GS = DefinedGlobals.find(GV.getGUID()); 106404c9a2d6STeresa Johnson if (GS == DefinedGlobals.end()) { 106504c9a2d6STeresa Johnson // Must have been promoted (possibly conservatively). Find original 106604c9a2d6STeresa Johnson // name so that we can access the correct summary and see if it can 106704c9a2d6STeresa Johnson // be internalized again. 106804c9a2d6STeresa Johnson // FIXME: Eventually we should control promotion instead of promoting 106904c9a2d6STeresa Johnson // and internalizing again. 107004c9a2d6STeresa Johnson StringRef OrigName = 107104c9a2d6STeresa Johnson ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName()); 107204c9a2d6STeresa Johnson std::string OrigId = GlobalValue::getGlobalIdentifier( 107304c9a2d6STeresa Johnson OrigName, GlobalValue::InternalLinkage, 107404c9a2d6STeresa Johnson TheModule.getSourceFileName()); 1075c3d677f9SPeter Collingbourne GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId)); 10767ab1f692STeresa Johnson if (GS == DefinedGlobals.end()) { 10777ab1f692STeresa Johnson // Also check the original non-promoted non-globalized name. In some 10787ab1f692STeresa Johnson // cases a preempted weak value is linked in as a local copy because 10797ab1f692STeresa Johnson // it is referenced by an alias (IRLinker::linkGlobalValueProto). 10807ab1f692STeresa Johnson // In that case, since it was originally not a local value, it was 10817ab1f692STeresa Johnson // recorded in the index using the original name. 10827ab1f692STeresa Johnson // FIXME: This may not be needed once PR27866 is fixed. 1083c3d677f9SPeter Collingbourne GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName)); 108404c9a2d6STeresa Johnson assert(GS != DefinedGlobals.end()); 10857ab1f692STeresa Johnson } 1086c3d677f9SPeter Collingbourne } 1087c3d677f9SPeter Collingbourne return !GlobalValue::isLocalLinkage(GS->second->linkage()); 108804c9a2d6STeresa Johnson }; 108904c9a2d6STeresa Johnson 109004c9a2d6STeresa Johnson // FIXME: See if we can just internalize directly here via linkage changes 109104c9a2d6STeresa Johnson // based on the index, rather than invoking internalizeModule. 1092e9ea08a0SEugene Zelenko internalizeModule(TheModule, MustPreserveGV); 109304c9a2d6STeresa Johnson } 109404c9a2d6STeresa Johnson 109581bbf742STeresa Johnson /// Make alias a clone of its aliasee. 109681bbf742STeresa Johnson static Function *replaceAliasWithAliasee(Module *SrcModule, GlobalAlias *GA) { 109781bbf742STeresa Johnson Function *Fn = cast<Function>(GA->getBaseObject()); 109881bbf742STeresa Johnson 109981bbf742STeresa Johnson ValueToValueMapTy VMap; 110081bbf742STeresa Johnson Function *NewFn = CloneFunction(Fn, VMap); 11015b2088d1STeresa Johnson // Clone should use the original alias's linkage, visibility and name, and we 11025b2088d1STeresa Johnson // ensure all uses of alias instead use the new clone (casted if necessary). 110381bbf742STeresa Johnson NewFn->setLinkage(GA->getLinkage()); 11045b2088d1STeresa Johnson NewFn->setVisibility(GA->getVisibility()); 110581bbf742STeresa Johnson GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewFn, GA->getType())); 110681bbf742STeresa Johnson NewFn->takeName(GA); 110781bbf742STeresa Johnson return NewFn; 110881bbf742STeresa Johnson } 110981bbf742STeresa Johnson 1110bf46e741SEugene Leviant // Internalize values that we marked with specific attribute 1111bf46e741SEugene Leviant // in processGlobalForThinLTO. 11123aef3528SEugene Leviant static void internalizeGVsAfterImport(Module &M) { 1113bf46e741SEugene Leviant for (auto &GV : M.globals()) 1114bf46e741SEugene Leviant // Skip GVs which have been converted to declarations 1115bf46e741SEugene Leviant // by dropDeadSymbols. 1116bf46e741SEugene Leviant if (!GV.isDeclaration() && GV.hasAttribute("thinlto-internalize")) { 1117bf46e741SEugene Leviant GV.setLinkage(GlobalValue::InternalLinkage); 1118bf46e741SEugene Leviant GV.setVisibility(GlobalValue::DefaultVisibility); 1119bf46e741SEugene Leviant } 1120bf46e741SEugene Leviant } 1121bf46e741SEugene Leviant 1122c8c55170SMehdi Amini // Automatically import functions in Module \p DestModule based on the summaries 1123c8c55170SMehdi Amini // index. 11247f00d0a1SPeter Collingbourne Expected<bool> FunctionImporter::importFunctions( 112566043797SAdrian Prantl Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) { 1126d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Starting import for Module " 1127311fef6eSMehdi Amini << DestModule.getModuleIdentifier() << "\n"); 112819e23874SEugene Leviant unsigned ImportedCount = 0, ImportedGVCount = 0; 1129c8c55170SMehdi Amini 11306d8f817fSPeter Collingbourne IRMover Mover(DestModule); 11317e88d0daSMehdi Amini // Do the actual import of functions now, one Module at a time 113201e32130SMehdi Amini std::set<StringRef> ModuleNameOrderedList; 113301e32130SMehdi Amini for (auto &FunctionsToImportPerModule : ImportList) { 113401e32130SMehdi Amini ModuleNameOrderedList.insert(FunctionsToImportPerModule.first()); 113501e32130SMehdi Amini } 113601e32130SMehdi Amini for (auto &Name : ModuleNameOrderedList) { 11377e88d0daSMehdi Amini // Get the module for the import 113801e32130SMehdi Amini const auto &FunctionsToImportPerModule = ImportList.find(Name); 113901e32130SMehdi Amini assert(FunctionsToImportPerModule != ImportList.end()); 1140d9445c49SPeter Collingbourne Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name); 1141d9445c49SPeter Collingbourne if (!SrcModuleOrErr) 1142d9445c49SPeter Collingbourne return SrcModuleOrErr.takeError(); 1143d9445c49SPeter Collingbourne std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr); 11447e88d0daSMehdi Amini assert(&DestModule.getContext() == &SrcModule->getContext() && 11457e88d0daSMehdi Amini "Context mismatch"); 11467e88d0daSMehdi Amini 11476cba37ceSTeresa Johnson // If modules were created with lazy metadata loading, materialize it 11486cba37ceSTeresa Johnson // now, before linking it (otherwise this will be a noop). 11497f00d0a1SPeter Collingbourne if (Error Err = SrcModule->materializeMetadata()) 11507f00d0a1SPeter Collingbourne return std::move(Err); 1151e5a61917STeresa Johnson 115201e32130SMehdi Amini auto &ImportGUIDs = FunctionsToImportPerModule->second; 115301e32130SMehdi Amini // Find the globals to import 11546d8f817fSPeter Collingbourne SetVector<GlobalValue *> GlobalsToImport; 11551f685e01SPiotr Padlewski for (Function &F : *SrcModule) { 11561f685e01SPiotr Padlewski if (!F.hasName()) 11570beb858eSTeresa Johnson continue; 11581f685e01SPiotr Padlewski auto GUID = F.getGUID(); 11590beb858eSTeresa Johnson auto Import = ImportGUIDs.count(GUID); 1160d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " 1161d34e60caSNicola Zaghen << GUID << " " << F.getName() << " from " 1162aeb1e59bSMehdi Amini << SrcModule->getSourceFileName() << "\n"); 11630beb858eSTeresa Johnson if (Import) { 11647f00d0a1SPeter Collingbourne if (Error Err = F.materialize()) 11657f00d0a1SPeter Collingbourne return std::move(Err); 11663b776128SPiotr Padlewski if (EnableImportMetadata) { 11676deaa6afSPiotr Padlewski // Add 'thinlto_src_module' metadata for statistics and debugging. 11683b776128SPiotr Padlewski F.setMetadata( 11693b776128SPiotr Padlewski "thinlto_src_module", 1170e9ea08a0SEugene Zelenko MDNode::get(DestModule.getContext(), 1171e9ea08a0SEugene Zelenko {MDString::get(DestModule.getContext(), 11726deaa6afSPiotr Padlewski SrcModule->getSourceFileName())})); 11733b776128SPiotr Padlewski } 11741f685e01SPiotr Padlewski GlobalsToImport.insert(&F); 117501e32130SMehdi Amini } 117601e32130SMehdi Amini } 11771f685e01SPiotr Padlewski for (GlobalVariable &GV : SrcModule->globals()) { 11782d28f7aaSMehdi Amini if (!GV.hasName()) 11792d28f7aaSMehdi Amini continue; 11802d28f7aaSMehdi Amini auto GUID = GV.getGUID(); 11812d28f7aaSMehdi Amini auto Import = ImportGUIDs.count(GUID); 1182d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " 1183d34e60caSNicola Zaghen << GUID << " " << GV.getName() << " from " 1184aeb1e59bSMehdi Amini << SrcModule->getSourceFileName() << "\n"); 11852d28f7aaSMehdi Amini if (Import) { 11867f00d0a1SPeter Collingbourne if (Error Err = GV.materialize()) 11877f00d0a1SPeter Collingbourne return std::move(Err); 118819e23874SEugene Leviant ImportedGVCount += GlobalsToImport.insert(&GV); 11892d28f7aaSMehdi Amini } 11902d28f7aaSMehdi Amini } 11911f685e01SPiotr Padlewski for (GlobalAlias &GA : SrcModule->aliases()) { 11921f685e01SPiotr Padlewski if (!GA.hasName()) 119301e32130SMehdi Amini continue; 11941f685e01SPiotr Padlewski auto GUID = GA.getGUID(); 119581bbf742STeresa Johnson auto Import = ImportGUIDs.count(GUID); 1196d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias " 1197d34e60caSNicola Zaghen << GUID << " " << GA.getName() << " from " 1198aeb1e59bSMehdi Amini << SrcModule->getSourceFileName() << "\n"); 119981bbf742STeresa Johnson if (Import) { 120081bbf742STeresa Johnson if (Error Err = GA.materialize()) 120181bbf742STeresa Johnson return std::move(Err); 120281bbf742STeresa Johnson // Import alias as a copy of its aliasee. 120381bbf742STeresa Johnson GlobalObject *Base = GA.getBaseObject(); 120481bbf742STeresa Johnson if (Error Err = Base->materialize()) 120581bbf742STeresa Johnson return std::move(Err); 120681bbf742STeresa Johnson auto *Fn = replaceAliasWithAliasee(SrcModule.get(), &GA); 1207d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Is importing aliasee fn " << Base->getGUID() 120881bbf742STeresa Johnson << " " << Base->getName() << " from " 120981bbf742STeresa Johnson << SrcModule->getSourceFileName() << "\n"); 121081bbf742STeresa Johnson if (EnableImportMetadata) { 121181bbf742STeresa Johnson // Add 'thinlto_src_module' metadata for statistics and debugging. 121281bbf742STeresa Johnson Fn->setMetadata( 121381bbf742STeresa Johnson "thinlto_src_module", 121481bbf742STeresa Johnson MDNode::get(DestModule.getContext(), 121581bbf742STeresa Johnson {MDString::get(DestModule.getContext(), 121681bbf742STeresa Johnson SrcModule->getSourceFileName())})); 121701e32130SMehdi Amini } 121881bbf742STeresa Johnson GlobalsToImport.insert(Fn); 121981bbf742STeresa Johnson } 122081bbf742STeresa Johnson } 122101e32130SMehdi Amini 122219ef4fadSMehdi Amini // Upgrade debug info after we're done materializing all the globals and we 122319ef4fadSMehdi Amini // have loaded all the required metadata! 122419ef4fadSMehdi Amini UpgradeDebugInfo(*SrcModule); 122519ef4fadSMehdi Amini 12267e88d0daSMehdi Amini // Link in the specified functions. 122701e32130SMehdi Amini if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport)) 12288d05185aSMehdi Amini return true; 12298d05185aSMehdi Amini 1230d29478f7STeresa Johnson if (PrintImports) { 1231d29478f7STeresa Johnson for (const auto *GV : GlobalsToImport) 1232d29478f7STeresa Johnson dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName() 1233d29478f7STeresa Johnson << " from " << SrcModule->getSourceFileName() << "\n"; 1234d29478f7STeresa Johnson } 1235d29478f7STeresa Johnson 12366d8f817fSPeter Collingbourne if (Mover.move(std::move(SrcModule), GlobalsToImport.getArrayRef(), 12376d8f817fSPeter Collingbourne [](GlobalValue &, IRMover::ValueAdder) {}, 1238e6fd9ff9SPeter Collingbourne /*IsPerformingImport=*/true)) 12397e88d0daSMehdi Amini report_fatal_error("Function Import: link error"); 12407e88d0daSMehdi Amini 124101e32130SMehdi Amini ImportedCount += GlobalsToImport.size(); 12426c475a75STeresa Johnson NumImportedModules++; 12437e88d0daSMehdi Amini } 1244e5a61917STeresa Johnson 12453aef3528SEugene Leviant internalizeGVsAfterImport(DestModule); 1246bf46e741SEugene Leviant 124719e23874SEugene Leviant NumImportedFunctions += (ImportedCount - ImportedGVCount); 124819e23874SEugene Leviant NumImportedGlobalVars += ImportedGVCount; 1249d29478f7STeresa Johnson 1250d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Imported " << ImportedCount - ImportedGVCount 1251d34e60caSNicola Zaghen << " functions for Module " 1252d34e60caSNicola Zaghen << DestModule.getModuleIdentifier() << "\n"); 1253d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Imported " << ImportedGVCount 125419e23874SEugene Leviant << " global variables for Module " 1255c8c55170SMehdi Amini << DestModule.getModuleIdentifier() << "\n"); 1256c8c55170SMehdi Amini return ImportedCount; 125742418abaSMehdi Amini } 125842418abaSMehdi Amini 1259598bd2a2SPeter Collingbourne static bool doImportingForModule(Module &M) { 1260598bd2a2SPeter Collingbourne if (SummaryFile.empty()) 1261598bd2a2SPeter Collingbourne report_fatal_error("error: -function-import requires -summary-file\n"); 12626de481a3SPeter Collingbourne Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr = 12636de481a3SPeter Collingbourne getModuleSummaryIndexForFile(SummaryFile); 12646de481a3SPeter Collingbourne if (!IndexPtrOrErr) { 12656de481a3SPeter Collingbourne logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(), 12666de481a3SPeter Collingbourne "Error loading file '" + SummaryFile + "': "); 126742418abaSMehdi Amini return false; 126842418abaSMehdi Amini } 1269598bd2a2SPeter Collingbourne std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr); 127042418abaSMehdi Amini 1271c86af334STeresa Johnson // First step is collecting the import list. 1272c86af334STeresa Johnson FunctionImporter::ImportMapTy ImportList; 127381bbf742STeresa Johnson // If requested, simply import all functions in the index. This is used 127481bbf742STeresa Johnson // when testing distributed backend handling via the opt tool, when 127581bbf742STeresa Johnson // we have distributed indexes containing exactly the summaries to import. 127681bbf742STeresa Johnson if (ImportAllIndex) 127781bbf742STeresa Johnson ComputeCrossModuleImportForModuleFromIndex(M.getModuleIdentifier(), *Index, 127881bbf742STeresa Johnson ImportList); 127981bbf742STeresa Johnson else 1280c86af334STeresa Johnson ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index, 1281c86af334STeresa Johnson ImportList); 128201e32130SMehdi Amini 12834fef68cbSTeresa Johnson // Conservatively mark all internal values as promoted. This interface is 12844fef68cbSTeresa Johnson // only used when doing importing via the function importing pass. The pass 12854fef68cbSTeresa Johnson // is only enabled when testing importing via the 'opt' tool, which does 12864fef68cbSTeresa Johnson // not do the ThinLink that would normally determine what values to promote. 12874fef68cbSTeresa Johnson for (auto &I : *Index) { 12889667b91bSPeter Collingbourne for (auto &S : I.second.SummaryList) { 12894fef68cbSTeresa Johnson if (GlobalValue::isLocalLinkage(S->linkage())) 12904fef68cbSTeresa Johnson S->setLinkage(GlobalValue::ExternalLinkage); 12914fef68cbSTeresa Johnson } 12924fef68cbSTeresa Johnson } 12934fef68cbSTeresa Johnson 129401e32130SMehdi Amini // Next we need to promote to global scope and rename any local values that 12951b00f2d9STeresa Johnson // are potentially exported to other modules. 129601e32130SMehdi Amini if (renameModuleForThinLTO(M, *Index, nullptr)) { 12971b00f2d9STeresa Johnson errs() << "Error renaming module\n"; 12981b00f2d9STeresa Johnson return false; 12991b00f2d9STeresa Johnson } 13001b00f2d9STeresa Johnson 130142418abaSMehdi Amini // Perform the import now. 1302d16c8065SMehdi Amini auto ModuleLoader = [&M](StringRef Identifier) { 1303d16c8065SMehdi Amini return loadFile(Identifier, M.getContext()); 1304d16c8065SMehdi Amini }; 13059d2bfc48SRafael Espindola FunctionImporter Importer(*Index, ModuleLoader); 130637e24591SPeter Collingbourne Expected<bool> Result = Importer.importFunctions(M, ImportList); 13077f00d0a1SPeter Collingbourne 13087f00d0a1SPeter Collingbourne // FIXME: Probably need to propagate Errors through the pass manager. 13097f00d0a1SPeter Collingbourne if (!Result) { 13107f00d0a1SPeter Collingbourne logAllUnhandledErrors(Result.takeError(), errs(), 13117f00d0a1SPeter Collingbourne "Error importing module: "); 13127f00d0a1SPeter Collingbourne return false; 13137f00d0a1SPeter Collingbourne } 13147f00d0a1SPeter Collingbourne 13157f00d0a1SPeter Collingbourne return *Result; 131621241571STeresa Johnson } 131721241571STeresa Johnson 131821241571STeresa Johnson namespace { 1319e9ea08a0SEugene Zelenko 132021241571STeresa Johnson /// Pass that performs cross-module function import provided a summary file. 132121241571STeresa Johnson class FunctionImportLegacyPass : public ModulePass { 132221241571STeresa Johnson public: 132321241571STeresa Johnson /// Pass identification, replacement for typeid 132421241571STeresa Johnson static char ID; 132521241571STeresa Johnson 1326e9ea08a0SEugene Zelenko explicit FunctionImportLegacyPass() : ModulePass(ID) {} 1327e9ea08a0SEugene Zelenko 132821241571STeresa Johnson /// Specify pass name for debug output 1329117296c0SMehdi Amini StringRef getPassName() const override { return "Function Importing"; } 133021241571STeresa Johnson 133121241571STeresa Johnson bool runOnModule(Module &M) override { 133221241571STeresa Johnson if (skipModule(M)) 133321241571STeresa Johnson return false; 133421241571STeresa Johnson 1335598bd2a2SPeter Collingbourne return doImportingForModule(M); 133642418abaSMehdi Amini } 133742418abaSMehdi Amini }; 1338e9ea08a0SEugene Zelenko 1339e9ea08a0SEugene Zelenko } // end anonymous namespace 134042418abaSMehdi Amini 134121241571STeresa Johnson PreservedAnalyses FunctionImportPass::run(Module &M, 1342fd03ac6aSSean Silva ModuleAnalysisManager &AM) { 1343598bd2a2SPeter Collingbourne if (!doImportingForModule(M)) 134421241571STeresa Johnson return PreservedAnalyses::all(); 134521241571STeresa Johnson 134621241571STeresa Johnson return PreservedAnalyses::none(); 134721241571STeresa Johnson } 134821241571STeresa Johnson 134921241571STeresa Johnson char FunctionImportLegacyPass::ID = 0; 135021241571STeresa Johnson INITIALIZE_PASS(FunctionImportLegacyPass, "function-import", 135142418abaSMehdi Amini "Summary Based Function Import", false, false) 135242418abaSMehdi Amini 135342418abaSMehdi Amini namespace llvm { 1354e9ea08a0SEugene Zelenko 1355598bd2a2SPeter Collingbourne Pass *createFunctionImportPass() { 1356598bd2a2SPeter Collingbourne return new FunctionImportLegacyPass(); 13575fcbdb71STeresa Johnson } 1358e9ea08a0SEugene Zelenko 1359e9ea08a0SEugene Zelenko } // end namespace llvm 1360