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