142418abaSMehdi Amini //===- FunctionImport.cpp - ThinLTO Summary-based Function Import ---------===// 242418abaSMehdi Amini // 342418abaSMehdi Amini // The LLVM Compiler Infrastructure 442418abaSMehdi Amini // 542418abaSMehdi Amini // This file is distributed under the University of Illinois Open Source 642418abaSMehdi Amini // License. See LICENSE.TXT for details. 742418abaSMehdi Amini // 842418abaSMehdi Amini //===----------------------------------------------------------------------===// 942418abaSMehdi Amini // 1042418abaSMehdi Amini // This file implements Function import based on summaries. 1142418abaSMehdi Amini // 1242418abaSMehdi Amini //===----------------------------------------------------------------------===// 1342418abaSMehdi Amini 1442418abaSMehdi Amini #include "llvm/Transforms/IPO/FunctionImport.h" 15e9ea08a0SEugene Zelenko #include "llvm/ADT/ArrayRef.h" 16e9ea08a0SEugene Zelenko #include "llvm/ADT/STLExtras.h" 17e9ea08a0SEugene Zelenko #include "llvm/ADT/SetVector.h" 1801e32130SMehdi Amini #include "llvm/ADT/SmallVector.h" 19d29478f7STeresa Johnson #include "llvm/ADT/Statistic.h" 20e9ea08a0SEugene Zelenko #include "llvm/ADT/StringMap.h" 21d3e7d19fSCharles Saternos #include "llvm/ADT/StringSet.h" 222ad768bbSVolodymyr Sapsai #include "llvm/ADT/StringRef.h" 23c15d60b7SPeter Collingbourne #include "llvm/Bitcode/BitcodeReader.h" 2442418abaSMehdi Amini #include "llvm/IR/AutoUpgrade.h" 2581bbf742STeresa Johnson #include "llvm/IR/Constants.h" 26e9ea08a0SEugene Zelenko #include "llvm/IR/Function.h" 27e9ea08a0SEugene Zelenko #include "llvm/IR/GlobalAlias.h" 28e9ea08a0SEugene Zelenko #include "llvm/IR/GlobalObject.h" 29e9ea08a0SEugene Zelenko #include "llvm/IR/GlobalValue.h" 30e9ea08a0SEugene Zelenko #include "llvm/IR/GlobalVariable.h" 31e9ea08a0SEugene Zelenko #include "llvm/IR/Metadata.h" 3242418abaSMehdi Amini #include "llvm/IR/Module.h" 33e9ea08a0SEugene Zelenko #include "llvm/IR/ModuleSummaryIndex.h" 3442418abaSMehdi Amini #include "llvm/IRReader/IRReader.h" 35e9ea08a0SEugene Zelenko #include "llvm/Linker/IRMover.h" 36e9ea08a0SEugene Zelenko #include "llvm/Object/ModuleSymbolTable.h" 37e9ea08a0SEugene Zelenko #include "llvm/Object/SymbolicFile.h" 38e9ea08a0SEugene Zelenko #include "llvm/Pass.h" 39e9ea08a0SEugene Zelenko #include "llvm/Support/Casting.h" 4042418abaSMehdi Amini #include "llvm/Support/CommandLine.h" 4142418abaSMehdi Amini #include "llvm/Support/Debug.h" 42e9ea08a0SEugene Zelenko #include "llvm/Support/Error.h" 43e9ea08a0SEugene Zelenko #include "llvm/Support/ErrorHandling.h" 44e9ea08a0SEugene Zelenko #include "llvm/Support/FileSystem.h" 4542418abaSMehdi Amini #include "llvm/Support/SourceMgr.h" 46e9ea08a0SEugene Zelenko #include "llvm/Support/raw_ostream.h" 4704c9a2d6STeresa Johnson #include "llvm/Transforms/IPO/Internalize.h" 4881bbf742STeresa Johnson #include "llvm/Transforms/Utils/Cloning.h" 49488a800aSTeresa Johnson #include "llvm/Transforms/Utils/FunctionImportUtils.h" 5081bbf742STeresa Johnson #include "llvm/Transforms/Utils/ValueMapper.h" 51e9ea08a0SEugene Zelenko #include <cassert> 52e9ea08a0SEugene Zelenko #include <memory> 53e9ea08a0SEugene Zelenko #include <set> 54e9ea08a0SEugene Zelenko #include <string> 55e9ea08a0SEugene Zelenko #include <system_error> 56e9ea08a0SEugene Zelenko #include <tuple> 57e9ea08a0SEugene Zelenko #include <utility> 587e88d0daSMehdi Amini 5942418abaSMehdi Amini using namespace llvm; 6042418abaSMehdi Amini 61e9ea08a0SEugene Zelenko #define DEBUG_TYPE "function-import" 62e9ea08a0SEugene Zelenko 636c475a75STeresa Johnson STATISTIC(NumImportedFunctions, "Number of functions imported"); 64*7331a0bfSEugene Leviant STATISTIC(NumImportedGlobalVars, "Number of global variables imported"); 656c475a75STeresa Johnson STATISTIC(NumImportedModules, "Number of modules imported from"); 666c475a75STeresa Johnson STATISTIC(NumDeadSymbols, "Number of dead stripped symbols in index"); 676c475a75STeresa Johnson STATISTIC(NumLiveSymbols, "Number of live symbols in index"); 68d29478f7STeresa Johnson 6939303619STeresa Johnson /// Limit on instruction count of imported functions. 7039303619STeresa Johnson static cl::opt<unsigned> ImportInstrLimit( 7139303619STeresa Johnson "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"), 7239303619STeresa Johnson cl::desc("Only import functions with less than N instructions")); 7339303619STeresa Johnson 7440641748SMehdi Amini static cl::opt<float> 7540641748SMehdi Amini ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7), 7640641748SMehdi Amini cl::Hidden, cl::value_desc("x"), 7740641748SMehdi Amini cl::desc("As we import functions, multiply the " 7840641748SMehdi Amini "`import-instr-limit` threshold by this factor " 7940641748SMehdi Amini "before processing newly imported functions")); 80ba72b95fSPiotr Padlewski 81d2869473SPiotr Padlewski static cl::opt<float> ImportHotInstrFactor( 82d2869473SPiotr Padlewski "import-hot-evolution-factor", cl::init(1.0), cl::Hidden, 83d2869473SPiotr Padlewski cl::value_desc("x"), 84d2869473SPiotr Padlewski cl::desc("As we import functions called from hot callsite, multiply the " 85d2869473SPiotr Padlewski "`import-instr-limit` threshold by this factor " 86d2869473SPiotr Padlewski "before processing newly imported functions")); 87d2869473SPiotr Padlewski 88d9830eb7SPiotr Padlewski static cl::opt<float> ImportHotMultiplier( 898260d665SDehao Chen "import-hot-multiplier", cl::init(10.0), cl::Hidden, cl::value_desc("x"), 90ba72b95fSPiotr Padlewski cl::desc("Multiply the `import-instr-limit` threshold for hot callsites")); 91ba72b95fSPiotr Padlewski 9264c46574SDehao Chen static cl::opt<float> ImportCriticalMultiplier( 9364c46574SDehao Chen "import-critical-multiplier", cl::init(100.0), cl::Hidden, 9464c46574SDehao Chen cl::value_desc("x"), 9564c46574SDehao Chen cl::desc( 9664c46574SDehao Chen "Multiply the `import-instr-limit` threshold for critical callsites")); 9764c46574SDehao Chen 98ba72b95fSPiotr Padlewski // FIXME: This multiplier was not really tuned up. 99ba72b95fSPiotr Padlewski static cl::opt<float> ImportColdMultiplier( 100ba72b95fSPiotr Padlewski "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"), 101ba72b95fSPiotr Padlewski cl::desc("Multiply the `import-instr-limit` threshold for cold callsites")); 10240641748SMehdi Amini 103d29478f7STeresa Johnson static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden, 104d29478f7STeresa Johnson cl::desc("Print imported functions")); 105d29478f7STeresa Johnson 1066c475a75STeresa Johnson static cl::opt<bool> ComputeDead("compute-dead", cl::init(true), cl::Hidden, 1076c475a75STeresa Johnson cl::desc("Compute dead symbols")); 1086c475a75STeresa Johnson 1093b776128SPiotr Padlewski static cl::opt<bool> EnableImportMetadata( 1103b776128SPiotr Padlewski "enable-import-metadata", cl::init( 1113b776128SPiotr Padlewski #if !defined(NDEBUG) 1123b776128SPiotr Padlewski true /*Enabled with asserts.*/ 1133b776128SPiotr Padlewski #else 1143b776128SPiotr Padlewski false 1153b776128SPiotr Padlewski #endif 1163b776128SPiotr Padlewski ), 1173b776128SPiotr Padlewski cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'")); 1183b776128SPiotr Padlewski 119e9ea08a0SEugene Zelenko /// Summary file to use for function importing when using -function-import from 120e9ea08a0SEugene Zelenko /// the command line. 121e9ea08a0SEugene Zelenko static cl::opt<std::string> 122e9ea08a0SEugene Zelenko SummaryFile("summary-file", 123e9ea08a0SEugene Zelenko cl::desc("The summary file to use for function importing.")); 124e9ea08a0SEugene Zelenko 12581bbf742STeresa Johnson /// Used when testing importing from distributed indexes via opt 12681bbf742STeresa Johnson // -function-import. 12781bbf742STeresa Johnson static cl::opt<bool> 12881bbf742STeresa Johnson ImportAllIndex("import-all-index", 12981bbf742STeresa Johnson cl::desc("Import all external functions in index.")); 13081bbf742STeresa Johnson 13142418abaSMehdi Amini // Load lazily a module from \p FileName in \p Context. 13242418abaSMehdi Amini static std::unique_ptr<Module> loadFile(const std::string &FileName, 13342418abaSMehdi Amini LLVMContext &Context) { 13442418abaSMehdi Amini SMDiagnostic Err; 13542418abaSMehdi Amini DEBUG(dbgs() << "Loading '" << FileName << "'\n"); 1366cba37ceSTeresa Johnson // Metadata isn't loaded until functions are imported, to minimize 1376cba37ceSTeresa Johnson // the memory overhead. 138a1080ee6STeresa Johnson std::unique_ptr<Module> Result = 139a1080ee6STeresa Johnson getLazyIRFileModule(FileName, Err, Context, 140a1080ee6STeresa Johnson /* ShouldLazyLoadMetadata = */ true); 14142418abaSMehdi Amini if (!Result) { 14242418abaSMehdi Amini Err.print("function-import", errs()); 143d7ad221cSMehdi Amini report_fatal_error("Abort"); 14442418abaSMehdi Amini } 14542418abaSMehdi Amini 14642418abaSMehdi Amini return Result; 14742418abaSMehdi Amini } 14842418abaSMehdi Amini 14901e32130SMehdi Amini /// Given a list of possible callee implementation for a call site, select one 15001e32130SMehdi Amini /// that fits the \p Threshold. 15101e32130SMehdi Amini /// 15201e32130SMehdi Amini /// FIXME: select "best" instead of first that fits. But what is "best"? 15301e32130SMehdi Amini /// - The smallest: more likely to be inlined. 15401e32130SMehdi Amini /// - The one with the least outgoing edges (already well optimized). 15501e32130SMehdi Amini /// - One from a module already being imported from in order to reduce the 15601e32130SMehdi Amini /// number of source modules parsed/linked. 15701e32130SMehdi Amini /// - One that has PGO data attached. 15801e32130SMehdi Amini /// - [insert you fancy metric here] 1592d28f7aaSMehdi Amini static const GlobalValueSummary * 160b4e1e829SMehdi Amini selectCallee(const ModuleSummaryIndex &Index, 1619667b91bSPeter Collingbourne ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList, 16283aaf358STeresa Johnson unsigned Threshold, StringRef CallerModulePath) { 16301e32130SMehdi Amini auto It = llvm::find_if( 16428e457bcSTeresa Johnson CalleeSummaryList, 16528e457bcSTeresa Johnson [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) { 16628e457bcSTeresa Johnson auto *GVSummary = SummaryPtr.get(); 167eaf5172cSGeorge Rimar if (!Index.isGlobalValueLive(GVSummary)) 168eaf5172cSGeorge Rimar return false; 169eaf5172cSGeorge Rimar 17073305f82STeresa Johnson // For SamplePGO, in computeImportForFunction the OriginalId 17173305f82STeresa Johnson // may have been used to locate the callee summary list (See 17273305f82STeresa Johnson // comment there). 17373305f82STeresa Johnson // The mapping from OriginalId to GUID may return a GUID 17473305f82STeresa Johnson // that corresponds to a static variable. Filter it out here. 17573305f82STeresa Johnson // This can happen when 17673305f82STeresa Johnson // 1) There is a call to a library function which is not defined 17773305f82STeresa Johnson // in the index. 17873305f82STeresa Johnson // 2) There is a static variable with the OriginalGUID identical 17973305f82STeresa Johnson // to the GUID of the library function in 1); 18073305f82STeresa Johnson // When this happens, the logic for SamplePGO kicks in and 18173305f82STeresa Johnson // the static variable in 2) will be found, which needs to be 18273305f82STeresa Johnson // filtered out. 18373305f82STeresa Johnson if (GVSummary->getSummaryKind() == GlobalValueSummary::GlobalVarKind) 18473305f82STeresa Johnson return false; 185f329be83SRafael Espindola if (GlobalValue::isInterposableLinkage(GVSummary->linkage())) 1865b85d8d6SMehdi Amini // There is no point in importing these, we can't inline them 18701e32130SMehdi Amini return false; 1882c719cc1SMehdi Amini 18981bbf742STeresa Johnson auto *Summary = cast<FunctionSummary>(GVSummary->getBaseObject()); 1907e88d0daSMehdi Amini 19183aaf358STeresa Johnson // If this is a local function, make sure we import the copy 19283aaf358STeresa Johnson // in the caller's module. The only time a local function can 19383aaf358STeresa Johnson // share an entry in the index is if there is a local with the same name 19483aaf358STeresa Johnson // in another module that had the same source file name (in a different 19583aaf358STeresa Johnson // directory), where each was compiled in their own directory so there 19683aaf358STeresa Johnson // was not distinguishing path. 19783aaf358STeresa Johnson // However, do the import from another module if there is only one 19883aaf358STeresa Johnson // entry in the list - in that case this must be a reference due 19983aaf358STeresa Johnson // to indirect call profile data, since a function pointer can point to 20083aaf358STeresa Johnson // a local in another module. 20183aaf358STeresa Johnson if (GlobalValue::isLocalLinkage(Summary->linkage()) && 20283aaf358STeresa Johnson CalleeSummaryList.size() > 1 && 20383aaf358STeresa Johnson Summary->modulePath() != CallerModulePath) 20483aaf358STeresa Johnson return false; 20583aaf358STeresa Johnson 206f9dc3deaSTeresa Johnson if (Summary->instCount() > Threshold) 207f9dc3deaSTeresa Johnson return false; 208f9dc3deaSTeresa Johnson 209519465b9STeresa Johnson if (Summary->notEligibleToImport()) 210b4e1e829SMehdi Amini return false; 211b4e1e829SMehdi Amini 21201e32130SMehdi Amini return true; 21301e32130SMehdi Amini }); 21428e457bcSTeresa Johnson if (It == CalleeSummaryList.end()) 21501e32130SMehdi Amini return nullptr; 2167e88d0daSMehdi Amini 217f9dc3deaSTeresa Johnson return cast<GlobalValueSummary>(It->get()); 218434e9561SRafael Espindola } 2197e88d0daSMehdi Amini 220e9ea08a0SEugene Zelenko namespace { 221e9ea08a0SEugene Zelenko 222475b51a7STeresa Johnson using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */, 223475b51a7STeresa Johnson GlobalValue::GUID>; 22401e32130SMehdi Amini 225e9ea08a0SEugene Zelenko } // anonymous namespace 226e9ea08a0SEugene Zelenko 2271958083dSTeresa Johnson static ValueInfo 2281958083dSTeresa Johnson updateValueInfoForIndirectCalls(const ModuleSummaryIndex &Index, ValueInfo VI) { 2291958083dSTeresa Johnson if (!VI.getSummaryList().empty()) 2301958083dSTeresa Johnson return VI; 2311958083dSTeresa Johnson // For SamplePGO, the indirect call targets for local functions will 2321958083dSTeresa Johnson // have its original name annotated in profile. We try to find the 2331958083dSTeresa Johnson // corresponding PGOFuncName as the GUID. 2341958083dSTeresa Johnson // FIXME: Consider updating the edges in the graph after building 2351958083dSTeresa Johnson // it, rather than needing to perform this mapping on each walk. 2361958083dSTeresa Johnson auto GUID = Index.getGUIDFromOriginalID(VI.getGUID()); 2371958083dSTeresa Johnson if (GUID == 0) 23828d8a49fSEugene Leviant return ValueInfo(); 2391958083dSTeresa Johnson return Index.getValueInfo(GUID); 2401958083dSTeresa Johnson } 2411958083dSTeresa Johnson 242*7331a0bfSEugene Leviant static void computeImportForReferencedGlobals( 243*7331a0bfSEugene Leviant const FunctionSummary &Summary, const GVSummaryMapTy &DefinedGVSummaries, 244*7331a0bfSEugene Leviant FunctionImporter::ImportMapTy &ImportList, 245*7331a0bfSEugene Leviant StringMap<FunctionImporter::ExportSetTy> *ExportLists) { 246*7331a0bfSEugene Leviant for (auto &VI : Summary.refs()) { 247*7331a0bfSEugene Leviant if (DefinedGVSummaries.count(VI.getGUID())) { 248*7331a0bfSEugene Leviant DEBUG(dbgs() << "Ref ignored! Target already in destination module.\n"); 249*7331a0bfSEugene Leviant continue; 250*7331a0bfSEugene Leviant } 251*7331a0bfSEugene Leviant 252*7331a0bfSEugene Leviant DEBUG(dbgs() << " ref -> " << VI.getGUID() << "\n"); 253*7331a0bfSEugene Leviant 254*7331a0bfSEugene Leviant for (auto &RefSummary : VI.getSummaryList()) 255*7331a0bfSEugene Leviant if (RefSummary->getSummaryKind() == GlobalValueSummary::GlobalVarKind && 256*7331a0bfSEugene Leviant // Don't try to import regular LTO summaries added to dummy module. 257*7331a0bfSEugene Leviant !RefSummary->modulePath().empty() && 258*7331a0bfSEugene Leviant !GlobalValue::isInterposableLinkage(RefSummary->linkage()) && 259*7331a0bfSEugene Leviant // For now we don't import global variables which have outgoing 260*7331a0bfSEugene Leviant // refs. Otherwise we have to promote referenced vars/functions. 261*7331a0bfSEugene Leviant RefSummary->refs().empty()) { 262*7331a0bfSEugene Leviant ImportList[RefSummary->modulePath()][VI.getGUID()] = 1; 263*7331a0bfSEugene Leviant if (ExportLists) 264*7331a0bfSEugene Leviant (*ExportLists)[RefSummary->modulePath()].insert(VI.getGUID()); 265*7331a0bfSEugene Leviant } 266*7331a0bfSEugene Leviant } 267*7331a0bfSEugene Leviant } 268*7331a0bfSEugene Leviant 26901e32130SMehdi Amini /// Compute the list of functions to import for a given caller. Mark these 27001e32130SMehdi Amini /// imported functions and the symbols they reference in their source module as 27101e32130SMehdi Amini /// exported from their source module. 27201e32130SMehdi Amini static void computeImportForFunction( 2733255eec1STeresa Johnson const FunctionSummary &Summary, const ModuleSummaryIndex &Index, 274d9830eb7SPiotr Padlewski const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries, 27501e32130SMehdi Amini SmallVectorImpl<EdgeInfo> &Worklist, 2769b490f10SMehdi Amini FunctionImporter::ImportMapTy &ImportList, 277c86af334STeresa Johnson StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) { 278*7331a0bfSEugene Leviant computeImportForReferencedGlobals(Summary, DefinedGVSummaries, ImportList, 279*7331a0bfSEugene Leviant ExportLists); 28001e32130SMehdi Amini for (auto &Edge : Summary.calls()) { 2819667b91bSPeter Collingbourne ValueInfo VI = Edge.first; 2829667b91bSPeter Collingbourne DEBUG(dbgs() << " edge -> " << VI.getGUID() << " Threshold:" << Threshold 2839667b91bSPeter Collingbourne << "\n"); 28401e32130SMehdi Amini 2851958083dSTeresa Johnson VI = updateValueInfoForIndirectCalls(Index, VI); 2869667b91bSPeter Collingbourne if (!VI) 2879667b91bSPeter Collingbourne continue; 2884a435e08SDehao Chen 2899667b91bSPeter Collingbourne if (DefinedGVSummaries.count(VI.getGUID())) { 29001e32130SMehdi Amini DEBUG(dbgs() << "ignored! Target already in destination module.\n"); 2917e88d0daSMehdi Amini continue; 292d450da32STeresa Johnson } 29340641748SMehdi Amini 294ba72b95fSPiotr Padlewski auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float { 295ba72b95fSPiotr Padlewski if (Hotness == CalleeInfo::HotnessType::Hot) 296ba72b95fSPiotr Padlewski return ImportHotMultiplier; 297ba72b95fSPiotr Padlewski if (Hotness == CalleeInfo::HotnessType::Cold) 298ba72b95fSPiotr Padlewski return ImportColdMultiplier; 29964c46574SDehao Chen if (Hotness == CalleeInfo::HotnessType::Critical) 30064c46574SDehao Chen return ImportCriticalMultiplier; 301ba72b95fSPiotr Padlewski return 1.0; 302ba72b95fSPiotr Padlewski }; 303ba72b95fSPiotr Padlewski 304d9830eb7SPiotr Padlewski const auto NewThreshold = 305c73cec84SEaswaran Raman Threshold * GetBonusMultiplier(Edge.second.getHotness()); 306d2869473SPiotr Padlewski 3079667b91bSPeter Collingbourne auto *CalleeSummary = selectCallee(Index, VI.getSummaryList(), NewThreshold, 3089667b91bSPeter Collingbourne Summary.modulePath()); 30901e32130SMehdi Amini if (!CalleeSummary) { 31001e32130SMehdi Amini DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n"); 3117e88d0daSMehdi Amini continue; 3127e88d0daSMehdi Amini } 3132f0cc477SDavid Blaikie 3142f0cc477SDavid Blaikie // "Resolve" the summary 31581bbf742STeresa Johnson const auto *ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary->getBaseObject()); 3162d28f7aaSMehdi Amini 317d9830eb7SPiotr Padlewski assert(ResolvedCalleeSummary->instCount() <= NewThreshold && 31801e32130SMehdi Amini "selectCallee() didn't honor the threshold"); 31901e32130SMehdi Amini 320d2869473SPiotr Padlewski auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) { 321d2869473SPiotr Padlewski // Adjust the threshold for next level of imported functions. 322d2869473SPiotr Padlewski // The threshold is different for hot callsites because we can then 323d2869473SPiotr Padlewski // inline chains of hot calls. 324d2869473SPiotr Padlewski if (IsHotCallsite) 325d2869473SPiotr Padlewski return Threshold * ImportHotInstrFactor; 326d2869473SPiotr Padlewski return Threshold * ImportInstrFactor; 327d2869473SPiotr Padlewski }; 328d2869473SPiotr Padlewski 329c73cec84SEaswaran Raman bool IsHotCallsite = 330c73cec84SEaswaran Raman Edge.second.getHotness() == CalleeInfo::HotnessType::Hot; 3311b859a23STeresa Johnson const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite); 3321b859a23STeresa Johnson 3331b859a23STeresa Johnson auto ExportModulePath = ResolvedCalleeSummary->modulePath(); 3349667b91bSPeter Collingbourne auto &ProcessedThreshold = ImportList[ExportModulePath][VI.getGUID()]; 3351b859a23STeresa Johnson /// Since the traversal of the call graph is DFS, we can revisit a function 3361b859a23STeresa Johnson /// a second time with a higher threshold. In this case, it is added back to 3371b859a23STeresa Johnson /// the worklist with the new threshold. 3381b859a23STeresa Johnson if (ProcessedThreshold && ProcessedThreshold >= AdjThreshold) { 3391b859a23STeresa Johnson DEBUG(dbgs() << "ignored! Target was already seen with Threshold " 3401b859a23STeresa Johnson << ProcessedThreshold << "\n"); 3411b859a23STeresa Johnson continue; 3421b859a23STeresa Johnson } 34319f2aa78STeresa Johnson bool PreviouslyImported = ProcessedThreshold != 0; 3441b859a23STeresa Johnson // Mark this function as imported in this module, with the current Threshold 3451b859a23STeresa Johnson ProcessedThreshold = AdjThreshold; 3461b859a23STeresa Johnson 3471b859a23STeresa Johnson // Make exports in the source module. 3481b859a23STeresa Johnson if (ExportLists) { 3491b859a23STeresa Johnson auto &ExportList = (*ExportLists)[ExportModulePath]; 3509667b91bSPeter Collingbourne ExportList.insert(VI.getGUID()); 35119f2aa78STeresa Johnson if (!PreviouslyImported) { 35219f2aa78STeresa Johnson // This is the first time this function was exported from its source 35319f2aa78STeresa Johnson // module, so mark all functions and globals it references as exported 3541b859a23STeresa Johnson // to the outside if they are defined in the same source module. 355edddca22STeresa Johnson // For efficiency, we unconditionally add all the referenced GUIDs 356edddca22STeresa Johnson // to the ExportList for this module, and will prune out any not 357edddca22STeresa Johnson // defined in the module later in a single pass. 3581b859a23STeresa Johnson for (auto &Edge : ResolvedCalleeSummary->calls()) { 3591b859a23STeresa Johnson auto CalleeGUID = Edge.first.getGUID(); 360edddca22STeresa Johnson ExportList.insert(CalleeGUID); 3611b859a23STeresa Johnson } 3621b859a23STeresa Johnson for (auto &Ref : ResolvedCalleeSummary->refs()) { 3631b859a23STeresa Johnson auto GUID = Ref.getGUID(); 364edddca22STeresa Johnson ExportList.insert(GUID); 3651b859a23STeresa Johnson } 3661b859a23STeresa Johnson } 36719f2aa78STeresa Johnson } 368d2869473SPiotr Padlewski 36901e32130SMehdi Amini // Insert the newly imported function to the worklist. 3709667b91bSPeter Collingbourne Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, VI.getGUID()); 371d450da32STeresa Johnson } 372d450da32STeresa Johnson } 373d450da32STeresa Johnson 37401e32130SMehdi Amini /// Given the list of globals defined in a module, compute the list of imports 37501e32130SMehdi Amini /// as well as the list of "exports", i.e. the list of symbols referenced from 37601e32130SMehdi Amini /// another module (that may require promotion). 37701e32130SMehdi Amini static void ComputeImportForModule( 378c851d216STeresa Johnson const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index, 3799b490f10SMehdi Amini FunctionImporter::ImportMapTy &ImportList, 38056584bbfSEvgeniy Stepanov StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) { 38101e32130SMehdi Amini // Worklist contains the list of function imported in this module, for which 38201e32130SMehdi Amini // we will analyse the callees and may import further down the callgraph. 38301e32130SMehdi Amini SmallVector<EdgeInfo, 128> Worklist; 38401e32130SMehdi Amini 38501e32130SMehdi Amini // Populate the worklist with the import for the functions in the current 38601e32130SMehdi Amini // module 38728e457bcSTeresa Johnson for (auto &GVSummary : DefinedGVSummaries) { 38856584bbfSEvgeniy Stepanov if (!Index.isGlobalValueLive(GVSummary.second)) { 3896c475a75STeresa Johnson DEBUG(dbgs() << "Ignores Dead GUID: " << GVSummary.first << "\n"); 3906c475a75STeresa Johnson continue; 3916c475a75STeresa Johnson } 392cfbd0892SPeter Collingbourne auto *FuncSummary = 393cfbd0892SPeter Collingbourne dyn_cast<FunctionSummary>(GVSummary.second->getBaseObject()); 3941aafabf7SMehdi Amini if (!FuncSummary) 3951aafabf7SMehdi Amini // Skip import for global variables 3961aafabf7SMehdi Amini continue; 39724524f31SXinliang David Li DEBUG(dbgs() << "Initialize import for " << GVSummary.first << "\n"); 3982d28f7aaSMehdi Amini computeImportForFunction(*FuncSummary, Index, ImportInstrLimit, 3999b490f10SMehdi Amini DefinedGVSummaries, Worklist, ImportList, 40001e32130SMehdi Amini ExportLists); 40101e32130SMehdi Amini } 40201e32130SMehdi Amini 403d2869473SPiotr Padlewski // Process the newly imported functions and add callees to the worklist. 40442418abaSMehdi Amini while (!Worklist.empty()) { 40501e32130SMehdi Amini auto FuncInfo = Worklist.pop_back_val(); 406475b51a7STeresa Johnson auto *Summary = std::get<0>(FuncInfo); 407475b51a7STeresa Johnson auto Threshold = std::get<1>(FuncInfo); 408475b51a7STeresa Johnson auto GUID = std::get<2>(FuncInfo); 409475b51a7STeresa Johnson 410475b51a7STeresa Johnson // Check if we later added this summary with a higher threshold. 411475b51a7STeresa Johnson // If so, skip this entry. 412475b51a7STeresa Johnson auto ExportModulePath = Summary->modulePath(); 413475b51a7STeresa Johnson auto &LatestProcessedThreshold = ImportList[ExportModulePath][GUID]; 414475b51a7STeresa Johnson if (LatestProcessedThreshold > Threshold) 415475b51a7STeresa Johnson continue; 41642418abaSMehdi Amini 4171aafabf7SMehdi Amini computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries, 4189b490f10SMehdi Amini Worklist, ImportList, ExportLists); 419c8c55170SMehdi Amini } 42042418abaSMehdi Amini } 421ffe2e4aaSMehdi Amini 422*7331a0bfSEugene Leviant #ifndef NDEBUG 423*7331a0bfSEugene Leviant static bool isGlobalVarSummary(const ModuleSummaryIndex &Index, 424*7331a0bfSEugene Leviant GlobalValue::GUID G) { 425*7331a0bfSEugene Leviant if (const auto &VI = Index.getValueInfo(G)) { 426*7331a0bfSEugene Leviant auto SL = VI.getSummaryList(); 427*7331a0bfSEugene Leviant if (!SL.empty()) 428*7331a0bfSEugene Leviant return SL[0]->getSummaryKind() == GlobalValueSummary::GlobalVarKind; 429*7331a0bfSEugene Leviant } 430*7331a0bfSEugene Leviant return false; 431*7331a0bfSEugene Leviant } 432*7331a0bfSEugene Leviant 433*7331a0bfSEugene Leviant static GlobalValue::GUID getGUID(GlobalValue::GUID G) { return G; } 434*7331a0bfSEugene Leviant 435*7331a0bfSEugene Leviant static GlobalValue::GUID 436*7331a0bfSEugene Leviant getGUID(const std::pair<const GlobalValue::GUID, unsigned> &P) { 437*7331a0bfSEugene Leviant return P.first; 438*7331a0bfSEugene Leviant } 439*7331a0bfSEugene Leviant 440*7331a0bfSEugene Leviant template <class T> 441*7331a0bfSEugene Leviant unsigned numGlobalVarSummaries(const ModuleSummaryIndex &Index, T &Cont) { 442*7331a0bfSEugene Leviant unsigned NumGVS = 0; 443*7331a0bfSEugene Leviant for (auto &V : Cont) 444*7331a0bfSEugene Leviant if (isGlobalVarSummary(Index, getGUID(V))) 445*7331a0bfSEugene Leviant ++NumGVS; 446*7331a0bfSEugene Leviant return NumGVS; 447*7331a0bfSEugene Leviant } 448*7331a0bfSEugene Leviant #endif 449*7331a0bfSEugene Leviant 450c86af334STeresa Johnson /// Compute all the import and export for every module using the Index. 45101e32130SMehdi Amini void llvm::ComputeCrossModuleImport( 45201e32130SMehdi Amini const ModuleSummaryIndex &Index, 453c851d216STeresa Johnson const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries, 45401e32130SMehdi Amini StringMap<FunctionImporter::ImportMapTy> &ImportLists, 45556584bbfSEvgeniy Stepanov StringMap<FunctionImporter::ExportSetTy> &ExportLists) { 45601e32130SMehdi Amini // For each module that has function defined, compute the import/export lists. 4571aafabf7SMehdi Amini for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) { 4589b490f10SMehdi Amini auto &ImportList = ImportLists[DefinedGVSummaries.first()]; 4591aafabf7SMehdi Amini DEBUG(dbgs() << "Computing import for Module '" 4601aafabf7SMehdi Amini << DefinedGVSummaries.first() << "'\n"); 4619b490f10SMehdi Amini ComputeImportForModule(DefinedGVSummaries.second, Index, ImportList, 46256584bbfSEvgeniy Stepanov &ExportLists); 46301e32130SMehdi Amini } 46401e32130SMehdi Amini 465edddca22STeresa Johnson // When computing imports we added all GUIDs referenced by anything 466edddca22STeresa Johnson // imported from the module to its ExportList. Now we prune each ExportList 467edddca22STeresa Johnson // of any not defined in that module. This is more efficient than checking 468edddca22STeresa Johnson // while computing imports because some of the summary lists may be long 469edddca22STeresa Johnson // due to linkonce (comdat) copies. 470edddca22STeresa Johnson for (auto &ELI : ExportLists) { 471edddca22STeresa Johnson const auto &DefinedGVSummaries = 472edddca22STeresa Johnson ModuleToDefinedGVSummaries.lookup(ELI.first()); 473edddca22STeresa Johnson for (auto EI = ELI.second.begin(); EI != ELI.second.end();) { 474edddca22STeresa Johnson if (!DefinedGVSummaries.count(*EI)) 475edddca22STeresa Johnson EI = ELI.second.erase(EI); 476edddca22STeresa Johnson else 477edddca22STeresa Johnson ++EI; 478edddca22STeresa Johnson } 479edddca22STeresa Johnson } 480edddca22STeresa Johnson 48101e32130SMehdi Amini #ifndef NDEBUG 48201e32130SMehdi Amini DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size() 48301e32130SMehdi Amini << " modules:\n"); 48401e32130SMehdi Amini for (auto &ModuleImports : ImportLists) { 48501e32130SMehdi Amini auto ModName = ModuleImports.first(); 48601e32130SMehdi Amini auto &Exports = ExportLists[ModName]; 487*7331a0bfSEugene Leviant unsigned NumGVS = numGlobalVarSummaries(Index, Exports); 488*7331a0bfSEugene Leviant DEBUG(dbgs() << "* Module " << ModName << " exports " 489*7331a0bfSEugene Leviant << Exports.size() - NumGVS << " functions and " << NumGVS 490*7331a0bfSEugene Leviant << " vars. Imports from " 491*7331a0bfSEugene Leviant << ModuleImports.second.size() << " modules.\n"); 49201e32130SMehdi Amini for (auto &Src : ModuleImports.second) { 49301e32130SMehdi Amini auto SrcModName = Src.first(); 494*7331a0bfSEugene Leviant unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second); 495*7331a0bfSEugene Leviant DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod 496*7331a0bfSEugene Leviant << " functions imported from " << SrcModName << "\n"); 497*7331a0bfSEugene Leviant DEBUG(dbgs() << " - " << NumGVSPerMod << " global vars imported from " 49801e32130SMehdi Amini << SrcModName << "\n"); 49901e32130SMehdi Amini } 50001e32130SMehdi Amini } 50101e32130SMehdi Amini #endif 50201e32130SMehdi Amini } 50301e32130SMehdi Amini 50481bbf742STeresa Johnson #ifndef NDEBUG 505*7331a0bfSEugene Leviant static void dumpImportListForModule(const ModuleSummaryIndex &Index, 506*7331a0bfSEugene Leviant StringRef ModulePath, 50781bbf742STeresa Johnson FunctionImporter::ImportMapTy &ImportList) { 50881bbf742STeresa Johnson DEBUG(dbgs() << "* Module " << ModulePath << " imports from " 50981bbf742STeresa Johnson << ImportList.size() << " modules.\n"); 51081bbf742STeresa Johnson for (auto &Src : ImportList) { 51181bbf742STeresa Johnson auto SrcModName = Src.first(); 512*7331a0bfSEugene Leviant unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second); 513*7331a0bfSEugene Leviant DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod 514*7331a0bfSEugene Leviant << " functions imported from " << SrcModName << "\n"); 515*7331a0bfSEugene Leviant DEBUG(dbgs() << " - " << NumGVSPerMod << " vars imported from " 51681bbf742STeresa Johnson << SrcModName << "\n"); 51781bbf742STeresa Johnson } 51881bbf742STeresa Johnson } 51969b2de84STeresa Johnson #endif 52081bbf742STeresa Johnson 521c86af334STeresa Johnson /// Compute all the imports for the given module in the Index. 522c86af334STeresa Johnson void llvm::ComputeCrossModuleImportForModule( 523c86af334STeresa Johnson StringRef ModulePath, const ModuleSummaryIndex &Index, 524c86af334STeresa Johnson FunctionImporter::ImportMapTy &ImportList) { 525c86af334STeresa Johnson // Collect the list of functions this module defines. 526c86af334STeresa Johnson // GUID -> Summary 527c851d216STeresa Johnson GVSummaryMapTy FunctionSummaryMap; 52828e457bcSTeresa Johnson Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap); 529c86af334STeresa Johnson 530c86af334STeresa Johnson // Compute the import list for this module. 531c86af334STeresa Johnson DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n"); 53228e457bcSTeresa Johnson ComputeImportForModule(FunctionSummaryMap, Index, ImportList); 533c86af334STeresa Johnson 534c86af334STeresa Johnson #ifndef NDEBUG 535*7331a0bfSEugene Leviant dumpImportListForModule(Index, ModulePath, ImportList); 53681bbf742STeresa Johnson #endif 537c86af334STeresa Johnson } 53881bbf742STeresa Johnson 53981bbf742STeresa Johnson // Mark all external summaries in Index for import into the given module. 54081bbf742STeresa Johnson // Used for distributed builds using a distributed index. 54181bbf742STeresa Johnson void llvm::ComputeCrossModuleImportForModuleFromIndex( 54281bbf742STeresa Johnson StringRef ModulePath, const ModuleSummaryIndex &Index, 54381bbf742STeresa Johnson FunctionImporter::ImportMapTy &ImportList) { 54481bbf742STeresa Johnson for (auto &GlobalList : Index) { 54581bbf742STeresa Johnson // Ignore entries for undefined references. 54681bbf742STeresa Johnson if (GlobalList.second.SummaryList.empty()) 54781bbf742STeresa Johnson continue; 54881bbf742STeresa Johnson 54981bbf742STeresa Johnson auto GUID = GlobalList.first; 55081bbf742STeresa Johnson assert(GlobalList.second.SummaryList.size() == 1 && 55181bbf742STeresa Johnson "Expected individual combined index to have one summary per GUID"); 55281bbf742STeresa Johnson auto &Summary = GlobalList.second.SummaryList[0]; 55381bbf742STeresa Johnson // Skip the summaries for the importing module. These are included to 55481bbf742STeresa Johnson // e.g. record required linkage changes. 55581bbf742STeresa Johnson if (Summary->modulePath() == ModulePath) 55681bbf742STeresa Johnson continue; 55781bbf742STeresa Johnson // Doesn't matter what value we plug in to the map, just needs an entry 55881bbf742STeresa Johnson // to provoke importing by thinBackend. 55981bbf742STeresa Johnson ImportList[Summary->modulePath()][GUID] = 1; 56081bbf742STeresa Johnson } 56181bbf742STeresa Johnson #ifndef NDEBUG 562*7331a0bfSEugene Leviant dumpImportListForModule(Index, ModulePath, ImportList); 563c86af334STeresa Johnson #endif 564c86af334STeresa Johnson } 565c86af334STeresa Johnson 56656584bbfSEvgeniy Stepanov void llvm::computeDeadSymbols( 56756584bbfSEvgeniy Stepanov ModuleSummaryIndex &Index, 568eaf5172cSGeorge Rimar const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols, 569eaf5172cSGeorge Rimar function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing) { 57056584bbfSEvgeniy Stepanov assert(!Index.withGlobalValueDeadStripping()); 5716c475a75STeresa Johnson if (!ComputeDead) 57256584bbfSEvgeniy Stepanov return; 5736c475a75STeresa Johnson if (GUIDPreservedSymbols.empty()) 5746c475a75STeresa Johnson // Don't do anything when nothing is live, this is friendly with tests. 57556584bbfSEvgeniy Stepanov return; 57656584bbfSEvgeniy Stepanov unsigned LiveSymbols = 0; 5779667b91bSPeter Collingbourne SmallVector<ValueInfo, 128> Worklist; 5789667b91bSPeter Collingbourne Worklist.reserve(GUIDPreservedSymbols.size() * 2); 5799667b91bSPeter Collingbourne for (auto GUID : GUIDPreservedSymbols) { 5809667b91bSPeter Collingbourne ValueInfo VI = Index.getValueInfo(GUID); 5819667b91bSPeter Collingbourne if (!VI) 5829667b91bSPeter Collingbourne continue; 58356584bbfSEvgeniy Stepanov for (auto &S : VI.getSummaryList()) 58456584bbfSEvgeniy Stepanov S->setLive(true); 5856c475a75STeresa Johnson } 58656584bbfSEvgeniy Stepanov 5876c475a75STeresa Johnson // Add values flagged in the index as live roots to the worklist. 58856584bbfSEvgeniy Stepanov for (const auto &Entry : Index) 58956584bbfSEvgeniy Stepanov for (auto &S : Entry.second.SummaryList) 59056584bbfSEvgeniy Stepanov if (S->isLive()) { 59156584bbfSEvgeniy Stepanov DEBUG(dbgs() << "Live root: " << Entry.first << "\n"); 59228d8a49fSEugene Leviant Worklist.push_back(ValueInfo(/*IsAnalysis=*/false, &Entry)); 59356584bbfSEvgeniy Stepanov ++LiveSymbols; 59456584bbfSEvgeniy Stepanov break; 5956c475a75STeresa Johnson } 5966c475a75STeresa Johnson 59756584bbfSEvgeniy Stepanov // Make value live and add it to the worklist if it was not live before. 59856584bbfSEvgeniy Stepanov auto visit = [&](ValueInfo VI) { 5991958083dSTeresa Johnson // FIXME: If we knew which edges were created for indirect call profiles, 6001958083dSTeresa Johnson // we could skip them here. Any that are live should be reached via 6011958083dSTeresa Johnson // other edges, e.g. reference edges. Otherwise, using a profile collected 6021958083dSTeresa Johnson // on a slightly different binary might provoke preserving, importing 6031958083dSTeresa Johnson // and ultimately promoting calls to functions not linked into this 6041958083dSTeresa Johnson // binary, which increases the binary size unnecessarily. Note that 6051958083dSTeresa Johnson // if this code changes, the importer needs to change so that edges 6061958083dSTeresa Johnson // to functions marked dead are skipped. 6071958083dSTeresa Johnson VI = updateValueInfoForIndirectCalls(Index, VI); 6081958083dSTeresa Johnson if (!VI) 6091958083dSTeresa Johnson return; 61056584bbfSEvgeniy Stepanov for (auto &S : VI.getSummaryList()) 611f625118eSTeresa Johnson if (S->isLive()) 612f625118eSTeresa Johnson return; 613eaf5172cSGeorge Rimar 614eaf5172cSGeorge Rimar // We do not keep live symbols that are known to be non-prevailing. 615eaf5172cSGeorge Rimar if (isPrevailing(VI.getGUID()) == PrevailingType::No) 616eaf5172cSGeorge Rimar return; 617eaf5172cSGeorge Rimar 618f625118eSTeresa Johnson for (auto &S : VI.getSummaryList()) 61956584bbfSEvgeniy Stepanov S->setLive(true); 62056584bbfSEvgeniy Stepanov ++LiveSymbols; 62156584bbfSEvgeniy Stepanov Worklist.push_back(VI); 62256584bbfSEvgeniy Stepanov }; 62356584bbfSEvgeniy Stepanov 6246c475a75STeresa Johnson while (!Worklist.empty()) { 6259667b91bSPeter Collingbourne auto VI = Worklist.pop_back_val(); 6269667b91bSPeter Collingbourne for (auto &Summary : VI.getSummaryList()) { 627cfbd0892SPeter Collingbourne GlobalValueSummary *Base = Summary->getBaseObject(); 628eaf5172cSGeorge Rimar // Set base value live in case it is an alias. 629eaf5172cSGeorge Rimar Base->setLive(true); 630cfbd0892SPeter Collingbourne for (auto Ref : Base->refs()) 63156584bbfSEvgeniy Stepanov visit(Ref); 632cfbd0892SPeter Collingbourne if (auto *FS = dyn_cast<FunctionSummary>(Base)) 63356584bbfSEvgeniy Stepanov for (auto Call : FS->calls()) 63456584bbfSEvgeniy Stepanov visit(Call.first); 6356c475a75STeresa Johnson } 6366c475a75STeresa Johnson } 63756584bbfSEvgeniy Stepanov Index.setWithGlobalValueDeadStripping(); 63856584bbfSEvgeniy Stepanov 63956584bbfSEvgeniy Stepanov unsigned DeadSymbols = Index.size() - LiveSymbols; 64056584bbfSEvgeniy Stepanov DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols 64156584bbfSEvgeniy Stepanov << " symbols Dead \n"); 64256584bbfSEvgeniy Stepanov NumDeadSymbols += DeadSymbols; 64356584bbfSEvgeniy Stepanov NumLiveSymbols += LiveSymbols; 6446c475a75STeresa Johnson } 6456c475a75STeresa Johnson 64684174c37STeresa Johnson /// Compute the set of summaries needed for a ThinLTO backend compilation of 64784174c37STeresa Johnson /// \p ModulePath. 64884174c37STeresa Johnson void llvm::gatherImportedSummariesForModule( 64984174c37STeresa Johnson StringRef ModulePath, 65084174c37STeresa Johnson const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries, 651cdbcbf74SMehdi Amini const FunctionImporter::ImportMapTy &ImportList, 65284174c37STeresa Johnson std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) { 65384174c37STeresa Johnson // Include all summaries from the importing module. 65484174c37STeresa Johnson ModuleToSummariesForIndex[ModulePath] = 65584174c37STeresa Johnson ModuleToDefinedGVSummaries.lookup(ModulePath); 65684174c37STeresa Johnson // Include summaries for imports. 65788c491ddSMehdi Amini for (auto &ILI : ImportList) { 65884174c37STeresa Johnson auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()]; 65984174c37STeresa Johnson const auto &DefinedGVSummaries = 66084174c37STeresa Johnson ModuleToDefinedGVSummaries.lookup(ILI.first()); 66184174c37STeresa Johnson for (auto &GI : ILI.second) { 66284174c37STeresa Johnson const auto &DS = DefinedGVSummaries.find(GI.first); 66384174c37STeresa Johnson assert(DS != DefinedGVSummaries.end() && 66484174c37STeresa Johnson "Expected a defined summary for imported global value"); 66584174c37STeresa Johnson SummariesForIndex[GI.first] = DS->second; 66684174c37STeresa Johnson } 66784174c37STeresa Johnson } 66884174c37STeresa Johnson } 66984174c37STeresa Johnson 6708570fe47STeresa Johnson /// Emit the files \p ModulePath will import from into \p OutputFilename. 671cdbcbf74SMehdi Amini std::error_code 672cdbcbf74SMehdi Amini llvm::EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename, 673cdbcbf74SMehdi Amini const FunctionImporter::ImportMapTy &ModuleImports) { 6748570fe47STeresa Johnson std::error_code EC; 6758570fe47STeresa Johnson raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None); 6768570fe47STeresa Johnson if (EC) 6778570fe47STeresa Johnson return EC; 678cdbcbf74SMehdi Amini for (auto &ILI : ModuleImports) 6798570fe47STeresa Johnson ImportsOS << ILI.first() << "\n"; 6808570fe47STeresa Johnson return std::error_code(); 6818570fe47STeresa Johnson } 6828570fe47STeresa Johnson 6835a95c477STeresa Johnson bool llvm::convertToDeclaration(GlobalValue &GV) { 6844566c6dbSTeresa Johnson DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName() << "\n"); 6854566c6dbSTeresa Johnson if (Function *F = dyn_cast<Function>(&GV)) { 6864566c6dbSTeresa Johnson F->deleteBody(); 6874566c6dbSTeresa Johnson F->clearMetadata(); 6887873669bSPeter Collingbourne F->setComdat(nullptr); 6894566c6dbSTeresa Johnson } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) { 6904566c6dbSTeresa Johnson V->setInitializer(nullptr); 6914566c6dbSTeresa Johnson V->setLinkage(GlobalValue::ExternalLinkage); 6924566c6dbSTeresa Johnson V->clearMetadata(); 6937873669bSPeter Collingbourne V->setComdat(nullptr); 6945a95c477STeresa Johnson } else { 6955a95c477STeresa Johnson GlobalValue *NewGV; 6965a95c477STeresa Johnson if (GV.getValueType()->isFunctionTy()) 6975a95c477STeresa Johnson NewGV = 6985a95c477STeresa Johnson Function::Create(cast<FunctionType>(GV.getValueType()), 6995a95c477STeresa Johnson GlobalValue::ExternalLinkage, "", GV.getParent()); 7005a95c477STeresa Johnson else 7015a95c477STeresa Johnson NewGV = 7025a95c477STeresa Johnson new GlobalVariable(*GV.getParent(), GV.getValueType(), 7035a95c477STeresa Johnson /*isConstant*/ false, GlobalValue::ExternalLinkage, 7045a95c477STeresa Johnson /*init*/ nullptr, "", 7055a95c477STeresa Johnson /*insertbefore*/ nullptr, GV.getThreadLocalMode(), 7065a95c477STeresa Johnson GV.getType()->getAddressSpace()); 7075a95c477STeresa Johnson NewGV->takeName(&GV); 7085a95c477STeresa Johnson GV.replaceAllUsesWith(NewGV); 7095a95c477STeresa Johnson return false; 7105a95c477STeresa Johnson } 7115a95c477STeresa Johnson return true; 712eaf5172cSGeorge Rimar } 7134566c6dbSTeresa Johnson 714eaf5172cSGeorge Rimar /// Fixup WeakForLinker linkages in \p TheModule based on summary analysis. 715eaf5172cSGeorge Rimar void llvm::thinLTOResolveWeakForLinkerModule( 716eaf5172cSGeorge Rimar Module &TheModule, const GVSummaryMapTy &DefinedGlobals) { 71704c9a2d6STeresa Johnson auto updateLinkage = [&](GlobalValue &GV) { 71804c9a2d6STeresa Johnson // See if the global summary analysis computed a new resolved linkage. 71904c9a2d6STeresa Johnson const auto &GS = DefinedGlobals.find(GV.getGUID()); 72004c9a2d6STeresa Johnson if (GS == DefinedGlobals.end()) 72104c9a2d6STeresa Johnson return; 72204c9a2d6STeresa Johnson auto NewLinkage = GS->second->linkage(); 72304c9a2d6STeresa Johnson if (NewLinkage == GV.getLinkage()) 72404c9a2d6STeresa Johnson return; 7256a5fbe52SDavide Italiano 7266a5fbe52SDavide Italiano // Switch the linkage to weakany if asked for, e.g. we do this for 7276a5fbe52SDavide Italiano // linker redefined symbols (via --wrap or --defsym). 728f4891d29SDavide Italiano // We record that the visibility should be changed here in `addThinLTO` 729f4891d29SDavide Italiano // as we need access to the resolution vectors for each input file in 730f4891d29SDavide Italiano // order to find which symbols have been redefined. 731f4891d29SDavide Italiano // We may consider reorganizing this code and moving the linkage recording 732f4891d29SDavide Italiano // somewhere else, e.g. in thinLTOResolveWeakForLinkerInIndex. 7336a5fbe52SDavide Italiano if (NewLinkage == GlobalValue::WeakAnyLinkage) { 7346a5fbe52SDavide Italiano GV.setLinkage(NewLinkage); 7356a5fbe52SDavide Italiano return; 7366a5fbe52SDavide Italiano } 7376a5fbe52SDavide Italiano 7386a5fbe52SDavide Italiano if (!GlobalValue::isWeakForLinker(GV.getLinkage())) 7396a5fbe52SDavide Italiano return; 7404566c6dbSTeresa Johnson // Check for a non-prevailing def that has interposable linkage 7414566c6dbSTeresa Johnson // (e.g. non-odr weak or linkonce). In that case we can't simply 7424566c6dbSTeresa Johnson // convert to available_externally, since it would lose the 7434566c6dbSTeresa Johnson // interposable property and possibly get inlined. Simply drop 7444566c6dbSTeresa Johnson // the definition in that case. 7454566c6dbSTeresa Johnson if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) && 7465a95c477STeresa Johnson GlobalValue::isInterposableLinkage(GV.getLinkage())) { 7475a95c477STeresa Johnson if (!convertToDeclaration(GV)) 7485a95c477STeresa Johnson // FIXME: Change this to collect replaced GVs and later erase 7495a95c477STeresa Johnson // them from the parent module once thinLTOResolveWeakForLinkerGUID is 7505a95c477STeresa Johnson // changed to enable this for aliases. 7515a95c477STeresa Johnson llvm_unreachable("Expected GV to be converted"); 7525a95c477STeresa Johnson } else { 75333ba93c2SSteven Wu // If the original symbols has global unnamed addr and linkonce_odr linkage, 75433ba93c2SSteven Wu // it should be an auto hide symbol. Add hidden visibility to the symbol to 75533ba93c2SSteven Wu // preserve the property. 75633ba93c2SSteven Wu if (GV.hasLinkOnceODRLinkage() && GV.hasGlobalUnnamedAddr() && 75733ba93c2SSteven Wu NewLinkage == GlobalValue::WeakODRLinkage) 75833ba93c2SSteven Wu GV.setVisibility(GlobalValue::HiddenVisibility); 75933ba93c2SSteven Wu 76004c9a2d6STeresa Johnson DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from " 76104c9a2d6STeresa Johnson << GV.getLinkage() << " to " << NewLinkage << "\n"); 76204c9a2d6STeresa Johnson GV.setLinkage(NewLinkage); 7634566c6dbSTeresa Johnson } 7644566c6dbSTeresa Johnson // Remove declarations from comdats, including available_externally 7656107a419STeresa Johnson // as this is a declaration for the linker, and will be dropped eventually. 7666107a419STeresa Johnson // It is illegal for comdats to contain declarations. 7676107a419STeresa Johnson auto *GO = dyn_cast_or_null<GlobalObject>(&GV); 7684566c6dbSTeresa Johnson if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) 7696107a419STeresa Johnson GO->setComdat(nullptr); 77004c9a2d6STeresa Johnson }; 77104c9a2d6STeresa Johnson 77204c9a2d6STeresa Johnson // Process functions and global now 77304c9a2d6STeresa Johnson for (auto &GV : TheModule) 77404c9a2d6STeresa Johnson updateLinkage(GV); 77504c9a2d6STeresa Johnson for (auto &GV : TheModule.globals()) 77604c9a2d6STeresa Johnson updateLinkage(GV); 77704c9a2d6STeresa Johnson for (auto &GV : TheModule.aliases()) 77804c9a2d6STeresa Johnson updateLinkage(GV); 77904c9a2d6STeresa Johnson } 78004c9a2d6STeresa Johnson 78104c9a2d6STeresa Johnson /// Run internalization on \p TheModule based on symmary analysis. 78204c9a2d6STeresa Johnson void llvm::thinLTOInternalizeModule(Module &TheModule, 78304c9a2d6STeresa Johnson const GVSummaryMapTy &DefinedGlobals) { 78404c9a2d6STeresa Johnson // Declare a callback for the internalize pass that will ask for every 78504c9a2d6STeresa Johnson // candidate GlobalValue if it can be internalized or not. 78604c9a2d6STeresa Johnson auto MustPreserveGV = [&](const GlobalValue &GV) -> bool { 78704c9a2d6STeresa Johnson // Lookup the linkage recorded in the summaries during global analysis. 788c3d677f9SPeter Collingbourne auto GS = DefinedGlobals.find(GV.getGUID()); 78904c9a2d6STeresa Johnson if (GS == DefinedGlobals.end()) { 79004c9a2d6STeresa Johnson // Must have been promoted (possibly conservatively). Find original 79104c9a2d6STeresa Johnson // name so that we can access the correct summary and see if it can 79204c9a2d6STeresa Johnson // be internalized again. 79304c9a2d6STeresa Johnson // FIXME: Eventually we should control promotion instead of promoting 79404c9a2d6STeresa Johnson // and internalizing again. 79504c9a2d6STeresa Johnson StringRef OrigName = 79604c9a2d6STeresa Johnson ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName()); 79704c9a2d6STeresa Johnson std::string OrigId = GlobalValue::getGlobalIdentifier( 79804c9a2d6STeresa Johnson OrigName, GlobalValue::InternalLinkage, 79904c9a2d6STeresa Johnson TheModule.getSourceFileName()); 800c3d677f9SPeter Collingbourne GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId)); 8017ab1f692STeresa Johnson if (GS == DefinedGlobals.end()) { 8027ab1f692STeresa Johnson // Also check the original non-promoted non-globalized name. In some 8037ab1f692STeresa Johnson // cases a preempted weak value is linked in as a local copy because 8047ab1f692STeresa Johnson // it is referenced by an alias (IRLinker::linkGlobalValueProto). 8057ab1f692STeresa Johnson // In that case, since it was originally not a local value, it was 8067ab1f692STeresa Johnson // recorded in the index using the original name. 8077ab1f692STeresa Johnson // FIXME: This may not be needed once PR27866 is fixed. 808c3d677f9SPeter Collingbourne GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName)); 80904c9a2d6STeresa Johnson assert(GS != DefinedGlobals.end()); 8107ab1f692STeresa Johnson } 811c3d677f9SPeter Collingbourne } 812c3d677f9SPeter Collingbourne return !GlobalValue::isLocalLinkage(GS->second->linkage()); 81304c9a2d6STeresa Johnson }; 81404c9a2d6STeresa Johnson 81504c9a2d6STeresa Johnson // FIXME: See if we can just internalize directly here via linkage changes 81604c9a2d6STeresa Johnson // based on the index, rather than invoking internalizeModule. 817e9ea08a0SEugene Zelenko internalizeModule(TheModule, MustPreserveGV); 81804c9a2d6STeresa Johnson } 81904c9a2d6STeresa Johnson 82081bbf742STeresa Johnson /// Make alias a clone of its aliasee. 82181bbf742STeresa Johnson static Function *replaceAliasWithAliasee(Module *SrcModule, GlobalAlias *GA) { 82281bbf742STeresa Johnson Function *Fn = cast<Function>(GA->getBaseObject()); 82381bbf742STeresa Johnson 82481bbf742STeresa Johnson ValueToValueMapTy VMap; 82581bbf742STeresa Johnson Function *NewFn = CloneFunction(Fn, VMap); 82681bbf742STeresa Johnson // Clone should use the original alias's linkage and name, and we ensure 82781bbf742STeresa Johnson // all uses of alias instead use the new clone (casted if necessary). 82881bbf742STeresa Johnson NewFn->setLinkage(GA->getLinkage()); 82981bbf742STeresa Johnson GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewFn, GA->getType())); 83081bbf742STeresa Johnson NewFn->takeName(GA); 83181bbf742STeresa Johnson return NewFn; 83281bbf742STeresa Johnson } 83381bbf742STeresa Johnson 834c8c55170SMehdi Amini // Automatically import functions in Module \p DestModule based on the summaries 835c8c55170SMehdi Amini // index. 8367f00d0a1SPeter Collingbourne Expected<bool> FunctionImporter::importFunctions( 83766043797SAdrian Prantl Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) { 8385411d051SMehdi Amini DEBUG(dbgs() << "Starting import for Module " 839311fef6eSMehdi Amini << DestModule.getModuleIdentifier() << "\n"); 840*7331a0bfSEugene Leviant unsigned ImportedCount = 0, ImportedGVCount = 0; 841c8c55170SMehdi Amini 8426d8f817fSPeter Collingbourne IRMover Mover(DestModule); 8437e88d0daSMehdi Amini // Do the actual import of functions now, one Module at a time 84401e32130SMehdi Amini std::set<StringRef> ModuleNameOrderedList; 84501e32130SMehdi Amini for (auto &FunctionsToImportPerModule : ImportList) { 84601e32130SMehdi Amini ModuleNameOrderedList.insert(FunctionsToImportPerModule.first()); 84701e32130SMehdi Amini } 84801e32130SMehdi Amini for (auto &Name : ModuleNameOrderedList) { 8497e88d0daSMehdi Amini // Get the module for the import 85001e32130SMehdi Amini const auto &FunctionsToImportPerModule = ImportList.find(Name); 85101e32130SMehdi Amini assert(FunctionsToImportPerModule != ImportList.end()); 852d9445c49SPeter Collingbourne Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name); 853d9445c49SPeter Collingbourne if (!SrcModuleOrErr) 854d9445c49SPeter Collingbourne return SrcModuleOrErr.takeError(); 855d9445c49SPeter Collingbourne std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr); 8567e88d0daSMehdi Amini assert(&DestModule.getContext() == &SrcModule->getContext() && 8577e88d0daSMehdi Amini "Context mismatch"); 8587e88d0daSMehdi Amini 8596cba37ceSTeresa Johnson // If modules were created with lazy metadata loading, materialize it 8606cba37ceSTeresa Johnson // now, before linking it (otherwise this will be a noop). 8617f00d0a1SPeter Collingbourne if (Error Err = SrcModule->materializeMetadata()) 8627f00d0a1SPeter Collingbourne return std::move(Err); 863e5a61917STeresa Johnson 86401e32130SMehdi Amini auto &ImportGUIDs = FunctionsToImportPerModule->second; 86501e32130SMehdi Amini // Find the globals to import 8666d8f817fSPeter Collingbourne SetVector<GlobalValue *> GlobalsToImport; 8671f685e01SPiotr Padlewski for (Function &F : *SrcModule) { 8681f685e01SPiotr Padlewski if (!F.hasName()) 8690beb858eSTeresa Johnson continue; 8701f685e01SPiotr Padlewski auto GUID = F.getGUID(); 8710beb858eSTeresa Johnson auto Import = ImportGUIDs.count(GUID); 872aeb1e59bSMehdi Amini DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " << GUID 8731f685e01SPiotr Padlewski << " " << F.getName() << " from " 874aeb1e59bSMehdi Amini << SrcModule->getSourceFileName() << "\n"); 8750beb858eSTeresa Johnson if (Import) { 8767f00d0a1SPeter Collingbourne if (Error Err = F.materialize()) 8777f00d0a1SPeter Collingbourne return std::move(Err); 8783b776128SPiotr Padlewski if (EnableImportMetadata) { 8796deaa6afSPiotr Padlewski // Add 'thinlto_src_module' metadata for statistics and debugging. 8803b776128SPiotr Padlewski F.setMetadata( 8813b776128SPiotr Padlewski "thinlto_src_module", 882e9ea08a0SEugene Zelenko MDNode::get(DestModule.getContext(), 883e9ea08a0SEugene Zelenko {MDString::get(DestModule.getContext(), 8846deaa6afSPiotr Padlewski SrcModule->getSourceFileName())})); 8853b776128SPiotr Padlewski } 8861f685e01SPiotr Padlewski GlobalsToImport.insert(&F); 88701e32130SMehdi Amini } 88801e32130SMehdi Amini } 8891f685e01SPiotr Padlewski for (GlobalVariable &GV : SrcModule->globals()) { 8902d28f7aaSMehdi Amini if (!GV.hasName()) 8912d28f7aaSMehdi Amini continue; 8922d28f7aaSMehdi Amini auto GUID = GV.getGUID(); 8932d28f7aaSMehdi Amini auto Import = ImportGUIDs.count(GUID); 894aeb1e59bSMehdi Amini DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " << GUID 895aeb1e59bSMehdi Amini << " " << GV.getName() << " from " 896aeb1e59bSMehdi Amini << SrcModule->getSourceFileName() << "\n"); 8972d28f7aaSMehdi Amini if (Import) { 8987f00d0a1SPeter Collingbourne if (Error Err = GV.materialize()) 8997f00d0a1SPeter Collingbourne return std::move(Err); 900*7331a0bfSEugene Leviant ImportedGVCount += GlobalsToImport.insert(&GV); 9012d28f7aaSMehdi Amini } 9022d28f7aaSMehdi Amini } 9031f685e01SPiotr Padlewski for (GlobalAlias &GA : SrcModule->aliases()) { 9041f685e01SPiotr Padlewski if (!GA.hasName()) 90501e32130SMehdi Amini continue; 9061f685e01SPiotr Padlewski auto GUID = GA.getGUID(); 90781bbf742STeresa Johnson auto Import = ImportGUIDs.count(GUID); 90881bbf742STeresa Johnson DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias " << GUID 9091f685e01SPiotr Padlewski << " " << GA.getName() << " from " 910aeb1e59bSMehdi Amini << SrcModule->getSourceFileName() << "\n"); 91181bbf742STeresa Johnson if (Import) { 91281bbf742STeresa Johnson if (Error Err = GA.materialize()) 91381bbf742STeresa Johnson return std::move(Err); 91481bbf742STeresa Johnson // Import alias as a copy of its aliasee. 91581bbf742STeresa Johnson GlobalObject *Base = GA.getBaseObject(); 91681bbf742STeresa Johnson if (Error Err = Base->materialize()) 91781bbf742STeresa Johnson return std::move(Err); 91881bbf742STeresa Johnson auto *Fn = replaceAliasWithAliasee(SrcModule.get(), &GA); 91981bbf742STeresa Johnson DEBUG(dbgs() << "Is importing aliasee fn " << Base->getGUID() 92081bbf742STeresa Johnson << " " << Base->getName() << " from " 92181bbf742STeresa Johnson << SrcModule->getSourceFileName() << "\n"); 92281bbf742STeresa Johnson if (EnableImportMetadata) { 92381bbf742STeresa Johnson // Add 'thinlto_src_module' metadata for statistics and debugging. 92481bbf742STeresa Johnson Fn->setMetadata( 92581bbf742STeresa Johnson "thinlto_src_module", 92681bbf742STeresa Johnson MDNode::get(DestModule.getContext(), 92781bbf742STeresa Johnson {MDString::get(DestModule.getContext(), 92881bbf742STeresa Johnson SrcModule->getSourceFileName())})); 92901e32130SMehdi Amini } 93081bbf742STeresa Johnson GlobalsToImport.insert(Fn); 93181bbf742STeresa Johnson } 93281bbf742STeresa Johnson } 93301e32130SMehdi Amini 93419ef4fadSMehdi Amini // Upgrade debug info after we're done materializing all the globals and we 93519ef4fadSMehdi Amini // have loaded all the required metadata! 93619ef4fadSMehdi Amini UpgradeDebugInfo(*SrcModule); 93719ef4fadSMehdi Amini 9387e88d0daSMehdi Amini // Link in the specified functions. 93901e32130SMehdi Amini if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport)) 9408d05185aSMehdi Amini return true; 9418d05185aSMehdi Amini 942d29478f7STeresa Johnson if (PrintImports) { 943d29478f7STeresa Johnson for (const auto *GV : GlobalsToImport) 944d29478f7STeresa Johnson dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName() 945d29478f7STeresa Johnson << " from " << SrcModule->getSourceFileName() << "\n"; 946d29478f7STeresa Johnson } 947d29478f7STeresa Johnson 9486d8f817fSPeter Collingbourne if (Mover.move(std::move(SrcModule), GlobalsToImport.getArrayRef(), 9496d8f817fSPeter Collingbourne [](GlobalValue &, IRMover::ValueAdder) {}, 950e6fd9ff9SPeter Collingbourne /*IsPerformingImport=*/true)) 9517e88d0daSMehdi Amini report_fatal_error("Function Import: link error"); 9527e88d0daSMehdi Amini 95301e32130SMehdi Amini ImportedCount += GlobalsToImport.size(); 9546c475a75STeresa Johnson NumImportedModules++; 9557e88d0daSMehdi Amini } 956e5a61917STeresa Johnson 957*7331a0bfSEugene Leviant NumImportedFunctions += (ImportedCount - ImportedGVCount); 958*7331a0bfSEugene Leviant NumImportedGlobalVars += ImportedGVCount; 959d29478f7STeresa Johnson 960*7331a0bfSEugene Leviant DEBUG(dbgs() << "Imported " << ImportedCount - ImportedGVCount 961*7331a0bfSEugene Leviant << " functions for Module " << DestModule.getModuleIdentifier() 962*7331a0bfSEugene Leviant << "\n"); 963*7331a0bfSEugene Leviant DEBUG(dbgs() << "Imported " << ImportedGVCount 964*7331a0bfSEugene Leviant << " global variables for Module " 965c8c55170SMehdi Amini << DestModule.getModuleIdentifier() << "\n"); 966c8c55170SMehdi Amini return ImportedCount; 96742418abaSMehdi Amini } 96842418abaSMehdi Amini 969598bd2a2SPeter Collingbourne static bool doImportingForModule(Module &M) { 970598bd2a2SPeter Collingbourne if (SummaryFile.empty()) 971598bd2a2SPeter Collingbourne report_fatal_error("error: -function-import requires -summary-file\n"); 9726de481a3SPeter Collingbourne Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr = 9736de481a3SPeter Collingbourne getModuleSummaryIndexForFile(SummaryFile); 9746de481a3SPeter Collingbourne if (!IndexPtrOrErr) { 9756de481a3SPeter Collingbourne logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(), 9766de481a3SPeter Collingbourne "Error loading file '" + SummaryFile + "': "); 97742418abaSMehdi Amini return false; 97842418abaSMehdi Amini } 979598bd2a2SPeter Collingbourne std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr); 98042418abaSMehdi Amini 981c86af334STeresa Johnson // First step is collecting the import list. 982c86af334STeresa Johnson FunctionImporter::ImportMapTy ImportList; 98381bbf742STeresa Johnson // If requested, simply import all functions in the index. This is used 98481bbf742STeresa Johnson // when testing distributed backend handling via the opt tool, when 98581bbf742STeresa Johnson // we have distributed indexes containing exactly the summaries to import. 98681bbf742STeresa Johnson if (ImportAllIndex) 98781bbf742STeresa Johnson ComputeCrossModuleImportForModuleFromIndex(M.getModuleIdentifier(), *Index, 98881bbf742STeresa Johnson ImportList); 98981bbf742STeresa Johnson else 990c86af334STeresa Johnson ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index, 991c86af334STeresa Johnson ImportList); 99201e32130SMehdi Amini 9934fef68cbSTeresa Johnson // Conservatively mark all internal values as promoted. This interface is 9944fef68cbSTeresa Johnson // only used when doing importing via the function importing pass. The pass 9954fef68cbSTeresa Johnson // is only enabled when testing importing via the 'opt' tool, which does 9964fef68cbSTeresa Johnson // not do the ThinLink that would normally determine what values to promote. 9974fef68cbSTeresa Johnson for (auto &I : *Index) { 9989667b91bSPeter Collingbourne for (auto &S : I.second.SummaryList) { 9994fef68cbSTeresa Johnson if (GlobalValue::isLocalLinkage(S->linkage())) 10004fef68cbSTeresa Johnson S->setLinkage(GlobalValue::ExternalLinkage); 10014fef68cbSTeresa Johnson } 10024fef68cbSTeresa Johnson } 10034fef68cbSTeresa Johnson 100401e32130SMehdi Amini // Next we need to promote to global scope and rename any local values that 10051b00f2d9STeresa Johnson // are potentially exported to other modules. 100601e32130SMehdi Amini if (renameModuleForThinLTO(M, *Index, nullptr)) { 10071b00f2d9STeresa Johnson errs() << "Error renaming module\n"; 10081b00f2d9STeresa Johnson return false; 10091b00f2d9STeresa Johnson } 10101b00f2d9STeresa Johnson 101142418abaSMehdi Amini // Perform the import now. 1012d16c8065SMehdi Amini auto ModuleLoader = [&M](StringRef Identifier) { 1013d16c8065SMehdi Amini return loadFile(Identifier, M.getContext()); 1014d16c8065SMehdi Amini }; 10159d2bfc48SRafael Espindola FunctionImporter Importer(*Index, ModuleLoader); 101637e24591SPeter Collingbourne Expected<bool> Result = Importer.importFunctions(M, ImportList); 10177f00d0a1SPeter Collingbourne 10187f00d0a1SPeter Collingbourne // FIXME: Probably need to propagate Errors through the pass manager. 10197f00d0a1SPeter Collingbourne if (!Result) { 10207f00d0a1SPeter Collingbourne logAllUnhandledErrors(Result.takeError(), errs(), 10217f00d0a1SPeter Collingbourne "Error importing module: "); 10227f00d0a1SPeter Collingbourne return false; 10237f00d0a1SPeter Collingbourne } 10247f00d0a1SPeter Collingbourne 10257f00d0a1SPeter Collingbourne return *Result; 102621241571STeresa Johnson } 102721241571STeresa Johnson 102821241571STeresa Johnson namespace { 1029e9ea08a0SEugene Zelenko 103021241571STeresa Johnson /// Pass that performs cross-module function import provided a summary file. 103121241571STeresa Johnson class FunctionImportLegacyPass : public ModulePass { 103221241571STeresa Johnson public: 103321241571STeresa Johnson /// Pass identification, replacement for typeid 103421241571STeresa Johnson static char ID; 103521241571STeresa Johnson 1036e9ea08a0SEugene Zelenko explicit FunctionImportLegacyPass() : ModulePass(ID) {} 1037e9ea08a0SEugene Zelenko 103821241571STeresa Johnson /// Specify pass name for debug output 1039117296c0SMehdi Amini StringRef getPassName() const override { return "Function Importing"; } 104021241571STeresa Johnson 104121241571STeresa Johnson bool runOnModule(Module &M) override { 104221241571STeresa Johnson if (skipModule(M)) 104321241571STeresa Johnson return false; 104421241571STeresa Johnson 1045598bd2a2SPeter Collingbourne return doImportingForModule(M); 104642418abaSMehdi Amini } 104742418abaSMehdi Amini }; 1048e9ea08a0SEugene Zelenko 1049e9ea08a0SEugene Zelenko } // end anonymous namespace 105042418abaSMehdi Amini 105121241571STeresa Johnson PreservedAnalyses FunctionImportPass::run(Module &M, 1052fd03ac6aSSean Silva ModuleAnalysisManager &AM) { 1053598bd2a2SPeter Collingbourne if (!doImportingForModule(M)) 105421241571STeresa Johnson return PreservedAnalyses::all(); 105521241571STeresa Johnson 105621241571STeresa Johnson return PreservedAnalyses::none(); 105721241571STeresa Johnson } 105821241571STeresa Johnson 105921241571STeresa Johnson char FunctionImportLegacyPass::ID = 0; 106021241571STeresa Johnson INITIALIZE_PASS(FunctionImportLegacyPass, "function-import", 106142418abaSMehdi Amini "Summary Based Function Import", false, false) 106242418abaSMehdi Amini 106342418abaSMehdi Amini namespace llvm { 1064e9ea08a0SEugene Zelenko 1065598bd2a2SPeter Collingbourne Pass *createFunctionImportPass() { 1066598bd2a2SPeter Collingbourne return new FunctionImportLegacyPass(); 10675fcbdb71STeresa Johnson } 1068e9ea08a0SEugene Zelenko 1069e9ea08a0SEugene Zelenko } // end namespace llvm 1070