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 #include "llvm/ADT/ArrayRef.h" 16 #include "llvm/ADT/STLExtras.h" 17 #include "llvm/ADT/SetVector.h" 18 #include "llvm/ADT/SmallVector.h" 19 #include "llvm/ADT/Statistic.h" 20 #include "llvm/ADT/StringMap.h" 21 #include "llvm/ADT/StringRef.h" 22 #include "llvm/ADT/StringSet.h" 23 #include "llvm/Bitcode/BitcodeReader.h" 24 #include "llvm/IR/AutoUpgrade.h" 25 #include "llvm/IR/Constants.h" 26 #include "llvm/IR/Function.h" 27 #include "llvm/IR/GlobalAlias.h" 28 #include "llvm/IR/GlobalObject.h" 29 #include "llvm/IR/GlobalValue.h" 30 #include "llvm/IR/GlobalVariable.h" 31 #include "llvm/IR/Metadata.h" 32 #include "llvm/IR/Module.h" 33 #include "llvm/IR/ModuleSummaryIndex.h" 34 #include "llvm/IRReader/IRReader.h" 35 #include "llvm/Linker/IRMover.h" 36 #include "llvm/Object/ModuleSymbolTable.h" 37 #include "llvm/Object/SymbolicFile.h" 38 #include "llvm/Pass.h" 39 #include "llvm/Support/Casting.h" 40 #include "llvm/Support/CommandLine.h" 41 #include "llvm/Support/Debug.h" 42 #include "llvm/Support/Error.h" 43 #include "llvm/Support/ErrorHandling.h" 44 #include "llvm/Support/FileSystem.h" 45 #include "llvm/Support/SourceMgr.h" 46 #include "llvm/Support/raw_ostream.h" 47 #include "llvm/Transforms/IPO/Internalize.h" 48 #include "llvm/Transforms/Utils/Cloning.h" 49 #include "llvm/Transforms/Utils/FunctionImportUtils.h" 50 #include "llvm/Transforms/Utils/ValueMapper.h" 51 #include <cassert> 52 #include <memory> 53 #include <set> 54 #include <string> 55 #include <system_error> 56 #include <tuple> 57 #include <utility> 58 59 using namespace llvm; 60 61 #define DEBUG_TYPE "function-import" 62 63 STATISTIC(NumImportedFunctionsThinLink, 64 "Number of functions thin link decided to import"); 65 STATISTIC(NumImportedHotFunctionsThinLink, 66 "Number of hot functions thin link decided to import"); 67 STATISTIC(NumImportedCriticalFunctionsThinLink, 68 "Number of critical functions thin link decided to import"); 69 STATISTIC(NumImportedGlobalVarsThinLink, 70 "Number of global variables thin link decided to import"); 71 STATISTIC(NumImportedFunctions, "Number of functions imported in backend"); 72 STATISTIC(NumImportedGlobalVars, 73 "Number of global variables imported in backend"); 74 STATISTIC(NumImportedModules, "Number of modules imported from"); 75 STATISTIC(NumDeadSymbols, "Number of dead stripped symbols in index"); 76 STATISTIC(NumLiveSymbols, "Number of live symbols in index"); 77 78 /// Limit on instruction count of imported functions. 79 static cl::opt<unsigned> ImportInstrLimit( 80 "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"), 81 cl::desc("Only import functions with less than N instructions")); 82 83 static cl::opt<int> ImportCutoff( 84 "import-cutoff", cl::init(-1), cl::Hidden, cl::value_desc("N"), 85 cl::desc("Only import first N functions if N>=0 (default -1)")); 86 87 static cl::opt<float> 88 ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7), 89 cl::Hidden, cl::value_desc("x"), 90 cl::desc("As we import functions, multiply the " 91 "`import-instr-limit` threshold by this factor " 92 "before processing newly imported functions")); 93 94 static cl::opt<float> ImportHotInstrFactor( 95 "import-hot-evolution-factor", cl::init(1.0), cl::Hidden, 96 cl::value_desc("x"), 97 cl::desc("As we import functions called from hot callsite, multiply the " 98 "`import-instr-limit` threshold by this factor " 99 "before processing newly imported functions")); 100 101 static cl::opt<float> ImportHotMultiplier( 102 "import-hot-multiplier", cl::init(10.0), cl::Hidden, cl::value_desc("x"), 103 cl::desc("Multiply the `import-instr-limit` threshold for hot callsites")); 104 105 static cl::opt<float> ImportCriticalMultiplier( 106 "import-critical-multiplier", cl::init(100.0), cl::Hidden, 107 cl::value_desc("x"), 108 cl::desc( 109 "Multiply the `import-instr-limit` threshold for critical callsites")); 110 111 // FIXME: This multiplier was not really tuned up. 112 static cl::opt<float> ImportColdMultiplier( 113 "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"), 114 cl::desc("Multiply the `import-instr-limit` threshold for cold callsites")); 115 116 static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden, 117 cl::desc("Print imported functions")); 118 119 static cl::opt<bool> PrintImportFailures( 120 "print-import-failures", cl::init(false), cl::Hidden, 121 cl::desc("Print information for functions rejected for importing")); 122 123 static cl::opt<bool> ComputeDead("compute-dead", cl::init(true), cl::Hidden, 124 cl::desc("Compute dead symbols")); 125 126 static cl::opt<bool> EnableImportMetadata( 127 "enable-import-metadata", cl::init( 128 #if !defined(NDEBUG) 129 true /*Enabled with asserts.*/ 130 #else 131 false 132 #endif 133 ), 134 cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'")); 135 136 /// Summary file to use for function importing when using -function-import from 137 /// the command line. 138 static cl::opt<std::string> 139 SummaryFile("summary-file", 140 cl::desc("The summary file to use for function importing.")); 141 142 /// Used when testing importing from distributed indexes via opt 143 // -function-import. 144 static cl::opt<bool> 145 ImportAllIndex("import-all-index", 146 cl::desc("Import all external functions in index.")); 147 148 // Load lazily a module from \p FileName in \p Context. 149 static std::unique_ptr<Module> loadFile(const std::string &FileName, 150 LLVMContext &Context) { 151 SMDiagnostic Err; 152 LLVM_DEBUG(dbgs() << "Loading '" << FileName << "'\n"); 153 // Metadata isn't loaded until functions are imported, to minimize 154 // the memory overhead. 155 std::unique_ptr<Module> Result = 156 getLazyIRFileModule(FileName, Err, Context, 157 /* ShouldLazyLoadMetadata = */ true); 158 if (!Result) { 159 Err.print("function-import", errs()); 160 report_fatal_error("Abort"); 161 } 162 163 return Result; 164 } 165 166 /// Given a list of possible callee implementation for a call site, select one 167 /// that fits the \p Threshold. 168 /// 169 /// FIXME: select "best" instead of first that fits. But what is "best"? 170 /// - The smallest: more likely to be inlined. 171 /// - The one with the least outgoing edges (already well optimized). 172 /// - One from a module already being imported from in order to reduce the 173 /// number of source modules parsed/linked. 174 /// - One that has PGO data attached. 175 /// - [insert you fancy metric here] 176 static const GlobalValueSummary * 177 selectCallee(const ModuleSummaryIndex &Index, 178 ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList, 179 unsigned Threshold, StringRef CallerModulePath, 180 FunctionImporter::ImportFailureReason &Reason, 181 GlobalValue::GUID GUID) { 182 Reason = FunctionImporter::ImportFailureReason::None; 183 auto It = llvm::find_if( 184 CalleeSummaryList, 185 [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) { 186 auto *GVSummary = SummaryPtr.get(); 187 if (!Index.isGlobalValueLive(GVSummary)) { 188 Reason = FunctionImporter::ImportFailureReason::NotLive; 189 return false; 190 } 191 192 // For SamplePGO, in computeImportForFunction the OriginalId 193 // may have been used to locate the callee summary list (See 194 // comment there). 195 // The mapping from OriginalId to GUID may return a GUID 196 // that corresponds to a static variable. Filter it out here. 197 // This can happen when 198 // 1) There is a call to a library function which is not defined 199 // in the index. 200 // 2) There is a static variable with the OriginalGUID identical 201 // to the GUID of the library function in 1); 202 // When this happens, the logic for SamplePGO kicks in and 203 // the static variable in 2) will be found, which needs to be 204 // filtered out. 205 if (GVSummary->getSummaryKind() == GlobalValueSummary::GlobalVarKind) { 206 Reason = FunctionImporter::ImportFailureReason::GlobalVar; 207 return false; 208 } 209 if (GlobalValue::isInterposableLinkage(GVSummary->linkage())) { 210 Reason = FunctionImporter::ImportFailureReason::InterposableLinkage; 211 // There is no point in importing these, we can't inline them 212 return false; 213 } 214 215 auto *Summary = cast<FunctionSummary>(GVSummary->getBaseObject()); 216 217 // If this is a local function, make sure we import the copy 218 // in the caller's module. The only time a local function can 219 // share an entry in the index is if there is a local with the same name 220 // in another module that had the same source file name (in a different 221 // directory), where each was compiled in their own directory so there 222 // was not distinguishing path. 223 // However, do the import from another module if there is only one 224 // entry in the list - in that case this must be a reference due 225 // to indirect call profile data, since a function pointer can point to 226 // a local in another module. 227 if (GlobalValue::isLocalLinkage(Summary->linkage()) && 228 CalleeSummaryList.size() > 1 && 229 Summary->modulePath() != CallerModulePath) { 230 Reason = 231 FunctionImporter::ImportFailureReason::LocalLinkageNotInModule; 232 return false; 233 } 234 235 if (Summary->instCount() > Threshold) { 236 Reason = FunctionImporter::ImportFailureReason::TooLarge; 237 return false; 238 } 239 240 // Skip if it isn't legal to import (e.g. may reference unpromotable 241 // locals). 242 if (Summary->notEligibleToImport()) { 243 Reason = FunctionImporter::ImportFailureReason::NotEligible; 244 return false; 245 } 246 247 // Don't bother importing if we can't inline it anyway. 248 if (Summary->fflags().NoInline) { 249 Reason = FunctionImporter::ImportFailureReason::NoInline; 250 return false; 251 } 252 253 return true; 254 }); 255 if (It == CalleeSummaryList.end()) 256 return nullptr; 257 258 return cast<GlobalValueSummary>(It->get()); 259 } 260 261 namespace { 262 263 using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */, 264 GlobalValue::GUID>; 265 266 } // anonymous namespace 267 268 static ValueInfo 269 updateValueInfoForIndirectCalls(const ModuleSummaryIndex &Index, ValueInfo VI) { 270 if (!VI.getSummaryList().empty()) 271 return VI; 272 // For SamplePGO, the indirect call targets for local functions will 273 // have its original name annotated in profile. We try to find the 274 // corresponding PGOFuncName as the GUID. 275 // FIXME: Consider updating the edges in the graph after building 276 // it, rather than needing to perform this mapping on each walk. 277 auto GUID = Index.getGUIDFromOriginalID(VI.getGUID()); 278 if (GUID == 0) 279 return ValueInfo(); 280 return Index.getValueInfo(GUID); 281 } 282 283 static void computeImportForReferencedGlobals( 284 const FunctionSummary &Summary, const GVSummaryMapTy &DefinedGVSummaries, 285 FunctionImporter::ImportMapTy &ImportList, 286 StringMap<FunctionImporter::ExportSetTy> *ExportLists) { 287 for (auto &VI : Summary.refs()) { 288 if (DefinedGVSummaries.count(VI.getGUID())) { 289 LLVM_DEBUG( 290 dbgs() << "Ref ignored! Target already in destination module.\n"); 291 continue; 292 } 293 294 LLVM_DEBUG(dbgs() << " ref -> " << VI << "\n"); 295 296 for (auto &RefSummary : VI.getSummaryList()) 297 if (isa<GlobalVarSummary>(RefSummary.get()) && 298 canImportGlobalVar(RefSummary.get())) { 299 auto ILI = ImportList[RefSummary->modulePath()].insert(VI.getGUID()); 300 // Only update stat if we haven't already imported this variable. 301 if (ILI.second) 302 NumImportedGlobalVarsThinLink++; 303 if (ExportLists) 304 (*ExportLists)[RefSummary->modulePath()].insert(VI.getGUID()); 305 break; 306 } 307 } 308 } 309 310 static const char * 311 getFailureName(FunctionImporter::ImportFailureReason Reason) { 312 switch (Reason) { 313 case FunctionImporter::ImportFailureReason::None: 314 return "None"; 315 case FunctionImporter::ImportFailureReason::GlobalVar: 316 return "GlobalVar"; 317 case FunctionImporter::ImportFailureReason::NotLive: 318 return "NotLive"; 319 case FunctionImporter::ImportFailureReason::TooLarge: 320 return "TooLarge"; 321 case FunctionImporter::ImportFailureReason::InterposableLinkage: 322 return "InterposableLinkage"; 323 case FunctionImporter::ImportFailureReason::LocalLinkageNotInModule: 324 return "LocalLinkageNotInModule"; 325 case FunctionImporter::ImportFailureReason::NotEligible: 326 return "NotEligible"; 327 case FunctionImporter::ImportFailureReason::NoInline: 328 return "NoInline"; 329 } 330 llvm_unreachable("invalid reason"); 331 } 332 333 /// Compute the list of functions to import for a given caller. Mark these 334 /// imported functions and the symbols they reference in their source module as 335 /// exported from their source module. 336 static void computeImportForFunction( 337 const FunctionSummary &Summary, const ModuleSummaryIndex &Index, 338 const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries, 339 SmallVectorImpl<EdgeInfo> &Worklist, 340 FunctionImporter::ImportMapTy &ImportList, 341 StringMap<FunctionImporter::ExportSetTy> *ExportLists, 342 FunctionImporter::ImportThresholdsTy &ImportThresholds) { 343 computeImportForReferencedGlobals(Summary, DefinedGVSummaries, ImportList, 344 ExportLists); 345 static int ImportCount = 0; 346 for (auto &Edge : Summary.calls()) { 347 ValueInfo VI = Edge.first; 348 LLVM_DEBUG(dbgs() << " edge -> " << VI << " Threshold:" << Threshold 349 << "\n"); 350 351 if (ImportCutoff >= 0 && ImportCount >= ImportCutoff) { 352 LLVM_DEBUG(dbgs() << "ignored! import-cutoff value of " << ImportCutoff 353 << " reached.\n"); 354 continue; 355 } 356 357 VI = updateValueInfoForIndirectCalls(Index, VI); 358 if (!VI) 359 continue; 360 361 if (DefinedGVSummaries.count(VI.getGUID())) { 362 LLVM_DEBUG(dbgs() << "ignored! Target already in destination module.\n"); 363 continue; 364 } 365 366 auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float { 367 if (Hotness == CalleeInfo::HotnessType::Hot) 368 return ImportHotMultiplier; 369 if (Hotness == CalleeInfo::HotnessType::Cold) 370 return ImportColdMultiplier; 371 if (Hotness == CalleeInfo::HotnessType::Critical) 372 return ImportCriticalMultiplier; 373 return 1.0; 374 }; 375 376 const auto NewThreshold = 377 Threshold * GetBonusMultiplier(Edge.second.getHotness()); 378 379 auto IT = ImportThresholds.insert(std::make_pair( 380 VI.getGUID(), std::make_tuple(NewThreshold, nullptr, nullptr))); 381 bool PreviouslyVisited = !IT.second; 382 auto &ProcessedThreshold = std::get<0>(IT.first->second); 383 auto &CalleeSummary = std::get<1>(IT.first->second); 384 auto &FailureInfo = std::get<2>(IT.first->second); 385 386 bool IsHotCallsite = 387 Edge.second.getHotness() == CalleeInfo::HotnessType::Hot; 388 bool IsCriticalCallsite = 389 Edge.second.getHotness() == CalleeInfo::HotnessType::Critical; 390 391 const FunctionSummary *ResolvedCalleeSummary = nullptr; 392 if (CalleeSummary) { 393 assert(PreviouslyVisited); 394 // Since the traversal of the call graph is DFS, we can revisit a function 395 // a second time with a higher threshold. In this case, it is added back 396 // to the worklist with the new threshold (so that its own callee chains 397 // can be considered with the higher threshold). 398 if (NewThreshold <= ProcessedThreshold) { 399 LLVM_DEBUG( 400 dbgs() << "ignored! Target was already imported with Threshold " 401 << ProcessedThreshold << "\n"); 402 continue; 403 } 404 // Update with new larger threshold. 405 ProcessedThreshold = NewThreshold; 406 ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary); 407 } else { 408 // If we already rejected importing a callee at the same or higher 409 // threshold, don't waste time calling selectCallee. 410 if (PreviouslyVisited && NewThreshold <= ProcessedThreshold) { 411 LLVM_DEBUG( 412 dbgs() << "ignored! Target was already rejected with Threshold " 413 << ProcessedThreshold << "\n"); 414 if (PrintImportFailures) { 415 assert(FailureInfo && 416 "Expected FailureInfo for previously rejected candidate"); 417 FailureInfo->Attempts++; 418 } 419 continue; 420 } 421 422 FunctionImporter::ImportFailureReason Reason; 423 CalleeSummary = selectCallee(Index, VI.getSummaryList(), NewThreshold, 424 Summary.modulePath(), Reason, VI.getGUID()); 425 if (!CalleeSummary) { 426 // Update with new larger threshold if this was a retry (otherwise 427 // we would have already inserted with NewThreshold above). Also 428 // update failure info if requested. 429 if (PreviouslyVisited) { 430 ProcessedThreshold = NewThreshold; 431 if (PrintImportFailures) { 432 assert(FailureInfo && 433 "Expected FailureInfo for previously rejected candidate"); 434 FailureInfo->Reason = Reason; 435 FailureInfo->Attempts++; 436 FailureInfo->MaxHotness = 437 std::max(FailureInfo->MaxHotness, Edge.second.getHotness()); 438 } 439 } else if (PrintImportFailures) { 440 assert(!FailureInfo && 441 "Expected no FailureInfo for newly rejected candidate"); 442 FailureInfo = llvm::make_unique<FunctionImporter::ImportFailureInfo>( 443 VI, Edge.second.getHotness(), Reason, 1); 444 } 445 LLVM_DEBUG( 446 dbgs() << "ignored! No qualifying callee with summary found.\n"); 447 continue; 448 } 449 450 // "Resolve" the summary 451 CalleeSummary = CalleeSummary->getBaseObject(); 452 ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary); 453 454 assert(ResolvedCalleeSummary->instCount() <= NewThreshold && 455 "selectCallee() didn't honor the threshold"); 456 457 auto ExportModulePath = ResolvedCalleeSummary->modulePath(); 458 auto ILI = ImportList[ExportModulePath].insert(VI.getGUID()); 459 // We previously decided to import this GUID definition if it was already 460 // inserted in the set of imports from the exporting module. 461 bool PreviouslyImported = !ILI.second; 462 if (!PreviouslyImported) { 463 NumImportedFunctionsThinLink++; 464 if (IsHotCallsite) 465 NumImportedHotFunctionsThinLink++; 466 if (IsCriticalCallsite) 467 NumImportedCriticalFunctionsThinLink++; 468 } 469 470 // Make exports in the source module. 471 if (ExportLists) { 472 auto &ExportList = (*ExportLists)[ExportModulePath]; 473 ExportList.insert(VI.getGUID()); 474 if (!PreviouslyImported) { 475 // This is the first time this function was exported from its source 476 // module, so mark all functions and globals it references as exported 477 // to the outside if they are defined in the same source module. 478 // For efficiency, we unconditionally add all the referenced GUIDs 479 // to the ExportList for this module, and will prune out any not 480 // defined in the module later in a single pass. 481 for (auto &Edge : ResolvedCalleeSummary->calls()) { 482 auto CalleeGUID = Edge.first.getGUID(); 483 ExportList.insert(CalleeGUID); 484 } 485 for (auto &Ref : ResolvedCalleeSummary->refs()) { 486 auto GUID = Ref.getGUID(); 487 ExportList.insert(GUID); 488 } 489 } 490 } 491 } 492 493 auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) { 494 // Adjust the threshold for next level of imported functions. 495 // The threshold is different for hot callsites because we can then 496 // inline chains of hot calls. 497 if (IsHotCallsite) 498 return Threshold * ImportHotInstrFactor; 499 return Threshold * ImportInstrFactor; 500 }; 501 502 const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite); 503 504 ImportCount++; 505 506 // Insert the newly imported function to the worklist. 507 Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, VI.getGUID()); 508 } 509 } 510 511 /// Given the list of globals defined in a module, compute the list of imports 512 /// as well as the list of "exports", i.e. the list of symbols referenced from 513 /// another module (that may require promotion). 514 static void ComputeImportForModule( 515 const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index, 516 StringRef ModName, FunctionImporter::ImportMapTy &ImportList, 517 StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) { 518 // Worklist contains the list of function imported in this module, for which 519 // we will analyse the callees and may import further down the callgraph. 520 SmallVector<EdgeInfo, 128> Worklist; 521 FunctionImporter::ImportThresholdsTy ImportThresholds; 522 523 // Populate the worklist with the import for the functions in the current 524 // module 525 for (auto &GVSummary : DefinedGVSummaries) { 526 #ifndef NDEBUG 527 // FIXME: Change the GVSummaryMapTy to hold ValueInfo instead of GUID 528 // so this map look up (and possibly others) can be avoided. 529 auto VI = Index.getValueInfo(GVSummary.first); 530 #endif 531 if (!Index.isGlobalValueLive(GVSummary.second)) { 532 LLVM_DEBUG(dbgs() << "Ignores Dead GUID: " << VI << "\n"); 533 continue; 534 } 535 auto *FuncSummary = 536 dyn_cast<FunctionSummary>(GVSummary.second->getBaseObject()); 537 if (!FuncSummary) 538 // Skip import for global variables 539 continue; 540 LLVM_DEBUG(dbgs() << "Initialize import for " << VI << "\n"); 541 computeImportForFunction(*FuncSummary, Index, ImportInstrLimit, 542 DefinedGVSummaries, Worklist, ImportList, 543 ExportLists, ImportThresholds); 544 } 545 546 // Process the newly imported functions and add callees to the worklist. 547 while (!Worklist.empty()) { 548 auto FuncInfo = Worklist.pop_back_val(); 549 auto *Summary = std::get<0>(FuncInfo); 550 auto Threshold = std::get<1>(FuncInfo); 551 552 computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries, 553 Worklist, ImportList, ExportLists, 554 ImportThresholds); 555 } 556 557 // Print stats about functions considered but rejected for importing 558 // when requested. 559 if (PrintImportFailures) { 560 dbgs() << "Missed imports into module " << ModName << "\n"; 561 for (auto &I : ImportThresholds) { 562 auto &ProcessedThreshold = std::get<0>(I.second); 563 auto &CalleeSummary = std::get<1>(I.second); 564 auto &FailureInfo = std::get<2>(I.second); 565 if (CalleeSummary) 566 continue; // We are going to import. 567 assert(FailureInfo); 568 FunctionSummary *FS = nullptr; 569 if (!FailureInfo->VI.getSummaryList().empty()) 570 FS = dyn_cast<FunctionSummary>( 571 FailureInfo->VI.getSummaryList()[0]->getBaseObject()); 572 dbgs() << FailureInfo->VI 573 << ": Reason = " << getFailureName(FailureInfo->Reason) 574 << ", Threshold = " << ProcessedThreshold 575 << ", Size = " << (FS ? (int)FS->instCount() : -1) 576 << ", MaxHotness = " << getHotnessName(FailureInfo->MaxHotness) 577 << ", Attempts = " << FailureInfo->Attempts << "\n"; 578 } 579 } 580 } 581 582 #ifndef NDEBUG 583 static bool isGlobalVarSummary(const ModuleSummaryIndex &Index, 584 GlobalValue::GUID G) { 585 if (const auto &VI = Index.getValueInfo(G)) { 586 auto SL = VI.getSummaryList(); 587 if (!SL.empty()) 588 return SL[0]->getSummaryKind() == GlobalValueSummary::GlobalVarKind; 589 } 590 return false; 591 } 592 593 static GlobalValue::GUID getGUID(GlobalValue::GUID G) { return G; } 594 595 template <class T> 596 static unsigned numGlobalVarSummaries(const ModuleSummaryIndex &Index, 597 T &Cont) { 598 unsigned NumGVS = 0; 599 for (auto &V : Cont) 600 if (isGlobalVarSummary(Index, getGUID(V))) 601 ++NumGVS; 602 return NumGVS; 603 } 604 #endif 605 606 /// Compute all the import and export for every module using the Index. 607 void llvm::ComputeCrossModuleImport( 608 const ModuleSummaryIndex &Index, 609 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries, 610 StringMap<FunctionImporter::ImportMapTy> &ImportLists, 611 StringMap<FunctionImporter::ExportSetTy> &ExportLists) { 612 // For each module that has function defined, compute the import/export lists. 613 for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) { 614 auto &ImportList = ImportLists[DefinedGVSummaries.first()]; 615 LLVM_DEBUG(dbgs() << "Computing import for Module '" 616 << DefinedGVSummaries.first() << "'\n"); 617 ComputeImportForModule(DefinedGVSummaries.second, Index, 618 DefinedGVSummaries.first(), ImportList, 619 &ExportLists); 620 } 621 622 // When computing imports we added all GUIDs referenced by anything 623 // imported from the module to its ExportList. Now we prune each ExportList 624 // of any not defined in that module. This is more efficient than checking 625 // while computing imports because some of the summary lists may be long 626 // due to linkonce (comdat) copies. 627 for (auto &ELI : ExportLists) { 628 const auto &DefinedGVSummaries = 629 ModuleToDefinedGVSummaries.lookup(ELI.first()); 630 for (auto EI = ELI.second.begin(); EI != ELI.second.end();) { 631 if (!DefinedGVSummaries.count(*EI)) 632 EI = ELI.second.erase(EI); 633 else 634 ++EI; 635 } 636 } 637 638 #ifndef NDEBUG 639 LLVM_DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size() 640 << " modules:\n"); 641 for (auto &ModuleImports : ImportLists) { 642 auto ModName = ModuleImports.first(); 643 auto &Exports = ExportLists[ModName]; 644 unsigned NumGVS = numGlobalVarSummaries(Index, Exports); 645 LLVM_DEBUG(dbgs() << "* Module " << ModName << " exports " 646 << Exports.size() - NumGVS << " functions and " << NumGVS 647 << " vars. Imports from " << ModuleImports.second.size() 648 << " modules.\n"); 649 for (auto &Src : ModuleImports.second) { 650 auto SrcModName = Src.first(); 651 unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second); 652 LLVM_DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod 653 << " functions imported from " << SrcModName << "\n"); 654 LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod 655 << " global vars imported from " << SrcModName << "\n"); 656 } 657 } 658 #endif 659 } 660 661 #ifndef NDEBUG 662 static void dumpImportListForModule(const ModuleSummaryIndex &Index, 663 StringRef ModulePath, 664 FunctionImporter::ImportMapTy &ImportList) { 665 LLVM_DEBUG(dbgs() << "* Module " << ModulePath << " imports from " 666 << ImportList.size() << " modules.\n"); 667 for (auto &Src : ImportList) { 668 auto SrcModName = Src.first(); 669 unsigned NumGVSPerMod = numGlobalVarSummaries(Index, Src.second); 670 LLVM_DEBUG(dbgs() << " - " << Src.second.size() - NumGVSPerMod 671 << " functions imported from " << SrcModName << "\n"); 672 LLVM_DEBUG(dbgs() << " - " << NumGVSPerMod << " vars imported from " 673 << SrcModName << "\n"); 674 } 675 } 676 #endif 677 678 /// Compute all the imports for the given module in the Index. 679 void llvm::ComputeCrossModuleImportForModule( 680 StringRef ModulePath, const ModuleSummaryIndex &Index, 681 FunctionImporter::ImportMapTy &ImportList) { 682 // Collect the list of functions this module defines. 683 // GUID -> Summary 684 GVSummaryMapTy FunctionSummaryMap; 685 Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap); 686 687 // Compute the import list for this module. 688 LLVM_DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n"); 689 ComputeImportForModule(FunctionSummaryMap, Index, ModulePath, ImportList); 690 691 #ifndef NDEBUG 692 dumpImportListForModule(Index, ModulePath, ImportList); 693 #endif 694 } 695 696 // Mark all external summaries in Index for import into the given module. 697 // Used for distributed builds using a distributed index. 698 void llvm::ComputeCrossModuleImportForModuleFromIndex( 699 StringRef ModulePath, const ModuleSummaryIndex &Index, 700 FunctionImporter::ImportMapTy &ImportList) { 701 for (auto &GlobalList : Index) { 702 // Ignore entries for undefined references. 703 if (GlobalList.second.SummaryList.empty()) 704 continue; 705 706 auto GUID = GlobalList.first; 707 assert(GlobalList.second.SummaryList.size() == 1 && 708 "Expected individual combined index to have one summary per GUID"); 709 auto &Summary = GlobalList.second.SummaryList[0]; 710 // Skip the summaries for the importing module. These are included to 711 // e.g. record required linkage changes. 712 if (Summary->modulePath() == ModulePath) 713 continue; 714 // Add an entry to provoke importing by thinBackend. 715 ImportList[Summary->modulePath()].insert(GUID); 716 } 717 #ifndef NDEBUG 718 dumpImportListForModule(Index, ModulePath, ImportList); 719 #endif 720 } 721 722 void llvm::computeDeadSymbols( 723 ModuleSummaryIndex &Index, 724 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols, 725 function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing) { 726 assert(!Index.withGlobalValueDeadStripping()); 727 if (!ComputeDead) 728 return; 729 if (GUIDPreservedSymbols.empty()) 730 // Don't do anything when nothing is live, this is friendly with tests. 731 return; 732 unsigned LiveSymbols = 0; 733 SmallVector<ValueInfo, 128> Worklist; 734 Worklist.reserve(GUIDPreservedSymbols.size() * 2); 735 for (auto GUID : GUIDPreservedSymbols) { 736 ValueInfo VI = Index.getValueInfo(GUID); 737 if (!VI) 738 continue; 739 for (auto &S : VI.getSummaryList()) 740 S->setLive(true); 741 } 742 743 // Add values flagged in the index as live roots to the worklist. 744 for (const auto &Entry : Index) { 745 auto VI = Index.getValueInfo(Entry); 746 for (auto &S : Entry.second.SummaryList) 747 if (S->isLive()) { 748 LLVM_DEBUG(dbgs() << "Live root: " << VI << "\n"); 749 Worklist.push_back(VI); 750 ++LiveSymbols; 751 break; 752 } 753 } 754 755 // Make value live and add it to the worklist if it was not live before. 756 auto visit = [&](ValueInfo VI) { 757 // FIXME: If we knew which edges were created for indirect call profiles, 758 // we could skip them here. Any that are live should be reached via 759 // other edges, e.g. reference edges. Otherwise, using a profile collected 760 // on a slightly different binary might provoke preserving, importing 761 // and ultimately promoting calls to functions not linked into this 762 // binary, which increases the binary size unnecessarily. Note that 763 // if this code changes, the importer needs to change so that edges 764 // to functions marked dead are skipped. 765 VI = updateValueInfoForIndirectCalls(Index, VI); 766 if (!VI) 767 return; 768 for (auto &S : VI.getSummaryList()) 769 if (S->isLive()) 770 return; 771 772 // We only keep live symbols that are known to be non-prevailing if any are 773 // available_externally, linkonceodr, weakodr. Those symbols are discarded 774 // later in the EliminateAvailableExternally pass and setting them to 775 // not-live could break downstreams users of liveness information (PR36483) 776 // or limit optimization opportunities. 777 if (isPrevailing(VI.getGUID()) == PrevailingType::No) { 778 bool KeepAliveLinkage = false; 779 bool Interposable = false; 780 for (auto &S : VI.getSummaryList()) { 781 if (S->linkage() == GlobalValue::AvailableExternallyLinkage || 782 S->linkage() == GlobalValue::WeakODRLinkage || 783 S->linkage() == GlobalValue::LinkOnceODRLinkage) 784 KeepAliveLinkage = true; 785 else if (GlobalValue::isInterposableLinkage(S->linkage())) 786 Interposable = true; 787 } 788 789 if (!KeepAliveLinkage) 790 return; 791 792 if (Interposable) 793 report_fatal_error( 794 "Interposable and available_externally/linkonce_odr/weak_odr symbol"); 795 } 796 797 for (auto &S : VI.getSummaryList()) 798 S->setLive(true); 799 ++LiveSymbols; 800 Worklist.push_back(VI); 801 }; 802 803 while (!Worklist.empty()) { 804 auto VI = Worklist.pop_back_val(); 805 for (auto &Summary : VI.getSummaryList()) { 806 GlobalValueSummary *Base = Summary->getBaseObject(); 807 // Set base value live in case it is an alias. 808 Base->setLive(true); 809 for (auto Ref : Base->refs()) 810 visit(Ref); 811 if (auto *FS = dyn_cast<FunctionSummary>(Base)) 812 for (auto Call : FS->calls()) 813 visit(Call.first); 814 } 815 } 816 Index.setWithGlobalValueDeadStripping(); 817 818 unsigned DeadSymbols = Index.size() - LiveSymbols; 819 LLVM_DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols 820 << " symbols Dead \n"); 821 NumDeadSymbols += DeadSymbols; 822 NumLiveSymbols += LiveSymbols; 823 } 824 825 // Compute dead symbols and propagate constants in combined index. 826 void llvm::computeDeadSymbolsWithConstProp( 827 ModuleSummaryIndex &Index, 828 const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols, 829 function_ref<PrevailingType(GlobalValue::GUID)> isPrevailing, 830 bool ImportEnabled) { 831 computeDeadSymbols(Index, GUIDPreservedSymbols, isPrevailing); 832 if (ImportEnabled) { 833 Index.propagateConstants(GUIDPreservedSymbols); 834 } else { 835 // If import is disabled we should drop read-only attribute 836 // from all summaries to prevent internalization. 837 for (auto &P : Index) 838 for (auto &S : P.second.SummaryList) 839 if (auto *GVS = dyn_cast<GlobalVarSummary>(S.get())) 840 GVS->setReadOnly(false); 841 } 842 } 843 844 /// Compute the set of summaries needed for a ThinLTO backend compilation of 845 /// \p ModulePath. 846 void llvm::gatherImportedSummariesForModule( 847 StringRef ModulePath, 848 const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries, 849 const FunctionImporter::ImportMapTy &ImportList, 850 std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) { 851 // Include all summaries from the importing module. 852 ModuleToSummariesForIndex[ModulePath] = 853 ModuleToDefinedGVSummaries.lookup(ModulePath); 854 // Include summaries for imports. 855 for (auto &ILI : ImportList) { 856 auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()]; 857 const auto &DefinedGVSummaries = 858 ModuleToDefinedGVSummaries.lookup(ILI.first()); 859 for (auto &GI : ILI.second) { 860 const auto &DS = DefinedGVSummaries.find(GI); 861 assert(DS != DefinedGVSummaries.end() && 862 "Expected a defined summary for imported global value"); 863 SummariesForIndex[GI] = DS->second; 864 } 865 } 866 } 867 868 /// Emit the files \p ModulePath will import from into \p OutputFilename. 869 std::error_code llvm::EmitImportsFiles( 870 StringRef ModulePath, StringRef OutputFilename, 871 const std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) { 872 std::error_code EC; 873 raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None); 874 if (EC) 875 return EC; 876 for (auto &ILI : ModuleToSummariesForIndex) 877 // The ModuleToSummariesForIndex map includes an entry for the current 878 // Module (needed for writing out the index files). We don't want to 879 // include it in the imports file, however, so filter it out. 880 if (ILI.first != ModulePath) 881 ImportsOS << ILI.first << "\n"; 882 return std::error_code(); 883 } 884 885 bool llvm::convertToDeclaration(GlobalValue &GV) { 886 LLVM_DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName() 887 << "\n"); 888 if (Function *F = dyn_cast<Function>(&GV)) { 889 F->deleteBody(); 890 F->clearMetadata(); 891 F->setComdat(nullptr); 892 } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) { 893 V->setInitializer(nullptr); 894 V->setLinkage(GlobalValue::ExternalLinkage); 895 V->clearMetadata(); 896 V->setComdat(nullptr); 897 } else { 898 GlobalValue *NewGV; 899 if (GV.getValueType()->isFunctionTy()) 900 NewGV = 901 Function::Create(cast<FunctionType>(GV.getValueType()), 902 GlobalValue::ExternalLinkage, "", GV.getParent()); 903 else 904 NewGV = 905 new GlobalVariable(*GV.getParent(), GV.getValueType(), 906 /*isConstant*/ false, GlobalValue::ExternalLinkage, 907 /*init*/ nullptr, "", 908 /*insertbefore*/ nullptr, GV.getThreadLocalMode(), 909 GV.getType()->getAddressSpace()); 910 NewGV->takeName(&GV); 911 GV.replaceAllUsesWith(NewGV); 912 return false; 913 } 914 return true; 915 } 916 917 /// Fixup prevailing symbol linkages in \p TheModule based on summary analysis. 918 void llvm::thinLTOResolvePrevailingInModule( 919 Module &TheModule, const GVSummaryMapTy &DefinedGlobals) { 920 auto updateLinkage = [&](GlobalValue &GV) { 921 // See if the global summary analysis computed a new resolved linkage. 922 const auto &GS = DefinedGlobals.find(GV.getGUID()); 923 if (GS == DefinedGlobals.end()) 924 return; 925 auto NewLinkage = GS->second->linkage(); 926 if (NewLinkage == GV.getLinkage()) 927 return; 928 929 // Switch the linkage to weakany if asked for, e.g. we do this for 930 // linker redefined symbols (via --wrap or --defsym). 931 // We record that the visibility should be changed here in `addThinLTO` 932 // as we need access to the resolution vectors for each input file in 933 // order to find which symbols have been redefined. 934 // We may consider reorganizing this code and moving the linkage recording 935 // somewhere else, e.g. in thinLTOResolvePrevailingInIndex. 936 if (NewLinkage == GlobalValue::WeakAnyLinkage) { 937 GV.setLinkage(NewLinkage); 938 return; 939 } 940 941 if (GlobalValue::isLocalLinkage(GV.getLinkage()) || 942 // In case it was dead and already converted to declaration. 943 GV.isDeclaration()) 944 return; 945 // Check for a non-prevailing def that has interposable linkage 946 // (e.g. non-odr weak or linkonce). In that case we can't simply 947 // convert to available_externally, since it would lose the 948 // interposable property and possibly get inlined. Simply drop 949 // the definition in that case. 950 if (GlobalValue::isAvailableExternallyLinkage(NewLinkage) && 951 GlobalValue::isInterposableLinkage(GV.getLinkage())) { 952 if (!convertToDeclaration(GV)) 953 // FIXME: Change this to collect replaced GVs and later erase 954 // them from the parent module once thinLTOResolvePrevailingGUID is 955 // changed to enable this for aliases. 956 llvm_unreachable("Expected GV to be converted"); 957 } else { 958 // If the original symbols has global unnamed addr and linkonce_odr linkage, 959 // it should be an auto hide symbol. Add hidden visibility to the symbol to 960 // preserve the property. 961 if (GV.hasLinkOnceODRLinkage() && GV.hasGlobalUnnamedAddr() && 962 NewLinkage == GlobalValue::WeakODRLinkage) 963 GV.setVisibility(GlobalValue::HiddenVisibility); 964 965 LLVM_DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() 966 << "` from " << GV.getLinkage() << " to " << NewLinkage 967 << "\n"); 968 GV.setLinkage(NewLinkage); 969 } 970 // Remove declarations from comdats, including available_externally 971 // as this is a declaration for the linker, and will be dropped eventually. 972 // It is illegal for comdats to contain declarations. 973 auto *GO = dyn_cast_or_null<GlobalObject>(&GV); 974 if (GO && GO->isDeclarationForLinker() && GO->hasComdat()) 975 GO->setComdat(nullptr); 976 }; 977 978 // Process functions and global now 979 for (auto &GV : TheModule) 980 updateLinkage(GV); 981 for (auto &GV : TheModule.globals()) 982 updateLinkage(GV); 983 for (auto &GV : TheModule.aliases()) 984 updateLinkage(GV); 985 } 986 987 /// Run internalization on \p TheModule based on symmary analysis. 988 void llvm::thinLTOInternalizeModule(Module &TheModule, 989 const GVSummaryMapTy &DefinedGlobals) { 990 // Declare a callback for the internalize pass that will ask for every 991 // candidate GlobalValue if it can be internalized or not. 992 auto MustPreserveGV = [&](const GlobalValue &GV) -> bool { 993 // Lookup the linkage recorded in the summaries during global analysis. 994 auto GS = DefinedGlobals.find(GV.getGUID()); 995 if (GS == DefinedGlobals.end()) { 996 // Must have been promoted (possibly conservatively). Find original 997 // name so that we can access the correct summary and see if it can 998 // be internalized again. 999 // FIXME: Eventually we should control promotion instead of promoting 1000 // and internalizing again. 1001 StringRef OrigName = 1002 ModuleSummaryIndex::getOriginalNameBeforePromote(GV.getName()); 1003 std::string OrigId = GlobalValue::getGlobalIdentifier( 1004 OrigName, GlobalValue::InternalLinkage, 1005 TheModule.getSourceFileName()); 1006 GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId)); 1007 if (GS == DefinedGlobals.end()) { 1008 // Also check the original non-promoted non-globalized name. In some 1009 // cases a preempted weak value is linked in as a local copy because 1010 // it is referenced by an alias (IRLinker::linkGlobalValueProto). 1011 // In that case, since it was originally not a local value, it was 1012 // recorded in the index using the original name. 1013 // FIXME: This may not be needed once PR27866 is fixed. 1014 GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName)); 1015 assert(GS != DefinedGlobals.end()); 1016 } 1017 } 1018 return !GlobalValue::isLocalLinkage(GS->second->linkage()); 1019 }; 1020 1021 // FIXME: See if we can just internalize directly here via linkage changes 1022 // based on the index, rather than invoking internalizeModule. 1023 internalizeModule(TheModule, MustPreserveGV); 1024 } 1025 1026 /// Make alias a clone of its aliasee. 1027 static Function *replaceAliasWithAliasee(Module *SrcModule, GlobalAlias *GA) { 1028 Function *Fn = cast<Function>(GA->getBaseObject()); 1029 1030 ValueToValueMapTy VMap; 1031 Function *NewFn = CloneFunction(Fn, VMap); 1032 // Clone should use the original alias's linkage and name, and we ensure 1033 // all uses of alias instead use the new clone (casted if necessary). 1034 NewFn->setLinkage(GA->getLinkage()); 1035 GA->replaceAllUsesWith(ConstantExpr::getBitCast(NewFn, GA->getType())); 1036 NewFn->takeName(GA); 1037 return NewFn; 1038 } 1039 1040 // Internalize values that we marked with specific attribute 1041 // in processGlobalForThinLTO. 1042 static void internalizeImmutableGVs(Module &M) { 1043 for (auto &GV : M.globals()) 1044 // Skip GVs which have been converted to declarations 1045 // by dropDeadSymbols. 1046 if (!GV.isDeclaration() && GV.hasAttribute("thinlto-internalize")) { 1047 GV.setLinkage(GlobalValue::InternalLinkage); 1048 GV.setVisibility(GlobalValue::DefaultVisibility); 1049 } 1050 } 1051 1052 // Automatically import functions in Module \p DestModule based on the summaries 1053 // index. 1054 Expected<bool> FunctionImporter::importFunctions( 1055 Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) { 1056 LLVM_DEBUG(dbgs() << "Starting import for Module " 1057 << DestModule.getModuleIdentifier() << "\n"); 1058 unsigned ImportedCount = 0, ImportedGVCount = 0; 1059 1060 IRMover Mover(DestModule); 1061 // Do the actual import of functions now, one Module at a time 1062 std::set<StringRef> ModuleNameOrderedList; 1063 for (auto &FunctionsToImportPerModule : ImportList) { 1064 ModuleNameOrderedList.insert(FunctionsToImportPerModule.first()); 1065 } 1066 for (auto &Name : ModuleNameOrderedList) { 1067 // Get the module for the import 1068 const auto &FunctionsToImportPerModule = ImportList.find(Name); 1069 assert(FunctionsToImportPerModule != ImportList.end()); 1070 Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name); 1071 if (!SrcModuleOrErr) 1072 return SrcModuleOrErr.takeError(); 1073 std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr); 1074 assert(&DestModule.getContext() == &SrcModule->getContext() && 1075 "Context mismatch"); 1076 1077 // If modules were created with lazy metadata loading, materialize it 1078 // now, before linking it (otherwise this will be a noop). 1079 if (Error Err = SrcModule->materializeMetadata()) 1080 return std::move(Err); 1081 1082 auto &ImportGUIDs = FunctionsToImportPerModule->second; 1083 // Find the globals to import 1084 SetVector<GlobalValue *> GlobalsToImport; 1085 for (Function &F : *SrcModule) { 1086 if (!F.hasName()) 1087 continue; 1088 auto GUID = F.getGUID(); 1089 auto Import = ImportGUIDs.count(GUID); 1090 LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " 1091 << GUID << " " << F.getName() << " from " 1092 << SrcModule->getSourceFileName() << "\n"); 1093 if (Import) { 1094 if (Error Err = F.materialize()) 1095 return std::move(Err); 1096 if (EnableImportMetadata) { 1097 // Add 'thinlto_src_module' metadata for statistics and debugging. 1098 F.setMetadata( 1099 "thinlto_src_module", 1100 MDNode::get(DestModule.getContext(), 1101 {MDString::get(DestModule.getContext(), 1102 SrcModule->getSourceFileName())})); 1103 } 1104 GlobalsToImport.insert(&F); 1105 } 1106 } 1107 for (GlobalVariable &GV : SrcModule->globals()) { 1108 if (!GV.hasName()) 1109 continue; 1110 auto GUID = GV.getGUID(); 1111 auto Import = ImportGUIDs.count(GUID); 1112 LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " 1113 << GUID << " " << GV.getName() << " from " 1114 << SrcModule->getSourceFileName() << "\n"); 1115 if (Import) { 1116 if (Error Err = GV.materialize()) 1117 return std::move(Err); 1118 ImportedGVCount += GlobalsToImport.insert(&GV); 1119 } 1120 } 1121 for (GlobalAlias &GA : SrcModule->aliases()) { 1122 if (!GA.hasName()) 1123 continue; 1124 auto GUID = GA.getGUID(); 1125 auto Import = ImportGUIDs.count(GUID); 1126 LLVM_DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing alias " 1127 << GUID << " " << GA.getName() << " from " 1128 << SrcModule->getSourceFileName() << "\n"); 1129 if (Import) { 1130 if (Error Err = GA.materialize()) 1131 return std::move(Err); 1132 // Import alias as a copy of its aliasee. 1133 GlobalObject *Base = GA.getBaseObject(); 1134 if (Error Err = Base->materialize()) 1135 return std::move(Err); 1136 auto *Fn = replaceAliasWithAliasee(SrcModule.get(), &GA); 1137 LLVM_DEBUG(dbgs() << "Is importing aliasee fn " << Base->getGUID() 1138 << " " << Base->getName() << " from " 1139 << SrcModule->getSourceFileName() << "\n"); 1140 if (EnableImportMetadata) { 1141 // Add 'thinlto_src_module' metadata for statistics and debugging. 1142 Fn->setMetadata( 1143 "thinlto_src_module", 1144 MDNode::get(DestModule.getContext(), 1145 {MDString::get(DestModule.getContext(), 1146 SrcModule->getSourceFileName())})); 1147 } 1148 GlobalsToImport.insert(Fn); 1149 } 1150 } 1151 1152 // Upgrade debug info after we're done materializing all the globals and we 1153 // have loaded all the required metadata! 1154 UpgradeDebugInfo(*SrcModule); 1155 1156 // Link in the specified functions. 1157 if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport)) 1158 return true; 1159 1160 if (PrintImports) { 1161 for (const auto *GV : GlobalsToImport) 1162 dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName() 1163 << " from " << SrcModule->getSourceFileName() << "\n"; 1164 } 1165 1166 if (Mover.move(std::move(SrcModule), GlobalsToImport.getArrayRef(), 1167 [](GlobalValue &, IRMover::ValueAdder) {}, 1168 /*IsPerformingImport=*/true)) 1169 report_fatal_error("Function Import: link error"); 1170 1171 ImportedCount += GlobalsToImport.size(); 1172 NumImportedModules++; 1173 } 1174 1175 internalizeImmutableGVs(DestModule); 1176 1177 NumImportedFunctions += (ImportedCount - ImportedGVCount); 1178 NumImportedGlobalVars += ImportedGVCount; 1179 1180 LLVM_DEBUG(dbgs() << "Imported " << ImportedCount - ImportedGVCount 1181 << " functions for Module " 1182 << DestModule.getModuleIdentifier() << "\n"); 1183 LLVM_DEBUG(dbgs() << "Imported " << ImportedGVCount 1184 << " global variables for Module " 1185 << DestModule.getModuleIdentifier() << "\n"); 1186 return ImportedCount; 1187 } 1188 1189 static bool doImportingForModule(Module &M) { 1190 if (SummaryFile.empty()) 1191 report_fatal_error("error: -function-import requires -summary-file\n"); 1192 Expected<std::unique_ptr<ModuleSummaryIndex>> IndexPtrOrErr = 1193 getModuleSummaryIndexForFile(SummaryFile); 1194 if (!IndexPtrOrErr) { 1195 logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(), 1196 "Error loading file '" + SummaryFile + "': "); 1197 return false; 1198 } 1199 std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr); 1200 1201 // First step is collecting the import list. 1202 FunctionImporter::ImportMapTy ImportList; 1203 // If requested, simply import all functions in the index. This is used 1204 // when testing distributed backend handling via the opt tool, when 1205 // we have distributed indexes containing exactly the summaries to import. 1206 if (ImportAllIndex) 1207 ComputeCrossModuleImportForModuleFromIndex(M.getModuleIdentifier(), *Index, 1208 ImportList); 1209 else 1210 ComputeCrossModuleImportForModule(M.getModuleIdentifier(), *Index, 1211 ImportList); 1212 1213 // Conservatively mark all internal values as promoted. This interface is 1214 // only used when doing importing via the function importing pass. The pass 1215 // is only enabled when testing importing via the 'opt' tool, which does 1216 // not do the ThinLink that would normally determine what values to promote. 1217 for (auto &I : *Index) { 1218 for (auto &S : I.second.SummaryList) { 1219 if (GlobalValue::isLocalLinkage(S->linkage())) 1220 S->setLinkage(GlobalValue::ExternalLinkage); 1221 } 1222 } 1223 1224 // Next we need to promote to global scope and rename any local values that 1225 // are potentially exported to other modules. 1226 if (renameModuleForThinLTO(M, *Index, nullptr)) { 1227 errs() << "Error renaming module\n"; 1228 return false; 1229 } 1230 1231 // Perform the import now. 1232 auto ModuleLoader = [&M](StringRef Identifier) { 1233 return loadFile(Identifier, M.getContext()); 1234 }; 1235 FunctionImporter Importer(*Index, ModuleLoader); 1236 Expected<bool> Result = Importer.importFunctions(M, ImportList); 1237 1238 // FIXME: Probably need to propagate Errors through the pass manager. 1239 if (!Result) { 1240 logAllUnhandledErrors(Result.takeError(), errs(), 1241 "Error importing module: "); 1242 return false; 1243 } 1244 1245 return *Result; 1246 } 1247 1248 namespace { 1249 1250 /// Pass that performs cross-module function import provided a summary file. 1251 class FunctionImportLegacyPass : public ModulePass { 1252 public: 1253 /// Pass identification, replacement for typeid 1254 static char ID; 1255 1256 explicit FunctionImportLegacyPass() : ModulePass(ID) {} 1257 1258 /// Specify pass name for debug output 1259 StringRef getPassName() const override { return "Function Importing"; } 1260 1261 bool runOnModule(Module &M) override { 1262 if (skipModule(M)) 1263 return false; 1264 1265 return doImportingForModule(M); 1266 } 1267 }; 1268 1269 } // end anonymous namespace 1270 1271 PreservedAnalyses FunctionImportPass::run(Module &M, 1272 ModuleAnalysisManager &AM) { 1273 if (!doImportingForModule(M)) 1274 return PreservedAnalyses::all(); 1275 1276 return PreservedAnalyses::none(); 1277 } 1278 1279 char FunctionImportLegacyPass::ID = 0; 1280 INITIALIZE_PASS(FunctionImportLegacyPass, "function-import", 1281 "Summary Based Function Import", false, false) 1282 1283 namespace llvm { 1284 1285 Pass *createFunctionImportPass() { 1286 return new FunctionImportLegacyPass(); 1287 } 1288 1289 } // end namespace llvm 1290