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