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" 210efed325SSimon Pilgrim #include "llvm/ADT/StringRef.h" 22b040fcc6SCharles Saternos #include "llvm/ADT/StringSet.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"); 6419e23874SEugene 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 74974706ebSTeresa Johnson static cl::opt<int> ImportCutoff( 75974706ebSTeresa Johnson "import-cutoff", cl::init(-1), cl::Hidden, cl::value_desc("N"), 76974706ebSTeresa Johnson cl::desc("Only import first N functions if N>=0 (default -1)")); 77974706ebSTeresa Johnson 7840641748SMehdi Amini static cl::opt<float> 7940641748SMehdi Amini ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7), 8040641748SMehdi Amini cl::Hidden, cl::value_desc("x"), 8140641748SMehdi Amini cl::desc("As we import functions, multiply the " 8240641748SMehdi Amini "`import-instr-limit` threshold by this factor " 8340641748SMehdi Amini "before processing newly imported functions")); 84ba72b95fSPiotr Padlewski 85d2869473SPiotr Padlewski static cl::opt<float> ImportHotInstrFactor( 86d2869473SPiotr Padlewski "import-hot-evolution-factor", cl::init(1.0), cl::Hidden, 87d2869473SPiotr Padlewski cl::value_desc("x"), 88d2869473SPiotr Padlewski cl::desc("As we import functions called from hot callsite, multiply the " 89d2869473SPiotr Padlewski "`import-instr-limit` threshold by this factor " 90d2869473SPiotr Padlewski "before processing newly imported functions")); 91d2869473SPiotr Padlewski 92d9830eb7SPiotr Padlewski static cl::opt<float> ImportHotMultiplier( 938260d665SDehao Chen "import-hot-multiplier", cl::init(10.0), cl::Hidden, cl::value_desc("x"), 94ba72b95fSPiotr Padlewski cl::desc("Multiply the `import-instr-limit` threshold for hot callsites")); 95ba72b95fSPiotr Padlewski 9664c46574SDehao Chen static cl::opt<float> ImportCriticalMultiplier( 9764c46574SDehao Chen "import-critical-multiplier", cl::init(100.0), cl::Hidden, 9864c46574SDehao Chen cl::value_desc("x"), 9964c46574SDehao Chen cl::desc( 10064c46574SDehao Chen "Multiply the `import-instr-limit` threshold for critical callsites")); 10164c46574SDehao Chen 102ba72b95fSPiotr Padlewski // FIXME: This multiplier was not really tuned up. 103ba72b95fSPiotr Padlewski static cl::opt<float> ImportColdMultiplier( 104ba72b95fSPiotr Padlewski "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"), 105ba72b95fSPiotr Padlewski cl::desc("Multiply the `import-instr-limit` threshold for cold callsites")); 10640641748SMehdi Amini 107d29478f7STeresa Johnson static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden, 108d29478f7STeresa Johnson cl::desc("Print imported functions")); 109d29478f7STeresa Johnson 1106c475a75STeresa Johnson static cl::opt<bool> ComputeDead("compute-dead", cl::init(true), cl::Hidden, 1116c475a75STeresa Johnson cl::desc("Compute dead symbols")); 1126c475a75STeresa Johnson 1133b776128SPiotr Padlewski static cl::opt<bool> EnableImportMetadata( 1143b776128SPiotr Padlewski "enable-import-metadata", cl::init( 1153b776128SPiotr Padlewski #if !defined(NDEBUG) 1163b776128SPiotr Padlewski true /*Enabled with asserts.*/ 1173b776128SPiotr Padlewski #else 1183b776128SPiotr Padlewski false 1193b776128SPiotr Padlewski #endif 1203b776128SPiotr Padlewski ), 1213b776128SPiotr Padlewski cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'")); 1223b776128SPiotr Padlewski 123e9ea08a0SEugene Zelenko /// Summary file to use for function importing when using -function-import from 124e9ea08a0SEugene Zelenko /// the command line. 125e9ea08a0SEugene Zelenko static cl::opt<std::string> 126e9ea08a0SEugene Zelenko SummaryFile("summary-file", 127e9ea08a0SEugene Zelenko cl::desc("The summary file to use for function importing.")); 128e9ea08a0SEugene Zelenko 12981bbf742STeresa Johnson /// Used when testing importing from distributed indexes via opt 13081bbf742STeresa Johnson // -function-import. 13181bbf742STeresa Johnson static cl::opt<bool> 13281bbf742STeresa Johnson ImportAllIndex("import-all-index", 13381bbf742STeresa Johnson cl::desc("Import all external functions in index.")); 13481bbf742STeresa Johnson 13542418abaSMehdi Amini // Load lazily a module from \p FileName in \p Context. 13642418abaSMehdi Amini static std::unique_ptr<Module> loadFile(const std::string &FileName, 13742418abaSMehdi Amini LLVMContext &Context) { 13842418abaSMehdi Amini SMDiagnostic Err; 139*d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Loading '" << FileName << "'\n"); 1406cba37ceSTeresa Johnson // Metadata isn't loaded until functions are imported, to minimize 1416cba37ceSTeresa Johnson // the memory overhead. 142a1080ee6STeresa Johnson std::unique_ptr<Module> Result = 143a1080ee6STeresa Johnson getLazyIRFileModule(FileName, Err, Context, 144a1080ee6STeresa Johnson /* ShouldLazyLoadMetadata = */ true); 14542418abaSMehdi Amini if (!Result) { 14642418abaSMehdi Amini Err.print("function-import", errs()); 147d7ad221cSMehdi Amini report_fatal_error("Abort"); 14842418abaSMehdi Amini } 14942418abaSMehdi Amini 15042418abaSMehdi Amini return Result; 15142418abaSMehdi Amini } 15242418abaSMehdi Amini 15301e32130SMehdi Amini /// Given a list of possible callee implementation for a call site, select one 15401e32130SMehdi Amini /// that fits the \p Threshold. 15501e32130SMehdi Amini /// 15601e32130SMehdi Amini /// FIXME: select "best" instead of first that fits. But what is "best"? 15701e32130SMehdi Amini /// - The smallest: more likely to be inlined. 15801e32130SMehdi Amini /// - The one with the least outgoing edges (already well optimized). 15901e32130SMehdi Amini /// - One from a module already being imported from in order to reduce the 16001e32130SMehdi Amini /// number of source modules parsed/linked. 16101e32130SMehdi Amini /// - One that has PGO data attached. 16201e32130SMehdi Amini /// - [insert you fancy metric here] 1632d28f7aaSMehdi Amini static const GlobalValueSummary * 164b4e1e829SMehdi Amini selectCallee(const ModuleSummaryIndex &Index, 1659667b91bSPeter Collingbourne ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList, 16683aaf358STeresa Johnson unsigned Threshold, StringRef CallerModulePath) { 16701e32130SMehdi Amini auto It = llvm::find_if( 16828e457bcSTeresa Johnson CalleeSummaryList, 16928e457bcSTeresa Johnson [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) { 17028e457bcSTeresa Johnson auto *GVSummary = SummaryPtr.get(); 171eaf5172cSGeorge Rimar if (!Index.isGlobalValueLive(GVSummary)) 172eaf5172cSGeorge Rimar return false; 173eaf5172cSGeorge Rimar 17473305f82STeresa Johnson // For SamplePGO, in computeImportForFunction the OriginalId 17573305f82STeresa Johnson // may have been used to locate the callee summary list (See 17673305f82STeresa Johnson // comment there). 17773305f82STeresa Johnson // The mapping from OriginalId to GUID may return a GUID 17873305f82STeresa Johnson // that corresponds to a static variable. Filter it out here. 17973305f82STeresa Johnson // This can happen when 18073305f82STeresa Johnson // 1) There is a call to a library function which is not defined 18173305f82STeresa Johnson // in the index. 18273305f82STeresa Johnson // 2) There is a static variable with the OriginalGUID identical 18373305f82STeresa Johnson // to the GUID of the library function in 1); 18473305f82STeresa Johnson // When this happens, the logic for SamplePGO kicks in and 18573305f82STeresa Johnson // the static variable in 2) will be found, which needs to be 18673305f82STeresa Johnson // filtered out. 18773305f82STeresa Johnson if (GVSummary->getSummaryKind() == GlobalValueSummary::GlobalVarKind) 18873305f82STeresa Johnson return false; 189f329be83SRafael Espindola if (GlobalValue::isInterposableLinkage(GVSummary->linkage())) 1905b85d8d6SMehdi Amini // There is no point in importing these, we can't inline them 19101e32130SMehdi Amini return false; 1922c719cc1SMehdi Amini 19381bbf742STeresa Johnson auto *Summary = cast<FunctionSummary>(GVSummary->getBaseObject()); 1947e88d0daSMehdi Amini 19583aaf358STeresa Johnson // If this is a local function, make sure we import the copy 19683aaf358STeresa Johnson // in the caller's module. The only time a local function can 19783aaf358STeresa Johnson // share an entry in the index is if there is a local with the same name 19883aaf358STeresa Johnson // in another module that had the same source file name (in a different 19983aaf358STeresa Johnson // directory), where each was compiled in their own directory so there 20083aaf358STeresa Johnson // was not distinguishing path. 20183aaf358STeresa Johnson // However, do the import from another module if there is only one 20283aaf358STeresa Johnson // entry in the list - in that case this must be a reference due 20383aaf358STeresa Johnson // to indirect call profile data, since a function pointer can point to 20483aaf358STeresa Johnson // a local in another module. 20583aaf358STeresa Johnson if (GlobalValue::isLocalLinkage(Summary->linkage()) && 20683aaf358STeresa Johnson CalleeSummaryList.size() > 1 && 20783aaf358STeresa Johnson Summary->modulePath() != CallerModulePath) 20883aaf358STeresa Johnson return false; 20983aaf358STeresa Johnson 210f9dc3deaSTeresa Johnson if (Summary->instCount() > Threshold) 211f9dc3deaSTeresa Johnson return false; 212f9dc3deaSTeresa Johnson 213519465b9STeresa Johnson if (Summary->notEligibleToImport()) 214b4e1e829SMehdi Amini return false; 215b4e1e829SMehdi Amini 21601e32130SMehdi Amini return true; 21701e32130SMehdi Amini }); 21828e457bcSTeresa Johnson if (It == CalleeSummaryList.end()) 21901e32130SMehdi Amini return nullptr; 2207e88d0daSMehdi Amini 221f9dc3deaSTeresa Johnson return cast<GlobalValueSummary>(It->get()); 222434e9561SRafael Espindola } 2237e88d0daSMehdi Amini 224e9ea08a0SEugene Zelenko namespace { 225e9ea08a0SEugene Zelenko 226475b51a7STeresa Johnson using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */, 227475b51a7STeresa Johnson GlobalValue::GUID>; 22801e32130SMehdi Amini 229e9ea08a0SEugene Zelenko } // anonymous namespace 230e9ea08a0SEugene Zelenko 2311958083dSTeresa Johnson static ValueInfo 2321958083dSTeresa Johnson updateValueInfoForIndirectCalls(const ModuleSummaryIndex &Index, ValueInfo VI) { 2331958083dSTeresa Johnson if (!VI.getSummaryList().empty()) 2341958083dSTeresa Johnson return VI; 2351958083dSTeresa Johnson // For SamplePGO, the indirect call targets for local functions will 2361958083dSTeresa Johnson // have its original name annotated in profile. We try to find the 2371958083dSTeresa Johnson // corresponding PGOFuncName as the GUID. 2381958083dSTeresa Johnson // FIXME: Consider updating the edges in the graph after building 2391958083dSTeresa Johnson // it, rather than needing to perform this mapping on each walk. 2401958083dSTeresa Johnson auto GUID = Index.getGUIDFromOriginalID(VI.getGUID()); 2411958083dSTeresa Johnson if (GUID == 0) 24228d8a49fSEugene Leviant return ValueInfo(); 2431958083dSTeresa Johnson return Index.getValueInfo(GUID); 2441958083dSTeresa Johnson } 2451958083dSTeresa Johnson 24619e23874SEugene Leviant static void computeImportForReferencedGlobals( 24719e23874SEugene Leviant const FunctionSummary &Summary, const GVSummaryMapTy &DefinedGVSummaries, 24819e23874SEugene Leviant FunctionImporter::ImportMapTy &ImportList, 24919e23874SEugene Leviant StringMap<FunctionImporter::ExportSetTy> *ExportLists) { 25019e23874SEugene Leviant for (auto &VI : Summary.refs()) { 25119e23874SEugene Leviant if (DefinedGVSummaries.count(VI.getGUID())) { 252*d34e60caSNicola Zaghen LLVM_DEBUG( 253*d34e60caSNicola Zaghen dbgs() << "Ref ignored! Target already in destination module.\n"); 25419e23874SEugene Leviant continue; 25519e23874SEugene Leviant } 25619e23874SEugene Leviant 257*d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " ref -> " << VI.getGUID() << "\n"); 25819e23874SEugene Leviant 25919e23874SEugene Leviant for (auto &RefSummary : VI.getSummaryList()) 26019e23874SEugene Leviant if (RefSummary->getSummaryKind() == GlobalValueSummary::GlobalVarKind && 26119e23874SEugene Leviant // Don't try to import regular LTO summaries added to dummy module. 26219e23874SEugene Leviant !RefSummary->modulePath().empty() && 26319e23874SEugene Leviant !GlobalValue::isInterposableLinkage(RefSummary->linkage()) && 26419e23874SEugene Leviant RefSummary->refs().empty()) { 26519e23874SEugene Leviant ImportList[RefSummary->modulePath()][VI.getGUID()] = 1; 26619e23874SEugene Leviant if (ExportLists) 26719e23874SEugene Leviant (*ExportLists)[RefSummary->modulePath()].insert(VI.getGUID()); 26819e23874SEugene Leviant break; 26919e23874SEugene Leviant } 27019e23874SEugene Leviant } 27119e23874SEugene Leviant } 27219e23874SEugene Leviant 27301e32130SMehdi Amini /// Compute the list of functions to import for a given caller. Mark these 27401e32130SMehdi Amini /// imported functions and the symbols they reference in their source module as 27501e32130SMehdi Amini /// exported from their source module. 27601e32130SMehdi Amini static void computeImportForFunction( 2773255eec1STeresa Johnson const FunctionSummary &Summary, const ModuleSummaryIndex &Index, 278d9830eb7SPiotr Padlewski const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries, 27901e32130SMehdi Amini SmallVectorImpl<EdgeInfo> &Worklist, 2809b490f10SMehdi Amini FunctionImporter::ImportMapTy &ImportList, 281c86af334STeresa Johnson StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) { 28219e23874SEugene Leviant computeImportForReferencedGlobals(Summary, DefinedGVSummaries, ImportList, 28319e23874SEugene Leviant ExportLists); 284974706ebSTeresa Johnson static int ImportCount = 0; 28501e32130SMehdi Amini for (auto &Edge : Summary.calls()) { 2869667b91bSPeter Collingbourne ValueInfo VI = Edge.first; 287*d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " edge -> " << VI.getGUID() 288*d34e60caSNicola Zaghen << " Threshold:" << Threshold << "\n"); 28901e32130SMehdi Amini 290974706ebSTeresa Johnson if (ImportCutoff >= 0 && ImportCount >= ImportCutoff) { 291*d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "ignored! import-cutoff value of " << ImportCutoff 292974706ebSTeresa Johnson << " reached.\n"); 293974706ebSTeresa Johnson continue; 294974706ebSTeresa Johnson } 295974706ebSTeresa Johnson 2961958083dSTeresa Johnson VI = updateValueInfoForIndirectCalls(Index, VI); 2979667b91bSPeter Collingbourne if (!VI) 2989667b91bSPeter Collingbourne continue; 2994a435e08SDehao Chen 3009667b91bSPeter Collingbourne if (DefinedGVSummaries.count(VI.getGUID())) { 301*d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "ignored! Target already in destination module.\n"); 3027e88d0daSMehdi Amini continue; 303d450da32STeresa Johnson } 30440641748SMehdi Amini 305ba72b95fSPiotr Padlewski auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float { 306ba72b95fSPiotr Padlewski if (Hotness == CalleeInfo::HotnessType::Hot) 307ba72b95fSPiotr Padlewski return ImportHotMultiplier; 308ba72b95fSPiotr Padlewski if (Hotness == CalleeInfo::HotnessType::Cold) 309ba72b95fSPiotr Padlewski return ImportColdMultiplier; 31064c46574SDehao Chen if (Hotness == CalleeInfo::HotnessType::Critical) 31164c46574SDehao Chen return ImportCriticalMultiplier; 312ba72b95fSPiotr Padlewski return 1.0; 313ba72b95fSPiotr Padlewski }; 314ba72b95fSPiotr Padlewski 315d9830eb7SPiotr Padlewski const auto NewThreshold = 316c73cec84SEaswaran Raman Threshold * GetBonusMultiplier(Edge.second.getHotness()); 317d2869473SPiotr Padlewski 3189667b91bSPeter Collingbourne auto *CalleeSummary = selectCallee(Index, VI.getSummaryList(), NewThreshold, 3199667b91bSPeter Collingbourne Summary.modulePath()); 32001e32130SMehdi Amini if (!CalleeSummary) { 321*d34e60caSNicola Zaghen LLVM_DEBUG( 322*d34e60caSNicola Zaghen dbgs() << "ignored! No qualifying callee with summary found.\n"); 3237e88d0daSMehdi Amini continue; 3247e88d0daSMehdi Amini } 3252f0cc477SDavid Blaikie 3262f0cc477SDavid Blaikie // "Resolve" the summary 32781bbf742STeresa Johnson const auto *ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary->getBaseObject()); 3282d28f7aaSMehdi Amini 329d9830eb7SPiotr Padlewski assert(ResolvedCalleeSummary->instCount() <= NewThreshold && 33001e32130SMehdi Amini "selectCallee() didn't honor the threshold"); 33101e32130SMehdi Amini 332d2869473SPiotr Padlewski auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) { 333d2869473SPiotr Padlewski // Adjust the threshold for next level of imported functions. 334d2869473SPiotr Padlewski // The threshold is different for hot callsites because we can then 335d2869473SPiotr Padlewski // inline chains of hot calls. 336d2869473SPiotr Padlewski if (IsHotCallsite) 337d2869473SPiotr Padlewski return Threshold * ImportHotInstrFactor; 338d2869473SPiotr Padlewski return Threshold * ImportInstrFactor; 339d2869473SPiotr Padlewski }; 340d2869473SPiotr Padlewski 341c73cec84SEaswaran Raman bool IsHotCallsite = 342c73cec84SEaswaran Raman Edge.second.getHotness() == CalleeInfo::HotnessType::Hot; 3431b859a23STeresa Johnson const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite); 3441b859a23STeresa Johnson 3451b859a23STeresa Johnson auto ExportModulePath = ResolvedCalleeSummary->modulePath(); 3469667b91bSPeter Collingbourne auto &ProcessedThreshold = ImportList[ExportModulePath][VI.getGUID()]; 3471b859a23STeresa Johnson /// Since the traversal of the call graph is DFS, we can revisit a function 3481b859a23STeresa Johnson /// a second time with a higher threshold. In this case, it is added back to 3491b859a23STeresa Johnson /// the worklist with the new threshold. 3501b859a23STeresa Johnson if (ProcessedThreshold && ProcessedThreshold >= AdjThreshold) { 351*d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "ignored! Target was already seen with Threshold " 3521b859a23STeresa Johnson << ProcessedThreshold << "\n"); 3531b859a23STeresa Johnson continue; 3541b859a23STeresa Johnson } 35519f2aa78STeresa Johnson bool PreviouslyImported = ProcessedThreshold != 0; 3561b859a23STeresa Johnson // Mark this function as imported in this module, with the current Threshold 3571b859a23STeresa Johnson ProcessedThreshold = AdjThreshold; 3581b859a23STeresa Johnson 359974706ebSTeresa Johnson ImportCount++; 360974706ebSTeresa Johnson 3611b859a23STeresa Johnson // Make exports in the source module. 3621b859a23STeresa Johnson if (ExportLists) { 3631b859a23STeresa Johnson auto &ExportList = (*ExportLists)[ExportModulePath]; 3649667b91bSPeter Collingbourne ExportList.insert(VI.getGUID()); 36519f2aa78STeresa Johnson if (!PreviouslyImported) { 36619f2aa78STeresa Johnson // This is the first time this function was exported from its source 36719f2aa78STeresa Johnson // module, so mark all functions and globals it references as exported 3681b859a23STeresa Johnson // to the outside if they are defined in the same source module. 369edddca22STeresa Johnson // For efficiency, we unconditionally add all the referenced GUIDs 370edddca22STeresa Johnson // to the ExportList for this module, and will prune out any not 371edddca22STeresa Johnson // defined in the module later in a single pass. 3721b859a23STeresa Johnson for (auto &Edge : ResolvedCalleeSummary->calls()) { 3731b859a23STeresa Johnson auto CalleeGUID = Edge.first.getGUID(); 374edddca22STeresa Johnson ExportList.insert(CalleeGUID); 3751b859a23STeresa Johnson } 3761b859a23STeresa Johnson for (auto &Ref : ResolvedCalleeSummary->refs()) { 3771b859a23STeresa Johnson auto GUID = Ref.getGUID(); 378edddca22STeresa Johnson ExportList.insert(GUID); 3791b859a23STeresa Johnson } 3801b859a23STeresa Johnson } 38119f2aa78STeresa Johnson } 382d2869473SPiotr Padlewski 38301e32130SMehdi Amini // Insert the newly imported function to the worklist. 3849667b91bSPeter Collingbourne Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, VI.getGUID()); 385d450da32STeresa Johnson } 386d450da32STeresa Johnson } 387d450da32STeresa Johnson 38801e32130SMehdi Amini /// Given the list of globals defined in a module, compute the list of imports 38901e32130SMehdi Amini /// as well as the list of "exports", i.e. the list of symbols referenced from 39001e32130SMehdi Amini /// another module (that may require promotion). 39101e32130SMehdi Amini static void ComputeImportForModule( 392c851d216STeresa Johnson const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index, 3939b490f10SMehdi Amini FunctionImporter::ImportMapTy &ImportList, 39456584bbfSEvgeniy Stepanov StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) { 39501e32130SMehdi Amini // Worklist contains the list of function imported in this module, for which 39601e32130SMehdi Amini // we will analyse the callees and may import further down the callgraph. 39701e32130SMehdi Amini SmallVector<EdgeInfo, 128> Worklist; 39801e32130SMehdi Amini 39901e32130SMehdi Amini // Populate the worklist with the import for the functions in the current 40001e32130SMehdi Amini // module 40128e457bcSTeresa Johnson for (auto &GVSummary : DefinedGVSummaries) { 40256584bbfSEvgeniy Stepanov if (!Index.isGlobalValueLive(GVSummary.second)) { 403*d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Ignores Dead GUID: " << GVSummary.first << "\n"); 4046c475a75STeresa Johnson continue; 4056c475a75STeresa Johnson } 406cfbd0892SPeter Collingbourne auto *FuncSummary = 407cfbd0892SPeter Collingbourne dyn_cast<FunctionSummary>(GVSummary.second->getBaseObject()); 4081aafabf7SMehdi Amini if (!FuncSummary) 4091aafabf7SMehdi Amini // Skip import for global variables 4101aafabf7SMehdi Amini continue; 411*d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Initialize import for " << GVSummary.first << "\n"); 4122d28f7aaSMehdi Amini computeImportForFunction(*FuncSummary, Index, ImportInstrLimit, 4139b490f10SMehdi Amini DefinedGVSummaries, Worklist, ImportList, 41401e32130SMehdi Amini ExportLists); 41501e32130SMehdi Amini } 41601e32130SMehdi Amini 417d2869473SPiotr Padlewski // Process the newly imported functions and add callees to the worklist. 41842418abaSMehdi Amini while (!Worklist.empty()) { 41901e32130SMehdi Amini auto FuncInfo = Worklist.pop_back_val(); 420475b51a7STeresa Johnson auto *Summary = std::get<0>(FuncInfo); 421475b51a7STeresa Johnson auto Threshold = std::get<1>(FuncInfo); 422475b51a7STeresa Johnson auto GUID = std::get<2>(FuncInfo); 423475b51a7STeresa Johnson 424475b51a7STeresa Johnson // Check if we later added this summary with a higher threshold. 425475b51a7STeresa Johnson // If so, skip this entry. 426475b51a7STeresa Johnson auto ExportModulePath = Summary->modulePath(); 427475b51a7STeresa Johnson auto &LatestProcessedThreshold = ImportList[ExportModulePath][GUID]; 428475b51a7STeresa Johnson if (LatestProcessedThreshold > Threshold) 429475b51a7STeresa Johnson continue; 43042418abaSMehdi Amini 4311aafabf7SMehdi Amini computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries, 4329b490f10SMehdi Amini Worklist, ImportList, ExportLists); 433c8c55170SMehdi Amini } 43442418abaSMehdi Amini } 435ffe2e4aaSMehdi Amini 43619e23874SEugene Leviant #ifndef NDEBUG 43719e23874SEugene Leviant static bool isGlobalVarSummary(const ModuleSummaryIndex &Index, 43819e23874SEugene Leviant GlobalValue::GUID G) { 43919e23874SEugene Leviant if (const auto &VI = Index.getValueInfo(G)) { 44019e23874SEugene Leviant auto SL = VI.getSummaryList(); 44119e23874SEugene Leviant if (!SL.empty()) 44219e23874SEugene Leviant return SL[0]->getSummaryKind() == GlobalValueSummary::GlobalVarKind; 44319e23874SEugene Leviant } 44419e23874SEugene Leviant return false; 44519e23874SEugene Leviant } 44619e23874SEugene Leviant 44719e23874SEugene Leviant static GlobalValue::GUID getGUID(GlobalValue::GUID G) { return G; } 44819e23874SEugene Leviant 44919e23874SEugene Leviant static GlobalValue::GUID 45019e23874SEugene Leviant getGUID(const std::pair<const GlobalValue::GUID, unsigned> &P) { 45119e23874SEugene Leviant return P.first; 45219e23874SEugene Leviant } 45319e23874SEugene Leviant 45419e23874SEugene Leviant template <class T> 4551fc0da48SBenjamin Kramer static unsigned numGlobalVarSummaries(const ModuleSummaryIndex &Index, 4561fc0da48SBenjamin Kramer T &Cont) { 45719e23874SEugene Leviant unsigned NumGVS = 0; 45819e23874SEugene Leviant for (auto &V : Cont) 45919e23874SEugene Leviant if (isGlobalVarSummary(Index, getGUID(V))) 46019e23874SEugene Leviant ++NumGVS; 46119e23874SEugene Leviant return NumGVS; 46219e23874SEugene Leviant } 46319e23874SEugene Leviant #endif 46419e23874SEugene Leviant 465c86af334STeresa Johnson /// Compute all the import and export for every module using the Index. 46601e32130SMehdi Amini void llvm::ComputeCrossModuleImport( 46701e32130SMehdi Amini const ModuleSummaryIndex &Index, 468c851d216STeresa Johnson const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries, 46901e32130SMehdi Amini StringMap<FunctionImporter::ImportMapTy> &ImportLists, 47056584bbfSEvgeniy Stepanov StringMap<FunctionImporter::ExportSetTy> &ExportLists) { 47101e32130SMehdi Amini // For each module that has function defined, compute the import/export lists. 4721aafabf7SMehdi Amini for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) { 4739b490f10SMehdi Amini auto &ImportList = ImportLists[DefinedGVSummaries.first()]; 474*d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Computing import for Module '" 4751aafabf7SMehdi Amini << DefinedGVSummaries.first() << "'\n"); 4769b490f10SMehdi Amini ComputeImportForModule(DefinedGVSummaries.second, Index, ImportList, 47756584bbfSEvgeniy Stepanov &ExportLists); 47801e32130SMehdi Amini } 47901e32130SMehdi Amini 480edddca22STeresa Johnson // When computing imports we added all GUIDs referenced by anything 481edddca22STeresa Johnson // imported from the module to its ExportList. Now we prune each ExportList 482edddca22STeresa Johnson // of any not defined in that module. This is more efficient than checking 483edddca22STeresa Johnson // while computing imports because some of the summary lists may be long 484edddca22STeresa Johnson // due to linkonce (comdat) copies. 485edddca22STeresa Johnson for (auto &ELI : ExportLists) { 486edddca22STeresa Johnson const auto &DefinedGVSummaries = 487edddca22STeresa Johnson ModuleToDefinedGVSummaries.lookup(ELI.first()); 488edddca22STeresa Johnson for (auto EI = ELI.second.begin(); EI != ELI.second.end();) { 489edddca22STeresa Johnson if (!DefinedGVSummaries.count(*EI)) 490edddca22STeresa Johnson EI = ELI.second.erase(EI); 491edddca22STeresa Johnson else 492edddca22STeresa Johnson ++EI; 493edddca22STeresa Johnson } 494edddca22STeresa Johnson } 495edddca22STeresa Johnson 49601e32130SMehdi Amini #ifndef NDEBUG 497*d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size() 49801e32130SMehdi Amini << " modules:\n"); 49901e32130SMehdi Amini for (auto &ModuleImports : ImportLists) { 50001e32130SMehdi Amini auto ModName = ModuleImports.first(); 50101e32130SMehdi Amini auto &Exports = ExportLists[ModName]; 50219e23874SEugene Leviant unsigned NumGVS = numGlobalVarSummaries(Index, Exports); 503*d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "* Module " << ModName << " exports " 50419e23874SEugene Leviant << Exports.size() - NumGVS << " functions and " << NumGVS 505*d34e60caSNicola Zaghen << " vars. Imports from " << ModuleImports.second.size() 506*d34e60caSNicola Zaghen << " modules.\n"); 50701e32130SMehdi Amini for (auto &Src : ModuleImports.second) { 50801e32130SMehdi Amini auto SrcModName = Src.first(); 50919e23874SEugene Leviant unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second); 510*d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod 51119e23874SEugene Leviant << " functions imported from " << SrcModName << "\n"); 512*d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod 513*d34e60caSNicola Zaghen << " global vars imported from " << SrcModName << "\n"); 51401e32130SMehdi Amini } 51501e32130SMehdi Amini } 51601e32130SMehdi Amini #endif 51701e32130SMehdi Amini } 51801e32130SMehdi Amini 51981bbf742STeresa Johnson #ifndef NDEBUG 52019e23874SEugene Leviant static void dumpImportListForModule(const ModuleSummaryIndex &Index, 52119e23874SEugene Leviant StringRef ModulePath, 52281bbf742STeresa Johnson FunctionImporter::ImportMapTy &ImportList) { 523*d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "* Module " << ModulePath << " imports from " 52481bbf742STeresa Johnson << ImportList.size() << " modules.\n"); 52581bbf742STeresa Johnson for (auto &Src : ImportList) { 52681bbf742STeresa Johnson auto SrcModName = Src.first(); 52719e23874SEugene Leviant unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second); 528*d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod 52919e23874SEugene Leviant << " functions imported from " << SrcModName << "\n"); 530*d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod << " vars imported from " 53181bbf742STeresa Johnson << SrcModName << "\n"); 53281bbf742STeresa Johnson } 53381bbf742STeresa Johnson } 53469b2de84STeresa Johnson #endif 53581bbf742STeresa Johnson 536c86af334STeresa Johnson /// Compute all the imports for the given module in the Index. 537c86af334STeresa Johnson void llvm::ComputeCrossModuleImportForModule( 538c86af334STeresa Johnson StringRef ModulePath, const ModuleSummaryIndex &Index, 539c86af334STeresa Johnson FunctionImporter::ImportMapTy &ImportList) { 540c86af334STeresa Johnson // Collect the list of functions this module defines. 541c86af334STeresa Johnson // GUID -> Summary 542c851d216STeresa Johnson GVSummaryMapTy FunctionSummaryMap; 54328e457bcSTeresa Johnson Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap); 544c86af334STeresa Johnson 545c86af334STeresa Johnson // Compute the import list for this module. 546*d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n"); 54728e457bcSTeresa Johnson ComputeImportForModule(FunctionSummaryMap, Index, ImportList); 548c86af334STeresa Johnson 549c86af334STeresa Johnson #ifndef NDEBUG 55019e23874SEugene Leviant dumpImportListForModule(Index, ModulePath, ImportList); 55181bbf742STeresa Johnson #endif 552c86af334STeresa Johnson } 55381bbf742STeresa Johnson 55481bbf742STeresa Johnson // Mark all external summaries in Index for import into the given module. 55581bbf742STeresa Johnson // Used for distributed builds using a distributed index. 55681bbf742STeresa Johnson void llvm::ComputeCrossModuleImportForModuleFromIndex( 55781bbf742STeresa Johnson StringRef ModulePath, const ModuleSummaryIndex &Index, 55881bbf742STeresa Johnson FunctionImporter::ImportMapTy &ImportList) { 55981bbf742STeresa Johnson for (auto &GlobalList : Index) { 56081bbf742STeresa Johnson // Ignore entries for undefined references. 56181bbf742STeresa Johnson if (GlobalList.second.SummaryList.empty()) 56281bbf742STeresa Johnson continue; 56381bbf742STeresa Johnson 56481bbf742STeresa Johnson auto GUID = GlobalList.first; 56581bbf742STeresa Johnson assert(GlobalList.second.SummaryList.size() == 1 && 56681bbf742STeresa Johnson "Expected individual combined index to have one summary per GUID"); 56781bbf742STeresa Johnson auto &Summary = GlobalList.second.SummaryList[0]; 56881bbf742STeresa Johnson // Skip the summaries for the importing module. These are included to 56981bbf742STeresa Johnson // e.g. record required linkage changes. 57081bbf742STeresa Johnson if (Summary->modulePath() == ModulePath) 57181bbf742STeresa Johnson continue; 57281bbf742STeresa Johnson // Doesn't matter what value we plug in to the map, just needs an entry 57381bbf742STeresa Johnson // to provoke importing by thinBackend. 57481bbf742STeresa Johnson ImportList[Summary->modulePath()][GUID] = 1; 57581bbf742STeresa Johnson } 57681bbf742STeresa Johnson #ifndef NDEBUG 57719e23874SEugene Leviant dumpImportListForModule(Index, ModulePath, ImportList); 578c86af334STeresa Johnson #endif 579c86af334STeresa Johnson } 580c86af334STeresa Johnson 58156584bbfSEvgeniy Stepanov void llvm::computeDeadSymbols( 58256584bbfSEvgeniy Stepanov ModuleSummaryIndex &Index, 583eaf5172cSGeorge Rimar const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols, 584eaf5172cSGeorge Rimar function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing) { 58556584bbfSEvgeniy Stepanov assert(!Index.withGlobalValueDeadStripping()); 5866c475a75STeresa Johnson if (!ComputeDead) 58756584bbfSEvgeniy Stepanov return; 5886c475a75STeresa Johnson if (GUIDPreservedSymbols.empty()) 5896c475a75STeresa Johnson // Don't do anything when nothing is live, this is friendly with tests. 59056584bbfSEvgeniy Stepanov return; 59156584bbfSEvgeniy Stepanov unsigned LiveSymbols = 0; 5929667b91bSPeter Collingbourne SmallVector<ValueInfo, 128> Worklist; 5939667b91bSPeter Collingbourne Worklist.reserve(GUIDPreservedSymbols.size() * 2); 5949667b91bSPeter Collingbourne for (auto GUID : GUIDPreservedSymbols) { 5959667b91bSPeter Collingbourne ValueInfo VI = Index.getValueInfo(GUID); 5969667b91bSPeter Collingbourne if (!VI) 5979667b91bSPeter Collingbourne continue; 59856584bbfSEvgeniy Stepanov for (auto &S : VI.getSummaryList()) 59956584bbfSEvgeniy Stepanov S->setLive(true); 6006c475a75STeresa Johnson } 60156584bbfSEvgeniy Stepanov 6026c475a75STeresa Johnson // Add values flagged in the index as live roots to the worklist. 60356584bbfSEvgeniy Stepanov for (const auto &Entry : Index) 60456584bbfSEvgeniy Stepanov for (auto &S : Entry.second.SummaryList) 60556584bbfSEvgeniy Stepanov if (S->isLive()) { 606*d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Live root: " << Entry.first << "\n"); 60728d8a49fSEugene Leviant Worklist.push_back(ValueInfo(/*IsAnalysis=*/false, &Entry)); 60856584bbfSEvgeniy Stepanov ++LiveSymbols; 60956584bbfSEvgeniy Stepanov break; 6106c475a75STeresa Johnson } 6116c475a75STeresa Johnson 61256584bbfSEvgeniy Stepanov // Make value live and add it to the worklist if it was not live before. 61356584bbfSEvgeniy Stepanov auto visit = [&](ValueInfo VI) { 6141958083dSTeresa Johnson // FIXME: If we knew which edges were created for indirect call profiles, 6151958083dSTeresa Johnson // we could skip them here. Any that are live should be reached via 6161958083dSTeresa Johnson // other edges, e.g. reference edges. Otherwise, using a profile collected 6171958083dSTeresa Johnson // on a slightly different binary might provoke preserving, importing 6181958083dSTeresa Johnson // and ultimately promoting calls to functions not linked into this 6191958083dSTeresa Johnson // binary, which increases the binary size unnecessarily. Note that 6201958083dSTeresa Johnson // if this code changes, the importer needs to change so that edges 6211958083dSTeresa Johnson // to functions marked dead are skipped. 6221958083dSTeresa Johnson VI = updateValueInfoForIndirectCalls(Index, VI); 6231958083dSTeresa Johnson if (!VI) 6241958083dSTeresa Johnson return; 62556584bbfSEvgeniy Stepanov for (auto &S : VI.getSummaryList()) 626f625118eSTeresa Johnson if (S->isLive()) 627f625118eSTeresa Johnson return; 628eaf5172cSGeorge Rimar 629aab60006SVlad Tsyrklevich // We only keep live symbols that are known to be non-prevailing if any are 630aab60006SVlad Tsyrklevich // available_externally. Those symbols are discarded later in the 631aab60006SVlad Tsyrklevich // EliminateAvailableExternally pass and setting them to not-live breaks 632aab60006SVlad Tsyrklevich // downstreams users of liveness information (PR36483). 633aab60006SVlad Tsyrklevich if (isPrevailing(VI.getGUID()) == PrevailingType::No) { 634aab60006SVlad Tsyrklevich bool AvailableExternally = false; 635aab60006SVlad Tsyrklevich bool Interposable = false; 636aab60006SVlad Tsyrklevich for (auto &S : VI.getSummaryList()) { 637aab60006SVlad Tsyrklevich if (S->linkage() == GlobalValue::AvailableExternallyLinkage) 638aab60006SVlad Tsyrklevich AvailableExternally = true; 639aab60006SVlad Tsyrklevich else if (GlobalValue::isInterposableLinkage(S->linkage())) 640aab60006SVlad Tsyrklevich Interposable = true; 641aab60006SVlad Tsyrklevich } 642aab60006SVlad Tsyrklevich 643aab60006SVlad Tsyrklevich if (!AvailableExternally) 644eaf5172cSGeorge Rimar return; 645eaf5172cSGeorge Rimar 646aab60006SVlad Tsyrklevich if (Interposable) 647aab60006SVlad Tsyrklevich report_fatal_error("Interposable and available_externally symbol"); 648aab60006SVlad Tsyrklevich } 649aab60006SVlad Tsyrklevich 650f625118eSTeresa Johnson for (auto &S : VI.getSummaryList()) 65156584bbfSEvgeniy Stepanov S->setLive(true); 65256584bbfSEvgeniy Stepanov ++LiveSymbols; 65356584bbfSEvgeniy Stepanov Worklist.push_back(VI); 65456584bbfSEvgeniy Stepanov }; 65556584bbfSEvgeniy Stepanov 6566c475a75STeresa Johnson while (!Worklist.empty()) { 6579667b91bSPeter Collingbourne auto VI = Worklist.pop_back_val(); 6589667b91bSPeter Collingbourne for (auto &Summary : VI.getSummaryList()) { 659cfbd0892SPeter Collingbourne GlobalValueSummary *Base = Summary->getBaseObject(); 660eaf5172cSGeorge Rimar // Set base value live in case it is an alias. 661eaf5172cSGeorge Rimar Base->setLive(true); 662cfbd0892SPeter Collingbourne for (auto Ref : Base->refs()) 66356584bbfSEvgeniy Stepanov visit(Ref); 664cfbd0892SPeter Collingbourne if (auto *FS = dyn_cast<FunctionSummary>(Base)) 66556584bbfSEvgeniy Stepanov for (auto Call : FS->calls()) 66656584bbfSEvgeniy Stepanov visit(Call.first); 6676c475a75STeresa Johnson } 6686c475a75STeresa Johnson } 66956584bbfSEvgeniy Stepanov Index.setWithGlobalValueDeadStripping(); 67056584bbfSEvgeniy Stepanov 67156584bbfSEvgeniy Stepanov unsigned DeadSymbols = Index.size() - LiveSymbols; 672*d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols 67356584bbfSEvgeniy Stepanov << " symbols Dead \n"); 67456584bbfSEvgeniy Stepanov NumDeadSymbols += DeadSymbols; 67556584bbfSEvgeniy Stepanov NumLiveSymbols += LiveSymbols; 6766c475a75STeresa Johnson } 6776c475a75STeresa Johnson 67884174c37STeresa Johnson /// Compute the set of summaries needed for a ThinLTO backend compilation of 67984174c37STeresa Johnson /// \p ModulePath. 68084174c37STeresa Johnson void llvm::gatherImportedSummariesForModule( 68184174c37STeresa Johnson StringRef ModulePath, 68284174c37STeresa Johnson const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries, 683cdbcbf74SMehdi Amini const FunctionImporter::ImportMapTy &ImportList, 68484174c37STeresa Johnson std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) { 68584174c37STeresa Johnson // Include all summaries from the importing module. 68684174c37STeresa Johnson ModuleToSummariesForIndex[ModulePath] = 68784174c37STeresa Johnson ModuleToDefinedGVSummaries.lookup(ModulePath); 68884174c37STeresa Johnson // Include summaries for imports. 68988c491ddSMehdi Amini for (auto &ILI : ImportList) { 69084174c37STeresa Johnson auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()]; 69184174c37STeresa Johnson const auto &DefinedGVSummaries = 69284174c37STeresa Johnson ModuleToDefinedGVSummaries.lookup(ILI.first()); 69384174c37STeresa Johnson for (auto &GI : ILI.second) { 69484174c37STeresa Johnson const auto &DS = DefinedGVSummaries.find(GI.first); 69584174c37STeresa Johnson assert(DS != DefinedGVSummaries.end() && 69684174c37STeresa Johnson "Expected a defined summary for imported global value"); 69784174c37STeresa Johnson SummariesForIndex[GI.first] = DS->second; 69884174c37STeresa Johnson } 69984174c37STeresa Johnson } 70084174c37STeresa Johnson } 70184174c37STeresa Johnson 7028570fe47STeresa Johnson /// Emit the files \p ModulePath will import from into \p OutputFilename. 703cdbcbf74SMehdi Amini std::error_code 704cdbcbf74SMehdi Amini llvm::EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename, 705cdbcbf74SMehdi Amini const FunctionImporter::ImportMapTy &ModuleImports) { 7068570fe47STeresa Johnson std::error_code EC; 7078570fe47STeresa Johnson raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None); 7088570fe47STeresa Johnson if (EC) 7098570fe47STeresa Johnson return EC; 710cdbcbf74SMehdi Amini for (auto &ILI : ModuleImports) 7118570fe47STeresa Johnson ImportsOS << ILI.first() << "\n"; 7128570fe47STeresa Johnson return std::error_code(); 7138570fe47STeresa Johnson } 7148570fe47STeresa Johnson 7155a95c477STeresa Johnson bool llvm::convertToDeclaration(GlobalValue &GV) { 716*d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName() 717*d34e60caSNicola Zaghen << "\n"); 7184566c6dbSTeresa Johnson if (Function *F = dyn_cast<Function>(&GV)) { 7194566c6dbSTeresa Johnson F->deleteBody(); 7204566c6dbSTeresa Johnson F->clearMetadata(); 7217873669bSPeter Collingbourne F->setComdat(nullptr); 7224566c6dbSTeresa Johnson } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) { 7234566c6dbSTeresa Johnson V->setInitializer(nullptr); 7244566c6dbSTeresa Johnson V->setLinkage(GlobalValue::ExternalLinkage); 7254566c6dbSTeresa Johnson V->clearMetadata(); 7267873669bSPeter Collingbourne V->setComdat(nullptr); 7275a95c477STeresa Johnson } else { 7285a95c477STeresa Johnson GlobalValue *NewGV; 7295a95c477STeresa Johnson if (GV.getValueType()->isFunctionTy()) 7305a95c477STeresa Johnson NewGV = 7315a95c477STeresa Johnson Function::Create(cast<FunctionType>(GV.getValueType()), 7325a95c477STeresa Johnson GlobalValue::ExternalLinkage, "", GV.getParent()); 7335a95c477STeresa Johnson else 7345a95c477STeresa Johnson NewGV = 7355a95c477STeresa Johnson new GlobalVariable(*GV.getParent(), GV.getValueType(), 7365a95c477STeresa Johnson /*isConstant*/ false, GlobalValue::ExternalLinkage, 7375a95c477STeresa Johnson /*init*/ nullptr, "", 7385a95c477STeresa Johnson /*insertbefore*/ nullptr, GV.getThreadLocalMode(), 7395a95c477STeresa Johnson GV.getType()->getAddressSpace()); 7405a95c477STeresa Johnson NewGV->takeName(&GV); 7415a95c477STeresa Johnson GV.replaceAllUsesWith(NewGV); 7425a95c477STeresa Johnson return false; 7435a95c477STeresa Johnson } 7445a95c477STeresa Johnson return true; 745eaf5172cSGeorge Rimar } 7464566c6dbSTeresa Johnson 747eaf5172cSGeorge Rimar /// Fixup WeakForLinker linkages in \p TheModule based on summary analysis. 748eaf5172cSGeorge Rimar void llvm::thinLTOResolveWeakForLinkerModule( 749eaf5172cSGeorge Rimar Module &TheModule, const GVSummaryMapTy &DefinedGlobals) { 75004c9a2d6STeresa Johnson auto updateLinkage = [&](GlobalValue &GV) { 75104c9a2d6STeresa Johnson // See if the global summary analysis computed a new resolved linkage. 75204c9a2d6STeresa Johnson const auto &GS = DefinedGlobals.find(GV.getGUID()); 75304c9a2d6STeresa Johnson if (GS == DefinedGlobals.end()) 75404c9a2d6STeresa Johnson return; 75504c9a2d6STeresa Johnson auto NewLinkage = GS->second->linkage(); 75604c9a2d6STeresa Johnson if (NewLinkage == GV.getLinkage()) 75704c9a2d6STeresa Johnson return; 7586a5fbe52SDavide Italiano 7596a5fbe52SDavide Italiano // Switch the linkage to weakany if asked for, e.g. we do this for 7606a5fbe52SDavide Italiano // linker redefined symbols (via --wrap or --defsym). 761f4891d29SDavide Italiano // We record that the visibility should be changed here in `addThinLTO` 762f4891d29SDavide Italiano // as we need access to the resolution vectors for each input file in 763f4891d29SDavide Italiano // order to find which symbols have been redefined. 764f4891d29SDavide Italiano // We may consider reorganizing this code and moving the linkage recording 765f4891d29SDavide Italiano // somewhere else, e.g. in thinLTOResolveWeakForLinkerInIndex. 7666a5fbe52SDavide Italiano if (NewLinkage == GlobalValue::WeakAnyLinkage) { 7676a5fbe52SDavide Italiano GV.setLinkage(NewLinkage); 7686a5fbe52SDavide Italiano return; 7696a5fbe52SDavide Italiano } 7706a5fbe52SDavide Italiano 7716a5fbe52SDavide Italiano if (!GlobalValue::isWeakForLinker(GV.getLinkage())) 7726a5fbe52SDavide Italiano return; 7734566c6dbSTeresa Johnson // Check for a non-prevailing def that has interposable linkage 7744566c6dbSTeresa Johnson // (e.g. non-odr weak or linkonce). In that case we can't simply 7754566c6dbSTeresa Johnson // convert to available_externally, since it would lose the 7764566c6dbSTeresa Johnson // interposable property and possibly get inlined. Simply drop 7774566c6dbSTeresa Johnson // the definition in that case. 7784566c6dbSTeresa Johnson if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) && 7795a95c477STeresa Johnson GlobalValue::isInterposableLinkage(GV.getLinkage())) { 7805a95c477STeresa Johnson if (!convertToDeclaration(GV)) 7815a95c477STeresa Johnson // FIXME: Change this to collect replaced GVs and later erase 7825a95c477STeresa Johnson // them from the parent module once thinLTOResolveWeakForLinkerGUID is 7835a95c477STeresa Johnson // changed to enable this for aliases. 7845a95c477STeresa Johnson llvm_unreachable("Expected GV to be converted"); 7855a95c477STeresa Johnson } else { 78633ba93c2SSteven Wu // If the original symbols has global unnamed addr and linkonce_odr linkage, 78733ba93c2SSteven Wu // it should be an auto hide symbol. Add hidden visibility to the symbol to 78833ba93c2SSteven Wu // preserve the property. 78933ba93c2SSteven Wu if (GV.hasLinkOnceODRLinkage() && GV.hasGlobalUnnamedAddr() && 79033ba93c2SSteven Wu NewLinkage == GlobalValue::WeakODRLinkage) 79133ba93c2SSteven Wu GV.setVisibility(GlobalValue::HiddenVisibility); 79233ba93c2SSteven Wu 793*d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() 794*d34e60caSNicola Zaghen << "` from " << GV.getLinkage() << " to " << NewLinkage 795*d34e60caSNicola Zaghen << "\n"); 79604c9a2d6STeresa Johnson GV.setLinkage(NewLinkage); 7974566c6dbSTeresa Johnson } 7984566c6dbSTeresa Johnson // Remove declarations from comdats, including available_externally 7996107a419STeresa Johnson // as this is a declaration for the linker, and will be dropped eventually. 8006107a419STeresa Johnson // It is illegal for comdats to contain declarations. 8016107a419STeresa Johnson auto *GO = dyn_cast_or_null<GlobalObject>(&GV); 8024566c6dbSTeresa Johnson if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) 8036107a419STeresa Johnson GO->setComdat(nullptr); 80404c9a2d6STeresa Johnson }; 80504c9a2d6STeresa Johnson 80604c9a2d6STeresa Johnson // Process functions and global now 80704c9a2d6STeresa Johnson for (auto &GV : TheModule) 80804c9a2d6STeresa Johnson updateLinkage(GV); 80904c9a2d6STeresa Johnson for (auto &GV : TheModule.globals()) 81004c9a2d6STeresa Johnson updateLinkage(GV); 81104c9a2d6STeresa Johnson for (auto &GV : TheModule.aliases()) 81204c9a2d6STeresa Johnson updateLinkage(GV); 81304c9a2d6STeresa Johnson } 81404c9a2d6STeresa Johnson 81504c9a2d6STeresa Johnson /// Run internalization on \p TheModule based on symmary analysis. 81604c9a2d6STeresa Johnson void llvm::thinLTOInternalizeModule(Module &TheModule, 81704c9a2d6STeresa Johnson const GVSummaryMapTy &DefinedGlobals) { 81804c9a2d6STeresa Johnson // Declare a callback for the internalize pass that will ask for every 81904c9a2d6STeresa Johnson // candidate GlobalValue if it can be internalized or not. 82004c9a2d6STeresa Johnson auto MustPreserveGV = [&](const GlobalValue &GV) -> bool { 82104c9a2d6STeresa Johnson // Lookup the linkage recorded in the summaries during global analysis. 822c3d677f9SPeter Collingbourne auto GS = DefinedGlobals.find(GV.getGUID()); 82304c9a2d6STeresa Johnson if (GS == DefinedGlobals.end()) { 82404c9a2d6STeresa Johnson // Must have been promoted (possibly conservatively). Find original 82504c9a2d6STeresa Johnson // name so that we can access the correct summary and see if it can 82604c9a2d6STeresa Johnson // be internalized again. 82704c9a2d6STeresa Johnson // FIXME: Eventually we should control promotion instead of promoting 82804c9a2d6STeresa Johnson // and internalizing again. 82904c9a2d6STeresa Johnson StringRef OrigName = 83004c9a2d6STeresa Johnson ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName()); 83104c9a2d6STeresa Johnson std::string OrigId = GlobalValue::getGlobalIdentifier( 83204c9a2d6STeresa Johnson OrigName, GlobalValue::InternalLinkage, 83304c9a2d6STeresa Johnson TheModule.getSourceFileName()); 834c3d677f9SPeter Collingbourne GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId)); 8357ab1f692STeresa Johnson if (GS == DefinedGlobals.end()) { 8367ab1f692STeresa Johnson // Also check the original non-promoted non-globalized name. In some 8377ab1f692STeresa Johnson // cases a preempted weak value is linked in as a local copy because 8387ab1f692STeresa Johnson // it is referenced by an alias (IRLinker::linkGlobalValueProto). 8397ab1f692STeresa Johnson // In that case, since it was originally not a local value, it was 8407ab1f692STeresa Johnson // recorded in the index using the original name. 8417ab1f692STeresa Johnson // FIXME: This may not be needed once PR27866 is fixed. 842c3d677f9SPeter Collingbourne GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName)); 84304c9a2d6STeresa Johnson assert(GS != DefinedGlobals.end()); 8447ab1f692STeresa Johnson } 845c3d677f9SPeter Collingbourne } 846c3d677f9SPeter Collingbourne return !GlobalValue::isLocalLinkage(GS->second->linkage()); 84704c9a2d6STeresa Johnson }; 84804c9a2d6STeresa Johnson 84904c9a2d6STeresa Johnson // FIXME: See if we can just internalize directly here via linkage changes 85004c9a2d6STeresa Johnson // based on the index, rather than invoking internalizeModule. 851e9ea08a0SEugene Zelenko internalizeModule(TheModule, MustPreserveGV); 85204c9a2d6STeresa Johnson } 85304c9a2d6STeresa Johnson 85481bbf742STeresa Johnson /// Make alias a clone of its aliasee. 85581bbf742STeresa Johnson static Function *replaceAliasWithAliasee(Module *SrcModule, GlobalAlias *GA) { 85681bbf742STeresa Johnson Function *Fn = cast<Function>(GA->getBaseObject()); 85781bbf742STeresa Johnson 85881bbf742STeresa Johnson ValueToValueMapTy VMap; 85981bbf742STeresa Johnson Function *NewFn = CloneFunction(Fn, VMap); 86081bbf742STeresa Johnson // Clone should use the original alias's linkage and name, and we ensure 86181bbf742STeresa Johnson // all uses of alias instead use the new clone (casted if necessary). 86281bbf742STeresa Johnson NewFn->setLinkage(GA->getLinkage()); 86381bbf742STeresa Johnson GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewFn, GA->getType())); 86481bbf742STeresa Johnson NewFn->takeName(GA); 86581bbf742STeresa Johnson return NewFn; 86681bbf742STeresa Johnson } 86781bbf742STeresa Johnson 868c8c55170SMehdi Amini // Automatically import functions in Module \p DestModule based on the summaries 869c8c55170SMehdi Amini // index. 8707f00d0a1SPeter Collingbourne Expected<bool> FunctionImporter::importFunctions( 87166043797SAdrian Prantl Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) { 872*d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Starting import for Module " 873311fef6eSMehdi Amini << DestModule.getModuleIdentifier() << "\n"); 87419e23874SEugene Leviant unsigned ImportedCount = 0, ImportedGVCount = 0; 875c8c55170SMehdi Amini 8766d8f817fSPeter Collingbourne IRMover Mover(DestModule); 8777e88d0daSMehdi Amini // Do the actual import of functions now, one Module at a time 87801e32130SMehdi Amini std::set<StringRef> ModuleNameOrderedList; 87901e32130SMehdi Amini for (auto &FunctionsToImportPerModule : ImportList) { 88001e32130SMehdi Amini ModuleNameOrderedList.insert(FunctionsToImportPerModule.first()); 88101e32130SMehdi Amini } 88201e32130SMehdi Amini for (auto &Name : ModuleNameOrderedList) { 8837e88d0daSMehdi Amini // Get the module for the import 88401e32130SMehdi Amini const auto &FunctionsToImportPerModule = ImportList.find(Name); 88501e32130SMehdi Amini assert(FunctionsToImportPerModule != ImportList.end()); 886d9445c49SPeter Collingbourne Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name); 887d9445c49SPeter Collingbourne if (!SrcModuleOrErr) 888d9445c49SPeter Collingbourne return SrcModuleOrErr.takeError(); 889d9445c49SPeter Collingbourne std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr); 8907e88d0daSMehdi Amini assert(&DestModule.getContext() == &SrcModule->getContext() && 8917e88d0daSMehdi Amini "Context mismatch"); 8927e88d0daSMehdi Amini 8936cba37ceSTeresa Johnson // If modules were created with lazy metadata loading, materialize it 8946cba37ceSTeresa Johnson // now, before linking it (otherwise this will be a noop). 8957f00d0a1SPeter Collingbourne if (Error Err = SrcModule->materializeMetadata()) 8967f00d0a1SPeter Collingbourne return std::move(Err); 897e5a61917STeresa Johnson 89801e32130SMehdi Amini auto &ImportGUIDs = FunctionsToImportPerModule->second; 89901e32130SMehdi Amini // Find the globals to import 9006d8f817fSPeter Collingbourne SetVector<GlobalValue *> GlobalsToImport; 9011f685e01SPiotr Padlewski for (Function &F : *SrcModule) { 9021f685e01SPiotr Padlewski if (!F.hasName()) 9030beb858eSTeresa Johnson continue; 9041f685e01SPiotr Padlewski auto GUID = F.getGUID(); 9050beb858eSTeresa Johnson auto Import = ImportGUIDs.count(GUID); 906*d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " 907*d34e60caSNicola Zaghen << GUID << " " << F.getName() << " from " 908aeb1e59bSMehdi Amini << SrcModule->getSourceFileName() << "\n"); 9090beb858eSTeresa Johnson if (Import) { 9107f00d0a1SPeter Collingbourne if (Error Err = F.materialize()) 9117f00d0a1SPeter Collingbourne return std::move(Err); 9123b776128SPiotr Padlewski if (EnableImportMetadata) { 9136deaa6afSPiotr Padlewski // Add 'thinlto_src_module' metadata for statistics and debugging. 9143b776128SPiotr Padlewski F.setMetadata( 9153b776128SPiotr Padlewski "thinlto_src_module", 916e9ea08a0SEugene Zelenko MDNode::get(DestModule.getContext(), 917e9ea08a0SEugene Zelenko {MDString::get(DestModule.getContext(), 9186deaa6afSPiotr Padlewski SrcModule->getSourceFileName())})); 9193b776128SPiotr Padlewski } 9201f685e01SPiotr Padlewski GlobalsToImport.insert(&F); 92101e32130SMehdi Amini } 92201e32130SMehdi Amini } 9231f685e01SPiotr Padlewski for (GlobalVariable &GV : SrcModule->globals()) { 9242d28f7aaSMehdi Amini if (!GV.hasName()) 9252d28f7aaSMehdi Amini continue; 9262d28f7aaSMehdi Amini auto GUID = GV.getGUID(); 9272d28f7aaSMehdi Amini auto Import = ImportGUIDs.count(GUID); 928*d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " 929*d34e60caSNicola Zaghen << GUID << " " << GV.getName() << " from " 930aeb1e59bSMehdi Amini << SrcModule->getSourceFileName() << "\n"); 9312d28f7aaSMehdi Amini if (Import) { 9327f00d0a1SPeter Collingbourne if (Error Err = GV.materialize()) 9337f00d0a1SPeter Collingbourne return std::move(Err); 93419e23874SEugene Leviant ImportedGVCount += GlobalsToImport.insert(&GV); 9352d28f7aaSMehdi Amini } 9362d28f7aaSMehdi Amini } 9371f685e01SPiotr Padlewski for (GlobalAlias &GA : SrcModule->aliases()) { 9381f685e01SPiotr Padlewski if (!GA.hasName()) 93901e32130SMehdi Amini continue; 9401f685e01SPiotr Padlewski auto GUID = GA.getGUID(); 94181bbf742STeresa Johnson auto Import = ImportGUIDs.count(GUID); 942*d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias " 943*d34e60caSNicola Zaghen << GUID << " " << GA.getName() << " from " 944aeb1e59bSMehdi Amini << SrcModule->getSourceFileName() << "\n"); 94581bbf742STeresa Johnson if (Import) { 94681bbf742STeresa Johnson if (Error Err = GA.materialize()) 94781bbf742STeresa Johnson return std::move(Err); 94881bbf742STeresa Johnson // Import alias as a copy of its aliasee. 94981bbf742STeresa Johnson GlobalObject *Base = GA.getBaseObject(); 95081bbf742STeresa Johnson if (Error Err = Base->materialize()) 95181bbf742STeresa Johnson return std::move(Err); 95281bbf742STeresa Johnson auto *Fn = replaceAliasWithAliasee(SrcModule.get(), &GA); 953*d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Is importing aliasee fn " << Base->getGUID() 95481bbf742STeresa Johnson << " " << Base->getName() << " from " 95581bbf742STeresa Johnson << SrcModule->getSourceFileName() << "\n"); 95681bbf742STeresa Johnson if (EnableImportMetadata) { 95781bbf742STeresa Johnson // Add 'thinlto_src_module' metadata for statistics and debugging. 95881bbf742STeresa Johnson Fn->setMetadata( 95981bbf742STeresa Johnson "thinlto_src_module", 96081bbf742STeresa Johnson MDNode::get(DestModule.getContext(), 96181bbf742STeresa Johnson {MDString::get(DestModule.getContext(), 96281bbf742STeresa Johnson SrcModule->getSourceFileName())})); 96301e32130SMehdi Amini } 96481bbf742STeresa Johnson GlobalsToImport.insert(Fn); 96581bbf742STeresa Johnson } 96681bbf742STeresa Johnson } 96701e32130SMehdi Amini 96819ef4fadSMehdi Amini // Upgrade debug info after we're done materializing all the globals and we 96919ef4fadSMehdi Amini // have loaded all the required metadata! 97019ef4fadSMehdi Amini UpgradeDebugInfo(*SrcModule); 97119ef4fadSMehdi Amini 9727e88d0daSMehdi Amini // Link in the specified functions. 97301e32130SMehdi Amini if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport)) 9748d05185aSMehdi Amini return true; 9758d05185aSMehdi Amini 976d29478f7STeresa Johnson if (PrintImports) { 977d29478f7STeresa Johnson for (const auto *GV : GlobalsToImport) 978d29478f7STeresa Johnson dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName() 979d29478f7STeresa Johnson << " from " << SrcModule->getSourceFileName() << "\n"; 980d29478f7STeresa Johnson } 981d29478f7STeresa Johnson 9826d8f817fSPeter Collingbourne if (Mover.move(std::move(SrcModule), GlobalsToImport.getArrayRef(), 9836d8f817fSPeter Collingbourne [](GlobalValue &, IRMover::ValueAdder) {}, 984e6fd9ff9SPeter Collingbourne /*IsPerformingImport=*/true)) 9857e88d0daSMehdi Amini report_fatal_error("Function Import: link error"); 9867e88d0daSMehdi Amini 98701e32130SMehdi Amini ImportedCount += GlobalsToImport.size(); 9886c475a75STeresa Johnson NumImportedModules++; 9897e88d0daSMehdi Amini } 990e5a61917STeresa Johnson 99119e23874SEugene Leviant NumImportedFunctions += (ImportedCount - ImportedGVCount); 99219e23874SEugene Leviant NumImportedGlobalVars += ImportedGVCount; 993d29478f7STeresa Johnson 994*d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Imported " << ImportedCount - ImportedGVCount 995*d34e60caSNicola Zaghen << " functions for Module " 996*d34e60caSNicola Zaghen << DestModule.getModuleIdentifier() << "\n"); 997*d34e60caSNicola Zaghen LLVM_DEBUG(dbgs() << "Imported " << ImportedGVCount 99819e23874SEugene Leviant << " global variables for Module " 999c8c55170SMehdi Amini << DestModule.getModuleIdentifier() << "\n"); 1000c8c55170SMehdi Amini return ImportedCount; 100142418abaSMehdi Amini } 100242418abaSMehdi Amini 1003598bd2a2SPeter Collingbourne static bool doImportingForModule(Module &M) { 1004598bd2a2SPeter Collingbourne if (SummaryFile.empty()) 1005598bd2a2SPeter Collingbourne report_fatal_error("error: -function-import requires -summary-file\n"); 10066de481a3SPeter Collingbourne Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr = 10076de481a3SPeter Collingbourne getModuleSummaryIndexForFile(SummaryFile); 10086de481a3SPeter Collingbourne if (!IndexPtrOrErr) { 10096de481a3SPeter Collingbourne logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(), 10106de481a3SPeter Collingbourne "Error loading file '" + SummaryFile + "': "); 101142418abaSMehdi Amini return false; 101242418abaSMehdi Amini } 1013598bd2a2SPeter Collingbourne std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr); 101442418abaSMehdi Amini 1015c86af334STeresa Johnson // First step is collecting the import list. 1016c86af334STeresa Johnson FunctionImporter::ImportMapTy ImportList; 101781bbf742STeresa Johnson // If requested, simply import all functions in the index. This is used 101881bbf742STeresa Johnson // when testing distributed backend handling via the opt tool, when 101981bbf742STeresa Johnson // we have distributed indexes containing exactly the summaries to import. 102081bbf742STeresa Johnson if (ImportAllIndex) 102181bbf742STeresa Johnson ComputeCrossModuleImportForModuleFromIndex(M.getModuleIdentifier(), *Index, 102281bbf742STeresa Johnson ImportList); 102381bbf742STeresa Johnson else 1024c86af334STeresa Johnson ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index, 1025c86af334STeresa Johnson ImportList); 102601e32130SMehdi Amini 10274fef68cbSTeresa Johnson // Conservatively mark all internal values as promoted. This interface is 10284fef68cbSTeresa Johnson // only used when doing importing via the function importing pass. The pass 10294fef68cbSTeresa Johnson // is only enabled when testing importing via the 'opt' tool, which does 10304fef68cbSTeresa Johnson // not do the ThinLink that would normally determine what values to promote. 10314fef68cbSTeresa Johnson for (auto &I : *Index) { 10329667b91bSPeter Collingbourne for (auto &S : I.second.SummaryList) { 10334fef68cbSTeresa Johnson if (GlobalValue::isLocalLinkage(S->linkage())) 10344fef68cbSTeresa Johnson S->setLinkage(GlobalValue::ExternalLinkage); 10354fef68cbSTeresa Johnson } 10364fef68cbSTeresa Johnson } 10374fef68cbSTeresa Johnson 103801e32130SMehdi Amini // Next we need to promote to global scope and rename any local values that 10391b00f2d9STeresa Johnson // are potentially exported to other modules. 104001e32130SMehdi Amini if (renameModuleForThinLTO(M, *Index, nullptr)) { 10411b00f2d9STeresa Johnson errs() << "Error renaming module\n"; 10421b00f2d9STeresa Johnson return false; 10431b00f2d9STeresa Johnson } 10441b00f2d9STeresa Johnson 104542418abaSMehdi Amini // Perform the import now. 1046d16c8065SMehdi Amini auto ModuleLoader = [&M](StringRef Identifier) { 1047d16c8065SMehdi Amini return loadFile(Identifier, M.getContext()); 1048d16c8065SMehdi Amini }; 10499d2bfc48SRafael Espindola FunctionImporter Importer(*Index, ModuleLoader); 105037e24591SPeter Collingbourne Expected<bool> Result = Importer.importFunctions(M, ImportList); 10517f00d0a1SPeter Collingbourne 10527f00d0a1SPeter Collingbourne // FIXME: Probably need to propagate Errors through the pass manager. 10537f00d0a1SPeter Collingbourne if (!Result) { 10547f00d0a1SPeter Collingbourne logAllUnhandledErrors(Result.takeError(), errs(), 10557f00d0a1SPeter Collingbourne "Error importing module: "); 10567f00d0a1SPeter Collingbourne return false; 10577f00d0a1SPeter Collingbourne } 10587f00d0a1SPeter Collingbourne 10597f00d0a1SPeter Collingbourne return *Result; 106021241571STeresa Johnson } 106121241571STeresa Johnson 106221241571STeresa Johnson namespace { 1063e9ea08a0SEugene Zelenko 106421241571STeresa Johnson /// Pass that performs cross-module function import provided a summary file. 106521241571STeresa Johnson class FunctionImportLegacyPass : public ModulePass { 106621241571STeresa Johnson public: 106721241571STeresa Johnson /// Pass identification, replacement for typeid 106821241571STeresa Johnson static char ID; 106921241571STeresa Johnson 1070e9ea08a0SEugene Zelenko explicit FunctionImportLegacyPass() : ModulePass(ID) {} 1071e9ea08a0SEugene Zelenko 107221241571STeresa Johnson /// Specify pass name for debug output 1073117296c0SMehdi Amini StringRef getPassName() const override { return "Function Importing"; } 107421241571STeresa Johnson 107521241571STeresa Johnson bool runOnModule(Module &M) override { 107621241571STeresa Johnson if (skipModule(M)) 107721241571STeresa Johnson return false; 107821241571STeresa Johnson 1079598bd2a2SPeter Collingbourne return doImportingForModule(M); 108042418abaSMehdi Amini } 108142418abaSMehdi Amini }; 1082e9ea08a0SEugene Zelenko 1083e9ea08a0SEugene Zelenko } // end anonymous namespace 108442418abaSMehdi Amini 108521241571STeresa Johnson PreservedAnalyses FunctionImportPass::run(Module &M, 1086fd03ac6aSSean Silva ModuleAnalysisManager &AM) { 1087598bd2a2SPeter Collingbourne if (!doImportingForModule(M)) 108821241571STeresa Johnson return PreservedAnalyses::all(); 108921241571STeresa Johnson 109021241571STeresa Johnson return PreservedAnalyses::none(); 109121241571STeresa Johnson } 109221241571STeresa Johnson 109321241571STeresa Johnson char FunctionImportLegacyPass::ID = 0; 109421241571STeresa Johnson INITIALIZE_PASS(FunctionImportLegacyPass, "function-import", 109542418abaSMehdi Amini "Summary Based Function Import", false, false) 109642418abaSMehdi Amini 109742418abaSMehdi Amini namespace llvm { 1098e9ea08a0SEugene Zelenko 1099598bd2a2SPeter Collingbourne Pass *createFunctionImportPass() { 1100598bd2a2SPeter Collingbourne return new FunctionImportLegacyPass(); 11015fcbdb71STeresa Johnson } 1102e9ea08a0SEugene Zelenko 1103e9ea08a0SEugene Zelenko } // end namespace llvm 1104