LLVM  6.0.0svn
FunctionImport.cpp
Go to the documentation of this file.
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 
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/StringSet.h"
22 #include "llvm/ADT/StringRef.h"
24 #include "llvm/IR/AutoUpgrade.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/IR/GlobalAlias.h"
27 #include "llvm/IR/GlobalObject.h"
28 #include "llvm/IR/GlobalValue.h"
29 #include "llvm/IR/GlobalVariable.h"
30 #include "llvm/IR/Metadata.h"
31 #include "llvm/IR/Module.h"
33 #include "llvm/IRReader/IRReader.h"
34 #include "llvm/Linker/IRMover.h"
37 #include "llvm/Pass.h"
38 #include "llvm/Support/Casting.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/Error.h"
44 #include "llvm/Support/SourceMgr.h"
48 #include <cassert>
49 #include <memory>
50 #include <set>
51 #include <string>
52 #include <system_error>
53 #include <tuple>
54 #include <utility>
55 
56 using namespace llvm;
57 
58 #define DEBUG_TYPE "function-import"
59 
60 STATISTIC(NumImportedFunctions, "Number of functions imported");
61 STATISTIC(NumImportedModules, "Number of modules imported from");
62 STATISTIC(NumDeadSymbols, "Number of dead stripped symbols in index");
63 STATISTIC(NumLiveSymbols, "Number of live symbols in index");
64 
65 /// Limit on instruction count of imported functions.
67  "import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"),
68  cl::desc("Only import functions with less than N instructions"));
69 
70 static cl::opt<float>
71  ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7),
73  cl::desc("As we import functions, multiply the "
74  "`import-instr-limit` threshold by this factor "
75  "before processing newly imported functions"));
76 
78  "import-hot-evolution-factor", cl::init(1.0), cl::Hidden,
79  cl::value_desc("x"),
80  cl::desc("As we import functions called from hot callsite, multiply the "
81  "`import-instr-limit` threshold by this factor "
82  "before processing newly imported functions"));
83 
85  "import-hot-multiplier", cl::init(10.0), cl::Hidden, cl::value_desc("x"),
86  cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"));
87 
89  "import-critical-multiplier", cl::init(100.0), cl::Hidden,
90  cl::value_desc("x"),
91  cl::desc(
92  "Multiply the `import-instr-limit` threshold for critical callsites"));
93 
94 // FIXME: This multiplier was not really tuned up.
96  "import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"),
97  cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"));
98 
99 static cl::opt<bool> PrintImports("print-imports", cl::init(false), cl::Hidden,
100  cl::desc("Print imported functions"));
101 
102 static cl::opt<bool> ComputeDead("compute-dead", cl::init(true), cl::Hidden,
103  cl::desc("Compute dead symbols"));
104 
106  "enable-import-metadata", cl::init(
107 #if !defined(NDEBUG)
108  true /*Enabled with asserts.*/
109 #else
110  false
111 #endif
112  ),
113  cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'"));
114 
115 /// Summary file to use for function importing when using -function-import from
116 /// the command line.
118  SummaryFile("summary-file",
119  cl::desc("The summary file to use for function importing."));
120 
121 // Load lazily a module from \p FileName in \p Context.
122 static std::unique_ptr<Module> loadFile(const std::string &FileName,
123  LLVMContext &Context) {
124  SMDiagnostic Err;
125  DEBUG(dbgs() << "Loading '" << FileName << "'\n");
126  // Metadata isn't loaded until functions are imported, to minimize
127  // the memory overhead.
128  std::unique_ptr<Module> Result =
129  getLazyIRFileModule(FileName, Err, Context,
130  /* ShouldLazyLoadMetadata = */ true);
131  if (!Result) {
132  Err.print("function-import", errs());
133  report_fatal_error("Abort");
134  }
135 
136  return Result;
137 }
138 
139 /// Given a list of possible callee implementation for a call site, select one
140 /// that fits the \p Threshold.
141 ///
142 /// FIXME: select "best" instead of first that fits. But what is "best"?
143 /// - The smallest: more likely to be inlined.
144 /// - The one with the least outgoing edges (already well optimized).
145 /// - One from a module already being imported from in order to reduce the
146 /// number of source modules parsed/linked.
147 /// - One that has PGO data attached.
148 /// - [insert you fancy metric here]
149 static const GlobalValueSummary *
151  ArrayRef<std::unique_ptr<GlobalValueSummary>> CalleeSummaryList,
152  unsigned Threshold, StringRef CallerModulePath) {
153  auto It = llvm::find_if(
154  CalleeSummaryList,
155  [&](const std::unique_ptr<GlobalValueSummary> &SummaryPtr) {
156  auto *GVSummary = SummaryPtr.get();
157  // For SamplePGO, in computeImportForFunction the OriginalId
158  // may have been used to locate the callee summary list (See
159  // comment there).
160  // The mapping from OriginalId to GUID may return a GUID
161  // that corresponds to a static variable. Filter it out here.
162  // This can happen when
163  // 1) There is a call to a library function which is not defined
164  // in the index.
165  // 2) There is a static variable with the OriginalGUID identical
166  // to the GUID of the library function in 1);
167  // When this happens, the logic for SamplePGO kicks in and
168  // the static variable in 2) will be found, which needs to be
169  // filtered out.
170  if (GVSummary->getSummaryKind() == GlobalValueSummary::GlobalVarKind)
171  return false;
172  if (GlobalValue::isInterposableLinkage(GVSummary->linkage()))
173  // There is no point in importing these, we can't inline them
174  return false;
175  if (isa<AliasSummary>(GVSummary))
176  // Aliases can't point to "available_externally".
177  // FIXME: we should import alias as available_externally *function*,
178  // the destination module does not need to know it is an alias.
179  return false;
180 
181  auto *Summary = cast<FunctionSummary>(GVSummary);
182 
183  // If this is a local function, make sure we import the copy
184  // in the caller's module. The only time a local function can
185  // share an entry in the index is if there is a local with the same name
186  // in another module that had the same source file name (in a different
187  // directory), where each was compiled in their own directory so there
188  // was not distinguishing path.
189  // However, do the import from another module if there is only one
190  // entry in the list - in that case this must be a reference due
191  // to indirect call profile data, since a function pointer can point to
192  // a local in another module.
193  if (GlobalValue::isLocalLinkage(Summary->linkage()) &&
194  CalleeSummaryList.size() > 1 &&
195  Summary->modulePath() != CallerModulePath)
196  return false;
197 
198  if (Summary->instCount() > Threshold)
199  return false;
200 
201  if (Summary->notEligibleToImport())
202  return false;
203 
204  return true;
205  });
206  if (It == CalleeSummaryList.end())
207  return nullptr;
208 
209  return cast<GlobalValueSummary>(It->get());
210 }
211 
212 namespace {
213 
214 using EdgeInfo = std::tuple<const FunctionSummary *, unsigned /* Threshold */,
216 
217 } // anonymous namespace
218 
219 static ValueInfo
221  if (!VI.getSummaryList().empty())
222  return VI;
223  // For SamplePGO, the indirect call targets for local functions will
224  // have its original name annotated in profile. We try to find the
225  // corresponding PGOFuncName as the GUID.
226  // FIXME: Consider updating the edges in the graph after building
227  // it, rather than needing to perform this mapping on each walk.
228  auto GUID = Index.getGUIDFromOriginalID(VI.getGUID());
229  if (GUID == 0)
230  return nullptr;
231  return Index.getValueInfo(GUID);
232 }
233 
234 /// Compute the list of functions to import for a given caller. Mark these
235 /// imported functions and the symbols they reference in their source module as
236 /// exported from their source module.
238  const FunctionSummary &Summary, const ModuleSummaryIndex &Index,
239  const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries,
240  SmallVectorImpl<EdgeInfo> &Worklist,
241  FunctionImporter::ImportMapTy &ImportList,
242  StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
243  for (auto &Edge : Summary.calls()) {
244  ValueInfo VI = Edge.first;
245  DEBUG(dbgs() << " edge -> " << VI.getGUID() << " Threshold:" << Threshold
246  << "\n");
247 
248  VI = updateValueInfoForIndirectCalls(Index, VI);
249  if (!VI)
250  continue;
251 
252  if (DefinedGVSummaries.count(VI.getGUID())) {
253  DEBUG(dbgs() << "ignored! Target already in destination module.\n");
254  continue;
255  }
256 
257  auto GetBonusMultiplier = [](CalleeInfo::HotnessType Hotness) -> float {
258  if (Hotness == CalleeInfo::HotnessType::Hot)
259  return ImportHotMultiplier;
260  if (Hotness == CalleeInfo::HotnessType::Cold)
261  return ImportColdMultiplier;
262  if (Hotness == CalleeInfo::HotnessType::Critical)
264  return 1.0;
265  };
266 
267  const auto NewThreshold =
268  Threshold * GetBonusMultiplier(Edge.second.Hotness);
269 
270  auto *CalleeSummary = selectCallee(Index, VI.getSummaryList(), NewThreshold,
271  Summary.modulePath());
272  if (!CalleeSummary) {
273  DEBUG(dbgs() << "ignored! No qualifying callee with summary found.\n");
274  continue;
275  }
276 
277  // "Resolve" the summary
278  assert(!isa<AliasSummary>(CalleeSummary) &&
279  "Unexpected alias in import list");
280  const auto *ResolvedCalleeSummary = cast<FunctionSummary>(CalleeSummary);
281 
282  assert(ResolvedCalleeSummary->instCount() <= NewThreshold &&
283  "selectCallee() didn't honor the threshold");
284 
285  auto GetAdjustedThreshold = [](unsigned Threshold, bool IsHotCallsite) {
286  // Adjust the threshold for next level of imported functions.
287  // The threshold is different for hot callsites because we can then
288  // inline chains of hot calls.
289  if (IsHotCallsite)
290  return Threshold * ImportHotInstrFactor;
291  return Threshold * ImportInstrFactor;
292  };
293 
294  bool IsHotCallsite = Edge.second.Hotness == CalleeInfo::HotnessType::Hot;
295  const auto AdjThreshold = GetAdjustedThreshold(Threshold, IsHotCallsite);
296 
297  auto ExportModulePath = ResolvedCalleeSummary->modulePath();
298  auto &ProcessedThreshold = ImportList[ExportModulePath][VI.getGUID()];
299  /// Since the traversal of the call graph is DFS, we can revisit a function
300  /// a second time with a higher threshold. In this case, it is added back to
301  /// the worklist with the new threshold.
302  if (ProcessedThreshold && ProcessedThreshold >= AdjThreshold) {
303  DEBUG(dbgs() << "ignored! Target was already seen with Threshold "
304  << ProcessedThreshold << "\n");
305  continue;
306  }
307  bool PreviouslyImported = ProcessedThreshold != 0;
308  // Mark this function as imported in this module, with the current Threshold
309  ProcessedThreshold = AdjThreshold;
310 
311  // Make exports in the source module.
312  if (ExportLists) {
313  auto &ExportList = (*ExportLists)[ExportModulePath];
314  ExportList.insert(VI.getGUID());
315  if (!PreviouslyImported) {
316  // This is the first time this function was exported from its source
317  // module, so mark all functions and globals it references as exported
318  // to the outside if they are defined in the same source module.
319  // For efficiency, we unconditionally add all the referenced GUIDs
320  // to the ExportList for this module, and will prune out any not
321  // defined in the module later in a single pass.
322  for (auto &Edge : ResolvedCalleeSummary->calls()) {
323  auto CalleeGUID = Edge.first.getGUID();
324  ExportList.insert(CalleeGUID);
325  }
326  for (auto &Ref : ResolvedCalleeSummary->refs()) {
327  auto GUID = Ref.getGUID();
328  ExportList.insert(GUID);
329  }
330  }
331  }
332 
333  // Insert the newly imported function to the worklist.
334  Worklist.emplace_back(ResolvedCalleeSummary, AdjThreshold, VI.getGUID());
335  }
336 }
337 
338 /// Given the list of globals defined in a module, compute the list of imports
339 /// as well as the list of "exports", i.e. the list of symbols referenced from
340 /// another module (that may require promotion).
342  const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index,
343  FunctionImporter::ImportMapTy &ImportList,
344  StringMap<FunctionImporter::ExportSetTy> *ExportLists = nullptr) {
345  // Worklist contains the list of function imported in this module, for which
346  // we will analyse the callees and may import further down the callgraph.
348 
349  // Populate the worklist with the import for the functions in the current
350  // module
351  for (auto &GVSummary : DefinedGVSummaries) {
352  if (!Index.isGlobalValueLive(GVSummary.second)) {
353  DEBUG(dbgs() << "Ignores Dead GUID: " << GVSummary.first << "\n");
354  continue;
355  }
356  auto *FuncSummary =
357  dyn_cast<FunctionSummary>(GVSummary.second->getBaseObject());
358  if (!FuncSummary)
359  // Skip import for global variables
360  continue;
361  DEBUG(dbgs() << "Initialize import for " << GVSummary.first << "\n");
362  computeImportForFunction(*FuncSummary, Index, ImportInstrLimit,
363  DefinedGVSummaries, Worklist, ImportList,
364  ExportLists);
365  }
366 
367  // Process the newly imported functions and add callees to the worklist.
368  while (!Worklist.empty()) {
369  auto FuncInfo = Worklist.pop_back_val();
370  auto *Summary = std::get<0>(FuncInfo);
371  auto Threshold = std::get<1>(FuncInfo);
372  auto GUID = std::get<2>(FuncInfo);
373 
374  // Check if we later added this summary with a higher threshold.
375  // If so, skip this entry.
376  auto ExportModulePath = Summary->modulePath();
377  auto &LatestProcessedThreshold = ImportList[ExportModulePath][GUID];
378  if (LatestProcessedThreshold > Threshold)
379  continue;
380 
381  computeImportForFunction(*Summary, Index, Threshold, DefinedGVSummaries,
382  Worklist, ImportList, ExportLists);
383  }
384 }
385 
386 /// Compute all the import and export for every module using the Index.
388  const ModuleSummaryIndex &Index,
389  const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
392  // For each module that has function defined, compute the import/export lists.
393  for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
394  auto &ImportList = ImportLists[DefinedGVSummaries.first()];
395  DEBUG(dbgs() << "Computing import for Module '"
396  << DefinedGVSummaries.first() << "'\n");
397  ComputeImportForModule(DefinedGVSummaries.second, Index, ImportList,
398  &ExportLists);
399  }
400 
401  // When computing imports we added all GUIDs referenced by anything
402  // imported from the module to its ExportList. Now we prune each ExportList
403  // of any not defined in that module. This is more efficient than checking
404  // while computing imports because some of the summary lists may be long
405  // due to linkonce (comdat) copies.
406  for (auto &ELI : ExportLists) {
407  const auto &DefinedGVSummaries =
408  ModuleToDefinedGVSummaries.lookup(ELI.first());
409  for (auto EI = ELI.second.begin(); EI != ELI.second.end();) {
410  if (!DefinedGVSummaries.count(*EI))
411  EI = ELI.second.erase(EI);
412  else
413  ++EI;
414  }
415  }
416 
417 #ifndef NDEBUG
418  DEBUG(dbgs() << "Import/Export lists for " << ImportLists.size()
419  << " modules:\n");
420  for (auto &ModuleImports : ImportLists) {
421  auto ModName = ModuleImports.first();
422  auto &Exports = ExportLists[ModName];
423  DEBUG(dbgs() << "* Module " << ModName << " exports " << Exports.size()
424  << " functions. Imports from " << ModuleImports.second.size()
425  << " modules.\n");
426  for (auto &Src : ModuleImports.second) {
427  auto SrcModName = Src.first();
428  DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
429  << SrcModName << "\n");
430  }
431  }
432 #endif
433 }
434 
435 /// Compute all the imports for the given module in the Index.
437  StringRef ModulePath, const ModuleSummaryIndex &Index,
438  FunctionImporter::ImportMapTy &ImportList) {
439  // Collect the list of functions this module defines.
440  // GUID -> Summary
441  GVSummaryMapTy FunctionSummaryMap;
442  Index.collectDefinedFunctionsForModule(ModulePath, FunctionSummaryMap);
443 
444  // Compute the import list for this module.
445  DEBUG(dbgs() << "Computing import for Module '" << ModulePath << "'\n");
446  ComputeImportForModule(FunctionSummaryMap, Index, ImportList);
447 
448 #ifndef NDEBUG
449  DEBUG(dbgs() << "* Module " << ModulePath << " imports from "
450  << ImportList.size() << " modules.\n");
451  for (auto &Src : ImportList) {
452  auto SrcModName = Src.first();
453  DEBUG(dbgs() << " - " << Src.second.size() << " functions imported from "
454  << SrcModName << "\n");
455  }
456 #endif
457 }
458 
460  ModuleSummaryIndex &Index,
461  const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols) {
463  if (!ComputeDead)
464  return;
465  if (GUIDPreservedSymbols.empty())
466  // Don't do anything when nothing is live, this is friendly with tests.
467  return;
468  unsigned LiveSymbols = 0;
470  Worklist.reserve(GUIDPreservedSymbols.size() * 2);
471  for (auto GUID : GUIDPreservedSymbols) {
472  ValueInfo VI = Index.getValueInfo(GUID);
473  if (!VI)
474  continue;
475  for (auto &S : VI.getSummaryList())
476  S->setLive(true);
477  }
478 
479  // Add values flagged in the index as live roots to the worklist.
480  for (const auto &Entry : Index)
481  for (auto &S : Entry.second.SummaryList)
482  if (S->isLive()) {
483  DEBUG(dbgs() << "Live root: " << Entry.first << "\n");
484  Worklist.push_back(ValueInfo(&Entry));
485  ++LiveSymbols;
486  break;
487  }
488 
489  // Make value live and add it to the worklist if it was not live before.
490  // FIXME: we should only make the prevailing copy live here
491  auto visit = [&](ValueInfo VI) {
492  // FIXME: If we knew which edges were created for indirect call profiles,
493  // we could skip them here. Any that are live should be reached via
494  // other edges, e.g. reference edges. Otherwise, using a profile collected
495  // on a slightly different binary might provoke preserving, importing
496  // and ultimately promoting calls to functions not linked into this
497  // binary, which increases the binary size unnecessarily. Note that
498  // if this code changes, the importer needs to change so that edges
499  // to functions marked dead are skipped.
501  if (!VI)
502  return;
503  for (auto &S : VI.getSummaryList())
504  if (S->isLive())
505  return;
506  for (auto &S : VI.getSummaryList())
507  S->setLive(true);
508  ++LiveSymbols;
509  Worklist.push_back(VI);
510  };
511 
512  while (!Worklist.empty()) {
513  auto VI = Worklist.pop_back_val();
514  for (auto &Summary : VI.getSummaryList()) {
515  GlobalValueSummary *Base = Summary->getBaseObject();
516  for (auto Ref : Base->refs())
517  visit(Ref);
518  if (auto *FS = dyn_cast<FunctionSummary>(Base))
519  for (auto Call : FS->calls())
520  visit(Call.first);
521  }
522  }
523  Index.setWithGlobalValueDeadStripping();
524 
525  unsigned DeadSymbols = Index.size() - LiveSymbols;
526  DEBUG(dbgs() << LiveSymbols << " symbols Live, and " << DeadSymbols
527  << " symbols Dead \n");
528  NumDeadSymbols += DeadSymbols;
529  NumLiveSymbols += LiveSymbols;
530 }
531 
532 /// Compute the set of summaries needed for a ThinLTO backend compilation of
533 /// \p ModulePath.
535  StringRef ModulePath,
536  const StringMap<GVSummaryMapTy> &ModuleToDefinedGVSummaries,
537  const FunctionImporter::ImportMapTy &ImportList,
538  std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
539  // Include all summaries from the importing module.
540  ModuleToSummariesForIndex[ModulePath] =
541  ModuleToDefinedGVSummaries.lookup(ModulePath);
542  // Include summaries for imports.
543  for (auto &ILI : ImportList) {
544  auto &SummariesForIndex = ModuleToSummariesForIndex[ILI.first()];
545  const auto &DefinedGVSummaries =
546  ModuleToDefinedGVSummaries.lookup(ILI.first());
547  for (auto &GI : ILI.second) {
548  const auto &DS = DefinedGVSummaries.find(GI.first);
549  assert(DS != DefinedGVSummaries.end() &&
550  "Expected a defined summary for imported global value");
551  SummariesForIndex[GI.first] = DS->second;
552  }
553  }
554 }
555 
556 /// Emit the files \p ModulePath will import from into \p OutputFilename.
557 std::error_code
559  const FunctionImporter::ImportMapTy &ModuleImports) {
560  std::error_code EC;
561  raw_fd_ostream ImportsOS(OutputFilename, EC, sys::fs::OpenFlags::F_None);
562  if (EC)
563  return EC;
564  for (auto &ILI : ModuleImports)
565  ImportsOS << ILI.first() << "\n";
566  return std::error_code();
567 }
568 
569 /// Fixup WeakForLinker linkages in \p TheModule based on summary analysis.
571  Module &TheModule, const GVSummaryMapTy &DefinedGlobals) {
572  auto ConvertToDeclaration = [](GlobalValue &GV) {
573  DEBUG(dbgs() << "Converting to a declaration: `" << GV.getName() << "\n");
574  if (Function *F = dyn_cast<Function>(&GV)) {
575  F->deleteBody();
576  F->clearMetadata();
577  } else if (GlobalVariable *V = dyn_cast<GlobalVariable>(&GV)) {
578  V->setInitializer(nullptr);
579  V->setLinkage(GlobalValue::ExternalLinkage);
580  V->clearMetadata();
581  } else
582  // For now we don't resolve or drop aliases. Once we do we'll
583  // need to add support here for creating either a function or
584  // variable declaration, and return the new GlobalValue* for
585  // the caller to use.
586  llvm_unreachable("Expected function or variable");
587  };
588 
589  auto updateLinkage = [&](GlobalValue &GV) {
590  // See if the global summary analysis computed a new resolved linkage.
591  const auto &GS = DefinedGlobals.find(GV.getGUID());
592  if (GS == DefinedGlobals.end())
593  return;
594  auto NewLinkage = GS->second->linkage();
595  if (NewLinkage == GV.getLinkage())
596  return;
597 
598  // Switch the linkage to weakany if asked for, e.g. we do this for
599  // linker redefined symbols (via --wrap or --defsym).
600  // We record that the visibility should be changed here in `addThinLTO`
601  // as we need access to the resolution vectors for each input file in
602  // order to find which symbols have been redefined.
603  // We may consider reorganizing this code and moving the linkage recording
604  // somewhere else, e.g. in thinLTOResolveWeakForLinkerInIndex.
605  if (NewLinkage == GlobalValue::WeakAnyLinkage) {
606  GV.setLinkage(NewLinkage);
607  return;
608  }
609 
610  if (!GlobalValue::isWeakForLinker(GV.getLinkage()))
611  return;
612  // Check for a non-prevailing def that has interposable linkage
613  // (e.g. non-odr weak or linkonce). In that case we can't simply
614  // convert to available_externally, since it would lose the
615  // interposable property and possibly get inlined. Simply drop
616  // the definition in that case.
618  GlobalValue::isInterposableLinkage(GV.getLinkage()))
619  ConvertToDeclaration(GV);
620  else {
621  DEBUG(dbgs() << "ODR fixing up linkage for `" << GV.getName() << "` from "
622  << GV.getLinkage() << " to " << NewLinkage << "\n");
623  GV.setLinkage(NewLinkage);
624  }
625  // Remove declarations from comdats, including available_externally
626  // as this is a declaration for the linker, and will be dropped eventually.
627  // It is illegal for comdats to contain declarations.
628  auto *GO = dyn_cast_or_null<GlobalObject>(&GV);
629  if (GO && GO->isDeclarationForLinker() && GO->hasComdat())
630  GO->setComdat(nullptr);
631  };
632 
633  // Process functions and global now
634  for (auto &GV : TheModule)
635  updateLinkage(GV);
636  for (auto &GV : TheModule.globals())
637  updateLinkage(GV);
638  for (auto &GV : TheModule.aliases())
639  updateLinkage(GV);
640 }
641 
642 /// Run internalization on \p TheModule based on symmary analysis.
644  const GVSummaryMapTy &DefinedGlobals) {
645  // Parse inline ASM and collect the list of symbols that are not defined in
646  // the current module.
647  StringSet<> AsmUndefinedRefs;
649  TheModule,
650  [&AsmUndefinedRefs](StringRef Name, object::BasicSymbolRef::Flags Flags) {
652  AsmUndefinedRefs.insert(Name);
653  });
654 
655  // Declare a callback for the internalize pass that will ask for every
656  // candidate GlobalValue if it can be internalized or not.
657  auto MustPreserveGV = [&](const GlobalValue &GV) -> bool {
658  // Can't be internalized if referenced in inline asm.
659  if (AsmUndefinedRefs.count(GV.getName()))
660  return true;
661 
662  // Lookup the linkage recorded in the summaries during global analysis.
663  auto GS = DefinedGlobals.find(GV.getGUID());
664  if (GS == DefinedGlobals.end()) {
665  // Must have been promoted (possibly conservatively). Find original
666  // name so that we can access the correct summary and see if it can
667  // be internalized again.
668  // FIXME: Eventually we should control promotion instead of promoting
669  // and internalizing again.
670  StringRef OrigName =
672  std::string OrigId = GlobalValue::getGlobalIdentifier(
674  TheModule.getSourceFileName());
675  GS = DefinedGlobals.find(GlobalValue::getGUID(OrigId));
676  if (GS == DefinedGlobals.end()) {
677  // Also check the original non-promoted non-globalized name. In some
678  // cases a preempted weak value is linked in as a local copy because
679  // it is referenced by an alias (IRLinker::linkGlobalValueProto).
680  // In that case, since it was originally not a local value, it was
681  // recorded in the index using the original name.
682  // FIXME: This may not be needed once PR27866 is fixed.
683  GS = DefinedGlobals.find(GlobalValue::getGUID(OrigName));
684  assert(GS != DefinedGlobals.end());
685  }
686  }
687  return !GlobalValue::isLocalLinkage(GS->second->linkage());
688  };
689 
690  // FIXME: See if we can just internalize directly here via linkage changes
691  // based on the index, rather than invoking internalizeModule.
692  internalizeModule(TheModule, MustPreserveGV);
693 }
694 
695 // Automatically import functions in Module \p DestModule based on the summaries
696 // index.
698  Module &DestModule, const FunctionImporter::ImportMapTy &ImportList) {
699  DEBUG(dbgs() << "Starting import for Module "
700  << DestModule.getModuleIdentifier() << "\n");
701  unsigned ImportedCount = 0;
702 
703  IRMover Mover(DestModule);
704  // Do the actual import of functions now, one Module at a time
705  std::set<StringRef> ModuleNameOrderedList;
706  for (auto &FunctionsToImportPerModule : ImportList) {
707  ModuleNameOrderedList.insert(FunctionsToImportPerModule.first());
708  }
709  for (auto &Name : ModuleNameOrderedList) {
710  // Get the module for the import
711  const auto &FunctionsToImportPerModule = ImportList.find(Name);
712  assert(FunctionsToImportPerModule != ImportList.end());
713  Expected<std::unique_ptr<Module>> SrcModuleOrErr = ModuleLoader(Name);
714  if (!SrcModuleOrErr)
715  return SrcModuleOrErr.takeError();
716  std::unique_ptr<Module> SrcModule = std::move(*SrcModuleOrErr);
717  assert(&DestModule.getContext() == &SrcModule->getContext() &&
718  "Context mismatch");
719 
720  // If modules were created with lazy metadata loading, materialize it
721  // now, before linking it (otherwise this will be a noop).
722  if (Error Err = SrcModule->materializeMetadata())
723  return std::move(Err);
724 
725  auto &ImportGUIDs = FunctionsToImportPerModule->second;
726  // Find the globals to import
727  SetVector<GlobalValue *> GlobalsToImport;
728  for (Function &F : *SrcModule) {
729  if (!F.hasName())
730  continue;
731  auto GUID = F.getGUID();
732  auto Import = ImportGUIDs.count(GUID);
733  DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing function " << GUID
734  << " " << F.getName() << " from "
735  << SrcModule->getSourceFileName() << "\n");
736  if (Import) {
737  if (Error Err = F.materialize())
738  return std::move(Err);
739  if (EnableImportMetadata) {
740  // Add 'thinlto_src_module' metadata for statistics and debugging.
741  F.setMetadata(
742  "thinlto_src_module",
743  MDNode::get(DestModule.getContext(),
744  {MDString::get(DestModule.getContext(),
745  SrcModule->getSourceFileName())}));
746  }
747  GlobalsToImport.insert(&F);
748  }
749  }
750  for (GlobalVariable &GV : SrcModule->globals()) {
751  if (!GV.hasName())
752  continue;
753  auto GUID = GV.getGUID();
754  auto Import = ImportGUIDs.count(GUID);
755  DEBUG(dbgs() << (Import ? "Is" : "Not") << " importing global " << GUID
756  << " " << GV.getName() << " from "
757  << SrcModule->getSourceFileName() << "\n");
758  if (Import) {
759  if (Error Err = GV.materialize())
760  return std::move(Err);
761  GlobalsToImport.insert(&GV);
762  }
763  }
764 #ifndef NDEBUG
765  for (GlobalAlias &GA : SrcModule->aliases()) {
766  if (!GA.hasName())
767  continue;
768  auto GUID = GA.getGUID();
769  assert(!ImportGUIDs.count(GUID) && "Unexpected alias in import list");
770  DEBUG(dbgs() << "Not importing alias " << GUID
771  << " " << GA.getName() << " from "
772  << SrcModule->getSourceFileName() << "\n");
773  }
774 #endif
775 
776  // Upgrade debug info after we're done materializing all the globals and we
777  // have loaded all the required metadata!
778  UpgradeDebugInfo(*SrcModule);
779 
780  // Link in the specified functions.
781  if (renameModuleForThinLTO(*SrcModule, Index, &GlobalsToImport))
782  return true;
783 
784  if (PrintImports) {
785  for (const auto *GV : GlobalsToImport)
786  dbgs() << DestModule.getSourceFileName() << ": Import " << GV->getName()
787  << " from " << SrcModule->getSourceFileName() << "\n";
788  }
789 
790  if (Mover.move(std::move(SrcModule), GlobalsToImport.getArrayRef(),
792  /*IsPerformingImport=*/true))
793  report_fatal_error("Function Import: link error");
794 
795  ImportedCount += GlobalsToImport.size();
796  NumImportedModules++;
797  }
798 
799  NumImportedFunctions += ImportedCount;
800 
801  DEBUG(dbgs() << "Imported " << ImportedCount << " functions for Module "
802  << DestModule.getModuleIdentifier() << "\n");
803  return ImportedCount;
804 }
805 
806 static bool doImportingForModule(Module &M) {
807  if (SummaryFile.empty())
808  report_fatal_error("error: -function-import requires -summary-file\n");
811  if (!IndexPtrOrErr) {
812  logAllUnhandledErrors(IndexPtrOrErr.takeError(), errs(),
813  "Error loading file '" + SummaryFile + "': ");
814  return false;
815  }
816  std::unique_ptr<ModuleSummaryIndex> Index = std::move(*IndexPtrOrErr);
817 
818  // First step is collecting the import list.
821  ImportList);
822 
823  // Conservatively mark all internal values as promoted. This interface is
824  // only used when doing importing via the function importing pass. The pass
825  // is only enabled when testing importing via the 'opt' tool, which does
826  // not do the ThinLink that would normally determine what values to promote.
827  for (auto &I : *Index) {
828  for (auto &S : I.second.SummaryList) {
829  if (GlobalValue::isLocalLinkage(S->linkage()))
830  S->setLinkage(GlobalValue::ExternalLinkage);
831  }
832  }
833 
834  // Next we need to promote to global scope and rename any local values that
835  // are potentially exported to other modules.
836  if (renameModuleForThinLTO(M, *Index, nullptr)) {
837  errs() << "Error renaming module\n";
838  return false;
839  }
840 
841  // Perform the import now.
842  auto ModuleLoader = [&M](StringRef Identifier) {
843  return loadFile(Identifier, M.getContext());
844  };
845  FunctionImporter Importer(*Index, ModuleLoader);
846  Expected<bool> Result = Importer.importFunctions(M, ImportList);
847 
848  // FIXME: Probably need to propagate Errors through the pass manager.
849  if (!Result) {
851  "Error importing module: ");
852  return false;
853  }
854 
855  return *Result;
856 }
857 
858 namespace {
859 
860 /// Pass that performs cross-module function import provided a summary file.
861 class FunctionImportLegacyPass : public ModulePass {
862 public:
863  /// Pass identification, replacement for typeid
864  static char ID;
865 
866  explicit FunctionImportLegacyPass() : ModulePass(ID) {}
867 
868  /// Specify pass name for debug output
869  StringRef getPassName() const override { return "Function Importing"; }
870 
871  bool runOnModule(Module &M) override {
872  if (skipModule(M))
873  return false;
874 
875  return doImportingForModule(M);
876  }
877 };
878 
879 } // end anonymous namespace
880 
882  ModuleAnalysisManager &AM) {
883  if (!doImportingForModule(M))
884  return PreservedAnalyses::all();
885 
886  return PreservedAnalyses::none();
887 }
888 
890 INITIALIZE_PASS(FunctionImportLegacyPass, "function-import",
891  "Summary Based Function Import", false, false)
892 
893 namespace llvm {
894 
896  return new FunctionImportLegacyPass();
897 }
898 
899 } // end namespace llvm
static bool isInterposableLinkage(LinkageTypes Linkage)
Whether the definition of this global may be replaced by something non-equivalent at link time...
Definition: GlobalValue.h:328
Pass interface - Implemented by all &#39;passes&#39;.
Definition: Pass.h:81
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
void computeDeadSymbols(ModuleSummaryIndex &Index, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols)
Compute all the symbols that are "dead": i.e these that can&#39;t be reached in the graph from any of the...
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
LLVMContext & Context
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
Definition: GlobalValue.h:483
LLVM_ATTRIBUTE_NORETURN void report_fatal_error(Error Err, bool gen_crash_diag=true)
Report a serious error, calling any installed error handler.
Definition: Error.cpp:115
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
void print(const char *ProgName, raw_ostream &S, bool ShowColors=true, bool ShowKindLabel=true) const
Definition: SourceMgr.cpp:345
ArrayRef< T > getArrayRef() const
Definition: SetVector.h:64
size_type size() const
Determine the number of elements in the SetVector.
Definition: SetVector.h:78
ValueInfo getValueInfo(GlobalValue::GUID GUID) const
Return a ValueInfo for GUID if it exists, otherwise return ValueInfo().
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner)
Log all errors (if any) in E to OS.
Definition: Error.cpp:57
static MDString * get(LLVMContext &Context, StringRef Str)
Definition: Metadata.cpp:446
Implements a dense probed hash-table based set.
Definition: DenseSet.h:221
ArrayRef< ValueInfo > refs() const
Return the list of values referenced by this global value definition.
This file contains the declarations for metadata subclasses.
Externally visible function.
Definition: GlobalValue.h:49
static StringRef getOriginalNameBeforePromote(StringRef Name)
Helper to obtain the unpromoted name for a global value (or the original name if not promoted)...
STATISTIC(NumFunctions, "Total number of functions")
bool isGlobalValueLive(const GlobalValueSummary *GVS) const
F(f)
Error takeError()
Take ownership of the stored error.
Definition: Error.h:537
std::string getGlobalIdentifier() const
Return the modified name for this global value suitable to be used as the key for a global lookup (e...
Definition: Globals.cpp:151
void reserve(size_type N)
Definition: SmallVector.h:380
static std::unique_ptr< Module > loadFile(const std::string &FileName, LLVMContext &Context)
static bool isLocalLinkage(LinkageTypes Linkage)
Definition: GlobalValue.h:312
GlobalValue::GUID getGUID() const
unsigned size() const
Definition: StringMap.h:112
static cl::opt< unsigned > ImportInstrLimit("import-instr-limit", cl::init(100), cl::Hidden, cl::value_desc("N"), cl::desc("Only import functions with less than N instructions"))
Limit on instruction count of imported functions.
static cl::opt< float > ImportHotMultiplier("import-hot-multiplier", cl::init(10.0), cl::Hidden, cl::value_desc("x"), cl::desc("Multiply the `import-instr-limit` threshold for hot callsites"))
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:237
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:42
Tagged union holding either a T or a Error.
Definition: CachePruning.h:23
static void CollectAsmSymbols(const Module &M, function_ref< void(StringRef, object::BasicSymbolRef::Flags)> AsmSymbol)
Parse inline ASM and collect the symbols that are defined or referenced in the current module...
static cl::opt< std::string > OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"), cl::init("-"))
static void computeImportForFunction(const FunctionSummary &Summary, const ModuleSummaryIndex &Index, const unsigned Threshold, const GVSummaryMapTy &DefinedGVSummaries, SmallVectorImpl< EdgeInfo > &Worklist, FunctionImporter::ImportMapTy &ImportList, StringMap< FunctionImporter::ExportSetTy > *ExportLists=nullptr)
Compute the list of functions to import for a given caller.
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:142
Error move(std::unique_ptr< Module > Src, ArrayRef< GlobalValue *> ValuesToLink, std::function< void(GlobalValue &GV, ValueAdder Add)> AddLazyFor, bool IsPerformingImport)
Move in the provide values in ValuesToLink from Src.
Definition: IRMover.cpp:1449
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
static cl::opt< float > ImportCriticalMultiplier("import-critical-multiplier", cl::init(100.0), cl::Hidden, cl::value_desc("x"), cl::desc("Multiply the `import-instr-limit` threshold for critical callsites"))
Class to hold module path string table and global value map, and encapsulate methods for operating on...
ArrayRef< std::unique_ptr< GlobalValueSummary > > getSummaryList() const
const std::string & getSourceFileName() const
Get the module&#39;s original source file name.
Definition: Module.h:214
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
Definition: PassManager.h:156
iterator find(const_arg_type_t< KeyT > Val)
Definition: DenseMap.h:146
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata *> MDs)
Definition: Metadata.h:1164
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:406
GlobalValue::GUID getGUIDFromOriginalID(GlobalValue::GUID OriginalID) const
Return the GUID for OriginalId in the OidGuidMap.
A set of analyses that are preserved following a run of a transformation pass.
Definition: PassManager.h:153
bool renameModuleForThinLTO(Module &M, const ModuleSummaryIndex &Index, SetVector< GlobalValue *> *GlobalsToImport=nullptr)
Perform in-place global value handling on the given Module for exported local functions renamed and p...
void gatherImportedSummariesForModule(StringRef ModulePath, const StringMap< GVSummaryMapTy > &ModuleToDefinedGVSummaries, const FunctionImporter::ImportMapTy &ImportList, std::map< std::string, GVSummaryMapTy > &ModuleToSummariesForIndex)
Compute the set of summaries needed for a ThinLTO backend compilation of ModulePath.
size_type count(StringRef Key) const
count - Return 1 if the element is in the map, 0 otherwise.
Definition: StringMap.h:363
Import information from summary.
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:69
Pass * createFunctionImportPass()
This pass performs iterative function importing from other modules.
bool UpgradeDebugInfo(Module &M)
Check the debug info version number, if it is out-dated, drop the debug info.
bool isWeakForLinker() const
Definition: GlobalValue.h:447
ValueTy lookup(StringRef Key) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: StringMap.h:351
INITIALIZE_PASS(FunctionImportLegacyPass, "function-import", "Summary Based Function Import", false, false) namespace llvm
Function and variable summary information to aid decisions and implementation of importing.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition: PassManager.h:159
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
Definition: Module.h:208
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
std::pair< typename base::iterator, bool > insert(StringRef Key)
Definition: StringSet.h:38
Struct that holds a reference to a particular GUID in a global value summary.
std::unique_ptr< Module > getLazyIRFileModule(StringRef Filename, SMDiagnostic &Err, LLVMContext &Context, bool ShouldLazyLoadMetadata=false)
If the given file holds a bitcode image, return a Module for it which does lazy deserialization of fu...
Definition: IRReader.cpp:54
static cl::opt< float > ImportInstrFactor("import-instr-evolution-factor", cl::init(0.7), cl::Hidden, cl::value_desc("x"), cl::desc("As we import functions, multiply the " "`import-instr-limit` threshold by this factor " "before processing newly imported functions"))
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:864
Module.h This file contains the declarations for the Module class.
static void ComputeImportForModule(const GVSummaryMapTy &DefinedGVSummaries, const ModuleSummaryIndex &Index, FunctionImporter::ImportMapTy &ImportList, StringMap< FunctionImporter::ExportSetTy > *ExportLists=nullptr)
Given the list of globals defined in a module, compute the list of imports as well as the list of "ex...
static bool isAvailableExternallyLinkage(LinkageTypes Linkage)
Definition: GlobalValue.h:285
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:385
static bool doImportingForModule(Module &M)
std::error_code EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename, const FunctionImporter::ImportMapTy &ModuleImports)
Emit into OutputFilename the files module ModulePath will import from.
static ValueInfo updateValueInfoForIndirectCalls(const ModuleSummaryIndex &Index, ValueInfo VI)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
Definition: StringMap.h:224
Expected< std::unique_ptr< ModuleSummaryIndex > > getModuleSummaryIndexForFile(StringRef Path, bool IgnoreEmptyThinLTOIndexFile=false)
Parse the module summary index out of an IR file and return the module summary index object if found...
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
Definition: GlobalValue.h:491
static cl::opt< float > ImportColdMultiplier("import-cold-multiplier", cl::init(0), cl::Hidden, cl::value_desc("N"), cl::desc("Multiply the `import-instr-limit` threshold for cold callsites"))
#define NDEBUG
Definition: regutils.h:48
static cl::opt< bool > ComputeDead("compute-dead", cl::init(true), cl::Hidden, cl::desc("Compute dead symbols"))
bool withGlobalValueDeadStripping() const
Expected< bool > importFunctions(Module &M, const ImportMapTy &ImportList)
Import functions in Module M based on the supplied import list.
void ComputeCrossModuleImport(const ModuleSummaryIndex &Index, const StringMap< GVSummaryMapTy > &ModuleToDefinedGVSummaries, StringMap< FunctionImporter::ImportMapTy > &ImportLists, StringMap< FunctionImporter::ExportSetTy > &ExportLists)
Compute all the imports and exports for every module in the Index.
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:361
void emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:656
static cl::opt< bool > PrintImports("print-imports", cl::init(false), cl::Hidden, cl::desc("Print imported functions"))
StringRef modulePath() const
Get the path to the module containing this function.
static cl::opt< float > ImportHotInstrFactor("import-hot-evolution-factor", cl::init(1.0), cl::Hidden, cl::value_desc("x"), cl::desc("As we import functions called from hot callsite, multiply the " "`import-instr-limit` threshold by this factor " "before processing newly imported functions"))
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:61
#define I(x, y, z)
Definition: MD5.cpp:58
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
Definition: Pass.h:225
iterator end()
Definition: DenseMap.h:79
void thinLTOInternalizeModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals)
Internalize TheModule based on the information recorded in the summaries during global summary-based ...
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
ArrayRef< EdgeTy > calls() const
Return the list of <CalleeValueInfo, CalleeInfo> pairs.
Keep one copy of named function when linking (weak)
Definition: GlobalValue.h:53
Rename collisions when linking (static functions).
Definition: GlobalValue.h:56
void thinLTOResolveWeakForLinkerModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals)
Resolve WeakForLinker values in TheModule based on the information recorded in the summaries during g...
Function summary information to aid decisions and implementation of importing.
size_type count(const_arg_type_t< KeyT > Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition: DenseMap.h:141
void ComputeCrossModuleImportForModule(StringRef ModulePath, const ModuleSummaryIndex &Index, FunctionImporter::ImportMapTy &ImportList)
Compute all the imports for the given module using the Index.
static int const Threshold
TODO: Write a new FunctionPass AliasAnalysis so that it can keep a cache.
static cl::opt< std::string > SummaryFile("summary-file", cl::desc("The summary file to use for function importing."))
Summary file to use for function importing when using -function-import from the command line...
ModuleSummaryIndex.h This file contains the declarations the classes that hold the module index and s...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
std::function< void(GlobalValue &)> ValueAdder
Definition: IRMover.h:65
The function importer is automatically importing function from other modules based on the provided su...
A vector that has set insertion semantics.
Definition: SetVector.h:41
Lightweight error class with error context and mandatory checking.
Definition: Error.h:156
StringSet - A wrapper for StringMap that provides set-like functionality.
Definition: StringSet.h:28
#define DEBUG(X)
Definition: Debug.h:118
static cl::opt< bool > EnableImportMetadata("enable-import-metadata", cl::init(true), cl::Hidden, cl::desc("Enable import metadata like 'thinlto_src_module'"))
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
A container for analyses that lazily runs them and caches their results.
static const GlobalValueSummary * selectCallee(const ModuleSummaryIndex &Index, ArrayRef< std::unique_ptr< GlobalValueSummary >> CalleeSummaryList, unsigned Threshold, StringRef CallerModulePath)
Given a list of possible callee implementation for a call site, select one that fits the Threshold...
auto find_if(R &&Range, UnaryPredicate P) -> decltype(std::begin(Range))
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:795
bool internalizeModule(Module &TheModule, std::function< bool(const GlobalValue &)> MustPreserveGV, CallGraph *CG=nullptr)
Helper function to internalize functions and variables in a Module.
Definition: Internalize.h:71
void collectDefinedFunctionsForModule(StringRef ModulePath, GVSummaryMapTy &GVSummaryMap) const
Collect for the given module the list of function it defines (GUID -> Summary).
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
Definition: SourceMgr.h:233