1 //===- FunctionImport.cpp - ThinLTO Summary-based Function Import ---------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements Function import based on summaries. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Transforms/IPO/FunctionImport.h" 15 16 #include "llvm/ADT/SmallVector.h" 17 #include "llvm/ADT/Statistic.h" 18 #include "llvm/ADT/StringSet.h" 19 #include "llvm/ADT/Triple.h" 20 #include "llvm/IR/AutoUpgrade.h" 21 #include "llvm/IR/DiagnosticPrinter.h" 22 #include "llvm/IR/IntrinsicInst.h" 23 #include "llvm/IR/Module.h" 24 #include "llvm/IR/Verifier.h" 25 #include "llvm/IRReader/IRReader.h" 26 #include "llvm/Linker/Linker.h" 27 #include "llvm/Object/IRObjectFile.h" 28 #include "llvm/Object/ModuleSummaryIndexObjectFile.h" 29 #include "llvm/Support/CommandLine.h" 30 #include "llvm/Support/Debug.h" 31 #include "llvm/Support/SourceMgr.h" 32 #include "llvm/Transforms/IPO/Internalize.h" 33 #include "llvm/Transforms/Utils/FunctionImportUtils.h" 34 35 #define DEBUG_TYPE "function-import" 36 37 using namespace llvm; 38 39 STATISTIC(NumImported, "Number of functions imported"); 40 41 /// Limit on instruction count of imported functions. 42 static cl::opt<unsigned> ImportInstrLimit( 43 "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"), 44 cl::desc("Only import functions with less than N instructions")); 45 46 static cl::opt<float> 47 ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7), 48 cl::Hidden, cl::value_desc("x"), 49 cl::desc("As we import functions, multiply the " 50 "`import-instr-limit` threshold by this factor " 51 "before processing newly imported functions")); 52 53 static cl::opt<float> ImportHotInstrFactor( 54 "import-hot-evolution-factor", cl::init(1.0), cl::Hidden, 55 cl::value_desc("x"), 56 cl::desc("As we import functions called from hot callsite, multiply the " 57 "`import-instr-limit` threshold by this factor " 58 "before processing newly imported functions")); 59 60 static cl::opt<float> ImportHotMultiplier( 61 "import-hot-multiplier", cl::init(3.0), cl::Hidden, cl::value_desc("x"), 62 cl::desc("Multiply the `import-instr-limit` threshold for hot callsites")); 63 64 // FIXME: This multiplier was not really tuned up. 65 static cl::opt<float> ImportColdMultiplier( 66 "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"), 67 cl::desc("Multiply the `import-instr-limit` threshold for cold callsites")); 68 69 static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden, 70 cl::desc("Print imported functions")); 71 72 // Temporary allows the function import pass to disable always linking 73 // referenced discardable symbols. 74 static cl::opt<bool> 75 DontForceImportReferencedDiscardableSymbols("disable-force-link-odr", 76 cl::init(false), cl::Hidden); 77 78 static cl::opt<bool> EnableImportMetadata( 79 "enable-import-metadata", cl::init( 80 #if !defined(NDEBUG) 81 true /*Enabled with asserts.*/ 82 #else 83 false 84 #endif 85 ), 86 cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'")); 87 88 // Load lazily a module from \p FileName in \p Context. 89 static std::unique_ptr<Module> loadFile(const std::string &FileName, 90 LLVMContext &Context) { 91 SMDiagnostic Err; 92 DEBUG(dbgs() << "Loading '" << FileName << "'\n"); 93 // Metadata isn't loaded until functions are imported, to minimize 94 // the memory overhead. 95 std::unique_ptr<Module> Result = 96 getLazyIRFileModule(FileName, Err, Context, 97 /* ShouldLazyLoadMetadata = */ true); 98 if (!Result) { 99 Err.print("function-import", errs()); 100 report_fatal_error("Abort"); 101 } 102 103 return Result; 104 } 105 106 namespace { 107 108 // Return true if the Summary describes a GlobalValue that can be externally 109 // referenced, i.e. it does not need renaming (linkage is not local) or renaming 110 // is possible (does not have a section for instance). 111 static bool canBeExternallyReferenced(const GlobalValueSummary &Summary) { 112 if (!Summary.needsRenaming()) 113 return true; 114 115 if (Summary.noRename()) 116 // Can't externally reference a global that needs renaming if has a section 117 // or is referenced from inline assembly, for example. 118 return false; 119 120 return true; 121 } 122 123 // Return true if \p GUID describes a GlobalValue that can be externally 124 // referenced, i.e. it does not need renaming (linkage is not local) or 125 // renaming is possible (does not have a section for instance). 126 static bool canBeExternallyReferenced(const ModuleSummaryIndex &Index, 127 GlobalValue::GUID GUID) { 128 auto Summaries = Index.findGlobalValueSummaryList(GUID); 129 if (Summaries == Index.end()) 130 return true; 131 if (Summaries->second.size() != 1) 132 // If there are multiple globals with this GUID, then we know it is 133 // not a local symbol, and it is necessarily externally referenced. 134 return true; 135 136 // We don't need to check for the module path, because if it can't be 137 // externally referenced and we call it, it is necessarilly in the same 138 // module 139 return canBeExternallyReferenced(**Summaries->second.begin()); 140 } 141 142 // Return true if the global described by \p Summary can be imported in another 143 // module. 144 static bool eligibleForImport(const ModuleSummaryIndex &Index, 145 const GlobalValueSummary &Summary) { 146 if (!canBeExternallyReferenced(Summary)) 147 // Can't import a global that needs renaming if has a section for instance. 148 // FIXME: we may be able to import it by copying it without promotion. 149 return false; 150 151 // Don't import functions that are not viable to inline. 152 if (Summary.isNotViableToInline()) 153 return false; 154 155 // Check references (and potential calls) in the same module. If the current 156 // value references a global that can't be externally referenced it is not 157 // eligible for import. First check the flag set when we have possible 158 // opaque references (e.g. inline asm calls), then check the call and 159 // reference sets. 160 if (Summary.hasInlineAsmMaybeReferencingInternal()) 161 return false; 162 bool AllRefsCanBeExternallyReferenced = 163 llvm::all_of(Summary.refs(), [&](const ValueInfo &VI) { 164 return canBeExternallyReferenced(Index, VI.getGUID()); 165 }); 166 if (!AllRefsCanBeExternallyReferenced) 167 return false; 168 169 if (auto *FuncSummary = dyn_cast<FunctionSummary>(&Summary)) { 170 bool AllCallsCanBeExternallyReferenced = llvm::all_of( 171 FuncSummary->calls(), [&](const FunctionSummary::EdgeTy &Edge) { 172 return canBeExternallyReferenced(Index, Edge.first.getGUID()); 173 }); 174 if (!AllCallsCanBeExternallyReferenced) 175 return false; 176 } 177 return true; 178 } 179 180 /// Given a list of possible callee implementation for a call site, select one 181 /// that fits the \p Threshold. 182 /// 183 /// FIXME: select "best" instead of first that fits. But what is "best"? 184 /// - The smallest: more likely to be inlined. 185 /// - The one with the least outgoing edges (already well optimized). 186 /// - One from a module already being imported from in order to reduce the 187 /// number of source modules parsed/linked. 188 /// - One that has PGO data attached. 189 /// - [insert you fancy metric here] 190 static const GlobalValueSummary * 191 selectCallee(const ModuleSummaryIndex &Index, 192 const GlobalValueSummaryList &CalleeSummaryList, 193 unsigned Threshold) { 194 auto It = llvm::find_if( 195 CalleeSummaryList, 196 [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) { 197 auto *GVSummary = SummaryPtr.get(); 198 if (GlobalValue::isInterposableLinkage(GVSummary->linkage())) 199 // There is no point in importing these, we can't inline them 200 return false; 201 if (auto *AS = dyn_cast<AliasSummary>(GVSummary)) { 202 GVSummary = &AS->getAliasee(); 203 // Alias can't point to "available_externally". However when we import 204 // linkOnceODR the linkage does not change. So we import the alias 205 // and aliasee only in this case. 206 // FIXME: we should import alias as available_externally *function*, 207 // the destination module does need to know it is an alias. 208 if (!GlobalValue::isLinkOnceODRLinkage(GVSummary->linkage())) 209 return false; 210 } 211 212 auto *Summary = cast<FunctionSummary>(GVSummary); 213 214 if (Summary->instCount() > Threshold) 215 return false; 216 217 if (!eligibleForImport(Index, *Summary)) 218 return false; 219 220 return true; 221 }); 222 if (It == CalleeSummaryList.end()) 223 return nullptr; 224 225 return cast<GlobalValueSummary>(It->get()); 226 } 227 228 /// Return the summary for the function \p GUID that fits the \p Threshold, or 229 /// null if there's no match. 230 static const GlobalValueSummary *selectCallee(GlobalValue::GUID GUID, 231 unsigned Threshold, 232 const ModuleSummaryIndex &Index) { 233 auto CalleeSummaryList = Index.findGlobalValueSummaryList(GUID); 234 if (CalleeSummaryList == Index.end()) 235 return nullptr; // This function does not have a summary 236 return selectCallee(Index, CalleeSummaryList->second, Threshold); 237 } 238 239 using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */, 240 GlobalValue::GUID>; 241 242 /// Compute the list of functions to import for a given caller. Mark these 243 /// imported functions and the symbols they reference in their source module as 244 /// exported from their source module. 245 static void computeImportForFunction( 246 const FunctionSummary &Summary, const ModuleSummaryIndex &Index, 247 const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries, 248 SmallVectorImpl<EdgeInfo> &Worklist, 249 FunctionImporter::ImportMapTy &ImportList, 250 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) { 251 for (auto &Edge : Summary.calls()) { 252 auto GUID = Edge.first.getGUID(); 253 DEBUG(dbgs() << " edge -> " << GUID << " Threshold:" << Threshold << "\n"); 254 255 if (DefinedGVSummaries.count(GUID)) { 256 DEBUG(dbgs() << "ignored! Target already in destination module.\n"); 257 continue; 258 } 259 260 auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float { 261 if (Hotness == CalleeInfo::HotnessType::Hot) 262 return ImportHotMultiplier; 263 if (Hotness == CalleeInfo::HotnessType::Cold) 264 return ImportColdMultiplier; 265 return 1.0; 266 }; 267 268 const auto NewThreshold = 269 Threshold * GetBonusMultiplier(Edge.second.Hotness); 270 271 auto *CalleeSummary = selectCallee(GUID, NewThreshold, Index); 272 if (!CalleeSummary) { 273 DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n"); 274 continue; 275 } 276 // "Resolve" the summary, traversing alias, 277 const FunctionSummary *ResolvedCalleeSummary; 278 if (isa<AliasSummary>(CalleeSummary)) { 279 ResolvedCalleeSummary = cast<FunctionSummary>( 280 &cast<AliasSummary>(CalleeSummary)->getAliasee()); 281 assert( 282 GlobalValue::isLinkOnceODRLinkage(ResolvedCalleeSummary->linkage()) && 283 "Unexpected alias to a non-linkonceODR in import list"); 284 } else 285 ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary); 286 287 assert(ResolvedCalleeSummary->instCount() <= NewThreshold && 288 "selectCallee() didn't honor the threshold"); 289 290 auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) { 291 // Adjust the threshold for next level of imported functions. 292 // The threshold is different for hot callsites because we can then 293 // inline chains of hot calls. 294 if (IsHotCallsite) 295 return Threshold * ImportHotInstrFactor; 296 return Threshold * ImportInstrFactor; 297 }; 298 299 bool IsHotCallsite = Edge.second.Hotness == CalleeInfo::HotnessType::Hot; 300 const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite); 301 302 auto ExportModulePath = ResolvedCalleeSummary->modulePath(); 303 auto &ProcessedThreshold = ImportList[ExportModulePath][GUID]; 304 /// Since the traversal of the call graph is DFS, we can revisit a function 305 /// a second time with a higher threshold. In this case, it is added back to 306 /// the worklist with the new threshold. 307 if (ProcessedThreshold && ProcessedThreshold >= AdjThreshold) { 308 DEBUG(dbgs() << "ignored! Target was already seen with Threshold " 309 << ProcessedThreshold << "\n"); 310 continue; 311 } 312 bool PreviouslyImported = ProcessedThreshold != 0; 313 // Mark this function as imported in this module, with the current Threshold 314 ProcessedThreshold = AdjThreshold; 315 316 // Make exports in the source module. 317 if (ExportLists) { 318 auto &ExportList = (*ExportLists)[ExportModulePath]; 319 ExportList.insert(GUID); 320 if (!PreviouslyImported) { 321 // This is the first time this function was exported from its source 322 // module, so mark all functions and globals it references as exported 323 // to the outside if they are defined in the same source module. 324 // For efficiency, we unconditionally add all the referenced GUIDs 325 // to the ExportList for this module, and will prune out any not 326 // defined in the module later in a single pass. 327 for (auto &Edge : ResolvedCalleeSummary->calls()) { 328 auto CalleeGUID = Edge.first.getGUID(); 329 ExportList.insert(CalleeGUID); 330 } 331 for (auto &Ref : ResolvedCalleeSummary->refs()) { 332 auto GUID = Ref.getGUID(); 333 ExportList.insert(GUID); 334 } 335 } 336 } 337 338 // Insert the newly imported function to the worklist. 339 Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, GUID); 340 } 341 } 342 343 /// Given the list of globals defined in a module, compute the list of imports 344 /// as well as the list of "exports", i.e. the list of symbols referenced from 345 /// another module (that may require promotion). 346 static void ComputeImportForModule( 347 const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index, 348 FunctionImporter::ImportMapTy &ImportList, 349 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) { 350 // Worklist contains the list of function imported in this module, for which 351 // we will analyse the callees and may import further down the callgraph. 352 SmallVector<EdgeInfo, 128> Worklist; 353 354 // Populate the worklist with the import for the functions in the current 355 // module 356 for (auto &GVSummary : DefinedGVSummaries) { 357 auto *Summary = GVSummary.second; 358 if (auto *AS = dyn_cast<AliasSummary>(Summary)) 359 Summary = &AS->getAliasee(); 360 auto *FuncSummary = dyn_cast<FunctionSummary>(Summary); 361 if (!FuncSummary) 362 // Skip import for global variables 363 continue; 364 DEBUG(dbgs() << "Initalize import for " << GVSummary.first << "\n"); 365 computeImportForFunction(*FuncSummary, Index, ImportInstrLimit, 366 DefinedGVSummaries, Worklist, ImportList, 367 ExportLists); 368 } 369 370 // Process the newly imported functions and add callees to the worklist. 371 while (!Worklist.empty()) { 372 auto FuncInfo = Worklist.pop_back_val(); 373 auto *Summary = std::get<0>(FuncInfo); 374 auto Threshold = std::get<1>(FuncInfo); 375 auto GUID = std::get<2>(FuncInfo); 376 377 // Check if we later added this summary with a higher threshold. 378 // If so, skip this entry. 379 auto ExportModulePath = Summary->modulePath(); 380 auto &LatestProcessedThreshold = ImportList[ExportModulePath][GUID]; 381 if (LatestProcessedThreshold > Threshold) 382 continue; 383 384 computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries, 385 Worklist, ImportList, ExportLists); 386 } 387 } 388 389 } // anonymous namespace 390 391 /// Compute all the import and export for every module using the Index. 392 void llvm::ComputeCrossModuleImport( 393 const ModuleSummaryIndex &Index, 394 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries, 395 StringMap<FunctionImporter::ImportMapTy> &ImportLists, 396 StringMap<FunctionImporter::ExportSetTy> &ExportLists) { 397 // For each module that has function defined, compute the import/export lists. 398 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) { 399 auto &ImportList = ImportLists[DefinedGVSummaries.first()]; 400 DEBUG(dbgs() << "Computing import for Module '" 401 << DefinedGVSummaries.first() << "'\n"); 402 ComputeImportForModule(DefinedGVSummaries.second, Index, ImportList, 403 &ExportLists); 404 } 405 406 // When computing imports we added all GUIDs referenced by anything 407 // imported from the module to its ExportList. Now we prune each ExportList 408 // of any not defined in that module. This is more efficient than checking 409 // while computing imports because some of the summary lists may be long 410 // due to linkonce (comdat) copies. 411 for (auto &ELI : ExportLists) { 412 const auto &DefinedGVSummaries = 413 ModuleToDefinedGVSummaries.lookup(ELI.first()); 414 for (auto EI = ELI.second.begin(); EI != ELI.second.end();) { 415 if (!DefinedGVSummaries.count(*EI)) 416 EI = ELI.second.erase(EI); 417 else 418 ++EI; 419 } 420 } 421 422 #ifndef NDEBUG 423 DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size() 424 << " modules:\n"); 425 for (auto &ModuleImports : ImportLists) { 426 auto ModName = ModuleImports.first(); 427 auto &Exports = ExportLists[ModName]; 428 DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size() 429 << " functions. Imports from " << ModuleImports.second.size() 430 << " modules.\n"); 431 for (auto &Src : ModuleImports.second) { 432 auto SrcModName = Src.first(); 433 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from " 434 << SrcModName << "\n"); 435 } 436 } 437 #endif 438 } 439 440 /// Compute all the imports for the given module in the Index. 441 void llvm::ComputeCrossModuleImportForModule( 442 StringRef ModulePath, const ModuleSummaryIndex &Index, 443 FunctionImporter::ImportMapTy &ImportList) { 444 445 // Collect the list of functions this module defines. 446 // GUID -> Summary 447 GVSummaryMapTy FunctionSummaryMap; 448 Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap); 449 450 // Compute the import list for this module. 451 DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n"); 452 ComputeImportForModule(FunctionSummaryMap, Index, ImportList); 453 454 #ifndef NDEBUG 455 DEBUG(dbgs() << "* Module " << ModulePath << " imports from " 456 << ImportList.size() << " modules.\n"); 457 for (auto &Src : ImportList) { 458 auto SrcModName = Src.first(); 459 DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from " 460 << SrcModName << "\n"); 461 } 462 #endif 463 } 464 465 /// Compute the set of summaries needed for a ThinLTO backend compilation of 466 /// \p ModulePath. 467 void llvm::gatherImportedSummariesForModule( 468 StringRef ModulePath, 469 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries, 470 const FunctionImporter::ImportMapTy &ImportList, 471 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) { 472 // Include all summaries from the importing module. 473 ModuleToSummariesForIndex[ModulePath] = 474 ModuleToDefinedGVSummaries.lookup(ModulePath); 475 // Include summaries for imports. 476 for (auto &ILI : ImportList) { 477 auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()]; 478 const auto &DefinedGVSummaries = 479 ModuleToDefinedGVSummaries.lookup(ILI.first()); 480 for (auto &GI : ILI.second) { 481 const auto &DS = DefinedGVSummaries.find(GI.first); 482 assert(DS != DefinedGVSummaries.end() && 483 "Expected a defined summary for imported global value"); 484 SummariesForIndex[GI.first] = DS->second; 485 } 486 } 487 } 488 489 /// Emit the files \p ModulePath will import from into \p OutputFilename. 490 std::error_code 491 llvm::EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename, 492 const FunctionImporter::ImportMapTy &ModuleImports) { 493 std::error_code EC; 494 raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None); 495 if (EC) 496 return EC; 497 for (auto &ILI : ModuleImports) 498 ImportsOS << ILI.first() << "\n"; 499 return std::error_code(); 500 } 501 502 /// Fixup WeakForLinker linkages in \p TheModule based on summary analysis. 503 void llvm::thinLTOResolveWeakForLinkerModule( 504 Module &TheModule, const GVSummaryMapTy &DefinedGlobals) { 505 auto updateLinkage = [&](GlobalValue &GV) { 506 if (!GlobalValue::isWeakForLinker(GV.getLinkage())) 507 return; 508 // See if the global summary analysis computed a new resolved linkage. 509 const auto &GS = DefinedGlobals.find(GV.getGUID()); 510 if (GS == DefinedGlobals.end()) 511 return; 512 auto NewLinkage = GS->second->linkage(); 513 if (NewLinkage == GV.getLinkage()) 514 return; 515 DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from " 516 << GV.getLinkage() << " to " << NewLinkage << "\n"); 517 GV.setLinkage(NewLinkage); 518 // Remove functions converted to available_externally from comdats, 519 // as this is a declaration for the linker, and will be dropped eventually. 520 // It is illegal for comdats to contain declarations. 521 auto *GO = dyn_cast_or_null<GlobalObject>(&GV); 522 if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) { 523 assert(GO->hasAvailableExternallyLinkage() && 524 "Expected comdat on definition (possibly available external)"); 525 GO->setComdat(nullptr); 526 } 527 }; 528 529 // Process functions and global now 530 for (auto &GV : TheModule) 531 updateLinkage(GV); 532 for (auto &GV : TheModule.globals()) 533 updateLinkage(GV); 534 for (auto &GV : TheModule.aliases()) 535 updateLinkage(GV); 536 } 537 538 /// Run internalization on \p TheModule based on symmary analysis. 539 void llvm::thinLTOInternalizeModule(Module &TheModule, 540 const GVSummaryMapTy &DefinedGlobals) { 541 // Parse inline ASM and collect the list of symbols that are not defined in 542 // the current module. 543 StringSet<> AsmUndefinedRefs; 544 ModuleSymbolTable::CollectAsmSymbols( 545 Triple(TheModule.getTargetTriple()), TheModule.getModuleInlineAsm(), 546 [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) { 547 if (Flags & object::BasicSymbolRef::SF_Undefined) 548 AsmUndefinedRefs.insert(Name); 549 }); 550 551 // Declare a callback for the internalize pass that will ask for every 552 // candidate GlobalValue if it can be internalized or not. 553 auto MustPreserveGV = [&](const GlobalValue &GV) -> bool { 554 // Can't be internalized if referenced in inline asm. 555 if (AsmUndefinedRefs.count(GV.getName())) 556 return true; 557 558 // Lookup the linkage recorded in the summaries during global analysis. 559 const auto &GS = DefinedGlobals.find(GV.getGUID()); 560 GlobalValue::LinkageTypes Linkage; 561 if (GS == DefinedGlobals.end()) { 562 // Must have been promoted (possibly conservatively). Find original 563 // name so that we can access the correct summary and see if it can 564 // be internalized again. 565 // FIXME: Eventually we should control promotion instead of promoting 566 // and internalizing again. 567 StringRef OrigName = 568 ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName()); 569 std::string OrigId = GlobalValue::getGlobalIdentifier( 570 OrigName, GlobalValue::InternalLinkage, 571 TheModule.getSourceFileName()); 572 const auto &GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId)); 573 if (GS == DefinedGlobals.end()) { 574 // Also check the original non-promoted non-globalized name. In some 575 // cases a preempted weak value is linked in as a local copy because 576 // it is referenced by an alias (IRLinker::linkGlobalValueProto). 577 // In that case, since it was originally not a local value, it was 578 // recorded in the index using the original name. 579 // FIXME: This may not be needed once PR27866 is fixed. 580 const auto &GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName)); 581 assert(GS != DefinedGlobals.end()); 582 Linkage = GS->second->linkage(); 583 } else { 584 Linkage = GS->second->linkage(); 585 } 586 } else 587 Linkage = GS->second->linkage(); 588 return !GlobalValue::isLocalLinkage(Linkage); 589 }; 590 591 // FIXME: See if we can just internalize directly here via linkage changes 592 // based on the index, rather than invoking internalizeModule. 593 llvm::internalizeModule(TheModule, MustPreserveGV); 594 } 595 596 // Automatically import functions in Module \p DestModule based on the summaries 597 // index. 598 // 599 Expected<bool> FunctionImporter::importFunctions( 600 Module &DestModule, const FunctionImporter::ImportMapTy &ImportList, 601 bool ForceImportReferencedDiscardableSymbols) { 602 DEBUG(dbgs() << "Starting import for Module " 603 << DestModule.getModuleIdentifier() << "\n"); 604 unsigned ImportedCount = 0; 605 606 // Linker that will be used for importing function 607 Linker TheLinker(DestModule); 608 // Do the actual import of functions now, one Module at a time 609 std::set<StringRef> ModuleNameOrderedList; 610 for (auto &FunctionsToImportPerModule : ImportList) { 611 ModuleNameOrderedList.insert(FunctionsToImportPerModule.first()); 612 } 613 for (auto &Name : ModuleNameOrderedList) { 614 // Get the module for the import 615 const auto &FunctionsToImportPerModule = ImportList.find(Name); 616 assert(FunctionsToImportPerModule != ImportList.end()); 617 Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name); 618 if (!SrcModuleOrErr) 619 return SrcModuleOrErr.takeError(); 620 std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr); 621 assert(&DestModule.getContext() == &SrcModule->getContext() && 622 "Context mismatch"); 623 624 // If modules were created with lazy metadata loading, materialize it 625 // now, before linking it (otherwise this will be a noop). 626 if (Error Err = SrcModule->materializeMetadata()) 627 return std::move(Err); 628 UpgradeDebugInfo(*SrcModule); 629 630 auto &ImportGUIDs = FunctionsToImportPerModule->second; 631 // Find the globals to import 632 DenseSet<const GlobalValue *> GlobalsToImport; 633 for (Function &F : *SrcModule) { 634 if (!F.hasName()) 635 continue; 636 auto GUID = F.getGUID(); 637 auto Import = ImportGUIDs.count(GUID); 638 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " << GUID 639 << " " << F.getName() << " from " 640 << SrcModule->getSourceFileName() << "\n"); 641 if (Import) { 642 if (Error Err = F.materialize()) 643 return std::move(Err); 644 if (EnableImportMetadata) { 645 // Add 'thinlto_src_module' metadata for statistics and debugging. 646 F.setMetadata( 647 "thinlto_src_module", 648 llvm::MDNode::get( 649 DestModule.getContext(), 650 {llvm::MDString::get(DestModule.getContext(), 651 SrcModule->getSourceFileName())})); 652 } 653 GlobalsToImport.insert(&F); 654 } 655 } 656 for (GlobalVariable &GV : SrcModule->globals()) { 657 if (!GV.hasName()) 658 continue; 659 auto GUID = GV.getGUID(); 660 auto Import = ImportGUIDs.count(GUID); 661 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " << GUID 662 << " " << GV.getName() << " from " 663 << SrcModule->getSourceFileName() << "\n"); 664 if (Import) { 665 if (Error Err = GV.materialize()) 666 return std::move(Err); 667 GlobalsToImport.insert(&GV); 668 } 669 } 670 for (GlobalAlias &GA : SrcModule->aliases()) { 671 if (!GA.hasName()) 672 continue; 673 auto GUID = GA.getGUID(); 674 auto Import = ImportGUIDs.count(GUID); 675 DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias " << GUID 676 << " " << GA.getName() << " from " 677 << SrcModule->getSourceFileName() << "\n"); 678 if (Import) { 679 // Alias can't point to "available_externally". However when we import 680 // linkOnceODR the linkage does not change. So we import the alias 681 // and aliasee only in this case. This has been handled by 682 // computeImportForFunction() 683 GlobalObject *GO = GA.getBaseObject(); 684 assert(GO->hasLinkOnceODRLinkage() && 685 "Unexpected alias to a non-linkonceODR in import list"); 686 #ifndef NDEBUG 687 if (!GlobalsToImport.count(GO)) 688 DEBUG(dbgs() << " alias triggers importing aliasee " << GO->getGUID() 689 << " " << GO->getName() << " from " 690 << SrcModule->getSourceFileName() << "\n"); 691 #endif 692 if (Error Err = GO->materialize()) 693 return std::move(Err); 694 GlobalsToImport.insert(GO); 695 if (Error Err = GA.materialize()) 696 return std::move(Err); 697 GlobalsToImport.insert(&GA); 698 } 699 } 700 701 // Link in the specified functions. 702 if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport)) 703 return true; 704 705 if (PrintImports) { 706 for (const auto *GV : GlobalsToImport) 707 dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName() 708 << " from " << SrcModule->getSourceFileName() << "\n"; 709 } 710 711 // Instruct the linker that the client will take care of linkonce resolution 712 unsigned Flags = Linker::Flags::None; 713 if (!ForceImportReferencedDiscardableSymbols) 714 Flags |= Linker::Flags::DontForceLinkLinkonceODR; 715 716 if (TheLinker.linkInModule(std::move(SrcModule), Flags, &GlobalsToImport)) 717 report_fatal_error("Function Import: link error"); 718 719 ImportedCount += GlobalsToImport.size(); 720 } 721 722 NumImported += ImportedCount; 723 724 DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module " 725 << DestModule.getModuleIdentifier() << "\n"); 726 return ImportedCount; 727 } 728 729 /// Summary file to use for function importing when using -function-import from 730 /// the command line. 731 static cl::opt<std::string> 732 SummaryFile("summary-file", 733 cl::desc("The summary file to use for function importing.")); 734 735 static bool doImportingForModule(Module &M) { 736 if (SummaryFile.empty()) 737 report_fatal_error("error: -function-import requires -summary-file\n"); 738 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr = 739 getModuleSummaryIndexForFile(SummaryFile); 740 if (!IndexPtrOrErr) { 741 logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(), 742 "Error loading file '" + SummaryFile + "': "); 743 return false; 744 } 745 std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr); 746 747 // First step is collecting the import list. 748 FunctionImporter::ImportMapTy ImportList; 749 ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index, 750 ImportList); 751 752 // Conservatively mark all internal values as promoted. This interface is 753 // only used when doing importing via the function importing pass. The pass 754 // is only enabled when testing importing via the 'opt' tool, which does 755 // not do the ThinLink that would normally determine what values to promote. 756 for (auto &I : *Index) { 757 for (auto &S : I.second) { 758 if (GlobalValue::isLocalLinkage(S->linkage())) 759 S->setLinkage(GlobalValue::ExternalLinkage); 760 } 761 } 762 763 // Next we need to promote to global scope and rename any local values that 764 // are potentially exported to other modules. 765 if (renameModuleForThinLTO(M, *Index, nullptr)) { 766 errs() << "Error renaming module\n"; 767 return false; 768 } 769 770 // Perform the import now. 771 auto ModuleLoader = [&M](StringRef Identifier) { 772 return loadFile(Identifier, M.getContext()); 773 }; 774 FunctionImporter Importer(*Index, ModuleLoader); 775 Expected<bool> Result = Importer.importFunctions( 776 M, ImportList, !DontForceImportReferencedDiscardableSymbols); 777 778 // FIXME: Probably need to propagate Errors through the pass manager. 779 if (!Result) { 780 logAllUnhandledErrors(Result.takeError(), errs(), 781 "Error importing module: "); 782 return false; 783 } 784 785 return *Result; 786 } 787 788 namespace { 789 /// Pass that performs cross-module function import provided a summary file. 790 class FunctionImportLegacyPass : public ModulePass { 791 public: 792 /// Pass identification, replacement for typeid 793 static char ID; 794 795 /// Specify pass name for debug output 796 StringRef getPassName() const override { return "Function Importing"; } 797 798 explicit FunctionImportLegacyPass() : ModulePass(ID) {} 799 800 bool runOnModule(Module &M) override { 801 if (skipModule(M)) 802 return false; 803 804 return doImportingForModule(M); 805 } 806 }; 807 } // anonymous namespace 808 809 PreservedAnalyses FunctionImportPass::run(Module &M, 810 ModuleAnalysisManager &AM) { 811 if (!doImportingForModule(M)) 812 return PreservedAnalyses::all(); 813 814 return PreservedAnalyses::none(); 815 } 816 817 char FunctionImportLegacyPass::ID = 0; 818 INITIALIZE_PASS(FunctionImportLegacyPass, "function-import", 819 "Summary Based Function Import", false, false) 820 821 namespace llvm { 822 Pass *createFunctionImportPass() { 823 return new FunctionImportLegacyPass(); 824 } 825 } 826