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