LLVM  5.0.0
ThinLTOCodeGenerator.cpp
Go to the documentation of this file.
1 //===-ThinLTOCodeGenerator.cpp - LLVM Link Time Optimizer -----------------===//
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 the Thin Link Time Optimization library. This library is
11 // intended to be used by linker to optimize code at link time.
12 //
13 //===----------------------------------------------------------------------===//
14 
16 
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/IR/DebugInfo.h"
29 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/Mangler.h"
32 #include "llvm/IR/Verifier.h"
33 #include "llvm/IRReader/IRReader.h"
34 #include "llvm/LTO/LTO.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/Error.h"
40 #include "llvm/Support/Path.h"
41 #include "llvm/Support/SHA1.h"
44 #include "llvm/Support/Threading.h"
46 #include "llvm/Support/VCSRevision.h"
48 #include "llvm/Transforms/IPO.h"
54 
55 #include <numeric>
56 
57 using namespace llvm;
58 
59 #define DEBUG_TYPE "thinlto"
60 
61 namespace llvm {
62 // Flags -discard-value-names, defined in LTOCodeGenerator.cpp
67 }
68 
69 namespace {
70 
71 static cl::opt<int>
72  ThreadCount("threads", cl::init(llvm::heavyweight_hardware_concurrency()));
73 
74 // Simple helper to save temporary files for debug.
75 static void saveTempBitcode(const Module &TheModule, StringRef TempDir,
76  unsigned count, StringRef Suffix) {
77  if (TempDir.empty())
78  return;
79  // User asked to save temps, let dump the bitcode file after import.
80  std::string SaveTempPath = (TempDir + llvm::utostr(count) + Suffix).str();
81  std::error_code EC;
82  raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
83  if (EC)
84  report_fatal_error(Twine("Failed to open ") + SaveTempPath +
85  " to save optimized bitcode\n");
86  WriteBitcodeToFile(&TheModule, OS, /* ShouldPreserveUseListOrder */ true);
87 }
88 
89 static const GlobalValueSummary *
90 getFirstDefinitionForLinker(const GlobalValueSummaryList &GVSummaryList) {
91  // If there is any strong definition anywhere, get it.
92  auto StrongDefForLinker = llvm::find_if(
93  GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
94  auto Linkage = Summary->linkage();
97  });
98  if (StrongDefForLinker != GVSummaryList.end())
99  return StrongDefForLinker->get();
100  // Get the first *linker visible* definition for this global in the summary
101  // list.
102  auto FirstDefForLinker = llvm::find_if(
103  GVSummaryList, [](const std::unique_ptr<GlobalValueSummary> &Summary) {
104  auto Linkage = Summary->linkage();
106  });
107  // Extern templates can be emitted as available_externally.
108  if (FirstDefForLinker == GVSummaryList.end())
109  return nullptr;
110  return FirstDefForLinker->get();
111 }
112 
113 // Populate map of GUID to the prevailing copy for any multiply defined
114 // symbols. Currently assume first copy is prevailing, or any strong
115 // definition. Can be refined with Linker information in the future.
116 static void computePrevailingCopies(
117  const ModuleSummaryIndex &Index,
119  auto HasMultipleCopies = [&](const GlobalValueSummaryList &GVSummaryList) {
120  return GVSummaryList.size() > 1;
121  };
122 
123  for (auto &I : Index) {
124  if (HasMultipleCopies(I.second.SummaryList))
125  PrevailingCopy[I.first] =
126  getFirstDefinitionForLinker(I.second.SummaryList);
127  }
128 }
129 
131 generateModuleMap(const std::vector<ThinLTOBuffer> &Modules) {
132  StringMap<MemoryBufferRef> ModuleMap;
133  for (auto &ModuleBuffer : Modules) {
134  assert(ModuleMap.find(ModuleBuffer.getBufferIdentifier()) ==
135  ModuleMap.end() &&
136  "Expect unique Buffer Identifier");
137  ModuleMap[ModuleBuffer.getBufferIdentifier()] = ModuleBuffer.getMemBuffer();
138  }
139  return ModuleMap;
140 }
141 
142 static void promoteModule(Module &TheModule, const ModuleSummaryIndex &Index) {
143  if (renameModuleForThinLTO(TheModule, Index))
144  report_fatal_error("renameModuleForThinLTO failed");
145 }
146 
147 namespace {
148 class ThinLTODiagnosticInfo : public DiagnosticInfo {
149  const Twine &Msg;
150 public:
151  ThinLTODiagnosticInfo(const Twine &DiagMsg,
152  DiagnosticSeverity Severity = DS_Error)
153  : DiagnosticInfo(DK_Linker, Severity), Msg(DiagMsg) {}
154  void print(DiagnosticPrinter &DP) const override { DP << Msg; }
155 };
156 }
157 
158 /// Verify the module and strip broken debug info.
159 static void verifyLoadedModule(Module &TheModule) {
160  bool BrokenDebugInfo = false;
161  if (verifyModule(TheModule, &dbgs(),
162  LTOStripInvalidDebugInfo ? &BrokenDebugInfo : nullptr))
163  report_fatal_error("Broken module found, compilation aborted!");
164  if (BrokenDebugInfo) {
165  TheModule.getContext().diagnose(ThinLTODiagnosticInfo(
166  "Invalid debug info found, debug info will be stripped", DS_Warning));
167  StripDebugInfo(TheModule);
168  }
169 }
170 
171 static std::unique_ptr<Module>
172 loadModuleFromBuffer(const MemoryBufferRef &Buffer, LLVMContext &Context,
173  bool Lazy, bool IsImporting) {
174  SMDiagnostic Err;
175  Expected<std::unique_ptr<Module>> ModuleOrErr =
176  Lazy
177  ? getLazyBitcodeModule(Buffer, Context,
178  /* ShouldLazyLoadMetadata */ true, IsImporting)
179  : parseBitcodeFile(Buffer, Context);
180  if (!ModuleOrErr) {
181  handleAllErrors(ModuleOrErr.takeError(), [&](ErrorInfoBase &EIB) {
183  SourceMgr::DK_Error, EIB.message());
184  Err.print("ThinLTO", errs());
185  });
186  report_fatal_error("Can't load module, abort.");
187  }
188  if (!Lazy)
189  verifyLoadedModule(*ModuleOrErr.get());
190  return std::move(ModuleOrErr.get());
191 }
192 
193 static void
194 crossImportIntoModule(Module &TheModule, const ModuleSummaryIndex &Index,
195  StringMap<MemoryBufferRef> &ModuleMap,
196  const FunctionImporter::ImportMapTy &ImportList) {
197  auto Loader = [&](StringRef Identifier) {
198  return loadModuleFromBuffer(ModuleMap[Identifier], TheModule.getContext(),
199  /*Lazy=*/true, /*IsImporting*/ true);
200  };
201 
202  FunctionImporter Importer(Index, Loader);
203  Expected<bool> Result = Importer.importFunctions(TheModule, ImportList);
204  if (!Result) {
205  handleAllErrors(Result.takeError(), [&](ErrorInfoBase &EIB) {
207  SourceMgr::DK_Error, EIB.message());
208  Err.print("ThinLTO", errs());
209  });
210  report_fatal_error("importFunctions failed");
211  }
212  // Verify again after cross-importing.
213  verifyLoadedModule(TheModule);
214 }
215 
216 static void optimizeModule(Module &TheModule, TargetMachine &TM,
217  unsigned OptLevel, bool Freestanding) {
218  // Populate the PassManager
219  PassManagerBuilder PMB;
221  if (Freestanding)
224  // FIXME: should get it from the bitcode?
225  PMB.OptLevel = OptLevel;
226  PMB.LoopVectorize = true;
227  PMB.SLPVectorize = true;
228  // Already did this in verifyLoadedModule().
229  PMB.VerifyInput = false;
230  PMB.VerifyOutput = false;
231 
233 
234  // Add the TTI (required to inform the vectorizer about register size for
235  // instance)
237 
238  // Add optimizations
240 
241  PM.run(TheModule);
242 }
243 
244 // Convert the PreservedSymbols map from "Name" based to "GUID" based.
246 computeGUIDPreservedSymbols(const StringSet<> &PreservedSymbols,
247  const Triple &TheTriple) {
248  DenseSet<GlobalValue::GUID> GUIDPreservedSymbols(PreservedSymbols.size());
249  for (auto &Entry : PreservedSymbols) {
250  StringRef Name = Entry.first();
251  if (TheTriple.isOSBinFormatMachO() && Name.size() > 0 && Name[0] == '_')
252  Name = Name.drop_front();
253  GUIDPreservedSymbols.insert(GlobalValue::getGUID(Name));
254  }
255  return GUIDPreservedSymbols;
256 }
257 
258 std::unique_ptr<MemoryBuffer> codegenModule(Module &TheModule,
259  TargetMachine &TM) {
260  SmallVector<char, 128> OutputBuffer;
261 
262  // CodeGen
263  {
264  raw_svector_ostream OS(OutputBuffer);
266 
267  // If the bitcode files contain ARC code and were compiled with optimization,
268  // the ObjCARCContractPass must be run, so do it unconditionally here.
270 
271  // Setup the codegen now.
273  /* DisableVerify */ true))
274  report_fatal_error("Failed to setup codegen");
275 
276  // Run codegen now. resulting binary is in OutputBuffer.
277  PM.run(TheModule);
278  }
279  return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
280 }
281 
282 /// Manage caching for a single Module.
283 class ModuleCacheEntry {
284  SmallString<128> EntryPath;
285 
286 public:
287  // Create a cache entry. This compute a unique hash for the Module considering
288  // the current list of export/import, and offer an interface to query to
289  // access the content in the cache.
290  ModuleCacheEntry(
291  StringRef CachePath, const ModuleSummaryIndex &Index, StringRef ModuleID,
292  const FunctionImporter::ImportMapTy &ImportList,
293  const FunctionImporter::ExportSetTy &ExportList,
294  const std::map<GlobalValue::GUID, GlobalValue::LinkageTypes> &ResolvedODR,
295  const GVSummaryMapTy &DefinedFunctions,
296  const DenseSet<GlobalValue::GUID> &PreservedSymbols, unsigned OptLevel,
297  bool Freestanding, const TargetMachineBuilder &TMBuilder) {
298  if (CachePath.empty())
299  return;
300 
301  if (!Index.modulePaths().count(ModuleID))
302  // The module does not have an entry, it can't have a hash at all
303  return;
304 
305  // Compute the unique hash for this entry
306  // This is based on the current compiler version, the module itself, the
307  // export list, the hash for every single module in the import list, the
308  // list of ResolvedODR for the module, and the list of preserved symbols.
309 
310  // Include the hash for the current module
311  auto ModHash = Index.getModuleHash(ModuleID);
312 
313  if (all_of(ModHash, [](uint32_t V) { return V == 0; }))
314  // No hash entry, no caching!
315  return;
316 
317  SHA1 Hasher;
318 
319  // Include the parts of the LTO configuration that affect code generation.
320  auto AddString = [&](StringRef Str) {
321  Hasher.update(Str);
322  Hasher.update(ArrayRef<uint8_t>{0});
323  };
324  auto AddUnsigned = [&](unsigned I) {
325  uint8_t Data[4];
326  Data[0] = I;
327  Data[1] = I >> 8;
328  Data[2] = I >> 16;
329  Data[3] = I >> 24;
330  Hasher.update(ArrayRef<uint8_t>{Data, 4});
331  };
332 
333  // Start with the compiler revision
334  Hasher.update(LLVM_VERSION_STRING);
335 #ifdef LLVM_REVISION
336  Hasher.update(LLVM_REVISION);
337 #endif
338 
339  // Hash the optimization level and the target machine settings.
340  AddString(TMBuilder.MCpu);
341  // FIXME: Hash more of Options. For now all clients initialize Options from
342  // command-line flags (which is unsupported in production), but may set
343  // RelaxELFRelocations. The clang driver can also pass FunctionSections,
344  // DataSections and DebuggerTuning via command line flags.
345  AddUnsigned(TMBuilder.Options.RelaxELFRelocations);
346  AddUnsigned(TMBuilder.Options.FunctionSections);
347  AddUnsigned(TMBuilder.Options.DataSections);
348  AddUnsigned((unsigned)TMBuilder.Options.DebuggerTuning);
349  AddString(TMBuilder.MAttr);
350  if (TMBuilder.RelocModel)
351  AddUnsigned(*TMBuilder.RelocModel);
352  AddUnsigned(TMBuilder.CGOptLevel);
353  AddUnsigned(OptLevel);
354  AddUnsigned(Freestanding);
355 
356  Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
357  for (auto F : ExportList)
358  // The export list can impact the internalization, be conservative here
359  Hasher.update(ArrayRef<uint8_t>((uint8_t *)&F, sizeof(F)));
360 
361  // Include the hash for every module we import functions from
362  for (auto &Entry : ImportList) {
363  auto ModHash = Index.getModuleHash(Entry.first());
364  Hasher.update(ArrayRef<uint8_t>((uint8_t *)&ModHash[0], sizeof(ModHash)));
365  }
366 
367  // Include the hash for the resolved ODR.
368  for (auto &Entry : ResolvedODR) {
369  Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.first,
370  sizeof(GlobalValue::GUID)));
371  Hasher.update(ArrayRef<uint8_t>((const uint8_t *)&Entry.second,
372  sizeof(GlobalValue::LinkageTypes)));
373  }
374 
375  // Include the hash for the preserved symbols.
376  for (auto &Entry : PreservedSymbols) {
377  if (DefinedFunctions.count(Entry))
378  Hasher.update(
379  ArrayRef<uint8_t>((const uint8_t *)&Entry, sizeof(GlobalValue::GUID)));
380  }
381 
382  // This choice of file name allows the cache to be pruned (see pruneCache()
383  // in include/llvm/Support/CachePruning.h).
384  sys::path::append(EntryPath, CachePath,
385  "llvmcache-" + toHex(Hasher.result()));
386  }
387 
388  // Access the path to this entry in the cache.
389  StringRef getEntryPath() { return EntryPath; }
390 
391  // Try loading the buffer for this cache entry.
392  ErrorOr<std::unique_ptr<MemoryBuffer>> tryLoadingBuffer() {
393  if (EntryPath.empty())
394  return std::error_code();
395  return MemoryBuffer::getFile(EntryPath);
396  }
397 
398  // Cache the Produced object file
399  void write(const MemoryBuffer &OutputBuffer) {
400  if (EntryPath.empty())
401  return;
402 
403  // Write to a temporary to avoid race condition
404  SmallString<128> TempFilename;
405  int TempFD;
406  std::error_code EC =
407  sys::fs::createTemporaryFile("Thin", "tmp.o", TempFD, TempFilename);
408  if (EC) {
409  errs() << "Error: " << EC.message() << "\n";
410  report_fatal_error("ThinLTO: Can't get a temporary file");
411  }
412  {
413  raw_fd_ostream OS(TempFD, /* ShouldClose */ true);
414  OS << OutputBuffer.getBuffer();
415  }
416  // Rename to final destination (hopefully race condition won't matter here)
417  EC = sys::fs::rename(TempFilename, EntryPath);
418  if (EC) {
419  sys::fs::remove(TempFilename);
420  raw_fd_ostream OS(EntryPath, EC, sys::fs::F_None);
421  if (EC)
422  report_fatal_error(Twine("Failed to open ") + EntryPath +
423  " to save cached entry\n");
424  OS << OutputBuffer.getBuffer();
425  }
426  }
427 };
428 
429 static std::unique_ptr<MemoryBuffer>
430 ProcessThinLTOModule(Module &TheModule, ModuleSummaryIndex &Index,
432  const FunctionImporter::ImportMapTy &ImportList,
433  const FunctionImporter::ExportSetTy &ExportList,
434  const DenseSet<GlobalValue::GUID> &GUIDPreservedSymbols,
435  const GVSummaryMapTy &DefinedGlobals,
436  const ThinLTOCodeGenerator::CachingOptions &CacheOptions,
437  bool DisableCodeGen, StringRef SaveTempsDir,
438  bool Freestanding, unsigned OptLevel, unsigned count) {
439 
440  // "Benchmark"-like optimization: single-source case
441  bool SingleModule = (ModuleMap.size() == 1);
442 
443  if (!SingleModule) {
444  promoteModule(TheModule, Index);
445 
446  // Apply summary-based LinkOnce/Weak resolution decisions.
447  thinLTOResolveWeakForLinkerModule(TheModule, DefinedGlobals);
448 
449  // Save temps: after promotion.
450  saveTempBitcode(TheModule, SaveTempsDir, count, ".1.promoted.bc");
451  }
452 
453  // Be friendly and don't nuke totally the module when the client didn't
454  // supply anything to preserve.
455  if (!ExportList.empty() || !GUIDPreservedSymbols.empty()) {
456  // Apply summary-based internalization decisions.
457  thinLTOInternalizeModule(TheModule, DefinedGlobals);
458  }
459 
460  // Save internalized bitcode
461  saveTempBitcode(TheModule, SaveTempsDir, count, ".2.internalized.bc");
462 
463  if (!SingleModule) {
464  crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
465 
466  // Save temps: after cross-module import.
467  saveTempBitcode(TheModule, SaveTempsDir, count, ".3.imported.bc");
468  }
469 
470  optimizeModule(TheModule, TM, OptLevel, Freestanding);
471 
472  saveTempBitcode(TheModule, SaveTempsDir, count, ".4.opt.bc");
473 
474  if (DisableCodeGen) {
475  // Configured to stop before CodeGen, serialize the bitcode and return.
476  SmallVector<char, 128> OutputBuffer;
477  {
478  raw_svector_ostream OS(OutputBuffer);
479  ProfileSummaryInfo PSI(TheModule);
480  auto Index = buildModuleSummaryIndex(TheModule, nullptr, &PSI);
481  WriteBitcodeToFile(&TheModule, OS, true, &Index);
482  }
483  return make_unique<ObjectMemoryBuffer>(std::move(OutputBuffer));
484  }
485 
486  return codegenModule(TheModule, TM);
487 }
488 
489 /// Resolve LinkOnce/Weak symbols. Record resolutions in the \p ResolvedODR map
490 /// for caching, and in the \p Index for application during the ThinLTO
491 /// backends. This is needed for correctness for exported symbols (ensure
492 /// at least one copy kept) and a compile-time optimization (to drop duplicate
493 /// copies when possible).
494 static void resolveWeakForLinkerInIndex(
495  ModuleSummaryIndex &Index,
496  StringMap<std::map<GlobalValue::GUID, GlobalValue::LinkageTypes>>
497  &ResolvedODR) {
498 
500  computePrevailingCopies(Index, PrevailingCopy);
501 
502  auto isPrevailing = [&](GlobalValue::GUID GUID, const GlobalValueSummary *S) {
503  const auto &Prevailing = PrevailingCopy.find(GUID);
504  // Not in map means that there was only one copy, which must be prevailing.
505  if (Prevailing == PrevailingCopy.end())
506  return true;
507  return Prevailing->second == S;
508  };
509 
510  auto recordNewLinkage = [&](StringRef ModuleIdentifier,
511  GlobalValue::GUID GUID,
512  GlobalValue::LinkageTypes NewLinkage) {
513  ResolvedODR[ModuleIdentifier][GUID] = NewLinkage;
514  };
515 
516  thinLTOResolveWeakForLinkerInIndex(Index, isPrevailing, recordNewLinkage);
517 }
518 
519 // Initialize the TargetMachine builder for a given Triple
520 static void initTMBuilder(TargetMachineBuilder &TMBuilder,
521  const Triple &TheTriple) {
522  // Set a default CPU for Darwin triples (copied from LTOCodeGenerator).
523  // FIXME this looks pretty terrible...
524  if (TMBuilder.MCpu.empty() && TheTriple.isOSDarwin()) {
525  if (TheTriple.getArch() == llvm::Triple::x86_64)
526  TMBuilder.MCpu = "core2";
527  else if (TheTriple.getArch() == llvm::Triple::x86)
528  TMBuilder.MCpu = "yonah";
529  else if (TheTriple.getArch() == llvm::Triple::aarch64)
530  TMBuilder.MCpu = "cyclone";
531  }
532  TMBuilder.TheTriple = std::move(TheTriple);
533 }
534 
535 } // end anonymous namespace
536 
538  ThinLTOBuffer Buffer(Data, Identifier);
540  StringRef TripleStr;
542  Context, getBitcodeTargetTriple(Buffer.getMemBuffer()));
543 
544  if (TripleOrErr)
545  TripleStr = *TripleOrErr;
546 
547  Triple TheTriple(TripleStr);
548 
549  if (Modules.empty())
550  initTMBuilder(TMBuilder, Triple(TheTriple));
551  else if (TMBuilder.TheTriple != TheTriple) {
552  if (!TMBuilder.TheTriple.isCompatibleWith(TheTriple))
553  report_fatal_error("ThinLTO modules with incompatible triples not "
554  "supported");
555  initTMBuilder(TMBuilder, Triple(TMBuilder.TheTriple.merge(TheTriple)));
556  }
557 
558  Modules.push_back(Buffer);
559 }
560 
562  PreservedSymbols.insert(Name);
563 }
564 
566  // FIXME: At the moment, we don't take advantage of this extra information,
567  // we're conservatively considering cross-references as preserved.
568  // CrossReferencedSymbols.insert(Name);
569  PreservedSymbols.insert(Name);
570 }
571 
572 // TargetMachine factory
573 std::unique_ptr<TargetMachine> TargetMachineBuilder::create() const {
574  std::string ErrMsg;
575  const Target *TheTarget =
577  if (!TheTarget) {
578  report_fatal_error("Can't load target for this Triple: " + ErrMsg);
579  }
580 
581  // Use MAttr as the default set of features.
583  Features.getDefaultSubtargetFeatures(TheTriple);
584  std::string FeatureStr = Features.getString();
585 
586  return std::unique_ptr<TargetMachine>(TheTarget->createTargetMachine(
587  TheTriple.str(), MCpu, FeatureStr, Options, RelocModel,
589 }
590 
591 /**
592  * Produce the combined summary index from all the bitcode files:
593  * "thin-link".
594  */
595 std::unique_ptr<ModuleSummaryIndex> ThinLTOCodeGenerator::linkCombinedIndex() {
596  std::unique_ptr<ModuleSummaryIndex> CombinedIndex =
597  llvm::make_unique<ModuleSummaryIndex>();
598  uint64_t NextModuleId = 0;
599  for (auto &ModuleBuffer : Modules) {
600  if (Error Err = readModuleSummaryIndex(ModuleBuffer.getMemBuffer(),
601  *CombinedIndex, NextModuleId++)) {
602  // FIXME diagnose
604  std::move(Err), errs(),
605  "error: can't create module summary index for buffer: ");
606  return nullptr;
607  }
608  }
609  return CombinedIndex;
610 }
611 
612 /**
613  * Perform promotion and renaming of exported internal functions.
614  * Index is updated to reflect linkage changes from weak resolution.
615  */
617  ModuleSummaryIndex &Index) {
618  auto ModuleCount = Index.modulePaths().size();
619  auto ModuleIdentifier = TheModule.getModuleIdentifier();
620 
621  // Collect for each module the list of function it defines (GUID -> Summary).
622  StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries;
623  Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
624 
625  // Convert the preserved symbols set from string to GUID
626  auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
627  PreservedSymbols, Triple(TheModule.getTargetTriple()));
628 
629  // Compute "dead" symbols, we don't want to import/export these!
630  computeDeadSymbols(Index, GUIDPreservedSymbols);
631 
632  // Generate import/export list
633  StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
634  StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
635  ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
636  ExportLists);
637 
638  // Resolve LinkOnce/Weak symbols.
640  resolveWeakForLinkerInIndex(Index, ResolvedODR);
641 
643  TheModule, ModuleToDefinedGVSummaries[ModuleIdentifier]);
644 
645  // Promote the exported values in the index, so that they are promoted
646  // in the module.
647  auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
648  const auto &ExportList = ExportLists.find(ModuleIdentifier);
649  return (ExportList != ExportLists.end() &&
650  ExportList->second.count(GUID)) ||
651  GUIDPreservedSymbols.count(GUID);
652  };
653  thinLTOInternalizeAndPromoteInIndex(Index, isExported);
654 
655  promoteModule(TheModule, Index);
656 }
657 
658 /**
659  * Perform cross-module importing for the module identified by ModuleIdentifier.
660  */
662  ModuleSummaryIndex &Index) {
663  auto ModuleMap = generateModuleMap(Modules);
664  auto ModuleCount = Index.modulePaths().size();
665 
666  // Collect for each module the list of function it defines (GUID -> Summary).
667  StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
668  Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
669 
670  // Convert the preserved symbols set from string to GUID
671  auto GUIDPreservedSymbols = computeGUIDPreservedSymbols(
672  PreservedSymbols, Triple(TheModule.getTargetTriple()));
673 
674  // Compute "dead" symbols, we don't want to import/export these!
675  computeDeadSymbols(Index, GUIDPreservedSymbols);
676 
677  // Generate import/export list
678  StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
679  StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
680  ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
681  ExportLists);
682  auto &ImportList = ImportLists[TheModule.getModuleIdentifier()];
683 
684  crossImportIntoModule(TheModule, Index, ModuleMap, ImportList);
685 }
686 
687 /**
688  * Compute the list of summaries needed for importing into module.
689  */
691  StringRef ModulePath, ModuleSummaryIndex &Index,
692  std::map<std::string, GVSummaryMapTy> &ModuleToSummariesForIndex) {
693  auto ModuleCount = Index.modulePaths().size();
694 
695  // Collect for each module the list of function it defines (GUID -> Summary).
696  StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
697  Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
698 
699  // Generate import/export list
700  StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
701  StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
702  ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
703  ExportLists);
704 
705  llvm::gatherImportedSummariesForModule(ModulePath, ModuleToDefinedGVSummaries,
706  ImportLists[ModulePath],
707  ModuleToSummariesForIndex);
708 }
709 
710 /**
711  * Emit the list of files needed for importing into module.
712  */
714  StringRef OutputName,
715  ModuleSummaryIndex &Index) {
716  auto ModuleCount = Index.modulePaths().size();
717 
718  // Collect for each module the list of function it defines (GUID -> Summary).
719  StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
720  Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
721 
722  // Generate import/export list
723  StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
724  StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
725  ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
726  ExportLists);
727 
728  std::error_code EC;
729  if ((EC = EmitImportsFiles(ModulePath, OutputName, ImportLists[ModulePath])))
730  report_fatal_error(Twine("Failed to open ") + OutputName +
731  " to save imports lists\n");
732 }
733 
734 /**
735  * Perform internalization. Index is updated to reflect linkage changes.
736  */
738  ModuleSummaryIndex &Index) {
739  initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
740  auto ModuleCount = Index.modulePaths().size();
741  auto ModuleIdentifier = TheModule.getModuleIdentifier();
742 
743  // Convert the preserved symbols set from string to GUID
744  auto GUIDPreservedSymbols =
745  computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
746 
747  // Collect for each module the list of function it defines (GUID -> Summary).
748  StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
749  Index.collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
750 
751  // Compute "dead" symbols, we don't want to import/export these!
752  computeDeadSymbols(Index, GUIDPreservedSymbols);
753 
754  // Generate import/export list
755  StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
756  StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
757  ComputeCrossModuleImport(Index, ModuleToDefinedGVSummaries, ImportLists,
758  ExportLists);
759  auto &ExportList = ExportLists[ModuleIdentifier];
760 
761  // Be friendly and don't nuke totally the module when the client didn't
762  // supply anything to preserve.
763  if (ExportList.empty() && GUIDPreservedSymbols.empty())
764  return;
765 
766  // Internalization
767  auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
768  const auto &ExportList = ExportLists.find(ModuleIdentifier);
769  return (ExportList != ExportLists.end() &&
770  ExportList->second.count(GUID)) ||
771  GUIDPreservedSymbols.count(GUID);
772  };
773  thinLTOInternalizeAndPromoteInIndex(Index, isExported);
774  thinLTOInternalizeModule(TheModule,
775  ModuleToDefinedGVSummaries[ModuleIdentifier]);
776 }
777 
778 /**
779  * Perform post-importing ThinLTO optimizations.
780  */
782  initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
783 
784  // Optimize now
785  optimizeModule(TheModule, *TMBuilder.create(), OptLevel, Freestanding);
786 }
787 
788 /**
789  * Perform ThinLTO CodeGen.
790  */
791 std::unique_ptr<MemoryBuffer> ThinLTOCodeGenerator::codegen(Module &TheModule) {
792  initTMBuilder(TMBuilder, Triple(TheModule.getTargetTriple()));
793  return codegenModule(TheModule, *TMBuilder.create());
794 }
795 
796 /// Write out the generated object file, either from CacheEntryPath or from
797 /// OutputBuffer, preferring hard-link when possible.
798 /// Returns the path to the generated file in SavedObjectsDirectoryPath.
799 static std::string writeGeneratedObject(int count, StringRef CacheEntryPath,
800  StringRef SavedObjectsDirectoryPath,
801  const MemoryBuffer &OutputBuffer) {
802  SmallString<128> OutputPath(SavedObjectsDirectoryPath);
803  llvm::sys::path::append(OutputPath, Twine(count) + ".thinlto.o");
804  OutputPath.c_str(); // Ensure the string is null terminated.
805  if (sys::fs::exists(OutputPath))
806  sys::fs::remove(OutputPath);
807 
808  // We don't return a memory buffer to the linker, just a list of files.
809  if (!CacheEntryPath.empty()) {
810  // Cache is enabled, hard-link the entry (or copy if hard-link fails).
811  auto Err = sys::fs::create_hard_link(CacheEntryPath, OutputPath);
812  if (!Err)
813  return OutputPath.str();
814  // Hard linking failed, try to copy.
815  Err = sys::fs::copy_file(CacheEntryPath, OutputPath);
816  if (!Err)
817  return OutputPath.str();
818  // Copy failed (could be because the CacheEntry was removed from the cache
819  // in the meantime by another process), fall back and try to write down the
820  // buffer to the output.
821  errs() << "error: can't link or copy from cached entry '" << CacheEntryPath
822  << "' to '" << OutputPath << "'\n";
823  }
824  // No cache entry, just write out the buffer.
825  std::error_code Err;
826  raw_fd_ostream OS(OutputPath, Err, sys::fs::F_None);
827  if (Err)
828  report_fatal_error("Can't open output '" + OutputPath + "'\n");
829  OS << OutputBuffer.getBuffer();
830  return OutputPath.str();
831 }
832 
833 // Main entry point for the ThinLTO processing
835  // Prepare the resulting object vector
836  assert(ProducedBinaries.empty() && "The generator should not be reused");
837  if (SavedObjectsDirectoryPath.empty())
838  ProducedBinaries.resize(Modules.size());
839  else {
840  sys::fs::create_directories(SavedObjectsDirectoryPath);
841  bool IsDir;
842  sys::fs::is_directory(SavedObjectsDirectoryPath, IsDir);
843  if (!IsDir)
844  report_fatal_error("Unexistent dir: '" + SavedObjectsDirectoryPath + "'");
845  ProducedBinaryFiles.resize(Modules.size());
846  }
847 
848  if (CodeGenOnly) {
849  // Perform only parallel codegen and return.
850  ThreadPool Pool;
851  int count = 0;
852  for (auto &ModuleBuffer : Modules) {
853  Pool.async([&](int count) {
856 
857  // Parse module now
858  auto TheModule =
859  loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false,
860  /*IsImporting*/ false);
861 
862  // CodeGen
863  auto OutputBuffer = codegen(*TheModule);
864  if (SavedObjectsDirectoryPath.empty())
865  ProducedBinaries[count] = std::move(OutputBuffer);
866  else
867  ProducedBinaryFiles[count] = writeGeneratedObject(
868  count, "", SavedObjectsDirectoryPath, *OutputBuffer);
869  }, count++);
870  }
871 
872  return;
873  }
874 
875  // Sequential linking phase
876  auto Index = linkCombinedIndex();
877 
878  // Save temps: index.
879  if (!SaveTempsDir.empty()) {
880  auto SaveTempPath = SaveTempsDir + "index.bc";
881  std::error_code EC;
882  raw_fd_ostream OS(SaveTempPath, EC, sys::fs::F_None);
883  if (EC)
884  report_fatal_error(Twine("Failed to open ") + SaveTempPath +
885  " to save optimized bitcode\n");
886  WriteIndexToFile(*Index, OS);
887  }
888 
889 
890  // Prepare the module map.
891  auto ModuleMap = generateModuleMap(Modules);
892  auto ModuleCount = Modules.size();
893 
894  // Collect for each module the list of function it defines (GUID -> Summary).
895  StringMap<GVSummaryMapTy> ModuleToDefinedGVSummaries(ModuleCount);
896  Index->collectDefinedGVSummariesPerModule(ModuleToDefinedGVSummaries);
897 
898  // Convert the preserved symbols set from string to GUID, this is needed for
899  // computing the caching hash and the internalization.
900  auto GUIDPreservedSymbols =
901  computeGUIDPreservedSymbols(PreservedSymbols, TMBuilder.TheTriple);
902 
903  // Compute "dead" symbols, we don't want to import/export these!
904  computeDeadSymbols(*Index, GUIDPreservedSymbols);
905 
906  // Collect the import/export lists for all modules from the call-graph in the
907  // combined index.
908  StringMap<FunctionImporter::ImportMapTy> ImportLists(ModuleCount);
909  StringMap<FunctionImporter::ExportSetTy> ExportLists(ModuleCount);
910  ComputeCrossModuleImport(*Index, ModuleToDefinedGVSummaries, ImportLists,
911  ExportLists);
912 
913  // We use a std::map here to be able to have a defined ordering when
914  // producing a hash for the cache entry.
915  // FIXME: we should be able to compute the caching hash for the entry based
916  // on the index, and nuke this map.
918 
919  // Resolve LinkOnce/Weak symbols, this has to be computed early because it
920  // impacts the caching.
921  resolveWeakForLinkerInIndex(*Index, ResolvedODR);
922 
923  auto isExported = [&](StringRef ModuleIdentifier, GlobalValue::GUID GUID) {
924  const auto &ExportList = ExportLists.find(ModuleIdentifier);
925  return (ExportList != ExportLists.end() &&
926  ExportList->second.count(GUID)) ||
927  GUIDPreservedSymbols.count(GUID);
928  };
929 
930  // Use global summary-based analysis to identify symbols that can be
931  // internalized (because they aren't exported or preserved as per callback).
932  // Changes are made in the index, consumed in the ThinLTO backends.
933  thinLTOInternalizeAndPromoteInIndex(*Index, isExported);
934 
935  // Make sure that every module has an entry in the ExportLists and
936  // ResolvedODR maps to enable threaded access to these maps below.
937  for (auto &DefinedGVSummaries : ModuleToDefinedGVSummaries) {
938  ExportLists[DefinedGVSummaries.first()];
939  ResolvedODR[DefinedGVSummaries.first()];
940  }
941 
942  // Compute the ordering we will process the inputs: the rough heuristic here
943  // is to sort them per size so that the largest module get schedule as soon as
944  // possible. This is purely a compile-time optimization.
945  std::vector<int> ModulesOrdering;
946  ModulesOrdering.resize(Modules.size());
947  std::iota(ModulesOrdering.begin(), ModulesOrdering.end(), 0);
948  std::sort(ModulesOrdering.begin(), ModulesOrdering.end(),
949  [&](int LeftIndex, int RightIndex) {
950  auto LSize = Modules[LeftIndex].getBuffer().size();
951  auto RSize = Modules[RightIndex].getBuffer().size();
952  return LSize > RSize;
953  });
954 
955  // Parallel optimizer + codegen
956  {
957  ThreadPool Pool(ThreadCount);
958  for (auto IndexCount : ModulesOrdering) {
959  auto &ModuleBuffer = Modules[IndexCount];
960  Pool.async([&](int count) {
961  auto ModuleIdentifier = ModuleBuffer.getBufferIdentifier();
962  auto &ExportList = ExportLists[ModuleIdentifier];
963 
964  auto &DefinedFunctions = ModuleToDefinedGVSummaries[ModuleIdentifier];
965 
966  // The module may be cached, this helps handling it.
967  ModuleCacheEntry CacheEntry(CacheOptions.Path, *Index, ModuleIdentifier,
968  ImportLists[ModuleIdentifier], ExportList,
969  ResolvedODR[ModuleIdentifier],
970  DefinedFunctions, GUIDPreservedSymbols,
971  OptLevel, Freestanding, TMBuilder);
972  auto CacheEntryPath = CacheEntry.getEntryPath();
973 
974  {
975  auto ErrOrBuffer = CacheEntry.tryLoadingBuffer();
976  DEBUG(dbgs() << "Cache " << (ErrOrBuffer ? "hit" : "miss") << " '"
977  << CacheEntryPath << "' for buffer " << count << " "
978  << ModuleIdentifier << "\n");
979 
980  if (ErrOrBuffer) {
981  // Cache Hit!
982  if (SavedObjectsDirectoryPath.empty())
983  ProducedBinaries[count] = std::move(ErrOrBuffer.get());
984  else
985  ProducedBinaryFiles[count] = writeGeneratedObject(
986  count, CacheEntryPath, SavedObjectsDirectoryPath,
987  *ErrOrBuffer.get());
988  return;
989  }
990  }
991 
994  Context.enableDebugTypeODRUniquing();
995  auto DiagFileOrErr = lto::setupOptimizationRemarks(
997  if (!DiagFileOrErr) {
998  errs() << "Error: " << toString(DiagFileOrErr.takeError()) << "\n";
999  report_fatal_error("ThinLTO: Can't get an output file for the "
1000  "remarks");
1001  }
1002 
1003  // Parse module now
1004  auto TheModule =
1005  loadModuleFromBuffer(ModuleBuffer.getMemBuffer(), Context, false,
1006  /*IsImporting*/ false);
1007 
1008  // Save temps: original file.
1009  saveTempBitcode(*TheModule, SaveTempsDir, count, ".0.original.bc");
1010 
1011  auto &ImportList = ImportLists[ModuleIdentifier];
1012  // Run the main process now, and generates a binary
1013  auto OutputBuffer = ProcessThinLTOModule(
1014  *TheModule, *Index, ModuleMap, *TMBuilder.create(), ImportList,
1015  ExportList, GUIDPreservedSymbols,
1016  ModuleToDefinedGVSummaries[ModuleIdentifier], CacheOptions,
1017  DisableCodeGen, SaveTempsDir, Freestanding, OptLevel, count);
1018 
1019  // Commit to the cache (if enabled)
1020  CacheEntry.write(*OutputBuffer);
1021 
1022  if (SavedObjectsDirectoryPath.empty()) {
1023  // We need to generated a memory buffer for the linker.
1024  if (!CacheEntryPath.empty()) {
1025  // Cache is enabled, reload from the cache
1026  // We do this to lower memory pressuree: the buffer is on the heap
1027  // and releasing it frees memory that can be used for the next input
1028  // file. The final binary link will read from the VFS cache
1029  // (hopefully!) or from disk if the memory pressure wasn't too high.
1030  auto ReloadedBufferOrErr = CacheEntry.tryLoadingBuffer();
1031  if (auto EC = ReloadedBufferOrErr.getError()) {
1032  // On error, keeping the preexisting buffer and printing a
1033  // diagnostic is more friendly than just crashing.
1034  errs() << "error: can't reload cached file '" << CacheEntryPath
1035  << "': " << EC.message() << "\n";
1036  } else {
1037  OutputBuffer = std::move(*ReloadedBufferOrErr);
1038  }
1039  }
1040  ProducedBinaries[count] = std::move(OutputBuffer);
1041  return;
1042  }
1043  ProducedBinaryFiles[count] = writeGeneratedObject(
1044  count, CacheEntryPath, SavedObjectsDirectoryPath, *OutputBuffer);
1045  }, IndexCount);
1046  }
1047  }
1048 
1049  pruneCache(CacheOptions.Path, CacheOptions.Policy);
1050 
1051  // If statistics were requested, print them out now.
1055 }
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition: StringRef.h:645
void print(const char *ProgName, raw_ostream &S, bool ShowColors=true, bool ShowKindLabel=true) const
Definition: SourceMgr.cpp:345
void computeDeadSymbols(ModuleSummaryIndex &Index, const DenseSet< GlobalValue::GUID > &GUIDPreservedSymbols)
Compute all the symbols that are "dead": i.e these that can't be reached in the graph from any of t...
std::error_code create_directories(const Twine &path, bool IgnoreExisting=true, perms Perms=owner_all|group_all)
Create all the non-existent directories in path.
Definition: Path.cpp:868
Represents either an error or a value T.
Definition: ErrorOr.h:69
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
bool isOSBinFormatMachO() const
Tests whether the environment is MachO.
Definition: Triple.h:587
LLVMContext & Context
PassManagerBuilder - This class is used to set up a standard optimization sequence for languages like...
uint64_t GUID
Declare a type to represent a global unique identifier for a global value.
Definition: GlobalValue.h:472
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:103
const ModuleHash & getModuleHash(const StringRef ModPath) const
Get the module SHA1 hash recorded for the given module path.
void getDefaultSubtargetFeatures(const Triple &Triple)
Adds the default features for the specified target triple.
void promote(Module &Module, ModuleSummaryIndex &Index)
Perform promotion and renaming of exported internal functions, and additionally resolve weak and link...
cl::opt< std::string > LTORemarksFilename("lto-pass-remarks-output", cl::desc("Output filename for pass remarks"), cl::value_desc("filename"))
unsigned heavyweight_hardware_concurrency()
Get the amount of currency to use for tasks requiring significant memory or other resources...
Definition: Threading.cpp:61
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:63
Expected< std::unique_ptr< Module > > getLazyBitcodeModule(MemoryBufferRef Buffer, LLVMContext &Context, bool ShouldLazyLoadMetadata=false, bool IsImporting=false)
Read the header of the specified bitcode buffer and prepare for lazy deserialization of function bodi...
GUID getGUID() const
Return a 64-bit global unique ID constructed from global value name (i.e.
Definition: GlobalValue.h:480
void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner)
Log all errors (if any) in E to OS.
Definition: Error.cpp:57
This is the interface to build a ModuleSummaryIndex for a module.
std::error_code remove(const Twine &path, bool IgnoreNonExisting=true)
Remove path.
This file provides a bitcode writing pass.
Implements a dense probed hash-table based set.
Definition: DenseSet.h:221
void populateThinLTOPassManager(legacy::PassManagerBase &PM)
unsigned DataSections
Emit data into separate sections.
std::unique_ptr< TargetMachine > create() const
Analysis providing profile information.
void enableDebugTypeODRUniquing()
void disableAllFunctions()
Disables all builtins.
ImmutablePass * createTargetTransformInfoWrapperPass(TargetIRAnalysis TIRA)
Create an analysis pass wrapper around a TTI object.
iterator find(StringRef Key)
Definition: StringMap.h:333
StringRef getBuffer() const
Definition: MemoryBuffer.h:59
A raw_ostream that writes to an SmallVector or SmallString.
Definition: raw_ostream.h:490
Implementation of the target library information.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:818
const std::string & str() const
Definition: Triple.h:350
A class that wrap the SHA1 algorithm.
Definition: SHA1.h:29
Error takeError()
Take ownership of the stored error.
Definition: Error.h:764
static const Target * lookupTarget(const std::string &Triple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
void addModule(StringRef Identifier, StringRef Data)
Add given module to the code generator.
Base class for error info classes.
Definition: Error.h:47
void reportAndResetTimings()
If -time-passes has been specified, report the timings immediately and then reset the timers to zero...
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition: Module.h:233
Pass * Inliner
Inliner - Specifies the inliner to use.
void setDiscardValueNames(bool Discard)
Set the Context runtime configuration to discard all value name (but GlobalValue).
ModuleSummaryIndex buildModuleSummaryIndex(const Module &M, std::function< BlockFrequencyInfo *(const Function &F)> GetBFICallback, ProfileSummaryInfo *PSI)
Direct function to compute a ModuleSummaryIndex from a given module.
Wrapper around MemoryBufferRef, owning the identifier.
std::shared_future< void > async(Function &&F, Args &&...ArgList)
Asynchronous submission of a task to the pool.
Definition: ThreadPool.h:54
const Triple & getTargetTriple() const
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition: Path.cpp:465
std::unordered_set< GlobalValue::GUID > ExportSetTy
The set contains an entry for every global value the module exports.
std::string toString(Error E)
Write all error messages (if any) in E to a string.
Definition: Error.h:578
void add(Pass *P) override
Add a pass to the queue of passes to run.
DiagnosticSeverity
Defines the different supported severity of a diagnostic.
std::unique_ptr< MemoryBuffer > codegen(Module &Module)
Perform ThinLTO CodeGen.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
cl::opt< bool > LTOStripInvalidDebugInfo("lto-strip-invalid-debug-info", cl::desc("Strip invalid debug info metadata during LTO instead of aborting."), cl::init(false), cl::Hidden)
MemoryBufferRef getMemBuffer() const
Tagged union holding either a T or a Error.
Definition: CachePruning.h:23
Interface for custom diagnostic printing.
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
Definition: Module.h:208
StringRef result()
Return a reference to the current raw 160-bits SHA1 for the digested data since the last call to init...
Definition: SHA1.cpp:261
std::vector< std::unique_ptr< GlobalValueSummary >> GlobalValueSummaryList
void run()
Process all the modules that were added to the code generator in parallel.
#define F(x, y, z)
Definition: MD5.cpp:55
cl::opt< bool > LTOPassRemarksWithHotness("lto-pass-remarks-with-hotness", cl::desc("With PGO, include profile count in optimization remarks"), cl::Hidden)
Pass * createObjCARCContractPass()
unsigned OptLevel
The Optimization Level - Specify the basic optimization level.
bool StripDebugInfo(Module &M)
Strip debug info in the module if it exists.
Definition: DebugInfo.cpp:325
const StringMap< std::pair< uint64_t, ModuleHash > > & modulePaths() const
Table of modules, containing module hash and id.
unsigned FunctionSections
Emit functions into separate sections.
static std::string utostr(uint64_t X, bool isNeg=false)
Definition: StringExtras.h:160
A ThreadPool for asynchronous parallel execution on a defined number of threads.
Definition: ThreadPool.h:36
ArchType getArch() const
getArch - Get the parsed architecture type of this triple.
Definition: Triple.h:281
auto count(R &&Range, const E &Element) -> typename std::iterator_traits< decltype(std::begin(Range))>::difference_type
Wrapper function around std::count to count the number of times an element Element occurs in the give...
Definition: STLExtras.h:880
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t size() const
size - Get the string size.
Definition: StringRef.h:138
Class to hold module path string table and global value map, and encapsulate methods for operating on...
const char * Name
void update(ArrayRef< uint8_t > Data)
Digest more data.
Definition: SHA1.cpp:213
bool isWeakForLinker() const
Definition: GlobalValue.h:436
virtual bool addPassesToEmitFile(PassManagerBase &, raw_pwrite_stream &, CodeGenFileType, bool=true, AnalysisID=nullptr, AnalysisID=nullptr, AnalysisID=nullptr, AnalysisID=nullptr)
Add passes to the specified pass manager to get the specified file emitted.
PassManager manages ModulePassManagers.
std::error_code copy_file(const Twine &From, const Twine &To)
Copy the contents of From to To.
Definition: Path.cpp:892
void WriteBitcodeToFile(const Module *M, raw_ostream &Out, bool ShouldPreserveUseListOrder=false, const ModuleSummaryIndex *Index=nullptr, bool GenerateHash=false, ModuleHash *ModHash=nullptr)
Write the specified module to the specified raw output stream.
DebuggerKind DebuggerTuning
Which debugger to tune for.
void crossReferenceSymbol(StringRef Name)
Adds to a list of all global symbols that are cross-referenced between ThinLTO files.
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:401
std::string ErrMsg
This is the base abstract class for diagnostic reporting in the backend.
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
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.
void optimize(Module &Module)
Perform post-importing ThinLTO optimizations.
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:68
TargetLibraryInfoImpl * LibraryInfo
LibraryInfo - Specifies information about the runtime library for the optimizer.
Helper to gather options relevant to the target machine creation.
virtual TargetIRAnalysis getTargetIRAnalysis()
Get a TargetIRAnalysis appropriate for the target.
unsigned size() const
Definition: StringMap.h:111
Expected< std::unique_ptr< tool_output_file > > setupOptimizationRemarks(LLVMContext &Context, StringRef LTORemarksFilename, bool LTOPassRemarksWithHotness, int Count=-1)
Setup optimization remarks.
Definition: LTO.cpp:1117
Expected< std::string > getBitcodeTargetTriple(MemoryBufferRef Buffer)
Read the header of the specified bitcode buffer and extract just the triple information.
Error readModuleSummaryIndex(MemoryBufferRef Buffer, ModuleSummaryIndex &CombinedIndex, uint64_t ModuleId)
Parse the specified bitcode buffer and merge the index into CombinedIndex.
void handleAllErrors(Error E, HandlerTs &&...Handlers)
Behaves the same as handleErrors, except that it requires that all errors be handled by the given han...
Definition: Error.h:555
std::error_code create_hard_link(const Twine &to, const Twine &from)
Create a hard link from from to to, or return an error.
Function and variable summary information to aid decisions and implementation of importing.
static void write(bool isBE, void *P, T V)
bool isCompatibleWith(const Triple &Other) const
Test whether target triples are compatible.
Definition: Triple.cpp:1492
bool pruneCache(StringRef Path, CachePruningPolicy Policy)
Peform pruning using the supplied policy, returns true if pruning occured, i.e.
std::string getString() const
Returns features as a string.
bool run(Module &M)
run - Execute all of the passes scheduled for execution.
bool is_directory(file_status status)
Does status represent a directory?
Definition: Path.cpp:971
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
static std::string writeGeneratedObject(int count, StringRef CacheEntryPath, StringRef SavedObjectsDirectoryPath, const MemoryBuffer &OutputBuffer)
Write out the generated object file, either from CacheEntryPath or from OutputBuffer, preferring hard-link when possible.
std::error_code rename(const Twine &from, const Twine &to)
Rename from to to.
bool isOSDarwin() const
isOSDarwin - Is this a "Darwin" OS (OS X, iOS, or watchOS).
Definition: Triple.h:466
TargetMachine * createTargetMachine(StringRef TT, StringRef CPU, StringRef Features, const TargetOptions &Options, Optional< Reloc::Model > RM, CodeModel::Model CM=CodeModel::Default, CodeGenOpt::Level OL=CodeGenOpt::Default) const
createTargetMachine - Create a target specific machine implementation for the specified Triple...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
static bool isAvailableExternallyLinkage(LinkageTypes Linkage)
Definition: GlobalValue.h:274
reference get()
Returns a reference to the stored T value.
Definition: Error.h:744
std::error_code EmitImportsFiles(StringRef ModulePath, StringRef OutputFilename, const FunctionImporter::ImportMapTy &ModuleImports)
Emit into OutputFilename the files module ModulePath will import from.
This interface provides simple read-only access to a block of memory, and provides simple methods for...
Definition: MemoryBuffer.h:40
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:220
Target - Wrapper for Target specific information.
Manages the enabling and disabling of subtarget specific features.
StringRef str() const
Explicit conversion to StringRef.
Definition: SmallString.h:267
LinkageTypes
An enumeration for the kinds of linkage for global values.
Definition: GlobalValue.h:48
void WriteIndexToFile(const ModuleSummaryIndex &Index, raw_ostream &Out, const std::map< std::string, GVSummaryMapTy > *ModuleToSummariesForIndex=nullptr)
Write the specified module summary index to the given raw output stream, where it will be written in ...
void collectDefinedGVSummariesPerModule(StringMap< GVSummaryMapTy > &ModuleToDefinedGVSummaries) const
Collect for each module the list of Summaries it defines (GUID -> Summary).
std::string toHex(StringRef Input)
Convert buffer Input to its hexadecimal representation.
Definition: StringExtras.h:79
std::unique_ptr< ModuleSummaryIndex > linkCombinedIndex()
Produce the combined summary index from all the bitcode files: "thin-link".
unsigned RelaxELFRelocations
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:133
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:126
bool verifyModule(const Module &M, raw_ostream *OS=nullptr, bool *BrokenDebugInfo=nullptr)
Check a module for errors.
Definition: Verifier.cpp:4624
static void gatherImportedSummariesForModule(StringRef ModulePath, ModuleSummaryIndex &Index, std::map< std::string, GVSummaryMapTy > &ModuleToSummariesForIndex)
Compute the list of summaries needed for importing into module.
Expected< std::unique_ptr< Module > > parseBitcodeFile(MemoryBufferRef Buffer, LLVMContext &Context)
Read the specified bitcode file, returning the module.
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.
cl::opt< bool > LTODiscardValueNames("lto-discard-value-names", cl::desc("Strip names from Value during LTO (other than GlobalValue)."), cl::init(false), cl::Hidden)
ErrorOr< T > expectedToErrorOrAndEmitErrors(LLVMContext &Ctx, Expected< T > Val)
Definition: BitcodeReader.h:37
A raw_ostream that writes to a file descriptor.
Definition: raw_ostream.h:357
void thinLTOResolveWeakForLinkerInIndex(ModuleSummaryIndex &Index, function_ref< bool(GlobalValue::GUID, const GlobalValueSummary *)> isPrevailing, function_ref< void(StringRef, GlobalValue::GUID, GlobalValue::LinkageTypes)> recordNewLinkage)
Resolve Weak and LinkOnce values in the Index.
Definition: LTO.cpp:270
std::error_code createTemporaryFile(const Twine &Prefix, StringRef Suffix, int &ResultFD, SmallVectorImpl< char > &ResultPath)
Create a file in the system temporary directory.
Definition: Path.cpp:783
const char * c_str()
Definition: SmallString.h:270
#define I(x, y, z)
Definition: MD5.cpp:58
void thinLTOInternalizeModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals)
Internalize TheModule based on the information recorded in the summaries during global summary-based ...
void preserveSymbol(StringRef Name)
Adds to a list of all global symbols that must exist in the final generated code. ...
void diagnose(const DiagnosticInfo &DI)
Report a message to the currently installed diagnostic handler.
void thinLTOResolveWeakForLinkerModule(Module &TheModule, const GVSummaryMapTy &DefinedGlobals)
Resolve WeakForLinker values in TheModule based on the information recorded in the summaries during g...
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition: DenseSet.h:91
void crossModuleImport(Module &Module, ModuleSummaryIndex &Index)
Perform cross-module importing for the module identified by ModuleIdentifier.
static ErrorOr< std::unique_ptr< MemoryBuffer > > getFile(const Twine &Filename, int64_t FileSize=-1, bool RequiresNullTerminator=true, bool IsVolatile=false)
Open the specified file as a MemoryBuffer, returning a new MemoryBuffer if successful, otherwise returning null.
void PrintStatistics()
Print statistics to the file returned by CreateInfoOutputFile().
Definition: Statistic.cpp:183
Optional< Reloc::Model > RelocModel
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
StringRef getBufferIdentifier() const
Definition: MemoryBuffer.h:171
Pass * createFunctionInliningPass()
createFunctionInliningPass - Return a new pass object that uses a heuristic to inline direct function...
void internalize(Module &Module, ModuleSummaryIndex &Index)
Perform internalization.
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...
The function importer is automatically importing function from other modules based on the provided su...
Lightweight error class with error context and mandatory checking.
Definition: Error.h:156
const FeatureBitset Features
StringSet - A wrapper for StringMap that provides set-like functionality.
Definition: StringSet.h:28
#define DEBUG(X)
Definition: Debug.h:118
Primary interface to the complete machine description for the target machine.
Definition: TargetMachine.h:56
static void emitImports(StringRef ModulePath, StringRef OutputName, ModuleSummaryIndex &Index)
Compute and emit the imported files for module at ModulePath.
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
void sort(Policy policy, RandomAccessIterator Start, RandomAccessIterator End, const Comparator &Comp=Comparator())
Definition: Parallel.h:201
This pass exposes codegen information to IR-level passes.
bool exists(file_status status)
Does file exist?
Definition: Path.cpp:956
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:846
std::string merge(const Triple &Other) const
Merge target triples.
Definition: Triple.cpp:1516
bool AreStatisticsEnabled()
Check if statistics are enabled.
Definition: Statistic.cpp:112
iterator end()
Definition: StringMap.h:318
void thinLTOInternalizeAndPromoteInIndex(ModuleSummaryIndex &Index, function_ref< bool(StringRef, GlobalValue::GUID)> isExported)
Update the linkages in the given Index to mark exported values as external and non-exported values as...
Definition: LTO.cpp:305
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:237
Instances of this class encapsulate one diagnostic report, allowing printing to a raw_ostream as a ca...
Definition: SourceMgr.h:232